@duckmind/dm-darwin-x64 0.52.6 → 0.53.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.
Files changed (58) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +14 -10
  3. package/extensions/dm-cua/bin/browser-cua.mjs +6 -6
  4. package/extensions/dm-cua/index.js +5 -5
  5. package/extensions/dm-cua/src/browser-cua-lib.mjs +2 -2
  6. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +8 -1
  7. package/extensions/greedysearch-dm/bin/cdp-headless.mjs +1 -1
  8. package/extensions/greedysearch-dm/bin/cdp-visible.mjs +1 -1
  9. package/extensions/greedysearch-dm/bin/cdp.mjs +29 -20
  10. package/extensions/greedysearch-dm/bin/gschrome.mjs +1 -8
  11. package/extensions/greedysearch-dm/bin/kill-visible.mjs +1 -1
  12. package/extensions/greedysearch-dm/bin/launch-visible.mjs +1 -2
  13. package/extensions/greedysearch-dm/bin/launch.mjs +9 -11
  14. package/extensions/greedysearch-dm/bin/mcp.mjs +375 -0
  15. package/extensions/greedysearch-dm/bin/search.mjs +309 -157
  16. package/extensions/greedysearch-dm/bin/visible.mjs +1 -1
  17. package/extensions/greedysearch-dm/extractors/bing-copilot.mjs +205 -68
  18. package/extensions/greedysearch-dm/extractors/chatgpt.mjs +229 -140
  19. package/extensions/greedysearch-dm/extractors/common.mjs +160 -50
  20. package/extensions/greedysearch-dm/extractors/consensus.mjs +226 -93
  21. package/extensions/greedysearch-dm/extractors/consent.mjs +44 -17
  22. package/extensions/greedysearch-dm/extractors/gemini.mjs +277 -138
  23. package/extensions/greedysearch-dm/extractors/google-ai.mjs +172 -64
  24. package/extensions/greedysearch-dm/extractors/logically.mjs +183 -69
  25. package/extensions/greedysearch-dm/extractors/perplexity.mjs +331 -65
  26. package/extensions/greedysearch-dm/extractors/semantic-scholar.mjs +118 -41
  27. package/extensions/greedysearch-dm/index.js +23 -20
  28. package/extensions/greedysearch-dm/package.json +8 -3
  29. package/extensions/greedysearch-dm/skills/greedy-search/skill.md +8 -8
  30. package/extensions/greedysearch-dm/src/fetcher.mjs +2 -2
  31. package/extensions/greedysearch-dm/src/formatters/results.js +8 -6
  32. package/extensions/greedysearch-dm/src/github.mjs +7 -7
  33. package/extensions/greedysearch-dm/src/reddit.mjs +1 -1
  34. package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +10 -8
  35. package/extensions/greedysearch-dm/src/search/challenge-detect.mjs +48 -0
  36. package/extensions/greedysearch-dm/src/search/chrome.mjs +130 -54
  37. package/extensions/greedysearch-dm/src/search/constants.mjs +6 -6
  38. package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
  39. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +160 -83
  40. package/extensions/greedysearch-dm/src/search/minimize.mjs +1 -0
  41. package/extensions/greedysearch-dm/src/search/paths.mjs +1 -1
  42. package/extensions/greedysearch-dm/src/search/pdf.mjs +1 -1
  43. package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -1
  44. package/extensions/greedysearch-dm/src/search/progress.mjs +2 -0
  45. package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
  46. package/extensions/greedysearch-dm/src/search/research.mjs +262 -167
  47. package/extensions/greedysearch-dm/src/search/scale-aware.mjs +11 -0
  48. package/extensions/greedysearch-dm/src/search/simple-research.mjs +827 -0
  49. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +9 -9
  50. package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
  51. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +23 -20
  52. package/extensions/greedysearch-dm/src/tools/shared.js +10 -9
  53. package/extensions/greedysearch-dm/src/utils/node-runtime.mjs +1 -1
  54. package/package.json +1 -1
  55. package/extensions/greedysearch-dm/src/search/cdp-endpoint.mjs +0 -3
  56. package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +0 -3
  57. package/extensions/greedysearch-dm/src/search/partial-output.mjs +0 -1
  58. package/extensions/greedysearch-dm/src/utils/browser-executable.mjs +0 -1
