@duckmind/dm-windows-x64 0.59.9 → 0.60.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{randomInt as Yt}from"node:crypto";import{spawn as Gt}from"node:child_process";import{basename as St}from"node:path";import{dirname as Rt,join as Lt}from"node:path";import{fileURLToPath as It}from"node:url";function Ft(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let i=St(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}var Et=Rt(It(import.meta.url)),te=Lt(Et,"..","bin","cdp.mjs"),ee=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function ne(t){if(!Array.isArray(t)||t.length===0)throw Error("cdp: args must be a non-empty array");if(t[0]==="test")return t.map((e,n)=>ft(e,n));if(!ee.has(t[0]))throw Error(`cdp: unknown subcommand '${t[0]}'`);return t.map((e,n)=>ft(e,n))}function ft(t,e){if(typeof t!=="string")throw Error(`cdp: argv[${e}] must be a string (got ${typeof t})`);if(t.includes("\x00"))throw Error(`cdp: argv[${e}] contains a null byte`);return t}function f(t,e=30000){return re(t,null,e)}function re(t,e=null,n=30000){let i=ne(t);return new Promise((r,l)=>{let o=Gt(Ft(),[te,...i],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)o.stdin.write(e),o.stdin.end();let u="",a="";o.stdout.on("data",(g)=>u+=g),o.stderr.on("data",(g)=>a+=g);let s=setTimeout(()=>{o.kill(),l(Error(`cdp timeout: ${t[0]}`))},n);o.on("close",(g)=>{if(clearTimeout(s),g===0)r(u.trim());else l(Error(a.trim()||`cdp exit ${g}`))})})}function st(t,e){let n=(o)=>String(o??"").replace(/\s+/g," ").trim(),i=n(t),r=n(e);if(!r)return!1;if(i.length<Math.ceil(r.length*0.8))return!1;let l=Math.min(40,r.length);return i.includes(r.slice(0,l))&&i.includes(r.slice(-l))}async function gt(t){if(t)return t;let e=(await f(["list"])).split(`
3
- `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await f(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),i;try{i=JSON.parse(n)}catch(o){throw Error(`Target.createTarget returned invalid JSON: ${o.message}`)}let{targetId:r}=i;if(!r)throw Error("Target.createTarget did not return a targetId");await f(["list"]);let l=r.slice(0,8);try{await ct(l)}catch(o){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${o.message}
4
- `)}return l}async function ct(t){await f(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
2
+ import{randomInt as Gt}from"node:crypto";import{spawn as Rt}from"node:child_process";import{basename as Ft}from"node:path";import{dirname as It,join as Et}from"node:path";import{fileURLToPath as te}from"node:url";function Lt(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let i=Ft(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}var ee=It(te(import.meta.url)),ne=Et(ee,"..","bin","cdp.mjs"),re=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function ie(t){if(!Array.isArray(t)||t.length===0)throw Error("cdp: args must be a non-empty array");if(t[0]==="test")return t.map((e,n)=>ct(e,n));if(!re.has(t[0]))throw Error(`cdp: unknown subcommand '${t[0]}'`);return t.map((e,n)=>ct(e,n))}function ct(t,e){if(typeof t!=="string")throw Error(`cdp: argv[${e}] must be a string (got ${typeof t})`);if(t.includes("\x00"))throw Error(`cdp: argv[${e}] contains a null byte`);return t}function s(t,e=30000){return oe(t,null,e)}function oe(t,e=null,n=30000){let i=ie(t);return new Promise((r,o)=>{let l=Rt(Lt(),[ne,...i],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)l.stdin.write(e),l.stdin.end();let u="",a="";l.stdout.on("data",(c)=>u+=c),l.stderr.on("data",(c)=>a+=c);let f=setTimeout(()=>{l.kill(),o(Error(`cdp timeout: ${t[0]}`))},n);l.on("close",(c)=>{if(clearTimeout(f),c===0)r(u.trim());else o(Error(a.trim()||`cdp exit ${c}`))})})}function gt(t,e){let n=(l)=>String(l??"").replace(/\s+/g," ").trim(),i=n(t),r=n(e);if(!r)return!1;if(i.length<Math.ceil(r.length*0.8))return!1;let o=Math.min(40,r.length);return i.includes(r.slice(0,o))&&i.includes(r.slice(-o))}async function pt(t){if(t)return t;let e=(await s(["list"])).split(`
3
+ `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await s(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),i;try{i=JSON.parse(n)}catch(l){throw Error(`Target.createTarget returned invalid JSON: ${l.message}`)}let{targetId:r}=i;if(!r)throw Error("Target.createTarget did not return a targetId");await s(["list"]);let o=r.slice(0,8);try{await ht(o)}catch(l){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${l.message}
4
+ `)}return o}async function ht(t){await s(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
5
5
  (function() {
6
6
  // ── Runtime.enable / CDP detection masking ──────────────
7
7
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -286,7 +286,7 @@ import{randomInt as Yt}from"node:crypto";import{spawn as Gt}from"node:child_proc
286
286
  };
287
287
  } catch(_) {}
288
288
  })();
289
- `})])}var I={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function H(t){let e=t*0.2,n=Yt(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function pt(t,e,n=15000,i=500){let r=String.raw`
289
+ `})])}var tt={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function U(t){let e=t*0.2,n=Gt(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function bt(t,e,n=15000,i=500){let r=String.raw`
290
290
  new Promise((resolve) => {
291
291
  const _deadline = Date.now() + ${n};
292
292
  const _baseInterval = ${i};
@@ -305,32 +305,31 @@ import{randomInt as Yt}from"node:crypto";import{spawn as Gt}from"node:child_proc
305
305
 
306
306
  _poll();
307
307
  })
308
- `;return await f(["eval",t,r],n+5000)==="true"}async function ht(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((r)=>{let l="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(o)=>l+=o),process.stdin.on("end",()=>r(l.trim()))}),i=[...t];return i[e]=n,i}function bt(t){let e=t.includes("--short"),n=t.filter((u)=>u!=="--short"),i=n.indexOf("--tab"),r=i===-1?null:n[i+1];if(i!==-1)n=n.filter((u,a)=>a!==i&&a!==i+1);let l=n.indexOf("--locale"),o=l===-1?null:n[l+1];if(l!==-1)n=n.filter((u,a)=>a!==l&&a!==l+1);return{query:n.join(" "),tabPrefix:r,short:e,locale:o}}function wt(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function yt(t,e,n=300){if(!e||t.length<=n)return t;let i=t.slice(0,n),r=i.lastIndexOf(" ");return r>0?`${i.slice(0,r)}…`:`${i}…`}function vt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
309
- `)}function w(t,e,n=null){if(!t||typeof t!=="object")return;let i=n?` (+${Date.now()-n}ms)`:"";if(t.lastStage=e,!Array.isArray(t.stages))t.stages=[];t.stages.push({stage:e,at:Date.now()});let r=t.engine||"extractor";console.error(`[${r}] stage: ${e}${i}`)}function E({engine:t,mode:e="headless",clipboardEmpty:n=null,fallbackUsed:i=null,blockedBy:r=null,verificationResult:l=null,inputReady:o=null,durationMs:u=null,lastStage:a=null,stages:s=null}={}){return{engine:t,mode:e,clipboardEmpty:n,fallbackUsed:i,blockedBy:r,verificationResult:l,inputReady:o,durationMs:u,lastStage:a,stages:s}}function mt(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
308
+ `;return await s(["eval",t,r],n+5000)==="true"}async function yt(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((r)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(l)=>o+=l),process.stdin.on("end",()=>r(o.trim()))}),i=[...t];return i[e]=n,i}function wt(t){let e=t.includes("--short"),n=t.filter((u)=>u!=="--short"),i=n.indexOf("--tab"),r=i===-1?null:n[i+1];if(i!==-1)n=n.filter((u,a)=>a!==i&&a!==i+1);let o=n.indexOf("--locale"),l=o===-1?null:n[o+1];if(o!==-1)n=n.filter((u,a)=>a!==o&&a!==o+1);return{query:n.join(" "),tabPrefix:r,short:e,locale:l}}function mt(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function vt(t,e,n=300){if(!e||t.length<=n)return t;let i=t.slice(0,n),r=i.lastIndexOf(" ");return r>0?`${i.slice(0,r)}…`:`${i}…`}function xt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
309
+ `)}function b(t,e,n=null){if(!t||typeof t!=="object")return;let i=n?` (+${Date.now()-n}ms)`:"";if(t.lastStage=e,!Array.isArray(t.stages))t.stages=[];t.stages.push({stage:e,at:Date.now()});let r=t.engine||"extractor";console.error(`[${r}] stage: ${e}${i}`)}function et({engine:t,mode:e="headless",clipboardEmpty:n=null,fallbackUsed:i=null,blockedBy:r=null,verificationResult:o=null,inputReady:l=null,durationMs:u=null,lastStage:a=null,stages:f=null}={}){return{engine:t,mode:e,clipboardEmpty:n,fallbackUsed:i,blockedBy:r,verificationResult:o,inputReady:l,durationMs:u,lastStage:a,stages:f}}function _t(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
310
310
  `)}process.stderr.write(`Error: ${t.message}
311
- `),process.exit(1)}import{readFileSync as Oe}from"node:fs";import{tmpdir as De}from"node:os";import{spawn as Xe,execFileSync as lt,execSync as dn}from"node:child_process";import{basename as ie}from"node:path";function _t(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let i=ie(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}import{existsSync as At,readFileSync as ut,renameSync as Ze,unlinkSync as m,writeFileSync as Y}from"node:fs";import at from"node:http";import{platform as Ot}from"node:os";import{join as qe}from"node:path";import{existsSync as xt}from"node:fs";import{platform as oe}from"node:os";import{join as $}from"node:path";function h(t){let e=oe()==="win32",n=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:$(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:$(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:$(n,"System32","netstat.exe"),taskkill:$(n,"System32","taskkill.exe"),tasklist:$(n,"System32","tasklist.exe"),cmd:$(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},r=e?i.win32:i.unix,l=t.toLowerCase();if(r[l]&&xt(r[l]))return r[l];if(e&&l==="netstat"){let o=$(n,"Sysnative","netstat.exe");if(xt(o))return o}return t}import{execFileSync as le}from"node:child_process";import{platform as ue}from"node:os";function ae(t,e){return le(h(t),e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function fe(t){let e=String(t||"").match(/\b(\d+)\b/);return e?Number.parseInt(e[1],10):null}function se(t){return fe(t)}function ge(t,e){for(let n of String(t||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(n))continue;if(!n.trim().split(/\s+/).slice(0,6).some((l)=>l.endsWith(`:${e}`)))continue;let r=n.match(/\bpid=(\d+)\b/);if(r)return Number.parseInt(r[1],10)}return null}function ce(t,e){for(let n of String(t||"").split(/\r?\n/)){let i=n.trim().split(/\s+/);if(i.length<5||i[0].toUpperCase()!=="TCP")continue;if(!i.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!i[1].endsWith(`:${e}`))continue;let r=Number.parseInt(i.at(-1),10);if(Number.isInteger(r)&&r>0)return r}return null}function tt(t,e,n){try{return t(e,n)}catch{return null}}function $t(t,{platformName:e=ue(),run:n=ae}={}){if(e==="win32")return ce(tt(n,"netstat",["-ano","-p","TCP"]),t);let i=tt(n,"lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"]),r=se(i);if(r)return r;if(e!=="linux")return null;return ge(tt(n,"ss",["-ltnp"]),t)}import{existsSync as M,mkdirSync as pe,readFileSync as jt,writeFileSync as he}from"node:fs";import{homedir as be}from"node:os";import{join as kt}from"node:path";import{tmpdir as we}from"node:os";function ye(t,e=9222){let n=Number.parseInt(String(t??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:e}var ve=we().replaceAll("\\","/"),c=ye(process.env.GREEDY_SEARCH_PORT),p=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${ve}/greedysearch-chrome-profile`).replaceAll("\\","/"),Z=`${p}/DevToolsActivePort`,z=process.env.GREEDY_SEARCH_PID_FILE||`${p}/browser.pid`,me=process.env.CDP_PAGES_CACHE||`${p}/cdp-pages.json`,x=process.env.GREEDY_SEARCH_MODE_FILE||`${p}/browser-mode`,Jt=process.env.GREEDY_SEARCH_METADATA_FILE||`${p}/browser-metadata.json`,Nt=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${p}/browser-launch.lock`,U=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${p}/browser-last-activity`,_n=(process.env.CDP_SOCKET_DIR||`${p}/cdp-sockets`).replaceAll("\\","/"),xn=`${p}/visible-recovery.jsonl`,nt=kt(be(),".dm"),v=kt(nt,"greedyconfig"),rt=["perplexity","google","chatgpt","gemini"],it="gemini";function _e(){try{if(M(v)){let t=jt(v,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((r)=>et[r]),i=e.engines.filter((r)=>!et[r]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${v}: ${i.join(", ")}
312
- [greedysearch] Available engines: ${Object.keys(et).join(", ")}
313
- `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${v}, falling back to defaults: ${rt.join(", ")}
314
- `)}}}catch{}return rt}function xe(){try{if(!M(nt))pe(nt,{recursive:!0});if(!M(v))he(v,JSON.stringify({engines:rt,synthesizer:it},null,2)+`
315
- `,"utf8")}catch{}}xe();var Wt=["gemini","chatgpt"];function $e(){try{if(M(v)){let t=jt(v,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(Wt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${v}
316
- [greedysearch] Available synthesizers: ${Wt.join(", ")}
317
- [greedysearch] Falling back to default: ${it}
318
- `)}}}catch{}return it}var et={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=_e();var Wn=$e(),jn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{execFileSync as Xt,execSync as Zt}from"node:child_process";import{existsSync as A,mkdirSync as We,readFileSync as N,unlinkSync as j,writeFileSync as k}from"node:fs";import{platform as Vt}from"node:os";var O=Jt,W=Nt,je=15000,D=z,P=x,q=U;function B(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function ke(t){if(!B(t))return null;try{if(Vt()==="win32")return Xt(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Xt(h("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Je(t,e,n=c){if(!t)return!1;let i=(o)=>String(o||"").replaceAll("\\","/").toLowerCase(),r=i(t),l=i(e);return r.includes(l)&&r.includes(`--remote-debugging-port=${n}`)&&!r.includes("--type=")}function qt(t,e,n=c){return Je(ke(t),e,n)}function Ne(t=c){try{if(Vt()==="win32"){let n=Zt(`${h("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),i=new RegExp(String.raw`TCP\s+\S+:${t}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),r=n.match(i);return r?Number.parseInt(r[1],10):null}let e=Zt(`${h("lsof")} -i :${t} -t 2>/dev/null || ${h("ss")} -tlnp 2>/dev/null | ${h("grep")} :${t} | ${h("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
319
- `)[0],10):null}catch{return null}}function Q(){try{if(A(O)){let t=N(O,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{let t=A(D)?Number.parseInt(N(D,"utf8").trim(),10)||void 0:void 0,e=A(P)?N(P,"utf8").trim()==="visible"?"visible":"headless":"headless",n=A(q)?Number.parseInt(N(q,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:c,tempDir:p,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function T(t){try{k(O,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)k(D,String(t.browserPid),"utf8")}catch{}try{k(P,t.sessionMode,"utf8")}catch{}try{k(q,String(t.lastActivity),"utf8")}catch{}}function Bt(){try{j(O)}catch{}try{j(D)}catch{}try{j(P)}catch{}try{j(q)}catch{}}function ot(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>B(n)||n===process.pid))]};return T(e),e}function C(t){let e=Date.now();try{if(t)T({...t,lastActivity:e});else k(q,String(e),"utf8")}catch{}}var Bn=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Qt=!1;function dt(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(Qt)return;Qt=!0;let t=Q();if(!t)return;if(t.browserPid){if(!B(t.browserPid)){Bt();return}if(!qt(t.browserPid,t.tempDir,t.debugPort))Bt();else T({...t,clientPids:t.clientPids.filter((r)=>B(r))})}let e=Ne();if(e&&e!==t.browserPid)if(qt(e,p,c))T({browserPid:e,debugPort:c,tempDir:p,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${e} on port ${c}.
320
- `)}function Ht(){We(p,{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return k(W,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=N(W,"utf8");if(JSON.parse(e).pid===process.pid)j(W)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=N(W,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!B(e.pid)||n>je){try{j(W)}catch{}try{let r=JSON.stringify({pid:process.pid,ts:Date.now()});return k(W,r,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{j(W)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Be=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Mt=z,V=U,Qe=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Ve=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function de(t,e=c){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Dt(){try{let t=S(),e=t?Pt(t):null,n=de(e);if(n!==null){try{Y(x,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!At(x))return!0;return ut(x,"utf8").trim()==="headless"}catch{return!0}}function He(){try{Y(V,String(Date.now()),"utf8")}catch{}try{let t=Q();if(t)C(t)}catch{}}function Pt(t){try{if(Ot()==="win32")return lt(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return lt(h("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Me(t){let e=String(t||"").replaceAll("\\","/"),n=p.replaceAll("\\","/");return e.includes(`--remote-debugging-port=${c}`)&&e.includes(`--user-data-dir=${n}`)&&!e.includes("--type=")}function S(){return $t(c)}function G(){let t=S();return t&&Me(Pt(t))?t:null}async function ze(t=1500){let e=G();if(!e)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
321
- `),!1;try{let i=await new Promise((l,o)=>{let u=at.get(`http://localhost:${c}/json/version`,(a)=>{let s="";a.on("data",(g)=>s+=g),a.on("end",()=>{try{l(JSON.parse(s))}catch{o(Error("bad JSON"))}})});u.on("error",o),u.setTimeout(1000,()=>{u.destroy(),o(Error("timeout"))})}),r=new globalThis.WebSocket(i.webSocketDebuggerUrl);await new Promise((l)=>{r.onopen=()=>{if(G()!==e){r.close(),l();return}r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),l()},200)},r.onerror=()=>l(),setTimeout(l,1000)})}catch{}let n=Date.now()+t;while(Date.now()<n){let i=S();if(!i)return!0;if(i!==e)return!1;await new Promise((r)=>setTimeout(r,150))}return Ue(e)}function Ue(t=null){try{let e=G();if(!e||t&&e!==t)return!1;if(Ot()==="win32")lt(h("taskkill"),["/F","/PID",String(e)],{stdio:"ignore",windowsHide:!0});else process.kill(e,"SIGKILL");return!0}catch{return!1}}async function Tt(){if(!G()){if(S())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
322
- `);return!1}if(!await _(500)){try{m(Mt)}catch{}try{m(V)}catch{}try{m(x)}catch{}return!1}let e=await ze(1500);try{m(Mt)}catch{}try{m(V)}catch{}try{m(x)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${c}.
323
- `);return e}var zt=Tt;async function Ae(){let e=Dt()?Qe:Ve;if(e<=0)return!1;if(!At(V))return He(),!1;try{let n=Number.parseInt(ut(V,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Tt()}catch{}return!1}function _(t=3000){return new Promise((e)=>{let n=at.get(`http://localhost:${c}/json/version`,(i)=>{i.resume(),e(i.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function Ut(t=3000,e=200){let n=Date.now()+t;while(Date.now()<n){if(!await _(300))return!0;await new Promise((i)=>setTimeout(i,e))}return!await _(300)}async function K(){let t=`${Z}.lock`,e=`${Z}.tmp`,n=5000,i=1000,r=await new Promise((l)=>{let o=Date.now(),u=()=>{try{let a=JSON.stringify({pid:process.pid,ts:Date.now()});Y(t,a,{encoding:"utf8",flag:"wx"}),l(!0)}catch(a){if(a?.code!=="EEXIST"){if(Date.now()-o<1000)setTimeout(u,50);else l(!1);return}try{let s=ut(t,"utf8").trim(),g=s.startsWith("{")?JSON.parse(s):{ts:Number(s)},J=Number(g?.ts)||0;if(J>0&&Date.now()-J>5000)try{m(t)}catch{}if(Date.now()-o<1000)setTimeout(u,50);else l(!1)}catch{if(Date.now()-o<1000)setTimeout(u,50);else l(!1)}}};u()});try{let l=await new Promise((a,s)=>{let g=at.get(`http://localhost:${c}/json/version`,(J)=>{let X="";J.on("data",(F)=>X+=F),J.on("end",()=>a(X))});g.on("error",s),g.setTimeout(3000,()=>{g.destroy(),s(Error("timeout"))})}),{webSocketDebuggerUrl:o}=JSON.parse(l),u=new URL(o).pathname;if(r){Y(e,`${c}
324
- ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}async function Ct(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await _()){await K();try{let l=Q();if(l)C(l),ot(l)}catch{}return}dt();let t=await Ae(),e=t?!1:await _();if(!e&&!t)await new Promise((l)=>setTimeout(l,500)),e=await _();let n=!1;if(e){let l=Dt(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!l)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
325
- `),await zt(),await Ut(),n=!0;else if(o&&l)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
326
- `),await zt(),await Ut(),n=!0}if(n?!1:await _()){await K();try{let l=Q();if(l)C(l),ot(l)}catch{}return}let r=Ht();if(!r.acquired){let l=Date.now()+12000,o=!1;while(Date.now()<l){if(o=await _(500),o)break;await new Promise((u)=>setTimeout(u,250))}if(o){await K();return}}try{if(await _(1000)){await K();return}process.stderr.write(`GreedySearch Chrome not running on port ${c} — auto-launching...
327
- `);let o=[qe(Be,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((u,a)=>{Xe(_t(),o,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(g)=>g===0?u():a(Error("launch.mjs failed")))})}finally{r.release()}}var Pe="https://logically.app/research-assistant/",y={input:'div.ProseMirror[contenteditable="true"]',submitButton:'.chat-control button[class*="MuiButton-black"], button[type="submit"]',answerContainer:'#last-message .chat-content, [class*="chat-content"]',citationSpan:'#last-message .chat-content span[title], [class*="chat-content"] span[title]'};async function Te(t){return f(["eval",t,`(() => {
311
+ `),process.exit(1)}import{readFileSync as Ye}from"node:fs";import{tmpdir as Ke}from"node:os";import{spawn as de,execFileSync as at,execSync as Yn}from"node:child_process";import{basename as le}from"node:path";function $t(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let i=le(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}import{existsSync as Dt,readFileSync as st,renameSync as He,unlinkSync as v,writeFileSync as G}from"node:fs";import ft from"node:http";import{platform as Tt}from"node:os";import{existsSync as Wt}from"node:fs";import{platform as ue}from"node:os";import{join as W}from"node:path";function w(t){let e=ue()==="win32",n=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:W(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:W(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:W(n,"System32","netstat.exe"),taskkill:W(n,"System32","taskkill.exe"),tasklist:W(n,"System32","tasklist.exe"),cmd:W(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},r=e?i.win32:i.unix,o=t.toLowerCase();if(r[o]&&Wt(r[o]))return r[o];if(e&&o==="netstat"){let l=W(n,"Sysnative","netstat.exe");if(Wt(l))return l}return t}import{execFileSync as ae}from"node:child_process";import{platform as se}from"node:os";function fe(t,e){return ae(w(t),e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function ce(t){let e=String(t||"").match(/\b(\d+)\b/);return e?Number.parseInt(e[1],10):null}function ge(t){return ce(t)}function pe(t,e){for(let n of String(t||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(n))continue;if(!n.trim().split(/\s+/).slice(0,6).some((o)=>o.endsWith(`:${e}`)))continue;let r=n.match(/\bpid=(\d+)\b/);if(r)return Number.parseInt(r[1],10)}return null}function he(t,e){for(let n of String(t||"").split(/\r?\n/)){let i=n.trim().split(/\s+/);if(i.length<5||i[0].toUpperCase()!=="TCP")continue;if(!i.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!i[1].endsWith(`:${e}`))continue;let r=Number.parseInt(i.at(-1),10);if(Number.isInteger(r)&&r>0)return r}return null}function nt(t,e,n){try{return t(e,n)}catch{return null}}function M(t,{platformName:e=se(),run:n=fe}={}){if(e==="win32")return he(nt(n,"netstat",["-ano","-p","TCP"]),t);let i=nt(n,"lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"]),r=ge(i);if(r)return r;if(e!=="linux")return null;return pe(nt(n,"ss",["-ltnp"]),t)}import{existsSync as jt}from"node:fs";import{dirname as be,join as Z}from"node:path";import{fileURLToPath as ye}from"node:url";function kt(t){return ye(new URL(".",t)).replace(/^\/([A-Z]:)/,"$1")}function we(t,e=jt){let n=new Set;for(let i of t.filter(Boolean)){if(n.has(i))continue;if(n.add(i),e(i))return i}return t.filter(Boolean).at(-1)}function Jt({moduleDir:t,entrypoint:e=process.argv[1],env:n=process.env,exists:i=jt}={}){let r=e?be(e):null,o=n.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return we([t?Z(t,"..","..","bin","launch.mjs"):null,t?Z(t,"launch.mjs"):null,o?Z(o,"bin","launch.mjs"):null,r?Z(r,"launch.mjs"):null,r?Z(r,"..","bin","launch.mjs"):null],i)}import{existsSync as z,mkdirSync as me,readFileSync as Xt,writeFileSync as ve}from"node:fs";import{homedir as xe}from"node:os";import{join as Zt}from"node:path";import{tmpdir as _e}from"node:os";function $e(t,e=9222){let n=Number.parseInt(String(t??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:e}var We=_e().replaceAll("\\","/"),g=$e(process.env.GREEDY_SEARCH_PORT),p=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${We}/greedysearch-chrome-profile`).replaceAll("\\","/"),q=`${p}/DevToolsActivePort`,A=process.env.GREEDY_SEARCH_PID_FILE||`${p}/browser.pid`,je=process.env.CDP_PAGES_CACHE||`${p}/cdp-pages.json`,$=process.env.GREEDY_SEARCH_MODE_FILE||`${p}/browser-mode`,qt=process.env.GREEDY_SEARCH_METADATA_FILE||`${p}/browser-metadata.json`,Bt=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${p}/browser-launch.lock`,O=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${p}/browser-last-activity`,Zn=(process.env.CDP_SOCKET_DIR||`${p}/cdp-sockets`).replaceAll("\\","/"),qn=`${p}/visible-recovery.jsonl`,it=Zt(xe(),".dm"),m=Zt(it,"greedyconfig"),ot=["perplexity","google","chatgpt","gemini"],lt="gemini";function ke(){try{if(z(m)){let t=Xt(m,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((r)=>rt[r]),i=e.engines.filter((r)=>!rt[r]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${m}: ${i.join(", ")}
312
+ [greedysearch] Available engines: ${Object.keys(rt).join(", ")}
313
+ `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${m}, falling back to defaults: ${ot.join(", ")}
314
+ `)}}}catch{}return ot}function Je(){try{if(!z(it))me(it,{recursive:!0});if(!z(m))ve(m,JSON.stringify({engines:ot,synthesizer:lt},null,2)+`
315
+ `,"utf8")}catch{}}Je();var Nt=["gemini","chatgpt"];function Ne(){try{if(z(m)){let t=Xt(m,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(Nt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${m}
316
+ [greedysearch] Available synthesizers: ${Nt.join(", ")}
317
+ [greedysearch] Falling back to default: ${lt}
318
+ `)}}}catch{}return lt}var rt={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"},Bn=ke();var Qn=Ne(),Vn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{execFileSync as Qt,execSync as Un}from"node:child_process";import{existsSync as D,mkdirSync as Xe,readFileSync as N,unlinkSync as k,writeFileSync as J}from"node:fs";import{platform as Ze}from"node:os";var T=qt,j=Bt,qe=15000,P=A,C=$,B=O;function Q(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Be(t){if(!Q(t))return null;try{if(Ze()==="win32")return Qt(w("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Qt(w("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Qe(t,e,n=g){if(!t)return!1;let i=(l)=>String(l||"").replaceAll("\\","/").toLowerCase(),r=i(t),o=i(e);return r.includes(o)&&r.includes(`--remote-debugging-port=${n}`)&&!r.includes("--type=")}function Vt(t,e,n=g){return Qe(Be(t),e,n)}function Ve(t=g){return M(t)}function V(){try{if(D(T)){let t=N(T,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{let t=D(P)?Number.parseInt(N(P,"utf8").trim(),10)||void 0:void 0,e=D(C)?N(C,"utf8").trim()==="visible"?"visible":"headless":"headless",n=D(B)?Number.parseInt(N(B,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:g,tempDir:p,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function Y(t){try{J(T,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)J(P,String(t.browserPid),"utf8")}catch{}try{J(C,t.sessionMode,"utf8")}catch{}try{J(B,String(t.lastActivity),"utf8")}catch{}}function dt(){try{k(T)}catch{}try{k(P)}catch{}try{k(C)}catch{}try{k(B)}catch{}}function ut(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>Q(n)||n===process.pid))]};return Y(e),e}function K(t){let e=Date.now();try{if(t)Y({...t,lastActivity:e});else J(B,String(e),"utf8")}catch{}}var Tn=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ht=!1;function Ut(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(Ht)return;Ht=!0;let t=V();if(!t)return;if(t.browserPid){if(!Q(t.browserPid)){dt();return}if(!Vt(t.browserPid,t.tempDir,t.debugPort))dt();else Y({...t,clientPids:t.clientPids.filter((r)=>Q(r))})}let e=Ve();if(e&&e!==t.browserPid)if(Vt(e,p,g))Y({browserPid:e,debugPort:g,tempDir:p,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${e} on port ${g}.
319
+ `)}function Mt(){Xe(p,{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return J(j,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=N(j,"utf8");if(JSON.parse(e).pid===process.pid)k(j)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=N(j,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!Q(e.pid)||n>qe){try{k(j)}catch{}try{let r=JSON.stringify({pid:process.pid,ts:Date.now()});return J(j,r,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{k(j)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Ue=kt(import.meta.url),zt=A,d=O,Me=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,ze=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Ae(t,e=g){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Pt(){try{let t=F(),e=t?Ct(t):null,n=Ae(e);if(n!==null){try{G($,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!Dt($))return!0;return st($,"utf8").trim()==="headless"}catch{return!0}}function Oe(){try{G(d,String(Date.now()),"utf8")}catch{}try{let t=V();if(t)K(t)}catch{}}function Ct(t){try{if(Tt()==="win32")return at(w("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return at(w("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function De(t){let e=String(t||"").replaceAll("\\","/"),n=p.replaceAll("\\","/");return e.includes(`--remote-debugging-port=${g}`)&&e.includes(`--user-data-dir=${n}`)&&!e.includes("--type=")}function F(){return M(g)}function R(){let t=F();return t&&De(Ct(t))?t:null}async function Te(t=1500){let e=R();if(!e)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
320
+ `),!1;try{let i=await new Promise((o,l)=>{let u=ft.get(`http://localhost:${g}/json/version`,(a)=>{let f="";a.on("data",(c)=>f+=c),a.on("end",()=>{try{o(JSON.parse(f))}catch{l(Error("bad JSON"))}})});u.on("error",l),u.setTimeout(1000,()=>{u.destroy(),l(Error("timeout"))})}),r=new globalThis.WebSocket(i.webSocketDebuggerUrl);await new Promise((o)=>{r.onopen=()=>{if(R()!==e){r.close(),o();return}r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),o()},200)},r.onerror=()=>o(),setTimeout(o,1000)})}catch{}let n=Date.now()+t;while(Date.now()<n){let i=F();if(!i)return!0;if(i!==e)return!1;await new Promise((r)=>setTimeout(r,150))}return Pe(e)}function Pe(t=null){try{let e=R();if(!e||t&&e!==t)return!1;if(Tt()==="win32")at(w("taskkill"),["/F","/PID",String(e)],{stdio:"ignore",windowsHide:!0});else process.kill(e,"SIGKILL");return!0}catch{return!1}}async function Yt(){if(!R()){if(F())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
321
+ `);return!1}if(!await x(500)){try{v(zt)}catch{}try{v(d)}catch{}try{v($)}catch{}return!1}let e=await Te(1500);try{v(zt)}catch{}try{v(d)}catch{}try{v($)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${g}.
322
+ `);return e}var At=Yt;async function Ce(){let e=Pt()?Me:ze;if(e<=0)return!1;if(!Dt(d))return Oe(),!1;try{let n=Number.parseInt(st(d,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Yt()}catch{}return!1}function x(t=3000){return new Promise((e)=>{let n=ft.get(`http://localhost:${g}/json/version`,(i)=>{i.resume(),e(i.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function Ot(t=3000,e=200){let n=Date.now()+t;while(Date.now()<n){if(!await x(300))return!0;await new Promise((i)=>setTimeout(i,e))}return!await x(300)}async function S(){let t=`${q}.lock`,e=`${q}.tmp`,n=5000,i=1000,r=await new Promise((o)=>{let l=Date.now(),u=()=>{try{let a=JSON.stringify({pid:process.pid,ts:Date.now()});G(t,a,{encoding:"utf8",flag:"wx"}),o(!0)}catch(a){if(a?.code!=="EEXIST"){if(Date.now()-l<1000)setTimeout(u,50);else o(!1);return}try{let f=st(t,"utf8").trim(),c=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},_=Number(c?.ts)||0;if(_>0&&Date.now()-_>5000)try{v(t)}catch{}if(Date.now()-l<1000)setTimeout(u,50);else o(!1)}catch{if(Date.now()-l<1000)setTimeout(u,50);else o(!1)}}};u()});try{let o=await new Promise((a,f)=>{let c=ft.get(`http://localhost:${g}/json/version`,(_)=>{let X="";_.on("data",(L)=>X+=L),_.on("end",()=>a(X))});c.on("error",f),c.setTimeout(3000,()=>{c.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:l}=JSON.parse(o),u=new URL(l).pathname;if(r){G(e,`${g}
323
+ ${u}`,"utf8");try{v(q)}catch{}He(e,q)}}catch{}finally{if(r)try{v(t)}catch{}}}async function Kt(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await x()){await S();try{let o=V();if(o)K(o),ut(o)}catch{}return}Ut();let t=await Ce(),e=t?!1:await x();if(!e&&!t)await new Promise((o)=>setTimeout(o,500)),e=await x();let n=!1;if(e){let o=Pt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!o)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
+ `),await At(),await Ot(),n=!0;else if(l&&o)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
325
+ `),await At(),await Ot(),n=!0}if(n?!1:await x()){await S();try{let o=V();if(o)K(o),ut(o)}catch{}return}let r=Mt();if(!r.acquired){let o=Date.now()+12000,l=!1;while(Date.now()<o){if(l=await x(500),l)break;await new Promise((u)=>setTimeout(u,250))}if(l){await S();return}}try{if(await x(1000)){await S();return}process.stderr.write(`GreedySearch Chrome not running on port ${g} — auto-launching...
326
+ `);let u=[Jt({moduleDir:Ue,entrypoint:process.argv[1],env:process.env})];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")u.push("--headless");await new Promise((a,f)=>{de($t(),u,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(_)=>_===0?a():f(Error("launch.mjs failed")))})}finally{r.release()}}var Se="https://logically.app/research-assistant/",y={input:'div.ProseMirror[contenteditable="true"]',submitButton:'.chat-control button[class*="MuiButton-black"], button[type="submit"]',answerContainer:'#last-message .chat-content, [class*="chat-content"]',citationSpan:'#last-message .chat-content span[title], [class*="chat-content"] span[title]'};async function Ge(t){return s(["eval",t,`(() => {
328
327
  const buttons = Array.from(document.querySelectorAll('button'));
329
328
  const create = buttons.find((b) => (b.innerText || '').trim() === 'Create');
330
329
  if (!create) return 'missing';
331
330
  create.click();
332
331
  return 'clicked';
333
- })()`],5000).catch(()=>"error")}async function Ce(t){return await f(["eval",t,`(() => {
332
+ })()`],5000).catch(()=>"error")}async function Re(t){return await s(["eval",t,`(() => {
334
333
  const url = document.location.href || '';
335
334
  if (url.includes('/login') || url.includes('/signup') || url.includes('/sign-up')) return true;
336
335
  const modalText = Array.from(document.querySelectorAll('[role="dialog"], .MuiModal-root'))
@@ -338,7 +337,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
338
337
  .join('
339
338
  ');
340
339
  return /create a free account|continue with google|have an account[?] log in|log in|sign up/i.test(modalText);
341
- })()`],5000).catch(()=>"false")==="true"}async function Ke(t){try{await f(["list"]);let e=`${De().replaceAll("\\\\","/")}/cdp-pages.json`,i=JSON.parse(Oe(e,"utf8")).find((r)=>r.targetId?.startsWith(t))?.targetId;if(i)await f(["browse",t,"Target.activateTarget",JSON.stringify({targetId:i})]).catch(()=>null),await new Promise((r)=>setTimeout(r,250))}catch{}}async function Ye(t,e){await Ke(t);let n=await f(["eval",t,`(() => {
340
+ })()`],5000).catch(()=>"false")==="true"}async function Fe(t){try{await s(["list"]);let e=`${Ke().replaceAll("\\\\","/")}/cdp-pages.json`,i=JSON.parse(Ye(e,"utf8")).find((r)=>r.targetId?.startsWith(t))?.targetId;if(i)await s(["browse",t,"Target.activateTarget",JSON.stringify({targetId:i})]).catch(()=>null),await new Promise((r)=>setTimeout(r,250))}catch{}}async function Le(t,e){await Fe(t);let n=await s(["eval",t,`(() => {
342
341
  const inputs = Array.from(document.querySelectorAll('${y.input}'));
343
342
  const input = inputs.find((el) => {
344
343
  const r = el.getBoundingClientRect();
@@ -348,7 +347,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
348
347
  input.scrollIntoView({ block: 'center', inline: 'center' });
349
348
  const r = input.getBoundingClientRect();
350
349
  return JSON.stringify({ x: Math.round(r.left + Math.min(80, r.width / 2)), y: Math.round(r.top + r.height / 2) });
351
- })()`]);if(!n)throw Error("Logically visible input not found");let i;try{i=JSON.parse(n)}catch{throw Error("Logically input coordinates were invalid")}await f(["click",t,y.input]).catch(()=>null),await new Promise((a)=>setTimeout(a,H(120))),await f(["clickxy",t,String(i.x),String(i.y)]),await new Promise((a)=>setTimeout(a,H(I.postClick)));let r=async()=>{let a=await f(["eval",t,`(() => {
350
+ })()`]);if(!n)throw Error("Logically visible input not found");let i;try{i=JSON.parse(n)}catch{throw Error("Logically input coordinates were invalid")}await s(["click",t,y.input]).catch(()=>null),await new Promise((a)=>setTimeout(a,U(120))),await s(["clickxy",t,String(i.x),String(i.y)]),await new Promise((a)=>setTimeout(a,U(tt.postClick)));let r=async()=>{let a=await s(["eval",t,`(() => {
352
351
  const ed = document.querySelector('${y.input}');
353
352
  if (!ed) return 'no-input';
354
353
  ed.focus();
@@ -359,7 +358,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
359
358
  }
360
359
  const ok = ed.editor.commands.insertContent(${JSON.stringify(e)});
361
360
  return ok ? 'ok' : 'tiptap-failed';
362
- })()`],5000);if(a!=="ok")throw Error(`Logically type failed: ${a}`);await new Promise((s)=>setTimeout(s,H(I.postType)))},l=async()=>{let a=await f(["eval",t,`JSON.stringify(Array.from(document.querySelectorAll('${y.input}')).map((el) => el.innerText || el.textContent || ''))`]);try{return JSON.parse(a)}catch{return[]}},o=async()=>{return(await l()).some((s)=>st(s,e))},u=async()=>{await f(["eval",t,`(() => {
361
+ })()`],5000);if(a!=="ok")throw Error(`Logically type failed: ${a}`);await new Promise((f)=>setTimeout(f,U(tt.postType)))},o=async()=>{let a=await s(["eval",t,`JSON.stringify(Array.from(document.querySelectorAll('${y.input}')).map((el) => el.innerText || el.textContent || ''))`]);try{return JSON.parse(a)}catch{return[]}},l=async()=>{return(await o()).some((f)=>gt(f,e))},u=async()=>{await s(["eval",t,`(() => {
363
362
  const ed = document.querySelector('${y.input}');
364
363
  if (!ed) return false;
365
364
  ed.focus();
@@ -374,7 +373,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
374
373
  selection.addRange(range);
375
374
  document.execCommand('delete');
376
375
  return true;
377
- })()`])};if(await r(),await o())return;if(await u(),await r(),!await o())throw Error("Logically input did not accept text — input verification failed")}async function Ge(t,e=90000){let n=String.raw`
376
+ })()`])};if(await r(),await l())return;if(await u(),await r(),!await l())throw Error("Logically input did not accept text — input verification failed")}async function Ie(t,e=90000){let n=String.raw`
378
377
  new Promise((resolve, reject) => {
379
378
  const deadline = Date.now() + ${e};
380
379
  let last = '';
@@ -395,7 +394,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
395
394
  } catch (e) { reject(e); }
396
395
  }
397
396
  poll();
398
- })`;return f(["eval",t,n],e+1e4)}async function Se(t){let e=`(() => {
397
+ })`;return s(["eval",t,n],e+1e4)}async function Ee(t){let e=`(() => {
399
398
  const el = document.querySelector('${y.answerContainer}');
400
399
  if (!el) return JSON.stringify({ answer: '', answerHtml: '' });
401
400
  const clone = el.cloneNode(true);
@@ -407,7 +406,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
407
406
  answer: (el.innerText || '').trim(),
408
407
  answerHtml: clone.innerHTML,
409
408
  });
410
- })()`;try{return JSON.parse(await f(["eval",t,e],1e4))}catch{return{answer:"",answerHtml:""}}}async function Fe(t){let e=String.raw`
409
+ })()`;try{return JSON.parse(await s(["eval",t,e],1e4))}catch{return{answer:"",answerHtml:""}}}async function tn(t){let e=String.raw`
411
410
  (async () => {
412
411
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
413
412
 
@@ -547,7 +546,7 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
547
546
  webCaptured: webSources.length,
548
547
  },
549
548
  });
550
- })()`,n=await f(["eval",t,e],20000);try{return JSON.parse(n)}catch{return{sources:[],summary:{expectedTotal:0,reason:"invalid-json"}}}}async function Re(t){let e=String.raw`
549
+ })()`,n=await s(["eval",t,e],20000);try{return JSON.parse(n)}catch{return{sources:[],summary:{expectedTotal:0,reason:"invalid-json"}}}}async function en(t){let e=String.raw`
551
550
  (async () => {
552
551
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
553
552
  const answer = document.querySelector('${y.answerContainer}');
@@ -651,8 +650,8 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
651
650
  }
652
651
  }
653
652
  return JSON.stringify(sources);
654
- })()`,n=await f(["eval",t,e],45000);try{return JSON.parse(n)}catch{return[]}}var Le=`Usage: node extractors/logically.mjs "<query>" [--tab <prefix>]
655
- `;async function Ie(){let t=await ht(process.argv.slice(2));wt(t,Le);let{query:e,tabPrefix:n,short:i}=bt(t),r=Date.now(),o={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 Ct(),!n)await f(["list"]);let u=await gt(n),a=await f(["eval",u,"document.location.href"]).catch(()=>""),s=!1;try{let b=new URL(a).hostname.toLowerCase();s=b==="logically.app"||b.endsWith(".logically.app")}catch{}if(!s)w(o,"nav",r),await f(["nav",u,Pe],25000),await new Promise((b)=>setTimeout(b,900));w(o,"new-chat",r),await Te(u),await new Promise((b)=>setTimeout(b,700)),w(o,"input-wait",r);let g=await pt(u,y.input,20000,400);if(o.inputReady=g,!g)throw Error("Logically input not found — page may not have loaded or is in unexpected state");if(process.env.GREEDY_SEARCH_HEADLESS==="1"){let b=await f(["eval",u,`(() => {
653
+ })()`,n=await s(["eval",t,e],45000);try{return JSON.parse(n)}catch{return[]}}var nn=`Usage: node extractors/logically.mjs "<query>" [--tab <prefix>]
654
+ `;async function rn(){let t=await yt(process.argv.slice(2));mt(t,nn);let{query:e,tabPrefix:n,short:i}=wt(t),r=Date.now(),l={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 Kt(),!n)await s(["list"]);let u=await pt(n),a=await s(["eval",u,"document.location.href"]).catch(()=>""),f=!1;try{let h=new URL(a).hostname.toLowerCase();f=h==="logically.app"||h.endsWith(".logically.app")}catch{}if(!f)b(l,"nav",r),await s(["nav",u,Se],25000),await new Promise((h)=>setTimeout(h,900));b(l,"new-chat",r),await Ge(u),await new Promise((h)=>setTimeout(h,700)),b(l,"input-wait",r);let c=await bt(u,y.input,20000,400);if(l.inputReady=c,!c)throw Error("Logically input not found — page may not have loaded or is in unexpected state");if(process.env.GREEDY_SEARCH_HEADLESS==="1"){let h=await s(["eval",u,`(() => {
656
655
  const text = document.body?.innerText || '';
657
656
  const m = text.match(/Chat messages\\s*\\n?\\s*(\\d+)\\s*\\/\\s*(\\d+)/i);
658
657
  if (m && parseInt(m[1], 10) >= parseInt(m[2], 10)) {
@@ -664,4 +663,4 @@ ${u}`,"utf8");try{m(Z)}catch{}Ze(e,Z)}}catch{}finally{if(r)try{m(t)}catch{}}}asy
664
663
  );
665
664
  if (createBtn && createBtn.disabled) return 'create-disabled';
666
665
  return 'ok';
667
- })()`],5000).catch(()=>"ok");if(b==="quota-exceeded"||b==="create-disabled")throw console.error("[logically] Rate Limited — skipping (visible retry won't help)"),o.blockedBy="rate-limit",Error("Rate Limited — Logically free message quota exhausted. Wait until reset.")}if(w(o,"type-and-submit",r),await Ye(u,e),await f(["eval",u,`(() => { const btn = document.querySelector('${y.submitButton}'); if (!btn) return 'missing'; btn.click(); return 'clicked'; })()`])!=="clicked")throw Error("Logically submit button not found");if(await new Promise((b)=>setTimeout(b,1500)),await Ce(u))throw o.blockedBy="signin",o.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.");w(o,"answer-wait",r),await Ge(u,90000),w(o,"extract-answer-html",r);let{answer:X,answerHtml:F}=await Se(u);if(!X)throw Error("No answer extracted — Logically may not have responded");w(o,"extract-full-citations",r);let d=await Fe(u),R=[],L=d.sources?.length?d.sources:null;if(!L)w(o,"extract-inline-citations",r),R=await Re(u),L=R;let Kt=await f(["eval",u,"document.location.href"]).catch(()=>"");o.durationMs=Date.now()-r,o.sourcePath=d.sources?.length?"citations-popover":"inline-citation-popovers",w(o,"done",r),vt({query:e,url:Kt,answer:yt(X,i),answerHtml:F,sources:L,inlineSources:R,citationSummary:d.summary,_envelope:E(o)})}catch(u){o.durationMs=Date.now()-r,mt(u,E(o))}}Ie();
666
+ })()`],5000).catch(()=>"ok");if(h==="quota-exceeded"||h==="create-disabled")throw console.error("[logically] Rate Limited — skipping (visible retry won't help)"),l.blockedBy="rate-limit",Error("Rate Limited — Logically free message quota exhausted. Wait until reset.")}if(b(l,"type-and-submit",r),await Le(u,e),await s(["eval",u,`(() => { const btn = document.querySelector('${y.submitButton}'); if (!btn) return 'missing'; btn.click(); return 'clicked'; })()`])!=="clicked")throw Error("Logically submit button not found");if(await new Promise((h)=>setTimeout(h,1500)),await Re(u))throw l.blockedBy="signin",l.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.");b(l,"answer-wait",r),await Ie(u,90000),b(l,"extract-answer-html",r);let{answer:X,answerHtml:L}=await Ee(u);if(!X)throw Error("No answer extracted — Logically may not have responded");b(l,"extract-full-citations",r);let H=await tn(u),I=[],E=H.sources?.length?H.sources:null;if(!E)b(l,"extract-inline-citations",r),I=await en(u),E=I;let St=await s(["eval",u,"document.location.href"]).catch(()=>"");l.durationMs=Date.now()-r,l.sourcePath=H.sources?.length?"citations-popover":"inline-citation-popovers",b(l,"done",r),xt({query:e,url:St,answer:vt(X,i),answerHtml:L,sources:E,inlineSources:I,citationSummary:H.summary,_envelope:et(l)})}catch(u){l.durationMs=Date.now()-r,_t(u,et(l))}}rn();
@@ -1,10 +1,9 @@
1
- import{execFileSync as p,execSync as C}from"node:child_process";import{existsSync as w,mkdirSync as Xq,readFileSync as g,unlinkSync as j,writeFileSync as b}from"node:fs";import{platform as S}from"node:os";import{existsSync as x,mkdirSync as E,readFileSync as P,writeFileSync as i}from"node:fs";import{homedir as r}from"node:os";import{join as F}from"node:path";import{tmpdir as d}from"node:os";function t(q,J=9222){let Q=Number.parseInt(String(q??""),10);return Number.isInteger(Q)&&Q>1024&&Q<65535?Q:J}var a=d().replaceAll("\\","/"),Z=t(process.env.GREEDY_SEARCH_PORT),W=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${a}/greedysearch-chrome-profile`).replaceAll("\\","/"),Hq=`${W}/DevToolsActivePort`,R=process.env.GREEDY_SEARCH_PID_FILE||`${W}/browser.pid`,kq=process.env.CDP_PAGES_CACHE||`${W}/cdp-pages.json`,L=process.env.GREEDY_SEARCH_MODE_FILE||`${W}/browser-mode`,l=process.env.GREEDY_SEARCH_METADATA_FILE||`${W}/browser-metadata.json`,c=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${W}/browser-launch.lock`,I=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${W}/browser-last-activity`,gq=(process.env.CDP_SOCKET_DIR||`${W}/cdp-sockets`).replaceAll("\\","/"),Uq=`${W}/visible-recovery.jsonl`,T=F(r(),".dm"),V=F(T,"greedyconfig"),O=["perplexity","google","chatgpt","gemini"],G="gemini";function e(){try{if(x(V)){let q=P(V,"utf8"),J=JSON.parse(q);if(Array.isArray(J.engines)&&J.engines.length>0&&J.engines.every((Q)=>typeof Q==="string")){let Q=J.engines.filter(($)=>Y[$]),X=J.engines.filter(($)=>!Y[$]);if(X.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${V}: ${X.join(", ")}
2
- [greedysearch] Available engines: ${Object.keys(Y).join(", ")}
3
- `);if(Q.length>0)return Q;process.stderr.write(`[greedysearch] Warning: no valid engines in ${V}, falling back to defaults: ${O.join(", ")}
4
- `)}}}catch{}return O}function qq(){try{if(!x(T))E(T,{recursive:!0});if(!x(V))i(V,JSON.stringify({engines:O,synthesizer:G},null,2)+`
5
- `,"utf8")}catch{}}qq();var D=["gemini","chatgpt"];function Jq(){try{if(x(V)){let q=P(V,"utf8"),J=JSON.parse(q);if(typeof J.synthesizer==="string"){let Q=J.synthesizer.toLowerCase();if(D.includes(Q))return Q;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${J.synthesizer}" in ${V}
6
- [greedysearch] Available synthesizers: ${D.join(", ")}
7
- [greedysearch] Falling back to default: ${G}
8
- `)}}}catch{}return G}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"},vq=e();var hq=Jq(),Mq=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=W;import{existsSync as _}from"node:fs";import{platform as Qq}from"node:os";import{join as z}from"node:path";function B(q){let J=Qq()==="win32",Q=process.env.SystemRoot||"C:\\Windows",X={win32:{powershell:z(Q,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:z(Q,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:z(Q,"System32","netstat.exe"),taskkill:z(Q,"System32","taskkill.exe"),tasklist:z(Q,"System32","tasklist.exe"),cmd:z(Q,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},$=J?X.win32:X.unix,k=q.toLowerCase();if($[k]&&_($[k]))return $[k];if(J&&k==="netstat"){let M=z(Q,"Sysnative","netstat.exe");if(_(M))return M}return q}var f=l,K=c,$q=15000,N=R,u=L,v=I;function H(q){if(!Number.isInteger(q)||q<=0)return!1;try{return process.kill(q,0),!0}catch{return!1}}function Wq(q){if(!H(q))return null;try{if(S()==="win32")return p(B("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${q}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return p(B("ps"),["-p",String(q),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Zq(q,J,Q=Z){if(!q)return!1;let X=(M)=>String(M||"").replaceAll("\\","/").toLowerCase(),$=X(q),k=X(J);return $.includes(k)&&$.includes(`--remote-debugging-port=${Q}`)&&!$.includes("--type=")}function U(q,J,Q=Z){return Zq(Wq(q),J,Q)}function y(q=Z){try{if(S()==="win32"){let Q=C(`${B("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),X=new RegExp(String.raw`TCP\s+\S+:${q}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),$=Q.match(X);return $?Number.parseInt($[1],10):null}let J=C(`${B("lsof")} -i :${q} -t 2>/dev/null || ${B("ss")} -tlnp 2>/dev/null | ${B("grep")} :${q} | ${B("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return J?Number.parseInt(J.split(`
9
- `)[0],10):null}catch{return null}}function Vq(q,J=null,Q=null){if(J&&!U(q,J,Q))return!1;try{if(S()==="win32")C(`${B("taskkill")} /F /T /PID ${q}`,{stdio:"ignore"});else{try{process.kill(-q,"SIGKILL")}catch{}try{process.kill(q,"SIGKILL")}catch{}}return!0}catch{return!1}}function o(){try{if(w(f)){let q=g(f,"utf8"),J=JSON.parse(q);if(J&&typeof J.tempDir==="string"&&typeof J.debugPort==="number")return{browserPid:Number.isInteger(J.browserPid)?J.browserPid:void 0,debugPort:J.debugPort,tempDir:J.tempDir,clientPids:Array.isArray(J.clientPids)?J.clientPids.filter((Q)=>Number.isInteger(Q)&&Q>0):[],sessionMode:J.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(J.lastActivity)?J.lastActivity:0,launchedAt:Number.isFinite(J.launchedAt)?J.launchedAt:0}}}catch{}try{let q=w(N)?Number.parseInt(g(N,"utf8").trim(),10)||void 0:void 0,J=w(u)?g(u,"utf8").trim()==="visible"?"visible":"headless":"headless",Q=w(v)?Number.parseInt(g(v,"utf8").trim(),10)||0:0;return{browserPid:q,debugPort:Z,tempDir:W,clientPids:q?[q]:[],sessionMode:J,lastActivity:Q,launchedAt:0}}catch{return null}}function h(q){try{b(f,JSON.stringify({browserPid:q.browserPid,debugPort:q.debugPort,tempDir:q.tempDir,clientPids:[...new Set(q.clientPids.filter((J)=>J>0))],sessionMode:q.sessionMode,lastActivity:q.lastActivity,launchedAt:q.launchedAt},null,2),"utf8")}catch{}try{if(q.browserPid)b(N,String(q.browserPid),"utf8")}catch{}try{b(u,q.sessionMode,"utf8")}catch{}try{b(v,String(q.lastActivity),"utf8")}catch{}}function A(){try{j(f)}catch{}try{j(N)}catch{}try{j(u)}catch{}try{j(v)}catch{}}function Cq(q){if(!q)return q;let J={...q,clientPids:[...new Set([...q.clientPids,process.pid].filter((Q)=>H(Q)||Q===process.pid))]};return h(J),J}function yq(q){if(!q)return q;let J={...q,clientPids:q.clientPids.filter((Q)=>Q!==process.pid).filter((Q)=>H(Q))};return h(J),J}function Sq(q){let J=Date.now();try{if(q)h({...q,lastActivity:J});else b(v,String(J),"utf8")}catch{}}var m=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;function Dq(q){if(m<=0)return!1;if(!q||!q.lastActivity)return!1;return(Date.now()-q.lastActivity)/60000>=m}var n=!1;function Bq(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(n)return;n=!0;let q=o();if(!q)return;if(q.browserPid){if(!H(q.browserPid)){A();return}if(!U(q.browserPid,q.tempDir,q.debugPort))A();else h({...q,clientPids:q.clientPids.filter(($)=>H($))})}let J=y();if(J&&J!==q.browserPid)if(U(J,W,Z))h({browserPid:J,debugPort:Z,tempDir:W,clientPids:[J],sessionMode:q.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${J} on port ${Z}.
10
- `)}function Pq(){Xq(W,{recursive:!0});try{let q=JSON.stringify({pid:process.pid,ts:Date.now()});return b(K,q,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let J=g(K,"utf8");if(JSON.parse(J).pid===process.pid)j(K)}catch{}}}}catch(q){if(q?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let q=g(K,"utf8"),J=JSON.parse(q),Q=Date.now()-(J.ts||0);if(!H(J.pid)||Q>$q){try{j(K)}catch{}try{let $=JSON.stringify({pid:process.pid,ts:Date.now()});return b(K,$,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{j(K)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}function s(){let q=o();if(!q||!q.browserPid){let X=y();if(X&&U(X,W,Z))return{running:!0,pid:X,metadata:q};return{running:!1,pid:null,metadata:null}}if(!H(q.browserPid))return{running:!1,pid:null,metadata:q};if(!U(q.browserPid,q.tempDir,q.debugPort)){let X=y();if(X&&U(X,W,Z))return{running:!0,pid:X,metadata:q};return{running:!1,pid:null,metadata:q}}return{running:!0,pid:q.browserPid,metadata:q}}function Fq(){let{running:q,pid:J,metadata:Q}=s();if(!q||!J)return A(),!1;let X=Vq(J,Q?.tempDir||W,Q?.debugPort||Z);return A(),X}async function Rq(){return Bq(),s()}export{h as writeMetadata,U as verifyBrowserProcess,yq as unregisterClient,Sq as touchActivity,Cq as registerClient,o as readMetadata,Fq as killChrome,Dq as isIdleExpired,Rq as ensureCleanSession,Zq as commandLineMatchesGreedyChrome,A as clearMetadata,Bq as cleanupStaleSessions,s as checkRunning,Pq as acquireLaunchLock,f as METADATA_FILE};
1
+ import{execFileSync as o,execSync as f0}from"node:child_process";import{existsSync as x,mkdirSync as z0,readFileSync as g,unlinkSync as f,writeFileSync as z}from"node:fs";import{platform as s}from"node:os";import{existsSync as h,mkdirSync as r,readFileSync as l,writeFileSync as E}from"node:fs";import{homedir as d}from"node:os";import{join as n}from"node:path";import{tmpdir as t}from"node:os";function e($,Q=9222){let W=Number.parseInt(String($??""),10);return Number.isInteger(W)&&W>1024&&W<65535?W:Q}var a=t().replaceAll("\\","/"),X=e(process.env.GREEDY_SEARCH_PORT),J=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${a}/greedysearch-chrome-profile`).replaceAll("\\","/"),M0=`${J}/DevToolsActivePort`,P=process.env.GREEDY_SEARCH_PID_FILE||`${J}/browser.pid`,N0=process.env.CDP_PAGES_CACHE||`${J}/cdp-pages.json`,c=process.env.GREEDY_SEARCH_MODE_FILE||`${J}/browser-mode`,D=process.env.GREEDY_SEARCH_METADATA_FILE||`${J}/browser-metadata.json`,F=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${J}/browser-launch.lock`,R=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${J}/browser-last-activity`,w0=(process.env.CDP_SOCKET_DIR||`${J}/cdp-sockets`).replaceAll("\\","/"),T0=`${J}/visible-recovery.jsonl`,C=n(d(),".dm"),b=n(C,"greedyconfig"),Y=["perplexity","google","chatgpt","gemini"],O="gemini";function $0(){try{if(h(b)){let $=l(b,"utf8"),Q=JSON.parse($);if(Array.isArray(Q.engines)&&Q.engines.length>0&&Q.engines.every((W)=>typeof W==="string")){let W=Q.engines.filter((u)=>A[u]),q=Q.engines.filter((u)=>!A[u]);if(q.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${b}: ${q.join(", ")}
2
+ [greedysearch] Available engines: ${Object.keys(A).join(", ")}
3
+ `);if(W.length>0)return W;process.stderr.write(`[greedysearch] Warning: no valid engines in ${b}, falling back to defaults: ${Y.join(", ")}
4
+ `)}}}catch{}return Y}function Q0(){try{if(!h(C))r(C,{recursive:!0});if(!h(b))E(b,JSON.stringify({engines:Y,synthesizer:O},null,2)+`
5
+ `,"utf8")}catch{}}Q0();var G=["gemini","chatgpt"];function W0(){try{if(h(b)){let $=l(b,"utf8"),Q=JSON.parse($);if(typeof Q.synthesizer==="string"){let W=Q.synthesizer.toLowerCase();if(G.includes(W))return W;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${Q.synthesizer}" in ${b}
6
+ [greedysearch] Available synthesizers: ${G.join(", ")}
7
+ [greedysearch] Falling back to default: ${O}
8
+ `)}}}catch{}return O}var A={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"},A0=$0();var C0=W0(),Y0=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=J;import{existsSync as L}from"node:fs";import{platform as q0}from"node:os";import{join as V}from"node:path";function j($){let Q=q0()==="win32",W=process.env.SystemRoot||"C:\\Windows",q={win32:{powershell:V(W,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:V(W,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:V(W,"System32","netstat.exe"),taskkill:V(W,"System32","taskkill.exe"),tasklist:V(W,"System32","tasklist.exe"),cmd:V(W,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},u=Q?q.win32:q.unix,Z=$.toLowerCase();if(u[Z]&&L(u[Z]))return u[Z];if(Q&&Z==="netstat"){let U=V(W,"Sysnative","netstat.exe");if(L(U))return U}return $}import{execFileSync as u0}from"node:child_process";import{platform as J0}from"node:os";function X0($,Q){return u0(j($),Q,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function b0($){let Q=String($||"").match(/\b(\d+)\b/);return Q?Number.parseInt(Q[1],10):null}function Z0($){return b0($)}function V0($,Q){for(let W of String($||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(W))continue;if(!W.trim().split(/\s+/).slice(0,6).some((Z)=>Z.endsWith(`:${Q}`)))continue;let u=W.match(/\bpid=(\d+)\b/);if(u)return Number.parseInt(u[1],10)}return null}function B0($,Q){for(let W of String($||"").split(/\r?\n/)){let q=W.trim().split(/\s+/);if(q.length<5||q[0].toUpperCase()!=="TCP")continue;if(!q.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!q[1].endsWith(`:${Q}`))continue;let u=Number.parseInt(q.at(-1),10);if(Number.isInteger(u)&&u>0)return u}return null}function y($,Q,W){try{return $(Q,W)}catch{return null}}function p($,{platformName:Q=J0(),run:W=X0}={}){if(Q==="win32")return B0(y(W,"netstat",["-ano","-p","TCP"]),$);let q=y(W,"lsof",["-nP",`-iTCP:${$}`,"-sTCP:LISTEN","-t"]),u=Z0(q);if(u)return u;if(Q!=="linux")return null;return V0(y(W,"ss",["-ltnp"]),$)}var M=D,B=F,K0=15000,N=P,w=c,k=R;function K($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function j0($){if(!K($))return null;try{if(s()==="win32")return o(j("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return o(j("ps"),["-p",String($),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function g0($,Q,W=X){if(!$)return!1;let q=(U)=>String(U||"").replaceAll("\\","/").toLowerCase(),u=q($),Z=q(Q);return u.includes(Z)&&u.includes(`--remote-debugging-port=${W}`)&&!u.includes("--type=")}function H($,Q,W=X){return g0(j0($),Q,W)}function S($=X){return p($)}function H0($,Q=null,W=null){if(Q&&!H($,Q,W))return!1;try{if(s()==="win32")f0(`${j("taskkill")} /F /T /PID ${$}`,{stdio:"ignore"});else{try{process.kill(-$,"SIGKILL")}catch{}try{process.kill($,"SIGKILL")}catch{}}return!0}catch{return!1}}function _(){try{if(x(M)){let $=g(M,"utf8"),Q=JSON.parse($);if(Q&&typeof Q.tempDir==="string"&&typeof Q.debugPort==="number")return{browserPid:Number.isInteger(Q.browserPid)?Q.browserPid:void 0,debugPort:Q.debugPort,tempDir:Q.tempDir,clientPids:Array.isArray(Q.clientPids)?Q.clientPids.filter((W)=>Number.isInteger(W)&&W>0):[],sessionMode:Q.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(Q.lastActivity)?Q.lastActivity:0,launchedAt:Number.isFinite(Q.launchedAt)?Q.launchedAt:0}}}catch{}try{let $=x(N)?Number.parseInt(g(N,"utf8").trim(),10)||void 0:void 0,Q=x(w)?g(w,"utf8").trim()==="visible"?"visible":"headless":"headless",W=x(k)?Number.parseInt(g(k,"utf8").trim(),10)||0:0;return{browserPid:$,debugPort:X,tempDir:J,clientPids:$?[$]:[],sessionMode:Q,lastActivity:W,launchedAt:0}}catch{return null}}function v($){try{z(M,JSON.stringify({browserPid:$.browserPid,debugPort:$.debugPort,tempDir:$.tempDir,clientPids:[...new Set($.clientPids.filter((Q)=>Q>0))],sessionMode:$.sessionMode,lastActivity:$.lastActivity,launchedAt:$.launchedAt},null,2),"utf8")}catch{}try{if($.browserPid)z(N,String($.browserPid),"utf8")}catch{}try{z(w,$.sessionMode,"utf8")}catch{}try{z(k,String($.lastActivity),"utf8")}catch{}}function T(){try{f(M)}catch{}try{f(N)}catch{}try{f(w)}catch{}try{f(k)}catch{}}function m0($){if(!$)return $;let Q={...$,clientPids:[...new Set([...$.clientPids,process.pid].filter((W)=>K(W)||W===process.pid))]};return v(Q),Q}function s0($){if(!$)return $;let Q={...$,clientPids:$.clientPids.filter((W)=>W!==process.pid).filter((W)=>K(W))};return v(Q),Q}function _0($){let Q=Date.now();try{if($)v({...$,lastActivity:Q});else z(k,String(Q),"utf8")}catch{}}var I=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;function i0($){if(I<=0)return!1;if(!$||!$.lastActivity)return!1;return(Date.now()-$.lastActivity)/60000>=I}var m=!1;function k0(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(m)return;m=!0;let $=_();if(!$)return;if($.browserPid){if(!K($.browserPid)){T();return}if(!H($.browserPid,$.tempDir,$.debugPort))T();else v({...$,clientPids:$.clientPids.filter((u)=>K(u))})}let Q=S();if(Q&&Q!==$.browserPid)if(H(Q,J,X))v({browserPid:Q,debugPort:X,tempDir:J,clientPids:[Q],sessionMode:$.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${Q} on port ${X}.
9
+ `)}function r0(){z0(J,{recursive:!0});try{let $=JSON.stringify({pid:process.pid,ts:Date.now()});return z(B,$,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let Q=g(B,"utf8");if(JSON.parse(Q).pid===process.pid)f(B)}catch{}}}}catch($){if($?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let $=g(B,"utf8"),Q=JSON.parse($),W=Date.now()-(Q.ts||0);if(!K(Q.pid)||W>K0){try{f(B)}catch{}try{let u=JSON.stringify({pid:process.pid,ts:Date.now()});return z(B,u,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{f(B)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}function i(){let $=_();if(!$||!$.browserPid){let q=S();if(q&&H(q,J,X))return{running:!0,pid:q,metadata:$};return{running:!1,pid:null,metadata:null}}if(!K($.browserPid))return{running:!1,pid:null,metadata:$};if(!H($.browserPid,$.tempDir,$.debugPort)){let q=S();if(q&&H(q,J,X))return{running:!0,pid:q,metadata:$};return{running:!1,pid:null,metadata:$}}return{running:!0,pid:$.browserPid,metadata:$}}function E0(){let{running:$,pid:Q,metadata:W}=i();if(!$||!Q)return T(),!1;let q=H0(Q,W?.tempDir||J,W?.debugPort||X);return T(),q}async function d0(){return k0(),i()}export{v as writeMetadata,H as verifyBrowserProcess,s0 as unregisterClient,_0 as touchActivity,m0 as registerClient,_ as readMetadata,E0 as killChrome,i0 as isIdleExpired,d0 as ensureCleanSession,g0 as commandLineMatchesGreedyChrome,T as clearMetadata,k0 as cleanupStaleSessions,i as checkRunning,r0 as acquireLaunchLock,M as METADATA_FILE};