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