@@ -1,9 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as T}from"node:child_process";import{basename as Q}from"node:path";function H(q=process.env,z=process.execPath){let E=q.GREEDY_SEARCH_NODE||q.NODE_BINARY||q.NODE;if(E?.trim())return E.trim();let F=Q(z||"").toLowerCase();if(F==="node"||F==="node.exe")return z;return"node"}var V=new URL("./launch.mjs",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),K=process.argv[2],O={"launch-headless":["--headless"],"launch-visible":[],kill:["--kill"],status:["--status"]}[K];if(!O)process.stderr.write(`Usage: node bin/gschrome.mjs <command>
3
-
4
- Commands:
5
- launch-headless Start a headless browser on GREEDY_SEARCH_PORT
6
- launch-visible Start a visible browser on GREEDY_SEARCH_PORT
7
- kill Stop the owned GreedySearch browser
8
- status Show running status
9
- `),process.exit(2);var W=T(H(),[V,...O],{stdio:"inherit",env:K==="launch-visible"?{...process.env,GREEDY_SEARCH_VISIBLE:"1"}:process.env});W.on("close",(q)=>process.exit(q??0));
2
+ import{spawn as a}from"node:child_process";import{fileURLToPath as e}from"node:url";import{basename as c}from"node:path";function u(s=process.env,i=process.execPath){let o=s.GREEDY_SEARCH_NODE||s.NODE_BINARY||s.NODE;if(o?.trim())return o.trim();let r=c(i||"").toLowerCase();if(r==="node"||r==="node.exe")return i;return"node"}var m=process.argv[2]||"status",n=e(new URL("./launch.mjs",import.meta.url)),p={"launch-headless":{args:[],visible:!1},"launch-visible":{args:[],visible:!0},kill:{args:["--kill"],visible:null},status:{args:["--status"],visible:null}},l=p[m];if(!l)console.error("Usage: gschrome.mjs launch-headless|launch-visible|kill|status"),process.exit(2);var t={...process.env};if(l.visible===!0)t.GREEDY_SEARCH_VISIBLE="1";if(l.visible===!1)delete t.GREEDY_SEARCH_VISIBLE;var E=a(u(),[n,...l.args],{stdio:"inherit",env:t});E.on("exit",(s,i)=>{if(i)process.kill(process.pid,i);process.exit(s??1)});
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as K}from"node:child_process";import{basename as H}from"node:path";function F(q=process.env,z=process.execPath){let A=q.GREEDY_SEARCH_NODE||q.NODE_BINARY||q.NODE;if(A?.trim())return A.trim();let E=H(z||"").toLowerCase();if(E==="node"||E==="node.exe")return z;return"node"}var O=new URL("./launch-visible.mjs",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Q=K(F(),[O,"--kill"],{stdio:"inherit"});Q.on("close",(q)=>process.exit(q??0));
2
+ import{spawn as J}from"node:child_process";import{basename as H}from"node:path";function F(k=process.env,q=process.execPath){let z=k.GREEDY_SEARCH_NODE||k.NODE_BINARY||k.NODE;if(z?.trim())return z.trim();let E=H(q||"").toLowerCase();if(E==="node"||E==="node.exe")return q;return"node"}var K=new URL("./launch-visible.mjs",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),L=J(F(),[K,"--kill"],{stdio:"inherit"});L.on("close",(k)=>process.exit(k??0));
@@ -1,3 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Q}from"node:child_process";import{basename as O}from"node:path";function H(q=process.env,A=process.execPath){let E=q.GREEDY_SEARCH_NODE||q.NODE_BINARY||q.NODE;if(E?.trim())return E.trim();let F=O(A||"").toLowerCase();if(F==="node"||F==="node.exe")return A;return"node"}var T=new URL("./launch.mjs",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),z=process.argv[2]||"",K=[T];if(z==="--kill"||z==="--status")K.push(z);else if(z)process.stderr.write(`Usage: node bin/launch-visible.mjs [--kill|--status]
3
- `),process.exit(2);var V=Q(H(),K,{stdio:"inherit",env:{...process.env,GREEDY_SEARCH_VISIBLE:"1"}});V.on("close",(q)=>process.exit(q??0));
2
+ import{spawn as m}from"node:child_process";import{fileURLToPath as E}from"node:url";import{basename as t}from"node:path";function s(o=process.env,i=process.execPath){let p=o.GREEDY_SEARCH_NODE||o.NODE_BINARY||o.NODE;if(p?.trim())return p.trim();let r=t(i||"").toLowerCase();if(r==="node"||r==="node.exe")return i;return"node"}var R=E(new URL("./launch.mjs",import.meta.url)),L=m(s(),[R,...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,GREEDY_SEARCH_VISIBLE:"1"}});L.on("exit",(o,i)=>{if(i)process.kill(process.pid,i);process.exit(o??1)});
@@ -1,12 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import{execSync as KJ,spawn as iJ}from"node:child_process";import{existsSync as E,mkdirSync as aJ,readdirSync as tJ,readFileSync as m,unlinkSync as U,writeFileSync as w}from"node:fs";import qJ from"node:http";import{platform as c,tmpdir as VJ}from"node:os";import{join as f}from"node:path";import{existsSync as l,mkdirSync as UJ,readFileSync as L,renameSync as MJ,unlinkSync as bJ,writeFileSync as s}from"node:fs";import YJ from"node:http";import{platform as o}from"node:os";import{dirname as OJ}from"node:path";var d=[9222,9223],NJ=/^(0|false|no|off)$/i;function kJ(J){return[...new Set(J.filter(Boolean))]}function r(J,X="localhost"){let $=String(J||"").trim().split(/\r?\n/).map((W)=>W.trim()).filter(Boolean);if($.length===0)throw Error("empty DevToolsActivePort");let[Q,Z=""]=$;if(/^wss?:\/\//i.test(Q))return Q;if(Q.includes(":"))return`ws://${Q}${Z}`;return`ws://${X}:${Q}${Z}`}function n(J,X="explicit"){let $=new URL(J),Q=$.protocol==="wss:"?"wss:":"ws:",Z=$.port?Number.parseInt($.port,10):Q==="wss:"?443:80;return{source:X,wsUrl:`${Q}//${$.host}${$.pathname}${$.search}`,host:$.hostname,port:Z,path:`${$.pathname}${$.search}`,httpUrl:`http://${$.hostname}:${Z}`}}function i(J=process.env){return![J.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,J.DM_CUA_REUSE_EXISTING_BROWSER].some((X)=>X!==void 0&&NJ.test(String(X)))}function S(J){let X=Number.parseInt(String(J??""),10);return Number.isInteger(X)&&X>0&&X<65536?X:null}function GJ(J){if(!J)return null;let X=String(J).trim();if(!X)return null;let $=new URL(X.includes("://")?X:`http://${X}`),Q=S($.port)||($.protocol==="https:"?443:80);return{host:$.hostname,port:Q,source:`env:${X}`}}function AJ(J){if(!J)return[];return String(J).split(/[,\s]+/).map(S).filter(Boolean)}function xJ({env:J=process.env,platformName:X=o(),procVersionText:$=null}={}){if(X!=="linux")return!1;if(J.WSL_DISTRO_NAME||J.WSL_INTEROP)return!0;let Q=$??(()=>{try{return L("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(Q)}function DJ({env:J=process.env,platformName:X=o(),procVersionText:$=null,resolvConfText:Q=null}={}){let Z=["localhost","127.0.0.1"];if(xJ({env:J,platformName:X,procVersionText:$})){let q=(Q??(()=>{try{return L("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(q)Z.push(q[1]);Z.push("host.docker.internal")}return kJ(Z)}function RJ({env:J=process.env,hosts:X=DJ({env:J}),autoPorts:$=d,excludePorts:Q=[]}={}){let Z=[];for(let z of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(J[z])Z.push({wsUrl:J[z],source:`env:${z}`});for(let z of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let V=GJ(J[z]);if(V)Z.push(V)}catch{}for(let z of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let V=S(J[z]);if(!V)continue;for(let O of X)Z.push({host:O,port:V,source:`env:${z}`})}let W=AJ(J.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let z of W)for(let V of X)Z.push({host:V,port:z,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let q=new Set(Q.filter(Boolean));if(i(J))for(let z of $){if(q.has(z))continue;for(let V of X)Z.push({host:V,port:z,source:"auto"})}let K=new Set;return Z.filter((z)=>{let V=z.wsUrl||`${z.host}:${z.port}`;if(K.has(V))return!1;return K.add(V),!0})}async function TJ(J,{timeoutMs:X=700}={}){if(J.wsUrl)return n(J.wsUrl,J.source);let $=J.host||"localhost",Q=J.port;if(!Q)return null;let Z=await new Promise((W)=>{let q=YJ.get({host:$,port:Q,path:"/json/version",timeout:X},(K)=>{let z="";K.setEncoding("utf8"),K.on("data",(V)=>z+=V),K.on("end",()=>W(K.statusCode===200?z:null))});q.on("error",()=>W(null)),q.setTimeout(X,()=>{q.destroy(),W(null)})});if(!Z)return null;try{let W=JSON.parse(Z);if(!W.webSocketDebuggerUrl)return null;let q=n(W.webSocketDebuggerUrl,J.source),K=q.path||new URL(W.webSocketDebuggerUrl).pathname;return{...q,host:$,port:Q,httpUrl:`http://${$}:${Q}`,wsUrl:`ws://${$}:${Q}${K}`,path:K}}catch{return null}}async function gJ(J={}){for(let X of RJ(J)){let $=await TJ(X,J);if($)return $}return null}function CJ(J){if(!J)throw Error("missing CDP endpoint");let X=new URL(J.wsUrl);return`${X.host}
3
- ${X.pathname}${X.search}
4
- `}function wJ(J,X){UJ(OJ(J),{recursive:!0});let $=`${J}.tmp-${process.pid}`;s($,CJ(X),"utf8");try{bJ(J)}catch{}MJ($,J)}async function a({activePortFile:J,modeFile:X,env:$=process.env,excludePorts:Q=[],autoPorts:Z=d}={}){if(!i($))return null;let W=await gJ({env:$,excludePorts:Q,autoPorts:Z});if(!W)return null;if(wJ(J,W),X)s(X,"existing","utf8");return W}function fJ(J){return String(J||"").trim()==="existing"}function y(J,X){if(!X||!l(X))return!1;if(!fJ(L(X,"utf8")))return!1;return!!J&&l(J)}import{existsSync as T,mkdirSync as hJ,readFileSync as e,writeFileSync as LJ}from"node:fs";import{homedir as SJ}from"node:os";import{join as JJ}from"node:path";import{tmpdir as g}from"node:os";function yJ(J,X=9222){let $=Number.parseInt(String(J??""),10);return Number.isInteger($)&&$>1024&&$<65535?$:X}var k=yJ(process.env.GREEDY_SEARCH_PORT,9222),G=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${g().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),NX=`${G}/DevToolsActivePort`,kX=`${g().replaceAll("\\","/")}/cdp-pages.json`,GX=process.env.GREEDY_SEARCH_MODE_FILE||`${g().replaceAll("\\","/")}/greedysearch-chrome-mode`,AX=`${g().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,I=JJ(SJ(),".dm"),j=JJ(I,"greedyconfig"),_=["perplexity","google","chatgpt"],F="gemini";function vJ(){try{if(T(j)){let J=e(j,"utf8"),X=JSON.parse(J);if(Array.isArray(X.engines)&&X.engines.length>0&&X.engines.every(($)=>typeof $==="string")){let $=X.engines.filter((Z)=>v[Z]),Q=X.engines.filter((Z)=>!v[Z]);if(Q.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${j}: ${Q.join(", ")}
5
- [greedysearch] Available engines: ${Object.keys(v).join(", ")}
6
- `);if($.length>0)return $;process.stderr.write(`[greedysearch] Warning: no valid engines in ${j}, falling back to defaults: ${_.join(", ")}
7
- `)}}}catch{}return _}function IJ(){try{if(!T(I))hJ(I,{recursive:!0});if(!T(j))LJ(j,JSON.stringify({engines:_,synthesizer:F},null,2)+`
8
- `,"utf8")}catch{}}IJ();var t=["gemini","chatgpt"];function _J(){try{if(T(j)){let J=e(j,"utf8"),X=JSON.parse(J);if(typeof X.synthesizer==="string"){let $=X.synthesizer.toLowerCase();if(t.includes($))return $;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${X.synthesizer}" in ${j}
9
- [greedysearch] Available synthesizers: ${t.join(", ")}
10
- [greedysearch] Falling back to default: ${F}
11
- `)}}}catch{}return F}var v={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"},xX=vJ();var DX=_J(),RX=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=G;import{execFileSync as $J,execSync as IX}from"node:child_process";import{platform as nJ,tmpdir as sJ}from"node:os";import{execFileSync as PJ}from"node:child_process";import{platform as uJ}from"node:os";import{existsSync as XJ}from"node:fs";import{platform as FJ}from"node:os";import{join as M}from"node:path";function A(J){let X=FJ()==="win32",$=process.env.SystemRoot||"C:\\Windows",Q={win32:{powershell:M($,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:M($,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:M($,"System32","netstat.exe"),taskkill:M($,"System32","taskkill.exe"),tasklist:M($,"System32","tasklist.exe"),cmd:M($,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},Z=X?Q.win32:Q.unix,W=J.toLowerCase();if(Z[W]&&XJ(Z[W]))return Z[W];if(X&&W==="netstat"){let q=M($,"Sysnative","netstat.exe");if(XJ(q))return q}return J}function EJ(J,X){return PJ(A(J),X,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function mJ(J){let X=String(J||"").match(/\b(\d+)\b/);return X?Number.parseInt(X[1],10):null}function cJ(J){return mJ(J)}function pJ(J,X){for(let $ of String(J||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test($))continue;if(!$.trim().split(/\s+/).slice(0,6).some((W)=>W.endsWith(`:${X}`)))continue;let Z=$.match(/\bpid=(\d+)\b/);if(Z)return Number.parseInt(Z[1],10)}return null}function lJ(J,X){for(let $ of String(J||"").split(/\r?\n/)){let Q=$.trim().split(/\s+/);if(Q.length<5||Q[0].toUpperCase()!=="TCP")continue;if(!Q.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!Q[1].endsWith(`:${X}`))continue;let W=Number.parseInt(Q.at(-1),10);if(Number.isInteger(W)&&W>0)return W}return null}function P(J,X,$){try{return J(X,$)}catch{return null}}function u(J,{platformName:X=uJ(),run:$=EJ}={}){if(X==="win32")return lJ(P($,"netstat",["-ano","-p","TCP"]),J);let Q=P($,"lsof",["-nP",`-iTCP:${J}`,"-sTCP:LISTEN","-t"]),Z=cJ(Q);if(Z)return Z;if(X!=="linux")return null;return pJ(P($,"ss",["-ltnp"]),J)}var x=sJ().replaceAll("\\","/"),EX=`${x}/greedysearch-chrome-metadata.json`,mX=`${x}/greedysearch-chrome-launch.lock`;var cX=`${x}/greedysearch-chrome.pid`,pX=`${x}/greedysearch-chrome-mode`,lX=`${x}/greedysearch-chrome-last-activity`;function oJ(J){if(!Number.isInteger(J)||J<=0)return!1;try{return process.kill(J,0),!0}catch{return!1}}function dJ(J){if(!oJ(J))return null;try{if(nJ()==="win32")return $J(A("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${J}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return $J(A("ps"),["-p",String(J),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function rJ(J,X,$=k){if(!J)return!1;let Q=(q)=>String(q||"").replaceAll("\\","/").toLowerCase(),Z=Q(J),W=Q(X);return Z.includes(W)&&Z.includes(`--remote-debugging-port=${$}`)&&!Z.includes("--type=")}function C(J,X,$=k){return rJ(dJ(J),X,$)}var nX=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var B=k,N=G,b=f(N,"DevToolsActivePort"),Y=process.env.GREEDY_SEARCH_PID_FILE||f(VJ(),"greedysearch-chrome.pid"),H=process.env.GREEDY_SEARCH_MODE_FILE||f(VJ(),"greedysearch-chrome-mode");function BJ(J){return J.find((X)=>X&&E(X))||null}function QJ(){let J=c();return BJ(J==="win32"?["C:/Program Files/CloakBrowser/CloakBrowser.exe","C:/Program Files (x86)/CloakBrowser/CloakBrowser.exe"]:J==="darwin"?["/Applications/CloakBrowser.app/Contents/MacOS/CloakBrowser","/Applications/Cloak Browser.app/Contents/MacOS/CloakBrowser"]:["/usr/bin/cloakbrowser","/usr/local/bin/cloakbrowser","/opt/CloakBrowser/CloakBrowser"])}function ZJ(){let J=c();return BJ(J==="win32"?["C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"]:J==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"])}function eJ(){let J=(process.env.GREEDY_SEARCH_BROWSER||process.env.DM_CUA_BROWSER||"auto").toLowerCase(),X=process.env.GREEDY_SEARCH_BROWSER_PATH||process.env.DM_CUA_BROWSER_PATH||process.env.DM_CUA_CLOAK_PATH||process.env.CLOAKBROWSER_BINARY_PATH||process.env.CHROME_PATH;if(X){let Q=X===process.env.DM_CUA_CLOAK_PATH||X===process.env.CLOAKBROWSER_BINARY_PATH,Z=X===process.env.CHROME_PATH;return{path:X,label:J==="chrome"||Z?"Chrome":J==="cloak"||Q?"CloakBrowser":"browser"}}if(J==="cloak")return{path:QJ(),label:"CloakBrowser"};if(J==="chrome")return{path:ZJ(),label:"Chrome"};let $=QJ();return{path:$||ZJ(),label:$?"CloakBrowser":"Chrome"}}var R=()=>process.env.GREEDY_SEARCH_VISIBLE!=="1",JX=[`--remote-debugging-port=${B}`,"--disable-features=DevToolsPrivacyUI","--no-first-run","--no-default-browser-check","--disable-default-apps","--disable-blink-features=AutomationControlled",`--user-data-dir=${N}`,"--profile-directory=Default","--window-size=1920,1080","--lang=en-US","--force-color-profile=srgb","--disable-background-timer-throttling","--disable-renderer-backgrounding","--disable-backgrounding-occluded-windows"];function XX(J){try{let X=f(J,".."),Q=tJ(X).find((Z)=>/^\d{1,10}\.\d{1,10}\.\d{1,10}\.\d{1,10}$/.test(Z));if(Q)return Q.split(".")[0]}catch{}try{let $=KJ(`"${J}" --version`,{encoding:"utf8",timeout:5000}).trim().match(/(\d{1,10})\.\d{1,10}\.\d{1,10}/);if($)return $[1]}catch{}return null}function $X(J){let X=[...JX];if(R()){X.push("--headless=new");let $=XX(J)||"136";X.push(`--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${$}.0.0.0 Safari/537.36`)}return X.push("about:blank"),X}var QX=()=>process.env.GREEDY_SEARCH_VISIBLE==="1";function ZX(){try{if(!E(H))return!0;return m(H,"utf8").trim()==="headless"}catch{return!0}}async function WX(){if(R())return;try{let J=await new Promise((q,K)=>{qJ.get(`http://localhost:${B}/json/version`,(z)=>{let V="";z.on("data",(O)=>V+=O),z.on("end",()=>q(JSON.parse(V)))}).on("error",K)}),X=new URL(J.webSocketDebuggerUrl).pathname,$=globalThis.WebSocket;if(!$)return;let Q=new $(`ws://localhost:${B}${X}`),Z=0,W=new Map;Q.onopen=()=>{let q=++Z;W.set(q,{resolve:(K)=>{let V=(K.targetInfos||[]).find((h)=>h.type==="page");if(!V){Q.close();return}let O=++Z;W.set(O,{resolve:(h)=>{let HJ=h.windowId,p=++Z;W.set(p,{resolve:()=>{},reject:()=>{}}),Q.send(JSON.stringify({id:p,method:"Browser.setWindowBounds",params:{windowId:HJ,bounds:{windowState:"minimized"}}})),setTimeout(()=>Q.close(),500)},reject:()=>Q.close()}),Q.send(JSON.stringify({id:O,method:"Browser.getWindowForTarget",params:{targetId:V.targetId}}))},reject:()=>Q.close()}),Q.send(JSON.stringify({id:q,method:"Target.getTargets",params:{}}))},Q.onmessage=(q)=>{let K=JSON.parse(q.data);if(K.id&&W.has(K.id)){let{resolve:z,reject:V}=W.get(K.id);if(W.delete(K.id),K.error)V?.(K.error);else z?.(K.result)}},setTimeout(()=>Q.close(),5000)}catch{}}function D(){if(!E(Y))return!1;let J=Number.parseInt(m(Y,"utf8").trim(),10);if(!J)return!1;try{return process.kill(J,0),C(J,N,B)?J:!1}catch{return!1}}function jJ(J){return u(J)}function WJ(J){try{if(c()==="win32")KJ(`taskkill /F /T /PID ${J}`,{stdio:"ignore"});else process.kill(J,"SIGTERM");return!0}catch{return!1}}function zX(){let J=jJ(B);if(!J)return!0;let X=D();if(X&&J===X)return!0;if(C(J,N,B))return w(Y,String(J),"utf8"),!0;return console.error(`Browser/CDP port ${B} is owned by unverified pid ${J}; refusing to kill it. Set GREEDY_SEARCH_PORT to a free port.`),!1}function KX(J,X=1000){return new Promise(($)=>{let Q=qJ.get(J,(Z)=>{let W="";Z.on("data",(q)=>W+=q),Z.on("end",()=>$({ok:Z.statusCode===200,body:W}))});Q.on("error",()=>$({ok:!1})),Q.setTimeout(X,()=>{Q.destroy(),$({ok:!1})})})}async function zJ(J=15000){let X=Date.now()+J;while(Date.now()<X){let{ok:$,body:Q}=await KX(`http://localhost:${B}/json/version`,1500);if($)try{let{webSocketDebuggerUrl:Z}=JSON.parse(Q),W=new URL(Z).pathname;return w(b,`${B}
12
- ${W}`,"utf8"),!0}catch{}await new Promise((Z)=>setTimeout(Z,400))}return!1}async function qX(){let J=process.argv[2];if(J==="--kill"){if(y(b,H)){try{U(b)}catch{}try{U(H)}catch{}console.log("Detached from existing browser CDP endpoint; no browser process was killed.");return}let K=jJ(B),z=D()||(K&&C(K,N,B)?K:null);if(z){let V=WJ(z);console.log(V?`Stopped browser (pid ${z}).`:`Failed to stop pid ${z}.`)}else console.log("GreedySearch browser is not running.");try{U(Y)}catch{}try{U(b)}catch{}try{U(H)}catch{}return}if(J==="--status"){if(y(b,H)){try{let z=r(m(b,"utf8"));console.log(`Reusing existing browser — ${z}`)}catch{console.log("Reusing existing browser.")}return}let K=D();if(K)console.log(`Running — pid ${K}, port ${B}`);else console.log("Not running.");return}if(!zX())process.exit(1);let X=D(),$=await a({activePortFile:b,modeFile:H,excludePorts:X?[B]:[],autoPorts:X?[9223]:[B,9223]});if($){console.log(`Reusing existing browser CDP endpoint ${$.httpUrl} (${$.source}).`);return}let Q=D();if(Q)if(process.env.GREEDY_SEARCH_VISIBLE==="1"&&!process.argv.includes("--headless")&&ZX()){console.log(`Headless browser running (pid ${Q}) but visible requested — killing...`),WJ(Q);try{U(Y)}catch{}try{U(H)}catch{}}else{if(await zJ(5000)){console.log(`GreedySearch browser already running (pid ${Q}).`);return}console.log(`Stale PID ${Q} — launching fresh.`);try{U(Y)}catch{}}let Z=eJ();if(!Z.path)console.error("CloakBrowser/Chrome not found. Set GREEDY_SEARCH_BROWSER_PATH, DM_CUA_BROWSER_PATH, DM_CUA_CLOAK_PATH, CLOAKBROWSER_BINARY_PATH, or CHROME_PATH."),process.exit(1);if(aJ(N,{recursive:!0}),console.log(`Launching GreedySearch ${Z.label} on port ${B}...`),R())console.log("Headless mode — no window will be shown");else if(!QX())console.log("Window will be minimized");let W=iJ(Z.path,$X(Z.path),{detached:!0,stdio:"ignore"});if(W.unref(),w(Y,String(W.pid)),w(H,R()?"headless":"visible","utf8"),!await zJ())console.error(`${Z.label} did not become ready within 15s.`),process.exit(1);if(R())console.log("Ready (headless).");else await WX(),console.log("Ready.")}qX();
2
+ import{execFileSync as T,execSync as zt,spawn as gt}from"node:child_process";import{existsSync as o,mkdirSync as xt,readdirSync as jt,readFileSync as _,unlinkSync as U,writeFileSync as A}from"node:fs";import{platform as c,tmpdir as Wu}from"node:os";import{join as kt}from"node:path";import E from"node:http";function x(t,u=1000){return new Promise((f)=>{let $=E.get(t,(b)=>{let J="";b.on("data",(q)=>J+=q),b.on("end",()=>f({ok:b.statusCode===200,body:J}))});$.on("error",()=>f({ok:!1})),$.setTimeout(u,()=>{$.destroy(),f({ok:!1})})})}async function p(t){try{let u=await x(`http://localhost:${t}/json/version`);if(!u.ok)return;let f=JSON.parse(u.body),$=await x(`http://localhost:${t}/json/list`);if(!$.ok)return;let J=JSON.parse($.body).find((h)=>h.type==="page")?.id;if(!J)return;let q=f.webSocketDebuggerUrl;if(typeof q!=="string")return;let g=new URL(q);if(g.hostname!=="localhost"&&g.hostname!=="127.0.0.1")return;if(!/^ws:\/\/localhost:\d+/.test(`ws://${g.host}`))return;let n=new WebSocket(`ws://localhost:${t}${g.pathname}`);await new Promise((h)=>{let a=!1,I=setTimeout(()=>V(),5000),V=()=>{if(a)return;a=!0,clearTimeout(I);try{n.close()}catch{}h()};n.onopen=()=>{try{n.send(JSON.stringify({id:1,method:"Browser.getWindowForTarget",params:{targetId:J}}))}catch{V()}},n.onmessage=(i)=>{try{let w=JSON.parse(i.data);if(w.id===1&&w.result?.windowId)n.send(JSON.stringify({id:2,method:"Browser.setWindowBounds",params:{windowId:w.result.windowId,bounds:{windowState:"minimized"}}}));else if(w.id===2)V();else if(w.id===1)V()}catch{V()}},n.onerror=V})}catch{}}import{existsSync as j,mkdirSync as tt,readFileSync as y,writeFileSync as ut}from"node:fs";import{homedir as ft}from"node:os";import{join as m}from"node:path";import{tmpdir as $t}from"node:os";function bt(t,u=9222){let f=Number.parseInt(String(t??""),10);return Number.isInteger(f)&&f>1024&&f<65535?f:u}var Jt=$t().replaceAll("\\","/"),G=bt(process.env.GREEDY_SEARCH_PORT),W=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Jt}/greedysearch-chrome-profile`).replaceAll("\\","/"),S=`${W}/DevToolsActivePort`,L=process.env.GREEDY_SEARCH_PID_FILE||`${W}/browser.pid`,mt=process.env.CDP_PAGES_CACHE||`${W}/cdp-pages.json`,O=process.env.GREEDY_SEARCH_MODE_FILE||`${W}/browser-mode`,Gt=process.env.GREEDY_SEARCH_METADATA_FILE||`${W}/browser-metadata.json`,St=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${W}/browser-launch.lock`,Lt=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${W}/browser-last-activity`,Ot=(process.env.CDP_SOCKET_DIR||`${W}/cdp-sockets`).replaceAll("\\","/"),Dt=`${W}/visible-recovery.jsonl`,r=m(ft(),".dm"),K=m(r,"greedyconfig"),Y=["perplexity","google","chatgpt","gemini"],N="gemini";function Wt(){try{if(j(K)){let t=y(K,"utf8"),u=JSON.parse(t);if(Array.isArray(u.engines)&&u.engines.length>0&&u.engines.every((f)=>typeof f==="string")){let f=u.engines.filter((b)=>M[b]),$=u.engines.filter((b)=>!M[b]);if($.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${K}: ${$.join(", ")}
3
+ [greedysearch] Available engines: ${Object.keys(M).join(", ")}
4
+ `);if(f.length>0)return f;process.stderr.write(`[greedysearch] Warning: no valid engines in ${K}, falling back to defaults: ${Y.join(", ")}
5
+ `)}}}catch{}return Y}function qt(){try{if(!j(r))tt(r,{recursive:!0});if(!j(K))ut(K,JSON.stringify({engines:Y,synthesizer:N},null,2)+`
6
+ `,"utf8")}catch{}}qt();var l=["gemini","chatgpt"];function Qt(){try{if(j(K)){let t=y(K,"utf8"),u=JSON.parse(t);if(typeof u.synthesizer==="string"){let f=u.synthesizer.toLowerCase();if(l.includes(f))return f;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${u.synthesizer}" in ${K}
7
+ [greedysearch] Available synthesizers: ${l.join(", ")}
8
+ [greedysearch] Falling back to default: ${N}
9
+ `)}}}catch{}return N}var M={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"},et=Wt();var Pt=Qt(),Ft=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=W;import{execFileSync as Bt}from"node:child_process";import{platform as Xt}from"node:os";import{existsSync as D}from"node:fs";import{platform as Kt}from"node:os";import{join as B}from"node:path";function Z(t){let u=Kt()==="win32",f=process.env.SystemRoot||"C:\\Windows",$={win32:{powershell:B(f,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:B(f,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:B(f,"System32","netstat.exe"),taskkill:B(f,"System32","taskkill.exe"),tasklist:B(f,"System32","tasklist.exe"),cmd:B(f,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},b=u?$.win32:$.unix,J=t.toLowerCase();if(b[J]&&D(b[J]))return b[J];if(u&&J==="netstat"){let q=B(f,"Sysnative","netstat.exe");if(D(q))return q}return t}function nt(t,u){return Bt(Z(t),u,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function Vt(t){let u=String(t||"").match(/\b(\d+)\b/);return u?Number.parseInt(u[1],10):null}function Zt(t){return Vt(t)}function Ut(t,u){for(let f of String(t||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(f))continue;if(!f.trim().split(/\s+/).slice(0,6).some((J)=>J.endsWith(`:${u}`)))continue;let b=f.match(/\bpid=(\d+)\b/);if(b)return Number.parseInt(b[1],10)}return null}function wt(t,u){for(let f of String(t||"").split(/\r?\n/)){let $=f.trim().split(/\s+/);if($.length<5||$[0].toUpperCase()!=="TCP")continue;if(!$.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!$[1].endsWith(`:${u}`))continue;let b=Number.parseInt($.at(-1),10);if(Number.isInteger(b)&&b>0)return b}return null}function C(t,u,f){try{return t(u,f)}catch{return null}}function e(t,{platformName:u=Xt(),run:f=nt}={}){if(u==="win32")return wt(C(f,"netstat",["-ano","-p","TCP"]),t);let $=C(f,"lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"]),b=Zt($);if(b)return b;if(u!=="linux")return null;return Ut(C(f,"ss",["-ltnp"]),t)}var Q=G,s=W,d=S,X=L,z=O;function vt(){let t=c();return(t==="win32"?["C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"]:t==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"]).find(o)||null}var k=()=>process.env.GREEDY_SEARCH_VISIBLE!=="1",At=[`--remote-debugging-port=${Q}`,"--disable-features=DevToolsPrivacyUI","--no-first-run","--no-default-browser-check","--disable-default-apps","--disable-blink-features=AutomationControlled",`--user-data-dir=${s}`,"--profile-directory=Default","--window-size=1920,1080","--lang=en-US","--force-color-profile=srgb","--disable-background-timer-throttling","--disable-renderer-backgrounding","--disable-backgrounding-occluded-windows"];function Ht(t){try{let u=kt(t,".."),$=jt(u).find((b)=>/^\d{1,10}\.\d{1,10}\.\d{1,10}\.\d{1,10}$/.test(b));if($)return $.split(".")[0]}catch{}try{let f=zt(`"${t}" --version`,{encoding:"utf8",timeout:5000}).trim().match(/(\d{1,10})\.\d{1,10}\.\d{1,10}/);if(f)return f[1]}catch{}return null}function ht(t){let u=[...At];if(k()){u.push("--headless=new");let f=Ht(t)||"136";u.push(`--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${f}.0.0.0 Safari/537.36`)}return u.push("about:blank"),u}var Mt=()=>process.env.GREEDY_SEARCH_VISIBLE==="1";function rt(){try{if(!o(z))return!0;return _(z,"utf8").trim()==="headless"}catch{return!0}}function Yt(t){try{if(c()==="win32")return T(Z("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return T(Z("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Nt(t,u=s,f=Q){let $=String(t||"").replaceAll("\\","/"),b=String(u||"").replaceAll("\\","/");return $.includes(`--remote-debugging-port=${f}`)&&$.includes(`--user-data-dir=${b}`)&&!$.includes("--type=")}function H(t){if(!Number.isInteger(t)||t<=0)return!1;try{process.kill(t,0)}catch{return!1}return Nt(Yt(t))}function v(){if(!o(X))return!1;let t=Number.parseInt(_(X,"utf8").trim(),10);return H(t)?t:!1}function R(t){return e(t)}function Ct(){let t=R(Q);return H(t)?t:null}function P(t){if(!H(t))return!1;try{if(c()==="win32")T(Z("taskkill"),["/F","/T","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGTERM");return!0}catch{return!1}}function Tt(){let t=R(Q);if(!t)return!0;let u=v();if(u&&t===u)return!0;if(H(t))return A(X,String(t),"utf8"),!0;return console.error(`Browser/CDP port ${Q} is owned by unverified pid ${t}; refusing to kill it. Set GREEDY_SEARCH_PORT to a free port.`),!1}async function F(t=15000){let u=Date.now()+t;while(Date.now()<u){let{ok:f,body:$}=await x(`http://localhost:${Q}/json/version`,1500);if(f)try{let{webSocketDebuggerUrl:b}=JSON.parse($),J=new URL(b).pathname;return A(d,`${Q}
10
+ ${J}`,"utf8"),!0}catch{}await new Promise((b)=>setTimeout(b,400))}return!1}async function ot(){let t=process.argv[2];if(!Tt()){process.exitCode=1;return}if(t==="--kill"){let J=v()||Ct();if(J){let q=P(J);console.log(q?`Stopped Chrome (pid ${J}).`:`Failed to stop pid ${J}.`)}else console.log("GreedySearch Chrome is not running.");try{U(X)}catch{}try{U(d)}catch{}try{U(z)}catch{}return}if(t==="--status"){let J=v();if(J)console.log(`Running — pid ${J}, port ${Q}`);else console.log("Not running.");return}let u=v();if(u)if(process.env.GREEDY_SEARCH_VISIBLE==="1"&&!process.argv.includes("--headless")&&rt()){console.log(`Headless Chrome running (pid ${u}) but visible requested — killing...`),P(u);try{U(X)}catch{}try{U(z)}catch{}}else{if(await F(5000)){console.log(`GreedySearch Chrome already running (pid ${u}).`);return}console.log(`Stale PID ${u} — launching fresh.`);try{U(X)}catch{}}let f=process.env.CHROME_PATH||vt();if(!f)console.error("Chrome not found. Set CHROME_PATH env var."),process.exit(1);if(xt(s,{recursive:!0}),console.log(`Launching GreedySearch Chrome on port ${Q}...`),k())console.log("Headless mode — no window will be shown");else if(!Mt())console.log("Window will be minimized");let $=gt(f,ht(f),{detached:!0,stdio:"ignore"});if($.unref(),A(X,String($.pid)),A(z,k()?"headless":"visible","utf8"),!await F())console.error("Chrome did not become ready within 15s."),process.exit(1);if(k())console.log("Ready (headless).");else await p(Q),console.log("Ready.")}ot();export{Nt as commandLineMatchesGreedyBrowser};
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as c0}from"node:module";var h0=Object.defineProperty;var p0=($)=>$;function u0($,Q){this[$]=p0.bind(null,Q)}var m0=($,Q)=>{for(var W in Q)h0($,W,{get:Q[W],enumerable:!0,configurable:!0,set:u0.bind(Q,W)})};var U=($,Q)=>()=>($&&(Q=$($=0)),Q);var P=c0(import.meta.url);import{basename as i0}from"node:path";function v($=process.env,Q=process.execPath){let W=$.GREEDY_SEARCH_NODE||$.NODE_BINARY||$.NODE;if(W?.trim())return W.trim();let X=i0(Q||"").toLowerCase();if(X==="node"||X==="node.exe")return Q;return"node"}var L=()=>{};async function d0(){if(y)return y;let[{Readability:$},{JSDOM:Q},{default:W}]=await Promise.all([import("@mozilla/readability"),import("jsdom"),import("turndown")]),X=new W({headingStyle:"atx",bulletListMarker:"-",codeBlockStyle:"fenced"});return X.addRule("removeDataUrls",{filter:(J)=>J.tagName==="IMG"&&J.getAttribute("src")?.startsWith("data:"),replacement:()=>""}),y={Readability:$,JSDOM:Q,turndown:X},y}function s0($){if(!$||$.includes(":"))return null;let Q=$.split(".");if(Q.length<1||Q.length>4)return null;if(!Q.every((J)=>o0.test(J)))return null;let W=Q.map((J)=>{if(/^0x/i.test(J))return parseInt(J,16);if(/^0[0-7]+$/.test(J))return parseInt(J,8);return parseInt(J,10)});if(W.some((J)=>!Number.isFinite(J)||J<0))return null;let X;if(W.length===1){if(W[0]>4294967295)return null;X=[W[0]>>>24&255,W[0]>>>16&255,W[0]>>>8&255,W[0]&255]}else if(W.length===2){if(W[0]>255||W[1]>16777215)return null;X=[W[0],W[1]>>>16&255,W[1]>>>8&255,W[1]&255]}else if(W.length===3){if(W[0]>255||W[1]>255||W[2]>65535)return null;X=[W[0],W[1],W[2]>>>8&255,W[2]&255]}else{if(W.some((J)=>J>255))return null;X=W}return X.join(".")}function a0($){let Q=$.match(l0);if(Q)return`${Q[1]}.${Q[2]}.${Q[3]}.${Q[4]}`;let W=$.match(n0);if(W){let X=parseInt(W[1],16),J=parseInt(W[2],16);if(X>65535||J>65535)return null;return[X>>>8&255,X&255,J>>>8&255,J&255].join(".")}return null}function e($){return X0.some((Q)=>Q.test($))}function J0($={}){return{...W0,...$}}function C($){try{if(typeof $!=="string"||!$.trim())return{blocked:!0,reason:"URL must be a non-empty string"};let Q=new URL($);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return{blocked:!0,reason:`Protocol not allowed: ${Q.protocol}`};let W=Q.hostname.toLowerCase();for(let J of X0)if(J.test(W))return{blocked:!0,reason:`Private/internal address: ${W}`};if(W.startsWith("[")&&W.endsWith("]")){let J=W.slice(1,-1),K=a0(J);if(K&&e(K))return{blocked:!0,reason:`Private/internal address: ${W} (maps to ${K})`}}let X=s0(W);if(X&&e(X))return{blocked:!0,reason:`Private/internal address: ${W} (normalizes to ${X})`};return{blocked:!1}}catch(Q){return{blocked:!0,reason:`Invalid URL: ${Q.message}`}}}function r0($){try{let Q=new URL($);if(!(Q.hostname==="github.com"||Q.hostname.endsWith(".github.com")))return $;let W=Q.pathname.split("/").filter(Boolean);if(W.length<5)return $;let[X,J,K,Z,...q]=W;if(K!=="blob")return $;let V=q.join("/");return`https://raw.githubusercontent.com/${X}/${J}/${Z}/${V}`}catch{return $}}async function Z0($,Q={}){let W=C($);if(W.blocked)return{ok:!1,url:$,finalUrl:$,status:403,error:`Blocked: ${W.reason}`,needsBrowser:!1};let X=$;if($=r0($),$!==X)console.error(`[fetcher] Rewrote GitHub URL: ${X.slice(0,60)}... → raw.githubusercontent.com`);let{timeoutMs:J=15000,userAgent:K,signal:Z}=Q,q=new AbortController,V=setTimeout(()=>q.abort(),J);if(Z)Z.addEventListener("abort",()=>q.abort(),{once:!0});try{let B=await fetch($,{method:"GET",headers:{...W0,"user-agent":K||Q0},redirect:"follow",signal:q.signal});clearTimeout(V);let j=B.headers.get("content-type")||"",H=B.url,Y=B.headers.get("last-modified")||"",N=C(H);if(N.blocked)return{ok:!1,url:$,finalUrl:H,status:B.status,error:`Blocked: ${N.reason}`,needsBrowser:!1};let A=!1;try{A=new URL(H).hostname.toLowerCase()==="raw.githubusercontent.com"}catch{}if(j.includes("text/plain")&&A){let T=await B.text();return{ok:!0,url:X,finalUrl:H,status:B.status,title:H.split("/").pop()||"GitHub File",byline:"",siteName:"GitHub",lang:"",publishedTime:Y,lastModified:Y,markdown:T,contentLength:T.length,excerpt:T.slice(0,300).replaceAll(/\n/g," "),needsBrowser:!1}}if(!j.includes("text/html")&&!j.includes("application/xhtml"))return{ok:!1,url:$,finalUrl:H,status:B.status,error:`Unsupported content type: ${j}`,needsBrowser:!1};let G=await B.text(),z=h(B.status,G,H,$);if(z.blocked)return{ok:!1,url:$,finalUrl:H,status:B.status,error:`Blocked: ${z.reason}`,needsBrowser:!0};let k=await p(G,H),t=u(k);if(!t.ok)return{ok:!1,url:$,finalUrl:H,status:B.status,error:`Low quality content: ${t.reason}`,needsBrowser:!0};return{ok:!0,url:$,finalUrl:H,status:B.status,title:k.title,byline:k.byline,siteName:k.siteName,lang:k.lang,publishedTime:k.publishedTime||Y,lastModified:Y,markdown:k.markdown,excerpt:k.excerpt,contentLength:k.markdown.length,needsBrowser:!1}}catch(B){clearTimeout(V);let j=W1(B);return{ok:!1,url:$,finalUrl:$,status:0,error:B.message,needsBrowser:j}}}function h($,Q,W,X){let J=Q.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.toLowerCase()||"",K=Q.slice(0,30000).toLowerCase(),Z=`${J} ${K}`;if($===403||$===429||$===503)return{blocked:!0,reason:`HTTP ${$}`};let q=[{pattern:/class=["'][^"']*captcha["']|<div[^>]*id=["']captcha/i,reason:"captcha"},{pattern:/g-recaptcha|data-sitekey|i['"]m not a robot/i,reason:"captcha"},{pattern:/checking your browser.{0,100}please wait|cf-browser-verification/i,reason:"cloudflare challenge"},{pattern:/just a moment.{0,50}security check|ddos protection by cloudflare/i,reason:"cloudflare challenge"},{pattern:/unusual traffic.{0,50}from your computer network/i,reason:"unusual traffic"},{pattern:/bot detected|automated.{0,20}request/i,reason:"bot detection"},{pattern:/enable\s+javascript\s+to\s+view|javascript\s+is\s+required.{0,50}enabled/i,reason:"requires javascript"},{pattern:/access denied|accessdenied/i,reason:"access denied"},{pattern:/protected by anubis|anubis uses a proof-of-work/i,reason:"anubis challenge"}];for(let B of q)if(B.pattern.test(Z))return{blocked:!0,reason:B.reason};let V=Q1(X,W,Q);if(V)return{blocked:!0,reason:V};return{blocked:!1}}function Q1($,Q,W){try{let X=new URL($),J=new URL(Q);if(X.hostname.toLowerCase()===J.hostname.toLowerCase())return;let K=J.hostname.toLowerCase();if(t0.some((q)=>K===q||K.endsWith(`.${q}`)))return`redirected to login (${J.hostname})`;if(e0.some((q)=>K.startsWith(q)))return`redirected to login (${J.hostname})`;let Z=W.slice(0,20000).toLowerCase();if($1.some((q)=>Z.includes(q)))return`redirected to login page (${J.hostname})`}catch{}return}function W1($){let Q=$.message.toLowerCase();return Q.includes("fetch failed")||Q.includes("unable to verify")||Q.includes("certificate")||Q.includes("timeout")}function $0($){let Q=['meta[property="article:published_time"]','meta[name="article:published_time"]','meta[property="og:published_time"]','meta[name="publication_date"]','meta[name="date"]','meta[itemprop="datePublished"]','time[itemprop="datePublished"]','meta[name="DC.date"]'];for(let W of Q){let X=$.querySelector(W),J=X?.getAttribute("content")||X?.getAttribute("datetime")||"";if(J)return J}return""}async function p($,Q){let{Readability:W,JSDOM:X,turndown:J}=await d0(),K=new X($,{url:Q});try{let Z=K.window.document,V=new W(Z).parse();if(V&&V.content){let H=J.turndown(V.content).replaceAll(/\n{3,}/g,`
3
+
4
+ `).trim(),Y=V.publishedTime||$0(Z)||"";return{title:V.title||Z.title||Q,byline:V.byline||"",siteName:V.siteName||"",lang:V.lang||"",publishedTime:Y,markdown:H,excerpt:H.slice(0,300).replaceAll(/\n/g," ")}}let B=Z.body;if(B){let j=B.cloneNode(!0);j.querySelectorAll("script, style, nav, footer, header, aside").forEach((N)=>N.remove());let Y=(j.textContent||"").replaceAll(/\s+/g," ").trim();return{title:Z.title||Q,byline:"",siteName:"",lang:"",publishedTime:$0(Z),markdown:Y,excerpt:Y.slice(0,300)}}return{title:Q,byline:"",siteName:"",lang:"",publishedTime:"",markdown:"",excerpt:""}}finally{K.window.close()}}function u($){let Q=$.markdown.trim().toLowerCase(),W=($.title||"").toLowerCase();if($.markdown.trim().length<100)return{ok:!1,reason:"content too short (< 100 chars)"};let X=Q.toLowerCase(),J=[{check:()=>X.includes("loading")&&X.includes("please wait"),desc:"loading page"},{check:()=>X.includes("please ensure javascript is enabled"),desc:"requires javascript"},{check:()=>X.includes("enable javascript to view"),desc:"requires javascript"},{check:()=>X.includes("just a moment"),desc:"cloudflare challenge detected in content"},{check:()=>X.includes("verify you are human"),desc:"human verification"},{check:()=>X.includes("captcha required"),desc:"captcha in extracted content"},{check:()=>X.includes("access denied"),desc:"access denied in content"},{check:()=>/^\s{0,10}sign\s{1,5}in\s{0,10}$|^\s{0,10}log\s{1,5}in\s{0,10}$/im.test(Q),desc:"login form only"}];for(let{check:K,desc:Z}of J)if(K())return{ok:!1,reason:Z};if(W.includes("just a moment")||W.includes("checking your browser"))return{ok:!1,reason:"cloudflare challenge page detected in title"};return{ok:!0}}var y=null,Q0="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",W0,X0,l0,n0,o0,t0,e0,$1;var K0=U(()=>{W0={"user-agent":Q0,accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8","accept-language":"en-US,en;q=0.9","accept-encoding":"gzip, deflate, br","cache-control":"no-cache",pragma:"no-cache","sec-ch-ua":'"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"document","sec-fetch-mode":"navigate","sec-fetch-site":"none","sec-fetch-user":"?1","upgrade-insecure-requests":"1"},X0=[/^localhost$/i,/^127\.\d+\.\d+\.\d+$/,/^0\.0\.0\.0$/,/^\[::1\]$/,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^fc00:/i,/^fe80:/i,/\.local$/i,/\.internal$/i,/\.localhost$/i],l0=/^::ffff:(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/i,n0=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,o0=/^(?:0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)$/i;t0=["accounts.google.com","login.microsoftonline.com","login.live.com","auth0.com","okta.com","auth.mozilla.auth0.com","id.atlassian.com"],e0=["login.","signin.","auth.","sso.","accounts.","idp."],$1=["sign in to continue","log in to continue","authentication required","create an account to continue","subscribe to continue reading","members only"]});function S($){try{let Q=new URL($);if(!(Q.hostname==="github.com"||Q.hostname.endsWith(".github.com")))return null;let W=Q.pathname.split("/").filter(Boolean);if(W.length<2)return null;let[X,J]=W;if(W.length===2)return{owner:X,repo:J,type:"root"};if(W.length>=4&&(W[2]==="blob"||W[2]==="tree")){let K=W[2],Z=W[3],q=W.slice(4).join("/");return{owner:X,repo:J,type:K,ref:Z,path:q}}return null}catch{return null}}async function D($,Q=1e4){let W=new AbortController,X=setTimeout(()=>W.abort(),Q);try{let J=await fetch(`https://api.github.com${$}`,{headers:V0,signal:W.signal});if(clearTimeout(X),!J.ok)throw Error(`GitHub API ${J.status}: ${$}`);return await J.json()}catch(J){throw clearTimeout(X),J}}async function X1($,Q){try{let W=await D(`/repos/${$}/${Q}/readme`);if(W.content&&W.encoding==="base64")return Buffer.from(W.content,"base64").toString("utf8");return""}catch{return""}}async function q0($,Q,W="HEAD",X="",J){try{let K;if(W==="HEAD")if(J)K=await D(`/repos/${$}/${Q}/git/ref/heads/${J}`).catch(()=>null);else K=await Promise.any([D(`/repos/${$}/${Q}/git/ref/heads/main`),D(`/repos/${$}/${Q}/git/ref/heads/master`)]).catch(()=>null);else K=await D(`/repos/${$}/${Q}/git/ref/heads/${W}`).catch(()=>D(`/repos/${$}/${Q}/git/ref/heads/master`).catch(()=>null));if(!K?.object?.sha)return[];let q=(await D(`/repos/${$}/${Q}/git/commits/${K.object.sha}`)).tree.sha,B=(await D(`/repos/${$}/${Q}/git/trees/${q}`)).tree||[];if(X)B=B.filter((j)=>j.path.startsWith(X));return B.slice(0,50).map((j)=>({path:j.path,type:j.type==="tree"?"dir":"file",size:j.size}))}catch{return[]}}async function J1($,Q,W,X,J=1e4,K){let Z=async(V)=>{let B=new AbortController,j=setTimeout(()=>B.abort(),J);try{let H=await fetch(V,{headers:{"user-agent":V0["user-agent"]},signal:B.signal});if(clearTimeout(j),H.ok)return await H.text();throw Error("not ok")}catch{throw clearTimeout(j),Error("failed")}};if(!W||W==="HEAD"){if(K)try{return await Z(`https://raw.githubusercontent.com/${$}/${Q}/${K}/${X}`)}catch{return null}try{return await Promise.any([Z(`https://raw.githubusercontent.com/${$}/${Q}/main/${X}`),Z(`https://raw.githubusercontent.com/${$}/${Q}/master/${X}`)])}catch{return null}}let q=[`https://raw.githubusercontent.com/${$}/${Q}/${W}/${X}`,`https://raw.githubusercontent.com/${$}/${Q}/master/${X}`];for(let V of q)try{return await Z(V)}catch{}return null}async function B0($){let Q=S($);if(!Q)return{ok:!1,error:"Not a valid GitHub URL"};let{owner:W,repo:X,type:J,ref:K,path:Z}=Q;try{if(J==="root"||J==="tree"&&!Z){let q=await D(`/repos/${W}/${X}`),[V,B]=await Promise.allSettled([X1(W,X),q0(W,X,K||"HEAD","",q.default_branch)]),j=V.status==="fulfilled"?V.value:"",H=B.status==="fulfilled"?B.value:[],Y=q?.description?`
5
+
6
+ > ${q.description}`:"",N=q?.stargazers_count==null?"":` ⭐ ${q.stargazers_count}`,A=q?.language?` · ${q.language}`:"",G=`# ${W}/${X}${N}${A}${Y}
7
+
8
+ `;if(j)G+=j.slice(0,6000);else G+=`[No README found]
9
+
10
+ Files:
11
+ ${H.map((z)=>` ${z.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${z.path}`).join(`
12
+ `)}`;return{ok:!0,title:`${W}/${X}`,content:G,tree:H.slice(0,30)}}if(J==="blob"&&Z){let q;if(!K||K==="HEAD")try{q=(await D(`/repos/${W}/${X}`)).default_branch}catch{q=void 0}let V=await J1(W,X,K,Z,1e4,q);if(V===null)return{ok:!1,error:`File not found: ${Z}`};return{ok:!0,title:`${W}/${X}: ${Z}`,content:V}}if(J==="tree"&&Z){let q;if(!K||K==="HEAD")try{q=(await D(`/repos/${W}/${X}`)).default_branch}catch{q=void 0}let V=await q0(W,X,K||"HEAD",Z,q),B=V.map((j)=>` ${j.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${j.path}`).join(`
13
+ `);return{ok:!0,title:`${W}/${X}/${Z}`,content:`[Directory: ${Z}]
14
+
15
+ Files:
16
+ ${B}`,tree:V}}return{ok:!1,error:"Unsupported GitHub URL type"}}catch(q){return{ok:!1,error:q.message}}}var V0;var j0=U(()=>{V0={"user-agent":"GreedySearch/1.0",accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});function Y0($){try{let Q=new URL($),W=Q.hostname.toLowerCase();if(!(W==="reddit.com"||W.endsWith(".reddit.com")))return null;let X=Q.pathname;if(X.match(/^\/(u|user)\/[^/]+\/?$/i))return{type:"user",cleanUrl:H0($)};if(X.match(/^\/r\/[^/]+\/comments\/[^/]+/i))return{type:"post",cleanUrl:H0($)};return null}catch{return null}}function H0($){try{let Q=new URL($);return`${Q.protocol}//${Q.hostname}${Q.pathname}`}catch{return $}}async function N0($,Q=8000){let W=Date.now();try{let X=$.replace(/\/+$/,"")+".json",J=new AbortController,K=setTimeout(()=>J.abort(),15000),Z=await fetch(X,{headers:Z1,signal:J.signal});if(clearTimeout(K),!Z.ok)throw Error(`Reddit API ${Z.status}`);let q=await Z.json();if(!Array.isArray(q)||q.length<1)throw Error("Invalid Reddit API response structure");let V=q[0],B=q[1],j=V?.data?.children?.[0]?.data;if(!j)throw Error("No post data in Reddit response");let H=K1(j,B,Q);return{ok:!0,url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:j.title||"Reddit Post",byline:`u/${j.author}`,siteName:`r/${j.subreddit}`,lang:"en",publishedTime:new Date(j.created_utc*1000).toISOString(),excerpt:j.selftext?.slice(0,300).replace(/\n/g," ")||"",markdown:H,contentLength:H.length,needsBrowser:!1,duration:Date.now()-W}}catch(X){return{ok:!1,url:$,finalUrl:$,status:0,error:`Reddit fetch failed: ${X.message}`,needsBrowser:!1,duration:Date.now()-W}}}function K1($,Q,W){let X="";if(X+=`# ${$.title}
17
+
18
+ `,X+=`**Subreddit:** r/${$.subreddit} | **Author:** u/${$.author} | **Score:** ${$.score}
19
+
20
+ `,$.selftext)X+=$.selftext,X+=`
21
+
22
+ `;else if($.url)try{let J=new URL($.url).hostname.toLowerCase();if(J!=="reddit.com"&&!J.endsWith(".reddit.com"))X+=`**Link:** ${$.url}
23
+
24
+ `}catch{X+=`**Link:** ${$.url}
25
+
26
+ `}if(Q?.data?.children?.length>0){X+=`---
27
+
28
+ ## Comments
29
+
30
+ `;let J=Q.data.children.filter((K)=>K.kind==="t1").slice(0,10);for(let K of J)X+=z0(K.data,0),X+=`
31
+ `}if(X.length>W)X=X.slice(0,W).trim()+`
32
+
33
+ ... (truncated)`;return X}function z0($,Q){if(!$||$.body==="[deleted]"||$.body==="[removed]")return"";let W="> ".repeat(Q),X="";if(X+=`${W}**u/${$.author}** (${$.score} pts)
34
+ `,X+=`${W}${$.body.replaceAll(`
35
+ `,`
36
+ `+W)}
37
+ `,Q<3&&$.replies?.data?.children){let J=$.replies.data.children.filter((K)=>K.kind==="t1");for(let K of J.slice(0,5))X+=`
38
+ `+z0(K.data,Q+1)}return X}var Z1;var M0=U(()=>{Z1={"user-agent":"GreedySearch/1.0 (Research Bot)",accept:"application/json"}});function F($,Q=8000){if(!$||$.length<=Q)return $;let W=`
39
+
40
+ [...content trimmed...]
41
+
42
+ `,X=Q-W.length,J=Math.floor(X*0.75),K=X-J,Z=J;while(Z>J-100&&$[Z]!==`
43
+ `)Z--;if(Z<=J-100)Z=J;let q=$.length-K;while(q<$.length-K+100&&$[q]!==`
44
+ `)q++;if(q>=$.length-K+100)q=$.length-K;let V=$.slice(0,Z).trimEnd(),B=$.slice(q).trimStart();return`${V}${W}${B}`}import{spawn as q1}from"node:child_process";import{dirname as V1,join as B1}from"node:path";import{fileURLToPath as j1}from"node:url";function z1($){if(!Array.isArray($)||$.length===0)throw Error("cdp: args must be a non-empty array");if($[0]==="test")return $.map((Q,W)=>A0(Q,W));if(!N1.has($[0]))throw Error(`cdp: unknown subcommand '${$[0]}'`);return $.map((Q,W)=>A0(Q,W))}function A0($,Q){if(typeof $!=="string")throw Error(`cdp: argv[${Q}] must be a string (got ${typeof $})`);if($.includes("\x00"))throw Error(`cdp: argv[${Q}] contains a null byte`);return $}function c($,Q=30000){return M1($,null,Q)}function M1($,Q=null,W=30000){let X=z1($);return new Promise((J,K)=>{let Z=q1(v(),[Y1,...X],{stdio:[Q==null?"ignore":"pipe","pipe","pipe"]});if(Q!=null)Z.stdin.write(Q),Z.stdin.end();let q="",V="";Z.stdout.on("data",(j)=>q+=j),Z.stderr.on("data",(j)=>V+=j);let B=setTimeout(()=>{Z.kill(),K(Error(`cdp timeout: ${$[0]}`))},W);Z.on("close",(j)=>{if(clearTimeout(B),j===0)J(q.trim());else K(Error(V.trim()||`cdp exit ${j}`))})})}async function i($){await c(["evalraw",$,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
45
+ (function() {
46
+ // ── Runtime.enable / CDP detection masking ──────────────
47
+ try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
48
+ try { delete window.__REBROWSER_DEVTOOLS; } catch(_) {}
49
+ try { delete window.__nightmare; } catch(_) {}
50
+ try { delete window.__phantom; } catch(_) {}
51
+ try { delete window.callPhantom; } catch(_) {}
52
+ try { delete window._phantom; } catch(_) {}
53
+ try { delete window.Buffer; } catch(_) {}
54
+
55
+ // Real Chrome without automation should not expose navigator.webdriver at all.
56
+ // A literal false or an own-property getter returning undefined is itself a
57
+ // common stealth tell; remove both instance and prototype properties when the
58
+ // descriptor is configurable (as it is with --disable-blink-features).
59
+ try { delete navigator.webdriver; } catch(_) {}
60
+ try { delete Navigator.prototype.webdriver; } catch(_) {}
61
+ Object.defineProperty(navigator, 'vendor', { get: () => 'Google Inc.', configurable: true });
62
+ Object.defineProperty(navigator, 'platform', { get: () => 'Win32', configurable: true });
63
+ Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0, configurable: true });
64
+ Object.defineProperty(navigator, 'pdfViewerEnabled', { get: () => true, configurable: true });
65
+ Object.defineProperty(navigator, 'productSub', { get: () => '20030107', configurable: true });
66
+ Object.defineProperty(navigator, 'product', { get: () => 'Gecko', configurable: true });
67
+ var __greedyMimeTypes = null;
68
+ function __makeMimeTypes() {
69
+ var pdf = { type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null };
70
+ var textPdf = { type: 'text/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null };
71
+ try { Object.setPrototypeOf(pdf, MimeType.prototype); } catch(_) {}
72
+ try { Object.setPrototypeOf(textPdf, MimeType.prototype); } catch(_) {}
73
+ var m = [pdf, textPdf];
74
+ try { Object.setPrototypeOf(m, MimeTypeArray.prototype); } catch(_) {}
75
+ m.item = function item(i) { return this[i] || null; };
76
+ m.namedItem = function namedItem(name) { return Array.prototype.find.call(this, function(x) { return x && x.type === name; }) || null; };
77
+ return m;
78
+ }
79
+ Object.defineProperty(navigator, 'plugins', {
80
+ get: () => {
81
+ __greedyMimeTypes = __greedyMimeTypes || __makeMimeTypes();
82
+ var plugin0 = { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format' };
83
+ var plugin1 = { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '' };
84
+ var plugin2 = { name: 'Native Client', filename: 'internal-nacl-plugin', description: '' };
85
+ try { Object.setPrototypeOf(plugin0, Plugin.prototype); } catch(_) {}
86
+ try { Object.setPrototypeOf(plugin1, Plugin.prototype); } catch(_) {}
87
+ try { Object.setPrototypeOf(plugin2, Plugin.prototype); } catch(_) {}
88
+ var p = [plugin0, plugin1, plugin2];
89
+ p.item = function item(i) { return this[i] || null; };
90
+ p.namedItem = function namedItem(name) { return Array.prototype.find.call(this, function(x) { return x && x.name === name; }) || null; };
91
+ p.refresh = function refresh() {};
92
+ try { Object.setPrototypeOf(p, PluginArray.prototype); } catch(_) {}
93
+ try {
94
+ __greedyMimeTypes[0].enabledPlugin = p[0];
95
+ __greedyMimeTypes[1].enabledPlugin = p[0];
96
+ } catch(_) {}
97
+ return p;
98
+ },
99
+ configurable: true,
100
+ });
101
+ Object.defineProperty(navigator, 'mimeTypes', {
102
+ get: () => {
103
+ __greedyMimeTypes = __greedyMimeTypes || __makeMimeTypes();
104
+ return __greedyMimeTypes;
105
+ },
106
+ configurable: true,
107
+ });
108
+ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'], configurable: true });
109
+ try {
110
+ Object.defineProperty(navigator, 'connection', { get: () => ({ effectiveType: '4g', rtt: 50, downlink: 10, downlinkMax: Infinity, saveData: false }), configurable: true });
111
+ } catch(_) {}
112
+ if (!navigator.mediaDevices) {
113
+ Object.defineProperty(navigator, 'mediaDevices', {
114
+ get: () => ({
115
+ enumerateDevices: () => Promise.resolve([
116
+ { deviceId: 'default', kind: 'audioinput', label: '', groupId: 'default' },
117
+ { deviceId: 'default', kind: 'audiooutput', label: '', groupId: 'default' },
118
+ { deviceId: '', kind: 'videoinput', label: '', groupId: '' },
119
+ ]),
120
+ getUserMedia: () => Promise.reject(new DOMException('NotAllowedError')),
121
+ getDisplayMedia: () => Promise.reject(new DOMException('NotAllowedError')),
122
+ }),
123
+ configurable: true,
124
+ });
125
+ }
126
+ // ── Missing platform APIs (headless often lacks these) ─
127
+ try {
128
+ if (!navigator.share) {
129
+ navigator.share = function() { return Promise.reject(new Error('NotAllowedError')); };
130
+ }
131
+ } catch(_) {}
132
+ try {
133
+ if (!navigator.contentIndex) {
134
+ Object.defineProperty(navigator, 'contentIndex', { get: () => ({ add: function() {}, delete: function() {}, getAll: function() { return Promise.resolve([]); } }), configurable: true });
135
+ }
136
+ } catch(_) {}
137
+
138
+ if (!window.chrome) {
139
+ window.chrome = {
140
+ app: { isInstalled: false, InstallState: {}, RunningState: {} },
141
+ runtime: {
142
+ OnInstalledReason: {}, OnRestartRequiredReason: {}, PlatformArch: {}, PlatformNaclArch: {}, PlatformOs: {}, RequestUpdateCheckStatus: {},
143
+ connect: () => ({}), sendMessage: () => {}, onMessage: { addListener: () => {} }
144
+ },
145
+ loadTimes: function() { return { requestTime: 0, startLoadTime: Date.now() - 5000, commitLoadTime: Date.now() - 3000, finishDocumentLoadTime: Date.now() - 2000, finishLoadTime: Date.now() - 1000, firstPaintTime: Date.now() - 800, navigationType: 'Other', wasFetchedViaSpdy: true, wasNpnNegotiated: true, npnNegotiatedProtocol: 'h2', wasAlternateProtocolAvailable: false, connectionInfo: 'http/2' }; },
146
+ csi: function() { var t = Date.now(); return { onloadT: t - 2000, startE: t - 5000, pageT: 'back', tran: 2 }; },
147
+ };
148
+ }
149
+ var __greedyNativeFns = [];
150
+ function __markNative(fn) { try { __greedyNativeFns.push(fn); } catch(_) {} return fn; }
151
+
152
+ var origQuery = navigator.permissions?.query;
153
+ if (origQuery) {
154
+ navigator.permissions.query = __markNative(function query(params) {
155
+ if (params && params.name === 'notifications') return Promise.resolve({ state: Notification.permission || 'default', onchange: null });
156
+ return origQuery.apply(this, arguments);
157
+ });
158
+ }
159
+ try {
160
+ var getParam = WebGLRenderingContext.prototype.getParameter;
161
+ WebGLRenderingContext.prototype.getParameter = __markNative(function getParameter(p) {
162
+ if (p === 37445) return 'Intel Inc.';
163
+ if (p === 37446) return 'Intel Iris OpenGL Engine';
164
+ return getParam.call(this, p);
165
+ });
166
+ } catch(_) {}
167
+ // ── WebGL readPixels noise ──────────────────────────
168
+ // CreepJS and other fingerprinters draw content with WebGL and read back the
169
+ // rendered pixels. Adding subtle noise breaks rendering-based fingerprinting.
170
+ try {
171
+ var origReadPixels = WebGLRenderingContext.prototype.readPixels;
172
+ WebGLRenderingContext.prototype.readPixels = __markNative(function readPixels(x, y, width, height, format, type, pixels) {
173
+ var result = origReadPixels.call(this, x, y, width, height, format, type, pixels);
174
+ if (pixels && pixels.length > 0) {
175
+ pixels[0] ^= 1;
176
+ }
177
+ return result;
178
+ });
179
+ } catch(_) {}
180
+ Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 8, configurable: true });
181
+ Object.defineProperty(navigator, 'deviceMemory', { get: () => 8, configurable: true });
182
+
183
+ // ── Canvas fingerprint noise ─────────────────────────
184
+ // Headless rendering engines produce slightly different canvas output
185
+ // than headed Chrome. Subtle noise breaks hash-based fingerprinting.
186
+ try {
187
+ var __canvasNoise = ((Date.now() & 0xFF) | 1);
188
+ var origFill = CanvasRenderingContext2D.prototype.fillText;
189
+ CanvasRenderingContext2D.prototype.fillText = __markNative(function fillText() {
190
+ this.globalAlpha = 0.9995;
191
+ return origFill.apply(this, arguments);
192
+ });
193
+ } catch(_) {}
194
+ try {
195
+ var origStroke = CanvasRenderingContext2D.prototype.strokeText;
196
+ CanvasRenderingContext2D.prototype.strokeText = __markNative(function strokeText() {
197
+ this.globalAlpha = 0.9995;
198
+ return origStroke.apply(this, arguments);
199
+ });
200
+ } catch(_) {}
201
+ try {
202
+ var origToDataURL = HTMLCanvasElement.prototype.toDataURL;
203
+ HTMLCanvasElement.prototype.toDataURL = __markNative(function toDataURL() {
204
+ var ctx = this.getContext('2d');
205
+ if (ctx) {
206
+ // Spread noise across canvas to break hash-based fingerprinting.
207
+ // Uses a deterministic pattern so it's consistent per page load
208
+ // but varies between sessions.
209
+ var w = this.width, h = this.height;
210
+ if (w > 0 && h > 0) {
211
+ var imgData = ctx.getImageData(0, 0, Math.min(w, 4), Math.min(h, 4));
212
+ if (imgData && imgData.data) {
213
+ for (var __i = 0; __i < imgData.data.length; __i += 4) {
214
+ imgData.data[__i] ^= (__canvasNoise + __i) & 0xFF;
215
+ }
216
+ ctx.putImageData(imgData, 0, 0);
217
+ }
218
+ }
219
+ }
220
+ return origToDataURL.apply(this, arguments);
221
+ });
222
+ } catch(_) {}
223
+
224
+ // ── AudioContext fingerprint noise ────────────────────
225
+ // Headless Chrome's AudioContext produces slightly different output.
226
+ // Subtle noise breaks audio-based fingerprinting.
227
+ try {
228
+ var __audioSeed = ((Date.now() & 0x1F) | 1);
229
+ var origGetChannelData = AudioBuffer.prototype.getChannelData;
230
+ AudioBuffer.prototype.getChannelData = __markNative(function getChannelData(channel) {
231
+ var data = origGetChannelData.call(this, channel);
232
+ for (var __i = 0; __i < data.length; __i += 64) {
233
+ data[__i] *= 0.99999;
234
+ }
235
+ return data;
236
+ });
237
+ } catch(_) {}
238
+
239
+ // ── window outer dimensions ──────────────────────────
240
+ // outerWidth/Height = 0 in headless — a well-known bot signal.
241
+ // Mirror innerWidth/Height (set by --window-size flag) so the ratio is sane.
242
+ try {
243
+ if (!window.outerWidth) Object.defineProperty(window, 'outerWidth', { get: () => window.innerWidth || 1920, configurable: true });
244
+ if (!window.outerHeight) Object.defineProperty(window, 'outerHeight', { get: () => window.innerHeight || 1080, configurable: true });
245
+ } catch(_) {}
246
+
247
+ // ── screen properties ─────────────────────────────────
248
+ // Headless Chrome often reports an 800x600 screen even when the viewport is
249
+ // 1920x1080. Keep screen metrics internally consistent with our launch flags.
250
+ try {
251
+ Object.defineProperty(screen, 'width', { get: () => 1920, configurable: true });
252
+ Object.defineProperty(screen, 'height', { get: () => 1080, configurable: true });
253
+ Object.defineProperty(screen, 'availWidth', { get: () => 1920, configurable: true });
254
+ Object.defineProperty(screen, 'availHeight', { get: () => 1040, configurable: true });
255
+ Object.defineProperty(screen, 'colorDepth', { get: () => 24, configurable: true });
256
+ Object.defineProperty(screen, 'pixelDepth', { get: () => 24, configurable: true });
257
+ } catch(_) {}
258
+
259
+ // ── navigator.userAgentData (UA Client Hints) ─────────
260
+ // Derive version from the UA string already set by --user-agent flag so the
261
+ // two APIs are always consistent. Removes any "HeadlessChrome" brand entry.
262
+ try {
263
+ var _uaMajor = (navigator.userAgent.match(new RegExp('Chrome/([0-9]+)')) || [])[1] || '136';
264
+ var _uaFull = (navigator.userAgent.match(new RegExp('Chrome/([0-9.]+)')) || [])[1] || (_uaMajor + '.0.0.0');
265
+ var _brands = [
266
+ { brand: 'Not)A;Brand', version: '99' },
267
+ { brand: 'Google Chrome', version: _uaMajor },
268
+ { brand: 'Chromium', version: _uaMajor },
269
+ ];
270
+ Object.defineProperty(navigator, 'userAgentData', {
271
+ get: function() {
272
+ return {
273
+ brands: _brands, mobile: false, platform: 'Windows',
274
+ getHighEntropyValues: function() {
275
+ return Promise.resolve({
276
+ architecture: 'x86', bitness: '64',
277
+ brands: _brands,
278
+ fullVersionList: [
279
+ { brand: 'Not)A;Brand', version: '99.0.0.0' },
280
+ { brand: 'Google Chrome', version: _uaFull },
281
+ { brand: 'Chromium', version: _uaFull },
282
+ ],
283
+ mobile: false, model: '', platform: 'Windows',
284
+ platformVersion: '15.0.0', uaFullVersion: _uaFull, wow64: false,
285
+ });
286
+ },
287
+ toJSON: function() { return { brands: _brands, mobile: false, platform: 'Windows' }; },
288
+ };
289
+ },
290
+ configurable: true,
291
+ });
292
+ } catch(_) {}
293
+
294
+ // ── CDP Runtime serialization guard ──────────────────
295
+ // Sites detect CDP by putting a getter on Error.prototype.stack
296
+ // and checking if console.log triggers it (only happens when
297
+ // Runtime domain is enabled). We monkey-patch console methods to
298
+ // strip custom getters from arguments before they reach CDP.
299
+ try {
300
+ var _origLog = console.log, _origError = console.error,
301
+ _origWarn = console.warn, _origDebug = console.debug,
302
+ _origInfo = console.info;
303
+ var _safeArg = function(a) {
304
+ if (a instanceof Error) {
305
+ try { return new Error(a.message); } catch(_) { return a; }
306
+ }
307
+ return a;
308
+ };
309
+ console.log = __markNative(function log() { return _origLog.apply(console, Array.prototype.map.call(arguments, _safeArg)); });
310
+ console.error = __markNative(function error() { return _origError.apply(console, Array.prototype.map.call(arguments, _safeArg)); });
311
+ console.warn = __markNative(function warn() { return _origWarn.apply(console, Array.prototype.map.call(arguments, _safeArg)); });
312
+ console.debug = __markNative(function debug() { return _origDebug.apply(console, Array.prototype.map.call(arguments, _safeArg)); });
313
+ console.info = __markNative(function info() { return _origInfo.apply(console, Array.prototype.map.call(arguments, _safeArg)); });
314
+ } catch(_) {}
315
+
316
+ // ── Native function masking ──────────────────────────
317
+ // Patched APIs should not stringify as user-defined stealth code.
318
+ try {
319
+ var __nativeToString = Function.prototype.toString;
320
+ Function.prototype.toString = function toString() {
321
+ if (__greedyNativeFns.indexOf(this) !== -1) {
322
+ var name = this.name || '';
323
+ return 'function ' + name + '() { [native code] }';
324
+ }
325
+ return __nativeToString.call(this);
326
+ };
327
+ } catch(_) {}
328
+ })();
329
+ `})])}var H1,Y1,N1;var G0=U(()=>{L();H1=V1(j1(import.meta.url)),Y1=B1(H1,"..","bin","cdp.mjs"),N1=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"])});var I=()=>{};var O0=U(()=>{I()});import{existsSync as _,mkdirSync as A1,readFileSync as D0,writeFileSync as G1}from"node:fs";import{homedir as U1}from"node:os";import{join as b0}from"node:path";import{tmpdir as O1}from"node:os";function k1($,Q=9222){let W=Number.parseInt(String($??""),10);return Number.isInteger(W)&&W>1024&&W<65535?W:Q}function T1(){try{if(_(b)){let $=D0(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((J)=>d[J]),X=Q.engines.filter((J)=>!d[J]);if(X.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${b}: ${X.join(", ")}
330
+ [greedysearch] Available engines: ${Object.keys(d).join(", ")}
331
+ `);if(W.length>0)return W;process.stderr.write(`[greedysearch] Warning: no valid engines in ${b}, falling back to defaults: ${n.join(", ")}
332
+ `)}}}catch{}return n}function P1(){try{if(!_(l))A1(l,{recursive:!0});if(!_(b))G1(b,JSON.stringify({engines:n,synthesizer:o},null,2)+`
333
+ `,"utf8")}catch{}}function L1(){try{if(_(b)){let $=D0(b,"utf8"),Q=JSON.parse($);if(typeof Q.synthesizer==="string"){let W=Q.synthesizer.toLowerCase();if(k0.includes(W))return W;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${Q.synthesizer}" in ${b}
334
+ [greedysearch] Available synthesizers: ${k0.join(", ")}
335
+ [greedysearch] Falling back to default: ${o}
336
+ `)}}}catch{}return o}var D1,F0,O,b1,v0,F1,w0,v1,w1,T0,F$,v$,l,b,n,o="gemini",k0,d,w$,T$,s;var x=U(()=>{D1=O1().replaceAll("\\","/"),F0=k1(process.env.GREEDY_SEARCH_PORT),O=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${D1}/greedysearch-chrome-profile`).replaceAll("\\","/"),b1=`${O}/DevToolsActivePort`,v0=process.env.GREEDY_SEARCH_PID_FILE||`${O}/browser.pid`,F1=process.env.CDP_PAGES_CACHE||`${O}/cdp-pages.json`,w0=process.env.GREEDY_SEARCH_MODE_FILE||`${O}/browser-mode`,v1=process.env.GREEDY_SEARCH_METADATA_FILE||`${O}/browser-metadata.json`,w1=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${O}/browser-launch.lock`,T0=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${O}/browser-last-activity`,F$=(process.env.CDP_SOCKET_DIR||`${O}/cdp-sockets`).replaceAll("\\","/"),v$=`${O}/visible-recovery.jsonl`,l=b0(U1(),".dm"),b=b0(l,"greedyconfig"),n=["perplexity","google","chatgpt","gemini"];P1();k0=["gemini","chatgpt"];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"},w$=T1(),T$=L1(),s=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=O});var C$;var P0=U(()=>{x();I();C$=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5});async function L0(){let Q=(await M(["list"])).split(`
337
+ `)[0];if(!Q)throw Error("No Chrome tabs found");return Q.slice(0,8)}async function f($="about:blank"){let Q=await L0(),W=new URL($).hostname;if(W==="copilot.microsoft.com"||W==="www.perplexity.ai"||W==="perplexity.ai"||W.endsWith(".perplexity.ai")){let Z=await M(["evalraw",Q,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:q}=JSON.parse(Z),V=q.slice(0,8);if(await M(["list"]).catch(()=>null),W==="copilot.microsoft.com")await i(V);else i(V).catch(()=>{});return await M(["list"]).catch(()=>null),q}let J=await M(["evalraw",Q,"Target.createTarget",JSON.stringify({url:$})]),{targetId:K}=JSON.parse(J);return await M(["list"]).catch(()=>null),K}async function R($){try{let Q=await L0();await M(["evalraw",Q,"Target.closeTarget",JSON.stringify({targetId:$})])}catch{}}var i$,d$,l$,M;var y0=U(()=>{L();G0();I();O0();x();P0();i$=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),d$=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,l$=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60,M=c});function y1(){if(typeof globalThis.DOMMatrix>"u")globalThis.DOMMatrix=class{constructor(Q=void 0){}multiplySelf(){return this}preMultiplySelf(){return this}translateSelf(){return this}scaleSelf(){return this}rotateSelf(){return this}};if(typeof globalThis.ImageData>"u")globalThis.ImageData=class{constructor(Q=void 0,W=0,X=0){this.data=Q,this.width=W,this.height=X}};if(typeof globalThis.Path2D>"u")globalThis.Path2D=class{constructor(Q=void 0){}}}async function C1(){y1();let $=await import("pdf-parse"),Q=$.PDFParse??$.default;if(!Q)throw Error("pdf-parse did not export PDFParse");return Q}async function C0($,Q){try{let X=new(await C1())({data:new Uint8Array($)});await X.load();let J=await X.getText(),K=J.text?.trim();if(!K)return null;return{title:new URL(Q).pathname.split("/").pop()||"Document.pdf",content:`## PDF Content (${J.total} pages)
338
+
339
+ ${K}`,pages:J.total}}catch(W){return{error:W.message||String(W)}}}function a($="",Q=240){let W=String($).replaceAll(/\s+/g," ").trim();if(W.length<=Q)return W;let X=W.slice(0,Q),J=X.lastIndexOf(" ");return J>0?`${X.slice(0,J)}...`:`${X}...`}var S0=()=>{};var f0={};m0(f0,{fetchTopSource:()=>f1,fetchSourceContent:()=>_0,fetchMultipleSources:()=>x1});async function S1($,Q,W=8000){let X=Date.now();try{let K=(await M(["evalraw",$,"Page.getFrameTree","{}"]).then((A)=>JSON.parse(A)).catch(()=>null))?.frameTree?.frame?.id||void 0,Z=await M(["evalraw",$,"Network.loadNetworkResource",JSON.stringify({frameId:K,url:Q,options:{disableCache:!0,includeCredentials:!1}})],20000),V=JSON.parse(Z).resource;if(!V?.success||!V.httpStatusCode)return{url:Q,error:V?.netErrorName||V?.netError||"loadNetworkResource failed",source:"chrome",duration:Date.now()-X,needsFallback:!0};let B="";if(V.stream)try{let A=await M(["evalraw",$,"IO.read",JSON.stringify({handle:V.stream})],1e4);B=JSON.parse(A).data||"",await M(["evalraw",$,"IO.close",JSON.stringify({handle:V.stream})]).catch(()=>{})}catch{}if(!B||B.length<100)return{url:Q,error:"Empty response body from Network.loadNetworkResource",source:"chrome",duration:Date.now()-X,needsFallback:!0};let j=h(V.httpStatusCode,B,Q,Q);if(j.blocked)return{url:Q,status:V.httpStatusCode,error:`Blocked: ${j.reason}`,source:"chrome",duration:Date.now()-X,needsBrowser:!0};let H=await p(B,Q),Y=u(H);if(!Y.ok)return{url:Q,status:V.httpStatusCode,error:`Low quality: ${Y.reason}`,source:"chrome",duration:Date.now()-X,needsBrowser:!0};let N=F(H.markdown,W);return{url:Q,finalUrl:Q,status:V.httpStatusCode,contentType:"text/markdown",lastModified:"",publishedTime:H.publishedTime||"",byline:H.byline||"",siteName:H.siteName||"",lang:H.lang||"",title:H.title||Q,snippet:H.excerpt,content:N,contentChars:N.length,source:"chrome",duration:Date.now()-X}}catch(J){return{url:Q,error:J.message,source:"chrome",duration:Date.now()-X,needsFallback:!0}}}function I0($){try{return new URL($).pathname.toLowerCase().endsWith(".pdf")}catch{return!1}}async function I1($,Q=8000){let W=C($);if(W.blocked)return{url:$,finalUrl:$,status:403,error:`Blocked: ${W.reason}`,source:"pdf-http"};let X=new AbortController,J=setTimeout(()=>X.abort(),20000),K=Date.now();try{let Z=await fetch($,{method:"GET",redirect:"follow",signal:X.signal,headers:J0({accept:"application/pdf,application/octet-stream;q=0.9,*/*;q=0.5"})});clearTimeout(J);let q=Z.headers.get("content-type")||"",V=Z.url||$,B=Number.parseInt(Z.headers.get("content-length")||"0",10);if(Z.status>=400)return{url:$,finalUrl:V,status:Z.status,error:`HTTP ${Z.status}`,source:"pdf-http",duration:Date.now()-K};if(!q.toLowerCase().includes("application/pdf")&&!I0(V))return null;if(B>31457280)return{url:$,finalUrl:V,status:Z.status,error:`PDF too large: ${B} bytes`,source:"pdf-http",duration:Date.now()-K};let j=Buffer.from(await Z.arrayBuffer()),H=await C0(j,V);if(!H||H.error)return{url:$,finalUrl:V,status:Z.status,error:H?.error||"PDF text extraction failed",source:"pdf-http",duration:Date.now()-K};let Y=F(H.content,Q);return{url:$,finalUrl:V,status:Z.status,contentType:"application/pdf",lastModified:Z.headers.get("last-modified")||"",title:H.title,snippet:a(Y,320),content:Y,contentChars:Y.length,pages:H.pages,source:"pdf-http",duration:Date.now()-K}}catch(Z){return clearTimeout(J),{url:$,finalUrl:$,error:Z.message||String(Z),source:"pdf-http",duration:Date.now()-K}}}async function _0($,Q=8000){let W=Date.now();if(I0($)){let K=await I1($,Q);if(K?.content||K?.status===403)return K}if(S($)){let K=S($);if(K&&(K.type==="root"||K.type==="tree"||K.type==="blob"&&!K.path?.includes("."))){let Z=await B0($);if(Z.ok){let q=F(Z.content,Q);return{url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:Z.title,snippet:q.slice(0,320),content:q,contentChars:q.length,source:"github-api",...Z.tree&&{tree:Z.tree},duration:Date.now()-W}}process.stderr.write(`[greedysearch] GitHub API fetch failed, trying HTTP: ${Z.error}
340
+ `)}}if(Y0($)?.type==="post"){process.stderr.write(`[greedysearch] Using Reddit JSON API for: ${$.slice(0,60)}...
341
+ `);let K=await N0($,Q);if(K.ok){let Z=F(K.markdown,Q);return{url:$,finalUrl:K.finalUrl,status:K.status,contentType:"text/markdown",lastModified:K.lastModified||"",publishedTime:K.publishedTime||"",byline:K.byline||"",siteName:K.siteName||"",lang:K.lang||"",title:K.title,snippet:K.excerpt,content:Z,contentChars:Z.length,source:"reddit-api",duration:Date.now()-W}}process.stderr.write(`[greedysearch] Reddit API fetch failed, falling back to HTTP: ${K.error}
342
+ `)}let J=await Z0($,{timeoutMs:1e4});if(J.ok){let K=F(J.markdown,Q);return{url:$,finalUrl:J.finalUrl,status:J.status,contentType:"text/markdown",lastModified:J.lastModified||"",publishedTime:J.publishedTime||"",byline:J.byline||"",siteName:J.siteName||"",lang:J.lang||"",title:J.title,snippet:J.excerpt,content:K,contentChars:K.length,source:"http",duration:Date.now()-W}}if(J.needsBrowser)try{let K=await f();try{let Z=await S1(K,$,Q);if(Z.content&&Z.content.length>100)return Z}finally{await R(K)}}catch{}return process.stderr.write(`[greedysearch] HTTP failed for ${$.slice(0,60)}, trying browser...
343
+ `),await _1($,Q)}async function x0($,Q=4000,W=200){let X=Date.now()+Q;while(Date.now()<X){try{if((await M(["eval",$,'document.readyState === "complete" && !!document.body && document.body.innerText.length > 500'])).trim()==="true")return}catch{}await new Promise((J)=>setTimeout(J,W))}}async function _1($,Q=8000){let W=Date.now(),X;try{X=await f()}catch(J){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:`openNewTab failed: ${J.message}`,source:"browser",duration:Date.now()-W}}try{await M(["nav",X,$],30000),await x0(X);let J=await M(["eval",X,String.raw`
344
+ (function(){
345
+ var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
346
+ var text = (el || document.body).innerText;
347
+ return JSON.stringify({
348
+ title: document.title,
349
+ content: text.replace(/\s+/g, ' ').trim(),
350
+ url: location.href
351
+ });
352
+ })()
353
+ `]),K=JSON.parse(J),Z=F(K.content,Q);return{url:$,finalUrl:K.url||$,status:200,contentType:"text/plain",lastModified:"",title:K.title,snippet:a(Z,320),content:Z,contentChars:Z.length,source:"browser",duration:Date.now()-W}}catch(J){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:J.message,source:"browser",duration:Date.now()-W}}finally{await R(X)}}async function x1($,Q=5,W=8000,X=s){let J=$.slice(0,Q);if(J.length===0)return[];let K=Math.min(J.length,Math.max(1,Number.parseInt(String(X),10)||s));process.stderr.write(`[greedysearch] Fetching content from ${J.length} sources via HTTP (concurrency ${K})...
354
+ `);let Z=Array(J.length),q=0,V=0;async function B(){while(!0){let N=q++;if(N>=J.length)return;let A=J[N],G=A.canonicalUrl||A.url;process.stderr.write(`[greedysearch] [${N+1}/${J.length}] Fetching: ${G.slice(0,60)}...
355
+ `);let z=await _0(G,W).catch((k)=>({url:G,title:"",content:null,snippet:"",contentChars:0,error:k.message,source:"error",duration:0}));if(Z[N]={id:A.id,...z},z.content&&z.content.length>100)process.stderr.write(`[greedysearch] ✓ ${z.source}: ${z.content.length} chars
356
+ `);else if(z.error)process.stderr.write(`[greedysearch] ✗ ${z.error.slice(0,80)}
357
+ `);V+=1,process.stderr.write(`PROGRESS:fetch:${V}/${J.length}
358
+ `)}}await Promise.all(Array.from({length:K},()=>B()));let j=Z.filter((N)=>N.content&&N.content.length>100),H=Z.filter((N)=>N.source==="http").length,Y=Z.filter((N)=>N.source==="browser").length;return process.stderr.write(`[greedysearch] Fetched ${j.length}/${Z.length} sources (HTTP: ${H}, Browser: ${Y})
359
+ `),Z}async function f1($){let Q=await f();try{await M(["nav",Q,$],30000),await x0(Q);let W=await M(["eval",Q,String.raw`
360
+ (function(){
361
+ var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
362
+ var text = (el || document.body).innerText;
363
+ return text.replace(/\s+/g, ' ').trim();
364
+ })()
365
+ `]);return{url:$,content:W}}catch(W){return{url:$,content:null,error:W.message}}finally{await R(Q)}}var R0=U(()=>{K0();j0();M0();y0();x();S0()});L();import{spawn as R1}from"node:child_process";import{createInterface as g1}from"node:readline";import{fileURLToPath as E1}from"node:url";import{dirname as h1,join as p1}from"node:path";var u1=h1(E1(import.meta.url)),g0=p1(u1,"search.mjs"),m1="2025-06-18",c1={name:"greedysearch",version:"1.0.0"},i1=360000;function g(...$){process.stderr.write(`[greedysearch-mcp] ${$.join(" ")}
366
+ `)}function E0($){process.stdout.write(`${JSON.stringify($)}
367
+ `)}function w($,Q){if($===void 0||$===null)return;E0({jsonrpc:"2.0",id:$,result:Q})}function E($,Q,W,X){if($===void 0||$===null)return;E0({jsonrpc:"2.0",id:$,error:{code:Q,message:W,...X?{data:X}:{}}})}var d1='Engine to use: "all" (default, fans out to configured engines and fetches top sources), "perplexity" (p), "google" (g), "chatgpt" (gpt), "gemini" (gem), "bing" (b). Research engines: "semantic-scholar" (s2) and "logically" (log).',l1={type:"object",properties:{query:{type:"string",description:"The search query"},engine:{type:"string",default:"all",description:d1},synthesize:{type:"boolean",default:!1,description:'Only for engine="all": synthesize the multi-engine results and fetched sources.'},synthesizer:{type:"string",description:'Synthesis engine for synthesize=true. Defaults to ~/.dm/greedyconfig synthesizer ("gemini" by default). Supported: "gemini", "chatgpt".'},depth:{type:"string",description:'Use "research" for the iterative research workflow. Legacy values: "fast" skips source fetching; "standard"/"deep" alias synthesize=true.'},breadth:{type:"number",default:3,description:'Only for depth="research": number of parallel research directions per round, 1-5.'},iterations:{type:"number",default:2,description:'Only for depth="research": number of iterative research rounds, 1-3.'},maxSources:{type:"number",description:'Only for depth="research": maximum fetched sources for the final report, 3-12.'},researchOutDir:{type:"string",description:'Only for depth="research": optional directory for the structured research bundle.'},writeResearchBundle:{type:"boolean",default:!0,description:'Only for depth="research": write the structured research bundle to disk.'},fullAnswer:{type:"boolean",default:!1,description:"When true, returns the complete answer instead of a truncated preview."},locale:{type:"string",description:'Force results language (e.g. "en", "de", "fr"). Defaults to GREEDY_SEARCH_LOCALE or "en".'},visible:{type:"boolean",default:!1,description:"Set to true to always use visible Chrome for this search (e.g. to solve a login/captcha challenge)."}},required:["query"]},n1={type:"object",properties:{url:{type:"string",description:"URL to fetch and extract content from"},maxChars:{type:"number",default:8000,description:"Maximum characters of extracted content to return."}},required:["url"]},o1=[{name:"greedy_search",description:"WEB/RESEARCH SEARCH ONLY — searches live web via Perplexity, Google AI, ChatGPT, and Gemini, "+'plus opt-in research through Semantic Scholar and Logically, using local headless Chrome automation (no API keys needed). Research mode (depth: "research") plans follow-up actions, fetches sources, audits citations, and writes a structured research bundle on disk. Searches take roughly 1-5 minutes.',inputSchema:l1},{name:"greedy_fetch",description:"Fetch a single URL and extract its readable content (title, byline, markdown body). Uses HTTP first, falling back to Chrome/browser rendering for JS-heavy or blocked pages.",inputSchema:n1}];function s1($){let Q=String($.engine??"all").trim()||"all",W=String($.depth??"").trim(),X=W==="research",J=W==="fast",K=W==="standard"||W==="deep",Z=Q==="all"&&!J&&($.synthesize===!0||K),q=X?"all":Q,V=$.visible===!0||process.env.GREEDY_SEARCH_VISIBLE==="1",B=[];if($.fullAnswer??q!=="all")B.push("--full");if(X){if(B.push("--depth","research"),typeof $.breadth==="number")B.push("--breadth",String($.breadth));if(typeof $.iterations==="number")B.push("--iterations",String($.iterations));if(typeof $.maxSources==="number")B.push("--max-sources",String($.maxSources));if(typeof $.researchOutDir==="string")B.push("--research-out-dir",$.researchOutDir);if($.writeResearchBundle===!1)B.push("--no-research-bundle")}else if(J)B.push("--fast");else if(W==="deep")B.push("--depth","deep");else if(Z)B.push("--synthesize");if(Z&&typeof $.synthesizer==="string")B.push("--synthesizer",$.synthesizer);if(typeof $.locale==="string"&&$.locale)B.push("--locale",$.locale);if(V)B.push("--always-visible");else B.push("--headless");return{engine:q,flags:B,visible:V}}function a1($,Q){return new Promise((W,X)=>{let{engine:J,flags:K,visible:Z}=s1(Q),q={...process.env};if(Z)q.GREEDY_SEARCH_VISIBLE="1",q.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let V=R1(v(),[g0,J,"--inline","--stdin",...K],{stdio:["pipe","pipe","pipe"],env:q});V.stdin.write($),V.stdin.end();let B="",j="",H=51200,Y=!1,N=parseInt(process.env.GREEDY_SEARCH_TIMEOUT_MS||"",10),A=Number.isNaN(N)?i1:N,G=setTimeout(()=>{if(Y)return;if(Y=!0,process.platform==="win32")V.kill();else V.kill("SIGTERM");X(Error(`greedy_search timed out after ${A}ms`))},A);G.unref(),V.stderr.on("data",(z)=>{if(j+=z,j.length>H)j=j.slice(-H);g(z.toString().trimEnd())}),V.stdout.on("data",(z)=>B+=z),V.on("error",(z)=>{if(Y)return;Y=!0,clearTimeout(G),X(z)}),V.on("close",(z)=>{if(Y)return;if(Y=!0,clearTimeout(G),z!==0){X(Error(j.trim()||`search.mjs exited with code ${z}`));return}try{W(JSON.parse(B.trim()))}catch{X(Error(`Invalid JSON from search.mjs: ${B.slice(0,200)}`))}})})}function r1($,Q){let W=[],X=Q._needsHumanVerification;if(X)W.push("## Manual verification required"),W.push(String(X.message||"Visible Chrome is open. Solve the verification challenge, then rerun the same search."));let J=Q._synthesis;if(J?.answer){W.push(String(J.answer));let Z=Array.isArray(Q._sources)?Q._sources:[];if(Z.length>0){W.push(`
368
+ Sources:`);for(let q of Z.slice(0,8))W.push(`- [${q.title||q.url}](${q.url})`)}return W.join(`
369
+ `).trim()}if(typeof Q.answer==="string"){W.push(Q.answer);let Z=Array.isArray(Q.sources)?Q.sources:[];if(Z.length>0){W.push(`
370
+ Sources:`);for(let q of Z.slice(0,8))W.push(`- [${q.title||q.url}](${q.url})`)}return W.join(`
371
+ `).trim()}let K=Object.keys(Q).filter((Z)=>!Z.startsWith("_")&&Q[Z]&&typeof Q[Z]==="object");for(let Z of K){let q=Q[Z];if(K.length>1)W.push(`
372
+ ## ${Z}`);if(q.error){W.push(`Error: ${q.error}`);continue}if(q.answer)W.push(String(q.answer));let V=Array.isArray(q.sources)?q.sources:[];if(V.length>0){W.push(`
373
+ Sources:`);for(let B of V.slice(0,5))W.push(`- [${B.title||B.url}](${B.url})`)}}return W.join(`
374
+ `).trim()||"No results returned."}async function t1($){if(!$||typeof $.query!=="string"||!$.query.trim())throw Error("query is required");let Q=await a1($.query,$);return{content:[{type:"text",text:r1($.engine??"all",Q)||"No results returned."},{type:"text",text:JSON.stringify(Q)}]}}var r;function e1(){if(!r)r=Promise.resolve().then(() => (R0(),f0)).then(($)=>$.fetchSourceContent);return r}async function $$($){if(!$||typeof $.url!=="string"||!$.url.trim())throw Error("url is required");let Q=typeof $.maxChars==="number"?$.maxChars:8000,X=await(await e1())($.url,Q);if(X?.error&&!X.content)return{content:[{type:"text",text:`Fetch failed: ${X.error}`}],isError:!0};return{content:[{type:"text",text:[`# ${X.title||$.url}`,"",X.byline?`By ${X.byline}`:null,X.siteName?`Source: ${X.siteName}`:null,"",X.content||"(no content extracted)"].filter((K)=>K!==null).join(`
375
+ `)},{type:"text",text:JSON.stringify(X)}]}}async function Q$($){let{id:Q,method:W,params:X}=$;switch(W){case"initialize":{let J=X?.protocolVersion;w(Q,{protocolVersion:typeof J==="string"?J:m1,capabilities:{tools:{}},serverInfo:c1});return}case"notifications/initialized":case"initialized":return;case"ping":w(Q,{});return;case"tools/list":w(Q,{tools:o1});return;case"tools/call":{let J=X?.name,K=X?.arguments??{};try{let Z;if(J==="greedy_search")Z=await t1(K);else if(J==="greedy_fetch")Z=await $$(K);else{E(Q,-32602,`Unknown tool: ${J}`);return}w(Q,Z)}catch(Z){w(Q,{content:[{type:"text",text:`Error: ${Z.message||String(Z)}`}],isError:!0})}return}default:if(W&&W.startsWith("notifications/"))return;E(Q,-32601,`Method not found: ${W}`)}}function W$(){let $=g1({input:process.stdin,terminal:!1});$.on("line",(Q)=>{let W=Q.trim();if(!W)return;let X;try{X=JSON.parse(W)}catch{E(null,-32700,"Parse error");return}Q$(X).catch((J)=>{g("Unhandled error:",J?.stack||String(J)),E(X?.id,-32603,"Internal error",String(J?.message||J))})}),$.on("close",()=>process.exit(0)),process.on("uncaughtException",(Q)=>{g("Uncaught exception:",Q?.stack||String(Q))}),g(`GreedySearch MCP server ready (${g0})`)}W$();