@duckmind/dm-darwin-x64 0.43.8 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +147 -218
  3. package/extensions/dm-9router-ext/package.json +0 -6
  4. package/extensions/dm-9router-ext/src/index.js +1 -1
  5. package/extensions/dm-ask-user/package.json +0 -4
  6. package/extensions/dm-caveman/LICENSE +21 -0
  7. package/extensions/dm-caveman/extensions/caveman.js +29 -0
  8. package/extensions/dm-caveman/package.json +20 -0
  9. package/extensions/dm-cli-anything/index.js +5 -5
  10. package/extensions/dm-cli-anything/package.json +0 -7
  11. package/extensions/dm-cli-anything/skills/cli-anything/SKILL.md +1 -3
  12. package/extensions/dm-context/package.json +0 -1
  13. package/extensions/dm-cua/package.json +0 -7
  14. package/extensions/dm-fff/package.json +0 -6
  15. package/extensions/dm-goal/package.json +0 -8
  16. package/extensions/dm-grill-me/index.js +2 -2
  17. package/extensions/dm-grill-me/package.json +0 -7
  18. package/extensions/dm-image2/package.json +0 -8
  19. package/extensions/dm-subagents/package.json +0 -11
  20. package/extensions/dm-tasks/package.json +0 -7
  21. package/extensions/dm-usage/package.json +0 -7
  22. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +1 -8
  23. package/extensions/greedysearch-dm/bin/gschrome.mjs +3 -3
  24. package/extensions/greedysearch-dm/bin/launch-visible.mjs +3 -3
  25. package/extensions/greedysearch-dm/bin/launch.mjs +4 -4
  26. package/extensions/greedysearch-dm/bin/search.mjs +106 -106
  27. package/extensions/greedysearch-dm/extractors/consensus.mjs +35 -35
  28. package/extensions/greedysearch-dm/extractors/gemini.mjs +38 -38
  29. package/extensions/greedysearch-dm/extractors/logically.mjs +35 -35
  30. package/extensions/greedysearch-dm/package.json +0 -10
  31. package/extensions/greedysearch-dm/src/search/chrome.mjs +23 -23
  32. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +35 -35
  33. package/extensions/greedysearch-dm/src/search/research.mjs +77 -77
  34. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +10 -10
  35. package/package.json +1 -1
  36. package/extensions/dm-9router-ext/README.md +0 -142
  37. package/extensions/dm-9router-ext/tsconfig.json +0 -17
  38. package/extensions/dm-ask-user/README.md +0 -226
  39. package/extensions/dm-cli-anything/README.md +0 -33
  40. package/extensions/dm-cli-anything/vendor/UPSTREAM.md +0 -14
  41. package/extensions/dm-context/AGENTS.md +0 -41
  42. package/extensions/dm-context/README.md +0 -18
  43. package/extensions/dm-context/tsconfig.json +0 -16
  44. package/extensions/dm-cua/README.md +0 -24
  45. package/extensions/dm-fff/README.md +0 -36
  46. package/extensions/dm-fff/tsconfig.json +0 -13
  47. package/extensions/dm-goal/CHANGELOG.md +0 -12
  48. package/extensions/dm-goal/README.md +0 -29
  49. package/extensions/dm-goal/tsconfig.json +0 -15
  50. package/extensions/dm-grill-me/DESIGN.md +0 -301
  51. package/extensions/dm-grill-me/README.md +0 -82
  52. package/extensions/dm-grill-me/tsconfig.json +0 -17
  53. package/extensions/dm-image2/README.md +0 -33
  54. package/extensions/dm-subagents/CHANGELOG.md +0 -1211
  55. package/extensions/dm-subagents/README.md +0 -29
  56. package/extensions/dm-subagents/biome.json +0 -26
  57. package/extensions/dm-subagents/tsconfig.json +0 -18
  58. package/extensions/dm-tasks/README.md +0 -30
  59. package/extensions/dm-tasks/biome.json +0 -26
  60. package/extensions/dm-tasks/tsconfig.json +0 -14
  61. package/extensions/dm-usage/README.md +0 -29
  62. package/extensions/greedysearch-dm/README.md +0 -222
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as i2}from"node:module";var u2=Object.defineProperty;var c2=($)=>$;function n2($,Z){this[$]=c2.bind(null,Z)}var y0=($,Z)=>{for(var X in Z)u2($,X,{get:Z[X],enumerable:!0,configurable:!0,set:n2.bind(Z,X)})};var c=($,Z)=>()=>($&&(Z=$($=0)),Z);var C1=i2(import.meta.url);import{basename as o2}from"node:path";function M0($=process.env,Z=process.execPath){let X=$.GREEDY_SEARCH_NODE||$.NODE_BINARY||$.NODE;if(X?.trim())return X.trim();let J=o2(Z||"").toLowerCase();if(J==="node"||J==="node.exe")return Z;return"node"}var h0=()=>{};import{spawn as a2}from"node:child_process";import{dirname as s2,join as t2}from"node:path";import{fileURLToPath as r2}from"node:url";function f$($,Z=30000){return Z8($,null,Z)}function Z8($,Z=null,X=30000){return new Promise((J,W)=>{let K=a2(M0(),[$8,...$],{stdio:[Z==null?"ignore":"pipe","pipe","pipe"]});if(Z!=null)K.stdin.write(Z),K.stdin.end();let V="",Y="";K.stdout.on("data",(Q)=>V+=Q),K.stderr.on("data",(Q)=>Y+=Q);let j=setTimeout(()=>{K.kill(),W(Error(`cdp timeout: ${$[0]}`))},X);K.on("close",(Q)=>{if(clearTimeout(j),Q===0)J(V.trim());else W(Error(Y.trim()||`cdp exit ${Q}`))})})}async function x$($){await f$(["evalraw",$,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
2
+ import{createRequire as u2}from"node:module";var m2=Object.defineProperty;var d2=($)=>$;function l2($,Z){this[$]=d2.bind(null,Z)}var p0=($,Z)=>{for(var X in Z)m2($,X,{get:Z[X],enumerable:!0,configurable:!0,set:l2.bind(Z,X)})};var c=($,Z)=>()=>($&&(Z=$($=0)),Z);var w1=u2(import.meta.url);import{basename as c2}from"node:path";function Z0($=process.env,Z=process.execPath){let X=$.GREEDY_SEARCH_NODE||$.NODE_BINARY||$.NODE;if(X?.trim())return X.trim();let J=c2(Z||"").toLowerCase();if(J==="node"||J==="node.exe")return Z;return"node"}var E0=()=>{};import{spawn as n2}from"node:child_process";import{dirname as i2,join as o2}from"node:path";import{fileURLToPath as a2}from"node:url";function x$($,Z=30000){return r2($,null,Z)}function r2($,Z=null,X=30000){return new Promise((J,W)=>{let K=n2(Z0(),[t2,...$],{stdio:[Z==null?"ignore":"pipe","pipe","pipe"]});if(Z!=null)K.stdin.write(Z),K.stdin.end();let V="",Y="";K.stdout.on("data",(Q)=>V+=Q),K.stderr.on("data",(Q)=>Y+=Q);let j=setTimeout(()=>{K.kill(),W(Error(`cdp timeout: ${$[0]}`))},X);K.on("close",(Q)=>{if(clearTimeout(j),Q===0)J(V.trim());else W(Error(Y.trim()||`cdp exit ${Q}`))})})}async function S$($){await x$(["evalraw",$,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
3
3
  (function() {
4
4
  // ── Runtime.enable / CDP detection masking ──────────────
5
5
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -207,39 +207,39 @@ import{createRequire as i2}from"node:module";var u2=Object.defineProperty;var c2
207
207
  };
208
208
  } catch(_) {}
209
209
  })();
210
- `})])}var e2,$8;var R1=c(()=>{h0();e2=s2(r2(import.meta.url)),$8=t2(e2,"..","bin","cdp.mjs")});import{existsSync as I1}from"node:fs";import{platform as X8}from"node:os";import{join as A0}from"node:path";function p($){let Z=X8()==="win32",X=process.env.SystemRoot||"C:\\Windows",J={win32:{powershell:A0(X,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:A0(X,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:A0(X,"System32","netstat.exe"),taskkill:A0(X,"System32","taskkill.exe"),tasklist:A0(X,"System32","tasklist.exe"),cmd:A0(X,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},W=Z?J.win32:J.unix,K=$.toLowerCase();if(W[K]&&I1(W[K]))return W[K];if(Z&&K==="netstat"){let V=A0(X,"Sysnative","netstat.exe");if(I1(V))return V}return $}var S$=()=>{};import{existsSync as K$,mkdirSync as J8,readFileSync as E1,writeFileSync as W8}from"node:fs";import{homedir as K8}from"node:os";import{join as b1}from"node:path";import{tmpdir as V$}from"node:os";function Y8(){try{if(K$(K0)){let $=E1(K0,"utf8"),Z=JSON.parse($);if(Array.isArray(Z.engines)&&Z.engines.length>0&&Z.engines.every((X)=>typeof X==="string")){let X=Z.engines.filter((W)=>Z0[W]),J=Z.engines.filter((W)=>!Z0[W]);if(J.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${K0}: ${J.join(", ")}
211
- [greedysearch] Available engines: ${Object.keys(Z0).join(", ")}
212
- `);if(X.length>0)return X;process.stderr.write(`[greedysearch] Warning: no valid engines in ${K0}, falling back to defaults: ${y$.join(", ")}
213
- `)}}}catch{}return y$}function j8(){try{if(!K$(g$))J8(g$,{recursive:!0});if(!K$(K0))W8(K0,JSON.stringify({engines:y$,synthesizer:h$},null,2)+`
214
- `,"utf8")}catch{}}function Q8(){try{if(K$(K0)){let $=E1(K0,"utf8"),Z=JSON.parse($);if(typeof Z.synthesizer==="string"){let X=Z.synthesizer.toLowerCase();if(p0.includes(X))return X;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${Z.synthesizer}" in ${K0}
215
- [greedysearch] Available synthesizers: ${p0.join(", ")}
216
- [greedysearch] Falling back to default: ${h$}
217
- `)}}}catch{}return h$}var y=9222,n,E0,V8,_0,q1,g$,K0,y$,h$="gemini",p0,Z0,e,p$,v1,m$;var V0=c(()=>{n=`${V$().replaceAll("\\","/")}/greedysearch-chrome-profile`,E0=`${n}/DevToolsActivePort`,V8=`${V$().replaceAll("\\","/")}/cdp-pages.json`,_0=`${V$().replaceAll("\\","/")}/greedysearch-chrome-mode`,q1=`${V$().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,g$=b1(K8(),".dm"),K0=b1(g$,"greedyconfig"),y$=["perplexity","google","chatgpt"];j8();p0=["gemini","chatgpt"];Z0={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"},e=Y8(),p$=e,v1=Q8(),m$=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=n});import{existsSync as Y4,mkdirSync as B8,readFileSync as x1,renameSync as H8,unlinkSync as M8,writeFileSync as S1}from"node:fs";import O8 from"node:http";import{platform as g1}from"node:os";import{dirname as G8}from"node:path";function z8($){return[...new Set($.filter(Boolean))]}function f1($,Z="explicit"){let X=new URL($),J=X.protocol==="wss:"?"wss:":"ws:",W=X.port?Number.parseInt(X.port,10):J==="wss:"?443:80;return{source:Z,wsUrl:`${J}//${X.host}${X.pathname}${X.search}`,host:X.hostname,port:W,path:`${X.pathname}${X.search}`,httpUrl:`http://${X.hostname}:${W}`}}function h1($=process.env){return![$.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,$.DM_CUA_REUSE_EXISTING_BROWSER].some((Z)=>Z!==void 0&&N8.test(String(Z)))}function d$($){let Z=Number.parseInt(String($??""),10);return Number.isInteger(Z)&&Z>0&&Z<65536?Z:null}function D8($){if(!$)return null;let Z=String($).trim();if(!Z)return null;let X=new URL(Z.includes("://")?Z:`http://${Z}`),J=d$(X.port)||(X.protocol==="https:"?443:80);return{host:X.hostname,port:J,source:`env:${Z}`}}function U8($){if(!$)return[];return String($).split(/[,\s]+/).map(d$).filter(Boolean)}function A8({env:$=process.env,platformName:Z=g1(),procVersionText:X=null}={}){if(Z!=="linux")return!1;if($.WSL_DISTRO_NAME||$.WSL_INTEROP)return!0;let J=X??(()=>{try{return x1("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(J)}function _8({env:$=process.env,platformName:Z=g1(),procVersionText:X=null,resolvConfText:J=null}={}){let W=["localhost","127.0.0.1"];if(A8({env:$,platformName:Z,procVersionText:X})){let V=(J??(()=>{try{return x1("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(V)W.push(V[1]);W.push("host.docker.internal")}return z8(W)}function P8({env:$=process.env,hosts:Z=_8({env:$}),autoPorts:X=y1,excludePorts:J=[]}={}){let W=[];for(let j of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if($[j])W.push({wsUrl:$[j],source:`env:${j}`});for(let j of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let Q=D8($[j]);if(Q)W.push(Q)}catch{}for(let j of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let Q=d$($[j]);if(!Q)continue;for(let B of Z)W.push({host:B,port:Q,source:`env:${j}`})}let K=U8($.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let j of K)for(let Q of Z)W.push({host:Q,port:j,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let V=new Set(J.filter(Boolean));if(h1($))for(let j of X){if(V.has(j))continue;for(let Q of Z)W.push({host:Q,port:j,source:"auto"})}let Y=new Set;return W.filter((j)=>{let Q=j.wsUrl||`${j.host}:${j.port}`;if(Y.has(Q))return!1;return Y.add(Q),!0})}async function k8($,{timeoutMs:Z=700}={}){if($.wsUrl)return f1($.wsUrl,$.source);let X=$.host||"localhost",J=$.port;if(!J)return null;let W=await new Promise((K)=>{let V=O8.get({host:X,port:J,path:"/json/version",timeout:Z},(Y)=>{let j="";Y.setEncoding("utf8"),Y.on("data",(Q)=>j+=Q),Y.on("end",()=>K(Y.statusCode===200?j:null))});V.on("error",()=>K(null)),V.setTimeout(Z,()=>{V.destroy(),K(null)})});if(!W)return null;try{let K=JSON.parse(W);if(!K.webSocketDebuggerUrl)return null;let V=f1(K.webSocketDebuggerUrl,$.source),Y=V.path||new URL(K.webSocketDebuggerUrl).pathname;return{...V,host:X,port:J,httpUrl:`http://${X}:${J}`,wsUrl:`ws://${X}:${J}${Y}`,path:Y}}catch{return null}}async function L8($={}){for(let Z of P8($)){let X=await k8(Z,$);if(X)return X}return null}function F8($){if(!$)throw Error("missing CDP endpoint");let Z=new URL($.wsUrl);return`${Z.host}
210
+ `})])}var s2,t2;var T1=c(()=>{E0();s2=i2(a2(import.meta.url)),t2=o2(s2,"..","bin","cdp.mjs")});import{existsSync as C1}from"node:fs";import{platform as e2}from"node:os";import{join as A0}from"node:path";function p($){let Z=e2()==="win32",X=process.env.SystemRoot||"C:\\Windows",J={win32:{powershell:A0(X,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:A0(X,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:A0(X,"System32","netstat.exe"),taskkill:A0(X,"System32","taskkill.exe"),tasklist:A0(X,"System32","tasklist.exe"),cmd:A0(X,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},W=Z?J.win32:J.unix,K=$.toLowerCase();if(W[K]&&C1(W[K]))return W[K];if(Z&&K==="netstat"){let V=A0(X,"Sysnative","netstat.exe");if(C1(V))return V}return $}var g$=()=>{};import{existsSync as K$,mkdirSync as $8,readFileSync as R1,writeFileSync as Z8}from"node:fs";import{homedir as X8}from"node:os";import{join as I1}from"node:path";import{tmpdir as V$}from"node:os";function W8(){try{if(K$(V0)){let $=R1(V0,"utf8"),Z=JSON.parse($);if(Array.isArray(Z.engines)&&Z.engines.length>0&&Z.engines.every((X)=>typeof X==="string")){let X=Z.engines.filter((W)=>X0[W]),J=Z.engines.filter((W)=>!X0[W]);if(J.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${V0}: ${J.join(", ")}
211
+ [greedysearch] Available engines: ${Object.keys(X0).join(", ")}
212
+ `);if(X.length>0)return X;process.stderr.write(`[greedysearch] Warning: no valid engines in ${V0}, falling back to defaults: ${h$.join(", ")}
213
+ `)}}}catch{}return h$}function K8(){try{if(!K$(y$))$8(y$,{recursive:!0});if(!K$(V0))Z8(V0,JSON.stringify({engines:h$,synthesizer:p$},null,2)+`
214
+ `,"utf8")}catch{}}function V8(){try{if(K$(V0)){let $=R1(V0,"utf8"),Z=JSON.parse($);if(typeof Z.synthesizer==="string"){let X=Z.synthesizer.toLowerCase();if(m0.includes(X))return X;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${Z.synthesizer}" in ${V0}
215
+ [greedysearch] Available synthesizers: ${m0.join(", ")}
216
+ [greedysearch] Falling back to default: ${p$}
217
+ `)}}}catch{}return p$}var y=9222,r,b0,J8,_0,E1,y$,V0,h$,p$="gemini",m0,X0,e,m$,b1,d$;var Y0=c(()=>{r=`${V$().replaceAll("\\","/")}/greedysearch-chrome-profile`,b0=`${r}/DevToolsActivePort`,J8=`${V$().replaceAll("\\","/")}/cdp-pages.json`,_0=`${V$().replaceAll("\\","/")}/greedysearch-chrome-mode`,E1=`${V$().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,y$=I1(X8(),".dm"),V0=I1(y$,"greedyconfig"),h$=["perplexity","google","chatgpt"];K8();m0=["gemini","chatgpt"];X0={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"},e=W8(),m$=e,b1=V8(),d$=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=r});import{existsSync as W4,mkdirSync as Y8,readFileSync as v1,renameSync as j8,unlinkSync as Q8,writeFileSync as f1}from"node:fs";import B8 from"node:http";import{platform as x1}from"node:os";import{dirname as H8}from"node:path";function G8($){return[...new Set($.filter(Boolean))]}function q1($,Z="explicit"){let X=new URL($),J=X.protocol==="wss:"?"wss:":"ws:",W=X.port?Number.parseInt(X.port,10):J==="wss:"?443:80;return{source:Z,wsUrl:`${J}//${X.host}${X.pathname}${X.search}`,host:X.hostname,port:W,path:`${X.pathname}${X.search}`,httpUrl:`http://${X.hostname}:${W}`}}function g1($=process.env){return![$.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,$.DM_CUA_REUSE_EXISTING_BROWSER].some((Z)=>Z!==void 0&&M8.test(String(Z)))}function l$($){let Z=Number.parseInt(String($??""),10);return Number.isInteger(Z)&&Z>0&&Z<65536?Z:null}function O8($){if(!$)return null;let Z=String($).trim();if(!Z)return null;let X=new URL(Z.includes("://")?Z:`http://${Z}`),J=l$(X.port)||(X.protocol==="https:"?443:80);return{host:X.hostname,port:J,source:`env:${Z}`}}function N8($){if(!$)return[];return String($).split(/[,\s]+/).map(l$).filter(Boolean)}function D8({env:$=process.env,platformName:Z=x1(),procVersionText:X=null}={}){if(Z!=="linux")return!1;if($.WSL_DISTRO_NAME||$.WSL_INTEROP)return!0;let J=X??(()=>{try{return v1("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(J)}function z8({env:$=process.env,platformName:Z=x1(),procVersionText:X=null,resolvConfText:J=null}={}){let W=["localhost","127.0.0.1"];if(D8({env:$,platformName:Z,procVersionText:X})){let V=(J??(()=>{try{return v1("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(V)W.push(V[1]);W.push("host.docker.internal")}return G8(W)}function U8({env:$=process.env,hosts:Z=z8({env:$}),autoPorts:X=S1,excludePorts:J=[]}={}){let W=[];for(let j of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if($[j])W.push({wsUrl:$[j],source:`env:${j}`});for(let j of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let Q=O8($[j]);if(Q)W.push(Q)}catch{}for(let j of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let Q=l$($[j]);if(!Q)continue;for(let B of Z)W.push({host:B,port:Q,source:`env:${j}`})}let K=N8($.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let j of K)for(let Q of Z)W.push({host:Q,port:j,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let V=new Set(J.filter(Boolean));if(g1($))for(let j of X){if(V.has(j))continue;for(let Q of Z)W.push({host:Q,port:j,source:"auto"})}let Y=new Set;return W.filter((j)=>{let Q=j.wsUrl||`${j.host}:${j.port}`;if(Y.has(Q))return!1;return Y.add(Q),!0})}async function A8($,{timeoutMs:Z=700}={}){if($.wsUrl)return q1($.wsUrl,$.source);let X=$.host||"localhost",J=$.port;if(!J)return null;let W=await new Promise((K)=>{let V=B8.get({host:X,port:J,path:"/json/version",timeout:Z},(Y)=>{let j="";Y.setEncoding("utf8"),Y.on("data",(Q)=>j+=Q),Y.on("end",()=>K(Y.statusCode===200?j:null))});V.on("error",()=>K(null)),V.setTimeout(Z,()=>{V.destroy(),K(null)})});if(!W)return null;try{let K=JSON.parse(W);if(!K.webSocketDebuggerUrl)return null;let V=q1(K.webSocketDebuggerUrl,$.source),Y=V.path||new URL(K.webSocketDebuggerUrl).pathname;return{...V,host:X,port:J,httpUrl:`http://${X}:${J}`,wsUrl:`ws://${X}:${J}${Y}`,path:Y}}catch{return null}}async function _8($={}){for(let Z of U8($)){let X=await A8(Z,$);if(X)return X}return null}function P8($){if(!$)throw Error("missing CDP endpoint");let Z=new URL($.wsUrl);return`${Z.host}
218
218
  ${Z.pathname}${Z.search}
219
- `}function w8($,Z){B8(G8($),{recursive:!0});let X=`${$}.tmp-${process.pid}`;S1(X,F8(Z),"utf8");try{M8($)}catch{}H8(X,$)}async function p1({activePortFile:$,modeFile:Z,env:X=process.env,excludePorts:J=[],autoPorts:W=y1}={}){if(!h1(X))return null;let K=await L8({env:X,excludePorts:J,autoPorts:W});if(!K)return null;if(w8($,K),Z)S1(Z,"existing","utf8");return K}var y1,N8;var m1=c(()=>{y1=[9222,9223],N8=/^(0|false|no|off)$/i});import{execFileSync as d1,execSync as l$}from"node:child_process";import{existsSync as Y$,mkdirSync as T8,readFileSync as b0,unlinkSync as k0,writeFileSync as L0}from"node:fs";import{platform as u$,tmpdir as i1}from"node:os";function d0($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function R8($){if(!d0($))return null;try{if(u$()==="win32")return d1(p("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return d1(p("ps"),["-p",String($),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function I8($,Z,X=y){if(!$)return!1;let J=(V)=>String(V||"").replaceAll("\\","/").toLowerCase(),W=J($),K=J(Z);return W.includes(K)&&W.includes(`--remote-debugging-port=${X}`)&&!W.includes("--type=")}function l1($,Z,X=y){return I8(R8($),Z,X)}function E8($=y){try{if(u$()==="win32"){let X=l$(`${p("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),J=new RegExp(String.raw`TCP\s+\S+:${$}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),W=X.match(J);return W?Number.parseInt(W[1],10):null}let Z=l$(`${p("lsof")} -i :${$} -t 2>/dev/null || ${p("ss")} -tlnp 2>/dev/null | ${p("grep")} :${$} | ${p("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return Z?Number.parseInt(Z.split(`
220
- `)[0],10):null}catch{return null}}function u1($){try{if(u$()==="win32")l$(`${p("taskkill")} /F /T /PID ${$}`,{stdio:"ignore"});else{try{process.kill(-$,"SIGKILL")}catch{}try{process.kill($,"SIGKILL")}catch{}}return!0}catch{return!1}}function u0(){try{if(Y$(j$)){let $=b0(j$,"utf8"),Z=JSON.parse($);if(Z&&typeof Z.tempDir==="string"&&typeof Z.debugPort==="number")return{browserPid:Number.isInteger(Z.browserPid)?Z.browserPid:void 0,debugPort:Z.debugPort,tempDir:Z.tempDir,clientPids:Array.isArray(Z.clientPids)?Z.clientPids.filter((X)=>Number.isInteger(X)&&X>0):[],sessionMode:Z.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(Z.lastActivity)?Z.lastActivity:0,launchedAt:Number.isFinite(Z.launchedAt)?Z.launchedAt:0}}}catch{}try{let $=Y$(Q$)?Number.parseInt(b0(Q$,"utf8").trim(),10)||void 0:void 0,Z=Y$(B$)?b0(B$,"utf8").trim()==="visible"?"visible":"headless":"headless",X=Y$(m0)?Number.parseInt(b0(m0,"utf8").trim(),10)||0:0;return{browserPid:$,debugPort:y,tempDir:n,clientPids:$?[$]:[],sessionMode:Z,lastActivity:X,launchedAt:0}}catch{return null}}function H$($){try{L0(j$,JSON.stringify({browserPid:$.browserPid,debugPort:$.debugPort,tempDir:$.tempDir,clientPids:[...new Set($.clientPids.filter((Z)=>Z>0))],sessionMode:$.sessionMode,lastActivity:$.lastActivity,launchedAt:$.launchedAt},null,2),"utf8")}catch{}try{if($.browserPid)L0(Q$,String($.browserPid),"utf8")}catch{}try{L0(B$,$.sessionMode,"utf8")}catch{}try{L0(m0,String($.lastActivity),"utf8")}catch{}}function c1(){try{k0(j$)}catch{}try{k0(Q$)}catch{}try{k0(B$)}catch{}try{k0(m0)}catch{}}function o1($){if(!$)return $;let Z={...$,clientPids:[...new Set([...$.clientPids,process.pid].filter((X)=>d0(X)||X===process.pid))]};return H$(Z),Z}function c$($){let Z=Date.now();try{if($)H$({...$,lastActivity:Z});else L0(m0,String(Z),"utf8")}catch{}}function a1(){if(n1)return;n1=!0;let $=u0();if(!$)return;if($.browserPid){if(!d0($.browserPid)){u1($.browserPid),c1();return}if(!l1($.browserPid,$.tempDir,$.debugPort))c1();else H$({...$,clientPids:$.clientPids.filter((W)=>d0(W))})}let Z=E8();if(Z&&Z!==$.browserPid)if(l1(Z,n,y))H$({browserPid:Z,debugPort:y,tempDir:n,clientPids:[Z],sessionMode:$.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else u1(Z)}function s1(){T8(i1(),{recursive:!0});try{let $=JSON.stringify({pid:process.pid,ts:Date.now()});return L0(P0,$,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let Z=b0(P0,"utf8");if(JSON.parse(Z).pid===process.pid)k0(P0)}catch{}}}}catch($){if($?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let $=b0(P0,"utf8"),Z=JSON.parse($),X=Date.now()-(Z.ts||0);if(!d0(Z.pid)||X>C8){try{k0(P0)}catch{}try{let W=JSON.stringify({pid:process.pid,ts:Date.now()});return L0(P0,W,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{k0(P0)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var l0,j$,P0,C8=15000,Q$,B$,m0,D4,n1=!1;var t1=c(()=>{V0();S$();l0=i1().replaceAll("\\","/"),j$=`${l0}/greedysearch-chrome-metadata.json`,P0=`${l0}/greedysearch-chrome-launch.lock`,Q$=`${l0}/greedysearch-chrome.pid`,B$=`${l0}/greedysearch-chrome-mode`,m0=`${l0}/greedysearch-chrome-last-activity`;D4=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5});import{spawn as b8,execFileSync as r1,execSync as o$}from"node:child_process";import{existsSync as i0,readFileSync as O$,renameSync as q8,unlinkSync as Y0,writeFileSync as M$}from"node:fs";import a$ from"node:http";import{platform as s$,tmpdir as v8}from"node:os";import{join as n$}from"node:path";function t$($=f8){let Z=[n$($,"launch.mjs"),n$($,"..","bin","launch.mjs"),n$($,"..","..","bin","launch.mjs")];for(let X of Z)if(i0(X))return X;return Z[Z.length-1]}function g8($,Z=y){let X=String($||"").toLowerCase();if(!X.includes(`--remote-debugging-port=${Z}`)||X.includes("--type="))return null;return X.includes("--headless")}function $2(){try{let $=r$(),Z=$?y8($):null,X=g8(Z);if(X!==null){try{M$(_0,X?"headless":"visible","utf8")}catch{}return X}}catch{}try{if(!i0(_0))return!0;return O$(_0,"utf8").trim()==="headless"}catch{return!0}}function G$(){try{M$(n0,String(Date.now()),"utf8")}catch{}try{let $=u0();if($)c$($)}catch{}}function y8($){try{if(s$()==="win32")return r1(p("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return r1(p("ps"),["-p",String($),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function r$(){try{if(s$()==="win32"){let Z=o$(`${p("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),X=new RegExp(String.raw`TCP\s+\S+:${y}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),J=Z.match(X);return J?Number.parseInt(J[1],10):null}let $=o$(`${p("lsof")} -i :${y} -t 2>/dev/null || ${p("ss")} -tlnp 2>/dev/null | ${p("grep")} :${y} | ${p("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return $?Number.parseInt($.split(`
221
- `)[0],10):null}catch{return null}}async function h8($=1500){try{let X=await new Promise((W,K)=>{let V=a$.get(`http://localhost:${y}/json/version`,(Y)=>{let j="";Y.on("data",(Q)=>j+=Q),Y.on("end",()=>{try{W(JSON.parse(j))}catch{K(Error("bad JSON"))}})});V.on("error",K),V.setTimeout(1000,()=>{V.destroy(),K(Error("timeout"))})}),J=new globalThis.WebSocket(X.webSocketDebuggerUrl);await new Promise((W)=>{J.onopen=()=>{J.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{J.close(),W()},200)},J.onerror=()=>W(),setTimeout(W,1000)})}catch{}let Z=Date.now()+$;while(Date.now()<Z){if(!r$())return!0;await new Promise((J)=>setTimeout(J,150))}return p8()}function p8(){try{let $=r$();if(!$&&i0(c0))$=Number.parseInt(O$(c0,"utf8").trim(),10)||null;if(!$)return!1;if(s$()==="win32")o$(`${p("taskkill")} /F /PID ${$}`,{stdio:"ignore"});else process.kill($,"SIGKILL");return!0}catch{return!1}}async function Z2(){if(!await q0(500)){try{Y0(c0)}catch{}try{Y0(n0)}catch{}try{Y0(_0)}catch{}return!1}let Z=await h8(1500);try{Y0(c0)}catch{}try{Y0(n0)}catch{}try{Y0(_0)}catch{}if(Z)process.stderr.write(`[greedysearch] Killed Chrome on port ${y}.
222
- `);return Z}async function m8(){let Z=$2()?x8:S8;if(Z<=0)return!1;if(!i0(n0))return G$(),!1;try{let X=Number.parseInt(O$(n0,"utf8").trim(),10);if(!X)return!1;if((Date.now()-X)/60000>=Z)return Z2()}catch{}return!1}async function X2(){let Z=(await q(["list"])).split(`
223
- `)[0];if(!Z)throw Error("No Chrome tabs found");return Z.slice(0,8)}async function j0($="about:blank"){let Z=await X2(),X=new URL($).hostname;if(X==="copilot.microsoft.com"||X==="www.perplexity.ai"||X==="perplexity.ai"||X.endsWith(".perplexity.ai")){let V=await q(["evalraw",Z,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:Y}=JSON.parse(V),j=Y.slice(0,8);if(await q(["list"]).catch(()=>null),X==="copilot.microsoft.com")await x$(j);else x$(j).catch(()=>{});return await q(["list"]).catch(()=>null),Y}let W=await q(["evalraw",Z,"Target.createTarget",JSON.stringify({url:$})]),{targetId:K}=JSON.parse(W);return await q(["list"]).catch(()=>null),K}async function O0($){try{let Z=await X2();await q(["evalraw",Z,"Target.closeTarget",JSON.stringify({targetId:$})])}catch{}}async function N$($=[]){if(await Promise.all($.filter(Boolean).map((Z)=>O0(Z).catch(()=>{}))),$.length>0)await q(["list"]).catch(()=>null)}function q0($=3000){return new Promise((Z)=>{let X=a$.get(`http://localhost:${y}/json/version`,(J)=>{J.resume(),Z(J.statusCode===200)});X.on("error",()=>Z(!1)),X.setTimeout($,()=>{X.destroy(),Z(!1)})})}async function i$(){let $=`${E0}.lock`,Z=`${E0}.tmp`,X=5000,J=1000,W=await new Promise((K)=>{let V=Date.now(),Y=()=>{try{let j=JSON.stringify({pid:process.pid,ts:Date.now()});M$($,j,{encoding:"utf8",flag:"wx"}),K(!0)}catch(j){if(j?.code!=="EEXIST"){if(Date.now()-V<1000)setTimeout(Y,50);else K(!1);return}try{let Q=O$($,"utf8").trim(),B=Q.startsWith("{")?JSON.parse(Q):{ts:Number(Q)},H=Number(B?.ts)||0;if(H>0&&Date.now()-H>5000)try{Y0($)}catch{}if(Date.now()-V<1000)setTimeout(Y,50);else K(!1)}catch{if(Date.now()-V<1000)setTimeout(Y,50);else K(!1)}}};Y()});try{let K=await new Promise((Q,B)=>{let H=a$.get(`http://localhost:${y}/json/version`,(G)=>{let O="";G.on("data",(z)=>O+=z),G.on("end",()=>Q(O))});H.on("error",B),H.setTimeout(3000,()=>{H.destroy(),B(Error("timeout"))})}),{webSocketDebuggerUrl:V}=JSON.parse(K),Y=new URL(V),j=`${Y.pathname}${Y.search}`;if(W){M$(Z,`localhost:${y}
224
- ${j}`,"utf8");try{Y0(E0)}catch{}q8(Z,E0)}}catch{}finally{if(W)try{Y0($)}catch{}}}async function o0(){let $=i0(c0)||!!u0(),Z=await p1({activePortFile:E0,modeFile:_0,excludePorts:$?[y]:[]});if(Z){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${Z.httpUrl} (${Z.source}).
225
- `);return}a1();let X=await m8(),J=X?!1:await q0();if(!J&&!X)await new Promise((Y)=>setTimeout(Y,500)),J=await q0();let W=!1;if(J){let Y=$2(),j=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!j&&!Y)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
219
+ `}function k8($,Z){Y8(H8($),{recursive:!0});let X=`${$}.tmp-${process.pid}`;f1(X,P8(Z),"utf8");try{Q8($)}catch{}j8(X,$)}async function y1({activePortFile:$,modeFile:Z,env:X=process.env,excludePorts:J=[],autoPorts:W=S1}={}){if(!g1(X))return null;let K=await _8({env:X,excludePorts:J,autoPorts:W});if(!K)return null;if(k8($,K),Z)f1(Z,"existing","utf8");return K}var S1,M8;var h1=c(()=>{S1=[9222,9223],M8=/^(0|false|no|off)$/i});import{execFileSync as p1,execSync as u$}from"node:child_process";import{existsSync as Y$,mkdirSync as L8,readFileSync as q0,unlinkSync as k0,writeFileSync as L0}from"node:fs";import{platform as c$,tmpdir as c1}from"node:os";function l0($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function w8($){if(!l0($))return null;try{if(c$()==="win32")return p1(p("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return p1(p("ps"),["-p",String($),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function T8($,Z,X=y){if(!$)return!1;let J=(V)=>String(V||"").replaceAll("\\","/").toLowerCase(),W=J($),K=J(Z);return W.includes(K)&&W.includes(`--remote-debugging-port=${X}`)&&!W.includes("--type=")}function m1($,Z,X=y){return T8(w8($),Z,X)}function C8($=y){try{if(c$()==="win32"){let X=u$(`${p("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),J=new RegExp(String.raw`TCP\s+\S+:${$}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),W=X.match(J);return W?Number.parseInt(W[1],10):null}let Z=u$(`${p("lsof")} -i :${$} -t 2>/dev/null || ${p("ss")} -tlnp 2>/dev/null | ${p("grep")} :${$} | ${p("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return Z?Number.parseInt(Z.split(`
220
+ `)[0],10):null}catch{return null}}function d1($){try{if(c$()==="win32")u$(`${p("taskkill")} /F /T /PID ${$}`,{stdio:"ignore"});else{try{process.kill(-$,"SIGKILL")}catch{}try{process.kill($,"SIGKILL")}catch{}}return!0}catch{return!1}}function c0(){try{if(Y$(j$)){let $=q0(j$,"utf8"),Z=JSON.parse($);if(Z&&typeof Z.tempDir==="string"&&typeof Z.debugPort==="number")return{browserPid:Number.isInteger(Z.browserPid)?Z.browserPid:void 0,debugPort:Z.debugPort,tempDir:Z.tempDir,clientPids:Array.isArray(Z.clientPids)?Z.clientPids.filter((X)=>Number.isInteger(X)&&X>0):[],sessionMode:Z.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(Z.lastActivity)?Z.lastActivity:0,launchedAt:Number.isFinite(Z.launchedAt)?Z.launchedAt:0}}}catch{}try{let $=Y$(Q$)?Number.parseInt(q0(Q$,"utf8").trim(),10)||void 0:void 0,Z=Y$(B$)?q0(B$,"utf8").trim()==="visible"?"visible":"headless":"headless",X=Y$(d0)?Number.parseInt(q0(d0,"utf8").trim(),10)||0:0;return{browserPid:$,debugPort:y,tempDir:r,clientPids:$?[$]:[],sessionMode:Z,lastActivity:X,launchedAt:0}}catch{return null}}function H$($){try{L0(j$,JSON.stringify({browserPid:$.browserPid,debugPort:$.debugPort,tempDir:$.tempDir,clientPids:[...new Set($.clientPids.filter((Z)=>Z>0))],sessionMode:$.sessionMode,lastActivity:$.lastActivity,launchedAt:$.launchedAt},null,2),"utf8")}catch{}try{if($.browserPid)L0(Q$,String($.browserPid),"utf8")}catch{}try{L0(B$,$.sessionMode,"utf8")}catch{}try{L0(d0,String($.lastActivity),"utf8")}catch{}}function l1(){try{k0(j$)}catch{}try{k0(Q$)}catch{}try{k0(B$)}catch{}try{k0(d0)}catch{}}function n1($){if(!$)return $;let Z={...$,clientPids:[...new Set([...$.clientPids,process.pid].filter((X)=>l0(X)||X===process.pid))]};return H$(Z),Z}function n$($){let Z=Date.now();try{if($)H$({...$,lastActivity:Z});else L0(d0,String(Z),"utf8")}catch{}}function i1(){if(u1)return;u1=!0;let $=c0();if(!$)return;if($.browserPid){if(!l0($.browserPid)){d1($.browserPid),l1();return}if(!m1($.browserPid,$.tempDir,$.debugPort))l1();else H$({...$,clientPids:$.clientPids.filter((W)=>l0(W))})}let Z=C8();if(Z&&Z!==$.browserPid)if(m1(Z,r,y))H$({browserPid:Z,debugPort:y,tempDir:r,clientPids:[Z],sessionMode:$.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else d1(Z)}function o1(){L8(c1(),{recursive:!0});try{let $=JSON.stringify({pid:process.pid,ts:Date.now()});return L0(P0,$,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let Z=q0(P0,"utf8");if(JSON.parse(Z).pid===process.pid)k0(P0)}catch{}}}}catch($){if($?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let $=q0(P0,"utf8"),Z=JSON.parse($),X=Date.now()-(Z.ts||0);if(!l0(Z.pid)||X>F8){try{k0(P0)}catch{}try{let W=JSON.stringify({pid:process.pid,ts:Date.now()});return L0(P0,W,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{k0(P0)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var u0,j$,P0,F8=15000,Q$,B$,d0,O4,u1=!1;var a1=c(()=>{Y0();g$();u0=c1().replaceAll("\\","/"),j$=`${u0}/greedysearch-chrome-metadata.json`,P0=`${u0}/greedysearch-chrome-launch.lock`,Q$=`${u0}/greedysearch-chrome.pid`,B$=`${u0}/greedysearch-chrome-mode`,d0=`${u0}/greedysearch-chrome-last-activity`;O4=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5});import{spawn as R8,execFileSync as s1,execSync as o$}from"node:child_process";import{existsSync as G$,readFileSync as O$,renameSync as I8,unlinkSync as j0,writeFileSync as M$}from"node:fs";import a$ from"node:http";import{platform as s$,tmpdir as E8}from"node:os";import{join as b8}from"node:path";function x8($,Z=y){let X=String($||"").toLowerCase();if(!X.includes(`--remote-debugging-port=${Z}`)||X.includes("--type="))return null;return X.includes("--headless")}function r1(){try{let $=t$(),Z=$?S8($):null,X=x8(Z);if(X!==null){try{M$(_0,X?"headless":"visible","utf8")}catch{}return X}}catch{}try{if(!G$(_0))return!0;return O$(_0,"utf8").trim()==="headless"}catch{return!0}}function N$(){try{M$(i0,String(Date.now()),"utf8")}catch{}try{let $=c0();if($)n$($)}catch{}}function S8($){try{if(s$()==="win32")return s1(p("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return s1(p("ps"),["-p",String($),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function t$(){try{if(s$()==="win32"){let Z=o$(`${p("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),X=new RegExp(String.raw`TCP\s+\S+:${y}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),J=Z.match(X);return J?Number.parseInt(J[1],10):null}let $=o$(`${p("lsof")} -i :${y} -t 2>/dev/null || ${p("ss")} -tlnp 2>/dev/null | ${p("grep")} :${y} | ${p("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return $?Number.parseInt($.split(`
221
+ `)[0],10):null}catch{return null}}async function g8($=1500){try{let X=await new Promise((W,K)=>{let V=a$.get(`http://localhost:${y}/json/version`,(Y)=>{let j="";Y.on("data",(Q)=>j+=Q),Y.on("end",()=>{try{W(JSON.parse(j))}catch{K(Error("bad JSON"))}})});V.on("error",K),V.setTimeout(1000,()=>{V.destroy(),K(Error("timeout"))})}),J=new globalThis.WebSocket(X.webSocketDebuggerUrl);await new Promise((W)=>{J.onopen=()=>{J.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{J.close(),W()},200)},J.onerror=()=>W(),setTimeout(W,1000)})}catch{}let Z=Date.now()+$;while(Date.now()<Z){if(!t$())return!0;await new Promise((J)=>setTimeout(J,150))}return y8()}function y8(){try{let $=t$();if(!$&&G$(n0))$=Number.parseInt(O$(n0,"utf8").trim(),10)||null;if(!$)return!1;if(s$()==="win32")o$(`${p("taskkill")} /F /PID ${$}`,{stdio:"ignore"});else process.kill($,"SIGKILL");return!0}catch{return!1}}async function e1(){if(!await v0(500)){try{j0(n0)}catch{}try{j0(i0)}catch{}try{j0(_0)}catch{}return!1}let Z=await g8(1500);try{j0(n0)}catch{}try{j0(i0)}catch{}try{j0(_0)}catch{}if(Z)process.stderr.write(`[greedysearch] Killed Chrome on port ${y}.
222
+ `);return Z}async function h8(){let Z=r1()?v8:f8;if(Z<=0)return!1;if(!G$(i0))return N$(),!1;try{let X=Number.parseInt(O$(i0,"utf8").trim(),10);if(!X)return!1;if((Date.now()-X)/60000>=Z)return e1()}catch{}return!1}async function $2(){let Z=(await q(["list"])).split(`
223
+ `)[0];if(!Z)throw Error("No Chrome tabs found");return Z.slice(0,8)}async function Q0($="about:blank"){let Z=await $2(),X=new URL($).hostname;if(X==="copilot.microsoft.com"||X==="www.perplexity.ai"||X==="perplexity.ai"||X.endsWith(".perplexity.ai")){let V=await q(["evalraw",Z,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:Y}=JSON.parse(V),j=Y.slice(0,8);if(await q(["list"]).catch(()=>null),X==="copilot.microsoft.com")await S$(j);else S$(j).catch(()=>{});return await q(["list"]).catch(()=>null),Y}let W=await q(["evalraw",Z,"Target.createTarget",JSON.stringify({url:$})]),{targetId:K}=JSON.parse(W);return await q(["list"]).catch(()=>null),K}async function G0($){try{let Z=await $2();await q(["evalraw",Z,"Target.closeTarget",JSON.stringify({targetId:$})])}catch{}}async function D$($=[]){if(await Promise.all($.filter(Boolean).map((Z)=>G0(Z).catch(()=>{}))),$.length>0)await q(["list"]).catch(()=>null)}function v0($=3000){return new Promise((Z)=>{let X=a$.get(`http://localhost:${y}/json/version`,(J)=>{J.resume(),Z(J.statusCode===200)});X.on("error",()=>Z(!1)),X.setTimeout($,()=>{X.destroy(),Z(!1)})})}async function i$(){let $=`${b0}.lock`,Z=`${b0}.tmp`,X=5000,J=1000,W=await new Promise((K)=>{let V=Date.now(),Y=()=>{try{let j=JSON.stringify({pid:process.pid,ts:Date.now()});M$($,j,{encoding:"utf8",flag:"wx"}),K(!0)}catch(j){if(j?.code!=="EEXIST"){if(Date.now()-V<1000)setTimeout(Y,50);else K(!1);return}try{let Q=O$($,"utf8").trim(),B=Q.startsWith("{")?JSON.parse(Q):{ts:Number(Q)},H=Number(B?.ts)||0;if(H>0&&Date.now()-H>5000)try{j0($)}catch{}if(Date.now()-V<1000)setTimeout(Y,50);else K(!1)}catch{if(Date.now()-V<1000)setTimeout(Y,50);else K(!1)}}};Y()});try{let K=await new Promise((Q,B)=>{let H=a$.get(`http://localhost:${y}/json/version`,(O)=>{let G="";O.on("data",(D)=>G+=D),O.on("end",()=>Q(G))});H.on("error",B),H.setTimeout(3000,()=>{H.destroy(),B(Error("timeout"))})}),{webSocketDebuggerUrl:V}=JSON.parse(K),Y=new URL(V),j=`${Y.pathname}${Y.search}`;if(W){M$(Z,`localhost:${y}
224
+ ${j}`,"utf8");try{j0(b0)}catch{}I8(Z,b0)}}catch{}finally{if(W)try{j0($)}catch{}}}async function o0(){let $=G$(n0)||!!c0(),Z=await y1({activePortFile:b0,modeFile:_0,excludePorts:$?[y]:[]});if(Z){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${Z.httpUrl} (${Z.source}).
225
+ `);return}i1();let X=await h8(),J=X?!1:await v0();if(!J&&!X)await new Promise((Y)=>setTimeout(Y,500)),J=await v0();let W=!1;if(J){let Y=r1(),j=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!j&&!Y)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
226
226
  `),await F0(),await new Promise((Q)=>setTimeout(Q,1000)),W=!0;else if(j&&Y)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
227
- `),await F0(),await new Promise((Q)=>setTimeout(Q,1000)),W=!0}if(W?!1:await q0()){await i$();try{let Y=u0();if(Y)c$(Y),o1(Y)}catch{}return}let V=s1();if(!V.acquired){if(await new Promise((j)=>setTimeout(j,3000)),await q0(5000)){await i$();return}}try{if(await q0(1000)){await i$();return}process.stderr.write(`GreedySearch Chrome not running on port ${y} — auto-launching...
228
- `);let j=[t$()];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")j.push("--headless");await new Promise((Q,B)=>{b8(M0(),j,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:n,GREEDY_SEARCH_PROFILE_DIR:n}}).on("close",(G)=>G===0?Q():B(Error("launch.mjs failed")))})}finally{V.release()}}var f8,e1,c0,n0,x8,S8,F0,q;var e$=c(()=>{R1();h0();S$();V0();m1();t1();f8=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");e1=v8().replaceAll("\\","/"),c0=`${e1}/greedysearch-chrome.pid`,n0=`${e1}/greedysearch-chrome-last-activity`,x8=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,S8=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;F0=Z2;q=f$});var Q2={};y0(Q2,{shouldUseBrowser:()=>X6,rewriteGitHubUrl:()=>j2,isPrivateUrl:()=>U$,fetchSourceHttp:()=>Z1,extractContent:()=>_$,detectBotBlock:()=>A$,defaultFetchHeaders:()=>$1,checkContentQuality:()=>P$});import{Readability as i8}from"@mozilla/readability";import{JSDOM as o8}from"jsdom";import a8 from"turndown";function $1($={}){return{...Y2,...$}}function U$($){try{let Z=new URL($),X=Z.hostname.toLowerCase();for(let J of s8)if(J.test(X))return{blocked:!0,reason:`Private/internal address: ${X}`};if(Z.protocol==="file:")return{blocked:!0,reason:"File protocol not allowed"};return{blocked:!1}}catch(Z){return{blocked:!0,reason:`Invalid URL: ${Z.message}`}}}function j2($){try{let Z=new URL($);if(!(Z.hostname==="github.com"||Z.hostname.endsWith(".github.com")))return $;let X=Z.pathname.split("/").filter(Boolean);if(X.length<5)return $;let[J,W,K,V,...Y]=X;if(K!=="blob")return $;let j=Y.join("/");return`https://raw.githubusercontent.com/${J}/${W}/${V}/${j}`}catch{return $}}async function Z1($,Z={}){let X=U$($);if(X.blocked)return{ok:!1,url:$,finalUrl:$,status:403,error:`Blocked: ${X.reason}`,needsBrowser:!1};let J=$;if($=j2($),$!==J)console.error(`[fetcher] Rewrote GitHub URL: ${J.slice(0,60)}... → raw.githubusercontent.com`);let{timeoutMs:W=15000,userAgent:K,signal:V}=Z,Y=new AbortController,j=setTimeout(()=>Y.abort(),W);if(V)V.addEventListener("abort",()=>Y.abort(),{once:!0});try{let Q=await fetch($,{method:"GET",headers:{...Y2,"user-agent":K||V2},redirect:"follow",signal:Y.signal});clearTimeout(j);let B=Q.headers.get("content-type")||"",H=Q.url,G=Q.headers.get("last-modified")||"",O=!1;try{O=new URL(H).hostname.toLowerCase()==="raw.githubusercontent.com"}catch{}if(B.includes("text/plain")&&O){let b=await Q.text();return{ok:!0,url:J,finalUrl:H,status:Q.status,title:H.split("/").pop()||"GitHub File",byline:"",siteName:"GitHub",lang:"",publishedTime:G,lastModified:G,markdown:b,contentLength:b.length,excerpt:b.slice(0,300).replaceAll(/\n/g," "),needsBrowser:!1}}if(!B.includes("text/html")&&!B.includes("application/xhtml"))return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Unsupported content type: ${B}`,needsBrowser:!1};let z=await Q.text(),D=A$(Q.status,z,H,$);if(D.blocked)return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Blocked: ${D.reason}`,needsBrowser:!0};let M=_$(z,H),A=P$(M);if(!A.ok)return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Low quality content: ${A.reason}`,needsBrowser:!0};return{ok:!0,url:$,finalUrl:H,status:Q.status,title:M.title,byline:M.byline,siteName:M.siteName,lang:M.lang,publishedTime:M.publishedTime||G,lastModified:G,markdown:M.markdown,excerpt:M.excerpt,contentLength:M.markdown.length,needsBrowser:!1}}catch(Q){clearTimeout(j);let B=Z6(Q);return{ok:!1,url:$,finalUrl:$,status:0,error:Q.message,needsBrowser:B}}}function A$($,Z,X,J){let W=Z.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.toLowerCase()||"",K=Z.slice(0,30000).toLowerCase(),V=`${W} ${K}`;if($===403||$===429||$===503)return{blocked:!0,reason:`HTTP ${$}`};let Y=[{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 Q of Y)if(Q.pattern.test(V))return{blocked:!0,reason:Q.reason};let j=$6(J,X,Z);if(j)return{blocked:!0,reason:j};return{blocked:!1}}function $6($,Z,X){try{let J=new URL($),W=new URL(Z);if(J.hostname.toLowerCase()===W.hostname.toLowerCase())return;let K=W.hostname.toLowerCase();if(t8.some((Y)=>K===Y||K.endsWith(`.${Y}`)))return`redirected to login (${W.hostname})`;if(r8.some((Y)=>K.startsWith(Y)))return`redirected to login (${W.hostname})`;let V=X.slice(0,20000).toLowerCase();if(e8.some((Y)=>V.includes(Y)))return`redirected to login page (${W.hostname})`}catch{}return}function Z6($){let Z=$.message.toLowerCase();return Z.includes("fetch failed")||Z.includes("unable to verify")||Z.includes("certificate")||Z.includes("timeout")}function W2($){let Z=['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 X of Z){let J=$.querySelector(X),W=J?.getAttribute("content")||J?.getAttribute("datetime")||"";if(W)return W}return""}function _$($,Z){let J=new o8($,{url:Z}).window.document,K=new i8(J).parse();if(K&&K.content){let j=K2.turndown(K.content).replaceAll(/\n{3,}/g,`
227
+ `),await F0(),await new Promise((Q)=>setTimeout(Q,1000)),W=!0}if(W?!1:await v0()){await i$();try{let Y=c0();if(Y)n$(Y),n1(Y)}catch{}return}let V=o1();if(!V.acquired){if(await new Promise((j)=>setTimeout(j,3000)),await v0(5000)){await i$();return}}try{if(await v0(1000)){await i$();return}process.stderr.write(`GreedySearch Chrome not running on port ${y} — auto-launching...
228
+ `);let j=[b8(q8,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")j.push("--headless");await new Promise((Q,B)=>{R8(Z0(),j,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(O)=>O===0?Q():B(Error("launch.mjs failed")))})}finally{V.release()}}var q8,t1,n0,i0,v8,f8,F0,q;var r$=c(()=>{T1();E0();g$();Y0();h1();a1();q8=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),t1=E8().replaceAll("\\","/"),n0=`${t1}/greedysearch-chrome.pid`,i0=`${t1}/greedysearch-chrome-last-activity`,v8=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,f8=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;F0=e1;q=x$});var Y2={};p0(Y2,{shouldUseBrowser:()=>$6,rewriteGitHubUrl:()=>V2,isPrivateUrl:()=>U$,fetchSourceHttp:()=>$1,extractContent:()=>_$,detectBotBlock:()=>A$,defaultFetchHeaders:()=>e$,checkContentQuality:()=>P$});import{Readability as c8}from"@mozilla/readability";import{JSDOM as n8}from"jsdom";import i8 from"turndown";function e$($={}){return{...K2,...$}}function U$($){try{let Z=new URL($),X=Z.hostname.toLowerCase();for(let J of o8)if(J.test(X))return{blocked:!0,reason:`Private/internal address: ${X}`};if(Z.protocol==="file:")return{blocked:!0,reason:"File protocol not allowed"};return{blocked:!1}}catch(Z){return{blocked:!0,reason:`Invalid URL: ${Z.message}`}}}function V2($){try{let Z=new URL($);if(!(Z.hostname==="github.com"||Z.hostname.endsWith(".github.com")))return $;let X=Z.pathname.split("/").filter(Boolean);if(X.length<5)return $;let[J,W,K,V,...Y]=X;if(K!=="blob")return $;let j=Y.join("/");return`https://raw.githubusercontent.com/${J}/${W}/${V}/${j}`}catch{return $}}async function $1($,Z={}){let X=U$($);if(X.blocked)return{ok:!1,url:$,finalUrl:$,status:403,error:`Blocked: ${X.reason}`,needsBrowser:!1};let J=$;if($=V2($),$!==J)console.error(`[fetcher] Rewrote GitHub URL: ${J.slice(0,60)}... → raw.githubusercontent.com`);let{timeoutMs:W=15000,userAgent:K,signal:V}=Z,Y=new AbortController,j=setTimeout(()=>Y.abort(),W);if(V)V.addEventListener("abort",()=>Y.abort(),{once:!0});try{let Q=await fetch($,{method:"GET",headers:{...K2,"user-agent":K||W2},redirect:"follow",signal:Y.signal});clearTimeout(j);let B=Q.headers.get("content-type")||"",H=Q.url,O=Q.headers.get("last-modified")||"",G=!1;try{G=new URL(H).hostname.toLowerCase()==="raw.githubusercontent.com"}catch{}if(B.includes("text/plain")&&G){let b=await Q.text();return{ok:!0,url:J,finalUrl:H,status:Q.status,title:H.split("/").pop()||"GitHub File",byline:"",siteName:"GitHub",lang:"",publishedTime:O,lastModified:O,markdown:b,contentLength:b.length,excerpt:b.slice(0,300).replaceAll(/\n/g," "),needsBrowser:!1}}if(!B.includes("text/html")&&!B.includes("application/xhtml"))return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Unsupported content type: ${B}`,needsBrowser:!1};let D=await Q.text(),z=A$(Q.status,D,H,$);if(z.blocked)return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Blocked: ${z.reason}`,needsBrowser:!0};let M=_$(D,H),A=P$(M);if(!A.ok)return{ok:!1,url:$,finalUrl:H,status:Q.status,error:`Low quality content: ${A.reason}`,needsBrowser:!0};return{ok:!0,url:$,finalUrl:H,status:Q.status,title:M.title,byline:M.byline,siteName:M.siteName,lang:M.lang,publishedTime:M.publishedTime||O,lastModified:O,markdown:M.markdown,excerpt:M.excerpt,contentLength:M.markdown.length,needsBrowser:!1}}catch(Q){clearTimeout(j);let B=e8(Q);return{ok:!1,url:$,finalUrl:$,status:0,error:Q.message,needsBrowser:B}}}function A$($,Z,X,J){let W=Z.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.toLowerCase()||"",K=Z.slice(0,30000).toLowerCase(),V=`${W} ${K}`;if($===403||$===429||$===503)return{blocked:!0,reason:`HTTP ${$}`};let Y=[{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 Q of Y)if(Q.pattern.test(V))return{blocked:!0,reason:Q.reason};let j=r8(J,X,Z);if(j)return{blocked:!0,reason:j};return{blocked:!1}}function r8($,Z,X){try{let J=new URL($),W=new URL(Z);if(J.hostname.toLowerCase()===W.hostname.toLowerCase())return;let K=W.hostname.toLowerCase();if(a8.some((Y)=>K===Y||K.endsWith(`.${Y}`)))return`redirected to login (${W.hostname})`;if(s8.some((Y)=>K.startsWith(Y)))return`redirected to login (${W.hostname})`;let V=X.slice(0,20000).toLowerCase();if(t8.some((Y)=>V.includes(Y)))return`redirected to login page (${W.hostname})`}catch{}return}function e8($){let Z=$.message.toLowerCase();return Z.includes("fetch failed")||Z.includes("unable to verify")||Z.includes("certificate")||Z.includes("timeout")}function X2($){let Z=['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 X of Z){let J=$.querySelector(X),W=J?.getAttribute("content")||J?.getAttribute("datetime")||"";if(W)return W}return""}function _$($,Z){let J=new n8($,{url:Z}).window.document,K=new c8(J).parse();if(K&&K.content){let j=J2.turndown(K.content).replaceAll(/\n{3,}/g,`
229
229
 
230
- `).trim(),Q=K.publishedTime||W2(J)||"";return{title:K.title||J.title||Z,byline:K.byline||"",siteName:K.siteName||"",lang:K.lang||"",publishedTime:Q,markdown:j,excerpt:j.slice(0,300).replaceAll(/\n/g," ")}}let V=J.body;if(V){let Y=V.cloneNode(!0);Y.querySelectorAll("script, style, nav, footer, header, aside").forEach((B)=>B.remove());let Q=(Y.textContent||"").replaceAll(/\s+/g," ").trim();return{title:J.title||Z,byline:"",siteName:"",lang:"",publishedTime:W2(J),markdown:Q,excerpt:Q.slice(0,300)}}return{title:Z,byline:"",siteName:"",lang:"",publishedTime:"",markdown:"",excerpt:""}}function P$($){let Z=$.markdown.trim().toLowerCase(),X=($.title||"").toLowerCase();if($.markdown.trim().length<100)return{ok:!1,reason:"content too short (< 100 chars)"};let J=Z.toLowerCase(),W=[{check:()=>J.includes("loading")&&J.includes("please wait"),desc:"loading page"},{check:()=>J.includes("please ensure javascript is enabled"),desc:"requires javascript"},{check:()=>J.includes("enable javascript to view"),desc:"requires javascript"},{check:()=>J.includes("just a moment"),desc:"cloudflare challenge detected in content"},{check:()=>J.includes("verify you are human"),desc:"human verification"},{check:()=>J.includes("captcha required"),desc:"captcha in extracted content"},{check:()=>J.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(Z),desc:"login form only"}];for(let{check:K,desc:V}of W)if(K())return{ok:!1,reason:V};if(X.includes("just a moment")||X.includes("checking your browser"))return{ok:!1,reason:"cloudflare challenge page detected in title"};return{ok:!0}}function X6($){try{let Z=new URL($),X=Z.hostname.toLowerCase(),J=Z.pathname.toLowerCase();if(["react.dev","nextjs.org","vuejs.org","angular.io","svelte.dev","docs.expo.dev","tailwindcss.com","storybook.js.org"].some((K)=>X===K||X.endsWith(`.${K}`)))return!0;if(J.includes("/playground")||J.includes("/demo")||J.includes("/app"))return!0;if(Z.hash&&Z.hash.length>1)return!0;return!1}catch{return!1}}var K2,V2="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",Y2,s8,t8,r8,e8;var X1=c(()=>{K2=new a8({headingStyle:"atx",bulletListMarker:"-",codeBlockStyle:"fenced"});K2.addRule("removeDataUrls",{filter:($)=>$.tagName==="IMG"&&$.getAttribute("src")?.startsWith("data:"),replacement:()=>""});Y2={"user-agent":V2,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"},s8=[/^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];t8=["accounts.google.com","login.microsoftonline.com","login.live.com","auth0.com","okta.com","auth.mozilla.auth0.com","id.atlassian.com"],r8=["login.","signin.","auth.","sso.","accounts.","idp."],e8=["sign in to continue","log in to continue","authentication required","create an account to continue","subscribe to continue reading","members only"]});var W1={};y0(W1,{parseGitHubUrl:()=>a0,fetchGitHubContent:()=>J1});function a0($){try{let Z=new URL($);if(!(Z.hostname==="github.com"||Z.hostname.endsWith(".github.com")))return null;let X=Z.pathname.split("/").filter(Boolean);if(X.length<2)return null;let[J,W]=X;if(X.length===2)return{owner:J,repo:W,type:"root"};if(X.length>=4&&(X[2]==="blob"||X[2]==="tree")){let K=X[2],V=X[3],Y=X.slice(4).join("/");return{owner:J,repo:W,type:K,ref:V,path:Y}}return null}catch{return null}}async function G0($,Z=1e4){let X=new AbortController,J=setTimeout(()=>X.abort(),Z);try{let W=await fetch(`https://api.github.com${$}`,{headers:H2,signal:X.signal});if(clearTimeout(J),!W.ok)throw Error(`GitHub API ${W.status}: ${$}`);return await W.json()}catch(W){throw clearTimeout(J),W}}async function J6($,Z){try{let X=await G0(`/repos/${$}/${Z}/readme`);if(X.content&&X.encoding==="base64")return Buffer.from(X.content,"base64").toString("utf8");return""}catch{return""}}async function B2($,Z,X="HEAD",J=""){try{let W=await G0(`/repos/${$}/${Z}/git/ref/heads/${X==="HEAD"?"main":X}`).catch(()=>G0(`/repos/${$}/${Z}/git/ref/heads/master`).catch(()=>null)),K;if(W?.object?.sha)K=(await G0(`/repos/${$}/${Z}/git/commits/${W.object.sha}`)).tree.sha;else{let j=await G0(`/repos/${$}/${Z}`);K=(await G0(`/repos/${$}/${Z}/branches/${j.default_branch}`)).commit.commit.tree.sha}let Y=(await G0(`/repos/${$}/${Z}/git/trees/${K}`)).tree||[];if(J)Y=Y.filter((j)=>j.path.startsWith(J));return Y.slice(0,50).map((j)=>({path:j.path,type:j.type==="tree"?"dir":"file",size:j.size}))}catch{return[]}}async function W6($,Z,X,J,W=1e4){let V=[`https://raw.githubusercontent.com/${$}/${Z}/${X&&X!=="HEAD"?X:"main"}/${J}`,`https://raw.githubusercontent.com/${$}/${Z}/master/${J}`];for(let Y of V){let j=new AbortController,Q=setTimeout(()=>j.abort(),W);try{let B=await fetch(Y,{headers:{"user-agent":H2["user-agent"]},signal:j.signal});if(clearTimeout(Q),B.ok)return await B.text()}catch{clearTimeout(Q)}}return null}async function J1($){let Z=a0($);if(!Z)return{ok:!1,error:"Not a valid GitHub URL"};let{owner:X,repo:J,type:W,ref:K,path:V}=Z;try{if(W==="root"||W==="tree"&&!V){let[Y,j,Q]=await Promise.allSettled([G0(`/repos/${X}/${J}`),J6(X,J),B2(X,J,K||"HEAD")]);if(Y.status==="rejected")return{ok:!1,error:Y.reason?.message||"Repo not found"};let B=Y.value,H=j.status==="fulfilled"?j.value:"",G=Q.status==="fulfilled"?Q.value:[],O=B?.description?`
230
+ `).trim(),Q=K.publishedTime||X2(J)||"";return{title:K.title||J.title||Z,byline:K.byline||"",siteName:K.siteName||"",lang:K.lang||"",publishedTime:Q,markdown:j,excerpt:j.slice(0,300).replaceAll(/\n/g," ")}}let V=J.body;if(V){let Y=V.cloneNode(!0);Y.querySelectorAll("script, style, nav, footer, header, aside").forEach((B)=>B.remove());let Q=(Y.textContent||"").replaceAll(/\s+/g," ").trim();return{title:J.title||Z,byline:"",siteName:"",lang:"",publishedTime:X2(J),markdown:Q,excerpt:Q.slice(0,300)}}return{title:Z,byline:"",siteName:"",lang:"",publishedTime:"",markdown:"",excerpt:""}}function P$($){let Z=$.markdown.trim().toLowerCase(),X=($.title||"").toLowerCase();if($.markdown.trim().length<100)return{ok:!1,reason:"content too short (< 100 chars)"};let J=Z.toLowerCase(),W=[{check:()=>J.includes("loading")&&J.includes("please wait"),desc:"loading page"},{check:()=>J.includes("please ensure javascript is enabled"),desc:"requires javascript"},{check:()=>J.includes("enable javascript to view"),desc:"requires javascript"},{check:()=>J.includes("just a moment"),desc:"cloudflare challenge detected in content"},{check:()=>J.includes("verify you are human"),desc:"human verification"},{check:()=>J.includes("captcha required"),desc:"captcha in extracted content"},{check:()=>J.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(Z),desc:"login form only"}];for(let{check:K,desc:V}of W)if(K())return{ok:!1,reason:V};if(X.includes("just a moment")||X.includes("checking your browser"))return{ok:!1,reason:"cloudflare challenge page detected in title"};return{ok:!0}}function $6($){try{let Z=new URL($),X=Z.hostname.toLowerCase(),J=Z.pathname.toLowerCase();if(["react.dev","nextjs.org","vuejs.org","angular.io","svelte.dev","docs.expo.dev","tailwindcss.com","storybook.js.org"].some((K)=>X===K||X.endsWith(`.${K}`)))return!0;if(J.includes("/playground")||J.includes("/demo")||J.includes("/app"))return!0;if(Z.hash&&Z.hash.length>1)return!0;return!1}catch{return!1}}var J2,W2="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",K2,o8,a8,s8,t8;var Z1=c(()=>{J2=new i8({headingStyle:"atx",bulletListMarker:"-",codeBlockStyle:"fenced"});J2.addRule("removeDataUrls",{filter:($)=>$.tagName==="IMG"&&$.getAttribute("src")?.startsWith("data:"),replacement:()=>""});K2={"user-agent":W2,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"},o8=[/^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];a8=["accounts.google.com","login.microsoftonline.com","login.live.com","auth0.com","okta.com","auth.mozilla.auth0.com","id.atlassian.com"],s8=["login.","signin.","auth.","sso.","accounts.","idp."],t8=["sign in to continue","log in to continue","authentication required","create an account to continue","subscribe to continue reading","members only"]});var J1={};p0(J1,{parseGitHubUrl:()=>a0,fetchGitHubContent:()=>X1});function a0($){try{let Z=new URL($);if(!(Z.hostname==="github.com"||Z.hostname.endsWith(".github.com")))return null;let X=Z.pathname.split("/").filter(Boolean);if(X.length<2)return null;let[J,W]=X;if(X.length===2)return{owner:J,repo:W,type:"root"};if(X.length>=4&&(X[2]==="blob"||X[2]==="tree")){let K=X[2],V=X[3],Y=X.slice(4).join("/");return{owner:J,repo:W,type:K,ref:V,path:Y}}return null}catch{return null}}async function O0($,Z=1e4){let X=new AbortController,J=setTimeout(()=>X.abort(),Z);try{let W=await fetch(`https://api.github.com${$}`,{headers:Q2,signal:X.signal});if(clearTimeout(J),!W.ok)throw Error(`GitHub API ${W.status}: ${$}`);return await W.json()}catch(W){throw clearTimeout(J),W}}async function Z6($,Z){try{let X=await O0(`/repos/${$}/${Z}/readme`);if(X.content&&X.encoding==="base64")return Buffer.from(X.content,"base64").toString("utf8");return""}catch{return""}}async function j2($,Z,X="HEAD",J=""){try{let W=await O0(`/repos/${$}/${Z}/git/ref/heads/${X==="HEAD"?"main":X}`).catch(()=>O0(`/repos/${$}/${Z}/git/ref/heads/master`).catch(()=>null)),K;if(W?.object?.sha)K=(await O0(`/repos/${$}/${Z}/git/commits/${W.object.sha}`)).tree.sha;else{let j=await O0(`/repos/${$}/${Z}`);K=(await O0(`/repos/${$}/${Z}/branches/${j.default_branch}`)).commit.commit.tree.sha}let Y=(await O0(`/repos/${$}/${Z}/git/trees/${K}`)).tree||[];if(J)Y=Y.filter((j)=>j.path.startsWith(J));return Y.slice(0,50).map((j)=>({path:j.path,type:j.type==="tree"?"dir":"file",size:j.size}))}catch{return[]}}async function X6($,Z,X,J,W=1e4){let V=[`https://raw.githubusercontent.com/${$}/${Z}/${X&&X!=="HEAD"?X:"main"}/${J}`,`https://raw.githubusercontent.com/${$}/${Z}/master/${J}`];for(let Y of V){let j=new AbortController,Q=setTimeout(()=>j.abort(),W);try{let B=await fetch(Y,{headers:{"user-agent":Q2["user-agent"]},signal:j.signal});if(clearTimeout(Q),B.ok)return await B.text()}catch{clearTimeout(Q)}}return null}async function X1($){let Z=a0($);if(!Z)return{ok:!1,error:"Not a valid GitHub URL"};let{owner:X,repo:J,type:W,ref:K,path:V}=Z;try{if(W==="root"||W==="tree"&&!V){let[Y,j,Q]=await Promise.allSettled([O0(`/repos/${X}/${J}`),Z6(X,J),j2(X,J,K||"HEAD")]);if(Y.status==="rejected")return{ok:!1,error:Y.reason?.message||"Repo not found"};let B=Y.value,H=j.status==="fulfilled"?j.value:"",O=Q.status==="fulfilled"?Q.value:[],G=B?.description?`
231
231
 
232
- > ${B.description}`:"",z=B?.stargazers_count==null?"":` ⭐ ${B.stargazers_count}`,D=B?.language?` · ${B.language}`:"",M=`# ${X}/${J}${z}${D}${O}
232
+ > ${B.description}`:"",D=B?.stargazers_count==null?"":` ⭐ ${B.stargazers_count}`,z=B?.language?` · ${B.language}`:"",M=`# ${X}/${J}${D}${z}${G}
233
233
 
234
234
  `;if(H)M+=H.slice(0,6000);else M+=`[No README found]
235
235
 
236
236
  Files:
237
- ${G.map((A)=>` ${A.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${A.path}`).join(`
238
- `)}`;return{ok:!0,title:`${X}/${J}`,content:M,tree:G.slice(0,30)}}if(W==="blob"&&V){let Y=await W6(X,J,K,V);if(Y===null)return{ok:!1,error:`File not found: ${V}`};return{ok:!0,title:`${X}/${J}: ${V}`,content:Y}}if(W==="tree"&&V){let Y=await B2(X,J,K||"HEAD",V),j=Y.map((Q)=>` ${Q.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${Q.path}`).join(`
237
+ ${O.map((A)=>` ${A.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${A.path}`).join(`
238
+ `)}`;return{ok:!0,title:`${X}/${J}`,content:M,tree:O.slice(0,30)}}if(W==="blob"&&V){let Y=await X6(X,J,K,V);if(Y===null)return{ok:!1,error:`File not found: ${V}`};return{ok:!0,title:`${X}/${J}: ${V}`,content:Y}}if(W==="tree"&&V){let Y=await j2(X,J,K||"HEAD",V),j=Y.map((Q)=>` ${Q.type==="dir"?"\uD83D\uDCC1":"\uD83D\uDCC4"} ${Q.path}`).join(`
239
239
  `);return{ok:!0,title:`${X}/${J}/${V}`,content:`[Directory: ${V}]
240
240
 
241
241
  Files:
242
- ${j}`,tree:Y}}return{ok:!1,error:"Unsupported GitHub URL type"}}catch(Y){return{ok:!1,error:Y.message}}}var H2;var k$=c(()=>{H2={"user-agent":"GreedySearch/1.0",accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});function O2($){try{let Z=new URL($),X=Z.hostname.toLowerCase();if(!(X==="reddit.com"||X.endsWith(".reddit.com")))return null;let J=Z.pathname;if(J.match(/^\/(u|user)\/[^/]+\/?$/i))return{type:"user",cleanUrl:M2($)};if(J.match(/^\/r\/[^/]+\/comments\/[^/]+/i))return{type:"post",cleanUrl:M2($)};return null}catch{return null}}function M2($){try{let Z=new URL($);return`${Z.protocol}//${Z.hostname}${Z.pathname}`}catch{return $}}async function G2($,Z=8000){let X=Date.now();try{let J=$.replaceAll(/\/?$/g,".json"),W=new AbortController,K=setTimeout(()=>W.abort(),15000),V=await fetch(J,{headers:K6,signal:W.signal});if(clearTimeout(K),!V.ok)throw Error(`Reddit API ${V.status}`);let Y=await V.json();if(!Array.isArray(Y)||Y.length<1)throw Error("Invalid Reddit API response structure");let j=Y[0],Q=Y[1],B=j?.data?.children?.[0]?.data;if(!B)throw Error("No post data in Reddit response");let H=V6(B,Q,Z);return{ok:!0,url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:B.title||"Reddit Post",byline:`u/${B.author}`,siteName:`r/${B.subreddit}`,lang:"en",publishedTime:new Date(B.created_utc*1000).toISOString(),excerpt:B.selftext?.slice(0,300).replace(/\n/g," ")||"",markdown:H,contentLength:H.length,needsBrowser:!1,duration:Date.now()-X}}catch(J){return{ok:!1,url:$,finalUrl:$,status:0,error:`Reddit fetch failed: ${J.message}`,needsBrowser:!1,duration:Date.now()-X}}}function V6($,Z,X){let J="";if(J+=`# ${$.title}
242
+ ${j}`,tree:Y}}return{ok:!1,error:"Unsupported GitHub URL type"}}catch(Y){return{ok:!1,error:Y.message}}}var Q2;var k$=c(()=>{Q2={"user-agent":"GreedySearch/1.0",accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});function H2($){try{let Z=new URL($),X=Z.hostname.toLowerCase();if(!(X==="reddit.com"||X.endsWith(".reddit.com")))return null;let J=Z.pathname;if(J.match(/^\/(u|user)\/[^/]+\/?$/i))return{type:"user",cleanUrl:B2($)};if(J.match(/^\/r\/[^/]+\/comments\/[^/]+/i))return{type:"post",cleanUrl:B2($)};return null}catch{return null}}function B2($){try{let Z=new URL($);return`${Z.protocol}//${Z.hostname}${Z.pathname}`}catch{return $}}async function M2($,Z=8000){let X=Date.now();try{let J=$.replaceAll(/\/?$/g,".json"),W=new AbortController,K=setTimeout(()=>W.abort(),15000),V=await fetch(J,{headers:J6,signal:W.signal});if(clearTimeout(K),!V.ok)throw Error(`Reddit API ${V.status}`);let Y=await V.json();if(!Array.isArray(Y)||Y.length<1)throw Error("Invalid Reddit API response structure");let j=Y[0],Q=Y[1],B=j?.data?.children?.[0]?.data;if(!B)throw Error("No post data in Reddit response");let H=W6(B,Q,Z);return{ok:!0,url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:B.title||"Reddit Post",byline:`u/${B.author}`,siteName:`r/${B.subreddit}`,lang:"en",publishedTime:new Date(B.created_utc*1000).toISOString(),excerpt:B.selftext?.slice(0,300).replace(/\n/g," ")||"",markdown:H,contentLength:H.length,needsBrowser:!1,duration:Date.now()-X}}catch(J){return{ok:!1,url:$,finalUrl:$,status:0,error:`Reddit fetch failed: ${J.message}`,needsBrowser:!1,duration:Date.now()-X}}}function W6($,Z,X){let J="";if(J+=`# ${$.title}
243
243
 
244
244
  `,J+=`**Subreddit:** r/${$.subreddit} | **Author:** u/${$.author} | **Score:** ${$.score}
245
245
 
@@ -253,27 +253,27 @@ ${j}`,tree:Y}}return{ok:!1,error:"Unsupported GitHub URL type"}}catch(Y){return{
253
253
 
254
254
  ## Comments
255
255
 
256
- `;let W=Z.data.children.filter((K)=>K.kind==="t1").slice(0,10);for(let K of W)J+=N2(K.data,0),J+=`
256
+ `;let W=Z.data.children.filter((K)=>K.kind==="t1").slice(0,10);for(let K of W)J+=G2(K.data,0),J+=`
257
257
  `}if(J.length>X)J=J.slice(0,X).trim()+`
258
258
 
259
- ... (truncated)`;return J}function N2($,Z){if(!$||$.body==="[deleted]"||$.body==="[removed]")return"";let X="> ".repeat(Z),J="";if(J+=`${X}**u/${$.author}** (${$.score} pts)
259
+ ... (truncated)`;return J}function G2($,Z){if(!$||$.body==="[deleted]"||$.body==="[removed]")return"";let X="> ".repeat(Z),J="";if(J+=`${X}**u/${$.author}** (${$.score} pts)
260
260
  `,J+=`${X}${$.body.replaceAll(`
261
261
  `,`
262
262
  `+X)}
263
263
  `,Z<3&&$.replies?.data?.children){let W=$.replies.data.children.filter((K)=>K.kind==="t1");for(let K of W.slice(0,5))J+=`
264
- `+N2(K.data,Z+1)}return J}var K6;var z2=c(()=>{K6={"user-agent":"GreedySearch/1.0 (Research Bot)",accept:"application/json"}});var V1={};y0(V1,{truncateContent:()=>Y6,trimContentHeadTail:()=>N0});function N0($,Z=8000){if(!$||$.length<=Z)return $;let X=`
264
+ `+G2(K.data,Z+1)}return J}var J6;var O2=c(()=>{J6={"user-agent":"GreedySearch/1.0 (Research Bot)",accept:"application/json"}});var K1={};p0(K1,{truncateContent:()=>K6,trimContentHeadTail:()=>N0});function N0($,Z=8000){if(!$||$.length<=Z)return $;let X=`
265
265
 
266
266
  [...content trimmed...]
267
267
 
268
268
  `,J=Z-X.length,W=Math.floor(J*0.75),K=J-W,V=W;while(V>W-100&&$[V]!==`
269
269
  `)V--;if(V<=W-100)V=W;let Y=$.length-K;while(Y<$.length-K+100&&$[Y]!==`
270
- `)Y++;if(Y>=$.length-K+100)Y=$.length-K;let j=$.slice(0,V).trimEnd(),Q=$.slice(Y).trimStart();return`${j}${X}${Q}`}function Y6($,Z=8000){if(!$||$.length<=Z)return $;let X=$.slice(0,Z),J=X.lastIndexOf(" ");return J>0?`${X.slice(0,J)}...`:`${X}...`}function j6(){if(typeof globalThis.DOMMatrix>"u")globalThis.DOMMatrix=class{constructor(Z=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(Z=void 0,X=0,J=0){this.data=Z,this.width=X,this.height=J}};if(typeof globalThis.Path2D>"u")globalThis.Path2D=class{constructor(Z=void 0){}}}async function Q6(){j6();let $=await import("pdf-parse"),Z=$.PDFParse??$.default;if(!Z)throw Error("pdf-parse did not export PDFParse");return Z}async function D2($,Z){try{let J=new(await Q6())({data:new Uint8Array($)});await J.load();let W=await J.getText(),K=W.text?.trim();if(!K)return null;return{title:new URL(Z).pathname.split("/").pop()||"Document.pdf",content:`## PDF Content (${W.total} pages)
270
+ `)Y++;if(Y>=$.length-K+100)Y=$.length-K;let j=$.slice(0,V).trimEnd(),Q=$.slice(Y).trimStart();return`${j}${X}${Q}`}function K6($,Z=8000){if(!$||$.length<=Z)return $;let X=$.slice(0,Z),J=X.lastIndexOf(" ");return J>0?`${X.slice(0,J)}...`:`${X}...`}function V6(){if(typeof globalThis.DOMMatrix>"u")globalThis.DOMMatrix=class{constructor(Z=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(Z=void 0,X=0,J=0){this.data=Z,this.width=X,this.height=J}};if(typeof globalThis.Path2D>"u")globalThis.Path2D=class{constructor(Z=void 0){}}}async function Y6(){V6();let $=await import("pdf-parse"),Z=$.PDFParse??$.default;if(!Z)throw Error("pdf-parse did not export PDFParse");return Z}async function N2($,Z){try{let J=new(await Y6())({data:new Uint8Array($)});await J.load();let W=await J.getText(),K=W.text?.trim();if(!K)return null;return{title:new URL(Z).pathname.split("/").pop()||"Document.pdf",content:`## PDF Content (${W.total} pages)
271
271
 
272
- ${K}`,pages:W.total}}catch(X){return{error:X.message||String(X)}}}function I($="",Z=240){let X=String($).replaceAll(/\s+/g," ").trim();if(X.length<=Z)return X;let J=X.slice(0,Z),W=J.lastIndexOf(" ");return W>0?`${J.slice(0,W)}...`:`${J}...`}function Y1($=""){let Z=I($,180);if(!Z)return"";if(/^https?:\/\//i.test(Z))return"";let X=Z.split(/\s+/).filter(Boolean).length,J=/[A-Z]/.test(Z),W=/\d/.test(Z);return Z===Z.toLowerCase()&&X<=4&&!J&&!W?"":Z}function j1($="",Z=""){let X=Y1($),J=Y1(Z);if(!J)return X;if(!X)return J;let W=/^https?:\/\//i.test(X),K=/^https?:\/\//i.test(J);if(W&&!K)return J;if(!W&&K)return X;return J.length>X.length?J:X}function $0($){if(!$)return null;try{let Z=new URL($);if(!["http:","https:"].includes(Z.protocol))return null;if(Z.hash="",Z.hostname=Z.hostname.toLowerCase(),Z.protocol==="https:"&&Z.port==="443"||Z.protocol==="http:"&&Z.port==="80")Z.port="";for(let W of[...Z.searchParams.keys()]){let K=W.toLowerCase();if(B6.includes(K)||K.startsWith("utm_"))Z.searchParams.delete(W)}Z.searchParams.sort();let X=Z.pathname.replace(/\/{1,10}$/,"")||"/";Z.pathname=X;let J=Z.toString();return X==="/"?J.replace(/\/$/,""):J}catch{return null}}function O6($){try{return new URL($).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function s0($,Z){return Z.some((X)=>$===X||$.endsWith(`.${X}`))}function Q1($,Z="",X=""){let J=Z.toLowerCase(),W=X.toLowerCase();if($==="github.com"||$==="gitlab.com")return"repo";if($==="arxiv.org"||$==="doi.org"||$==="semanticscholar.org"||$.endsWith(".semanticscholar.org")||W.includes("/paper/")||W.includes("/pdf/"))return"academic";if(s0($,A2))return"social";if(s0($,H6))return"community";if(s0($,M6))return"news";if($.startsWith("docs.")||$.startsWith("developer.")||$.startsWith("developers.")||$.startsWith("api.")||J.includes("documentation")||J.includes("docs")||J.includes("reference")||W.includes("/docs/")||W.includes("/reference/")||W.includes("/api/"))return"official-docs";if($.startsWith("blog.")||W.includes("/blog/"))return"maintainer-blog";return"website"}function G6($){switch($){case"official-docs":return 5;case"repo":return 4;case"academic":return 4;case"maintainer-blog":return 3;case"website":return 2;case"community":return 1;case"news":return 0;case"social":return-6;default:return 0}}function N6($){let Z=Object.values($.perEngine||{}).map((X)=>X?.rank||99);return Z.length?Math.min(...Z):99}function w0($){return $.smartScore*3+$.engineCount*5+G6($.sourceType)*2+Math.max(0,7-N6($))}function D6($){let Z=$.toLowerCase(),X=[];if(Z.includes("openai")||Z.includes("gpt")||Z.includes("chatgpt"))X.push("openai.com","platform.openai.com","help.openai.com");if(Z.includes("anthropic")||Z.includes("claude"))X.push("anthropic.com","docs.anthropic.com");if(Z.includes("bun"))X.push("bun.sh","bun.com");if(Z.includes("next.js")||Z.includes("nextjs"))X.push("nextjs.org","vercel.com");if(Z.includes("playwright"))X.push("playwright.dev");if(Z.includes("supabase"))X.push("supabase.com","supabase.io");if(Z.includes("prisma"))X.push("prisma.io");if(Z.includes("tailwind"))X.push("tailwindcss.com");if(Z.includes("vite"))X.push("vitejs.dev","vite.dev");if(Z.includes("astro"))X.push("astro.build");if(Z.includes("svelte"))X.push("svelte.dev");if(Z.includes("solid"))X.push("solidjs.com");if(Z.includes("vue")||Z.includes("nuxt"))X.push("vuejs.org","nuxt.com");if(Z.includes("react")||Z.includes("react native"))X.push("react.dev","reactnative.dev");if(Z.includes("angular"))X.push("angular.io","angular.dev");if(Z.includes("node.js")||Z.includes("nodejs"))X.push("nodejs.org","nodejs.dev","npmjs.com");if(/\bgo\b/.test(Z)||Z.includes("golang"))X.push("go.dev","golang.org","pkg.go.dev");if(Z.includes("deno"))X.push("deno.land","deno.com");if(Z.includes("fresh"))X.push("fresh.deno.dev");if(Z.includes("typescript")||Z.includes("ts"))X.push("typescriptlang.org");if(Z.includes("python"))X.push("python.org","docs.python.org");if(Z.includes("rust"))X.push("rust-lang.org","docs.rs","crates.io");if(Z.includes("zig"))X.push("ziglang.org");if(Z.includes("docker"))X.push("docker.com","docs.docker.com","hub.docker.com");if(Z.includes("kubernetes")||Z.includes("k8s"))X.push("kubernetes.io","k8s.io");if(Z.includes("postgres")||Z.includes("postgresql"))X.push("postgresql.org","neon.tech","supabase.com");if(Z.includes("redis"))X.push("redis.io");if(Z.includes("sqlite"))X.push("sqlite.org");if(Z.includes("cloudflare"))X.push("developers.cloudflare.com","cloudflare.com");if(Z.includes("vercel"))X.push("vercel.com","nextjs.org");if(Z.includes("netlify"))X.push("netlify.com","docs.netlify.com");if(Z.includes("stripe"))X.push("stripe.com","docs.stripe.com");if(Z.includes("github"))X.push("github.com","docs.github.com");if(Z.includes("gitlab"))X.push("gitlab.com","docs.gitlab.com");if(Z.includes("aws"))X.push("aws.amazon.com","docs.aws.amazon.com");if(Z.includes("azure"))X.push("azure.microsoft.com","learn.microsoft.com");if(Z.includes("gcp")||Z.includes("google cloud"))X.push("cloud.google.com","developers.google.com");if(Z.includes("gemini")||Z.includes("google ai"))X.push("ai.google.dev","developers.google.com");for(let J of A2){let W=J.replace(/\.com$/,"");if(Z.includes(W))X.push(J)}return[...new Set(X)]}function U2($,Z){return $===Z||$.endsWith(`.${Z}`)}function x0($,Z=""){let X=new Map,J=Object.keys($||{}).filter((Q)=>!Q.startsWith("_")),W=D6(Z);for(let Q of J){let B=$[Q];if(!B?.sources)continue;for(let H=0;H<B.sources.length;H++){let G=B.sources[H],O=$0(G.url);if(!O||O.length<10)continue;let z=Y1(G.title||""),D=O6(O),M=Q1(D,z,O),A=0;if(W.some((x)=>U2(D,x)))A+=10;if(M==="official-docs")A+=3;let b=O.toLowerCase();if(/\/docs\/|\/documentation\/|\.dev\/|\/api\/|\/reference\//.test(b))A+=2;let P=W.some((x)=>U2(D,x));if(M==="social"&&!P)A-=20;if(W.length>0){if(s0(D,z6))A-=3;else if(M==="community"&&!s0(D,["stackoverflow.com","stackexchange.com"]))A-=1}let F=X.get(O)||{id:"",canonicalUrl:O,displayUrl:G.url||O,domain:D,title:"",engines:[],engineCount:0,perEngine:{},sourceType:M,isOfficial:M==="official-docs",smartScore:0};if(F.title=j1(F.title,z),F.displayUrl=F.displayUrl||G.url||O,F.sourceType=F.sourceType||M,F.isOfficial=F.isOfficial||M==="official-docs",F.smartScore=Math.max(F.smartScore,A),!F.engines.includes(Q))F.engines.push(Q);F.perEngine[Q]={rank:H+1,title:j1(F.perEngine[Q]?.title||"",z)},X.set(O,F)}}let K=Array.from(X.values()).map((Q)=>({...Q,engineCount:Q.engines.length})),V=K.filter((Q)=>Q.sourceType!=="social"),Y=K.filter((Q)=>Q.sourceType==="social");return V.sort((Q,B)=>{let H=w0(B)-w0(Q);if(H!==0)return H;return Q.domain.localeCompare(B.domain)}),Y.sort((Q,B)=>{let H=w0(B)-w0(Q);if(H!==0)return H;return Q.domain.localeCompare(B.domain)}),[...V,...Y].slice(0,12).map((Q,B)=>({...Q,id:`S${B+1}`,title:Q.title||Q.domain||Q.canonicalUrl}))}function L$($,Z){let X=new Map(Z.map((J)=>[J.id,J]));return $.map((J)=>{let W=X.get(J.id);if(!W)return J;let K=j1(J.title,W.title||"");return{...J,title:K||J.title,fetch:{attempted:!0,ok:!W.error&&W.contentChars>100,status:W.status||null,finalUrl:W.finalUrl||W.url||J.canonicalUrl,contentType:W.contentType||"",lastModified:W.lastModified||"",publishedTime:W.publishedTime||"",byline:W.byline||"",siteName:W.siteName||"",lang:W.lang||"",title:W.title||"",snippet:W.snippet||"",contentChars:W.contentChars||0,source:W.source||"unknown",duration:W.duration||0,error:W.error||""}}})}var B6,H6,M6,A2,z6;var S0=c(()=>{B6=["fbclid","gclid","ref","ref_src","ref_url","source","utm_campaign","utm_content","utm_medium","utm_source","utm_term"],H6=["dev.to","hashnode.com","medium.com","reddit.com","stackoverflow.com","stackexchange.com","substack.com"],M6=["arstechnica.com","techcrunch.com","theverge.com","venturebeat.com","wired.com","zdnet.com"],A2=["facebook.com","instagram.com","linkedin.com","pinterest.com","tiktok.com","twitter.com","x.com"];z6=["reddit.com","news.ycombinator.com","lobste.rs"]});var k2={};y0(k2,{fetchTopSource:()=>t0,fetchSourceContent:()=>P2,fetchMultipleSources:()=>B1});async function U6($,Z,X=8000){let J=Date.now();try{let K=(await q(["evalraw",$,"Page.getFrameTree","{}"]).then((z)=>JSON.parse(z)).catch(()=>null))?.frameTree?.frame?.id||void 0,V=await q(["evalraw",$,"Network.loadNetworkResource",JSON.stringify({frameId:K,url:Z,options:{disableCache:!0,includeCredentials:!1}})],20000),j=JSON.parse(V).resource;if(!j?.success||!j.httpStatusCode)return{url:Z,error:j?.netErrorName||j?.netError||"loadNetworkResource failed",source:"chrome",duration:Date.now()-J,needsFallback:!0};let Q="";if(j.stream)try{let z=await q(["evalraw",$,"IO.read",JSON.stringify({handle:j.stream})],1e4);Q=JSON.parse(z).data||"",await q(["evalraw",$,"IO.close",JSON.stringify({handle:j.stream})]).catch(()=>{})}catch{}if(!Q||Q.length<100)return{url:Z,error:"Empty response body from Network.loadNetworkResource",source:"chrome",duration:Date.now()-J,needsFallback:!0};let B=A$(j.httpStatusCode,Q,Z,Z);if(B.blocked)return{url:Z,status:j.httpStatusCode,error:`Blocked: ${B.reason}`,source:"chrome",duration:Date.now()-J,needsBrowser:!0};let H=_$(Q,Z),G=P$(H);if(!G.ok)return{url:Z,status:j.httpStatusCode,error:`Low quality: ${G.reason}`,source:"chrome",duration:Date.now()-J,needsBrowser:!0};let O=N0(H.markdown,X);return{url:Z,finalUrl:Z,status:j.httpStatusCode,contentType:"text/markdown",lastModified:"",publishedTime:H.publishedTime||"",byline:H.byline||"",siteName:H.siteName||"",lang:H.lang||"",title:H.title||Z,snippet:H.excerpt,content:O,contentChars:O.length,source:"chrome",duration:Date.now()-J}}catch(W){return{url:Z,error:W.message,source:"chrome",duration:Date.now()-J,needsFallback:!0}}}function _2($){try{return new URL($).pathname.toLowerCase().endsWith(".pdf")}catch{return!1}}async function A6($,Z=8000){let X=U$($);if(X.blocked)return{url:$,finalUrl:$,status:403,error:`Blocked: ${X.reason}`,source:"pdf-http"};let J=new AbortController,W=setTimeout(()=>J.abort(),20000),K=Date.now();try{let V=await fetch($,{method:"GET",redirect:"follow",signal:J.signal,headers:$1({accept:"application/pdf,application/octet-stream;q=0.9,*/*;q=0.5"})});clearTimeout(W);let Y=V.headers.get("content-type")||"",j=V.url||$,Q=Number.parseInt(V.headers.get("content-length")||"0",10);if(V.status>=400)return{url:$,finalUrl:j,status:V.status,error:`HTTP ${V.status}`,source:"pdf-http",duration:Date.now()-K};if(!Y.toLowerCase().includes("application/pdf")&&!_2(j))return null;if(Q>31457280)return{url:$,finalUrl:j,status:V.status,error:`PDF too large: ${Q} bytes`,source:"pdf-http",duration:Date.now()-K};let B=Buffer.from(await V.arrayBuffer()),H=await D2(B,j);if(!H||H.error)return{url:$,finalUrl:j,status:V.status,error:H?.error||"PDF text extraction failed",source:"pdf-http",duration:Date.now()-K};let G=N0(H.content,Z);return{url:$,finalUrl:j,status:V.status,contentType:"application/pdf",lastModified:V.headers.get("last-modified")||"",title:H.title,snippet:I(G,320),content:G,contentChars:G.length,pages:H.pages,source:"pdf-http",duration:Date.now()-K}}catch(V){return clearTimeout(W),{url:$,finalUrl:$,error:V.message||String(V),source:"pdf-http",duration:Date.now()-K}}}async function P2($,Z=8000){let X=Date.now();if(_2($)){let K=await A6($,Z);if(K?.content||K?.status===403)return K}if(a0($)){let K=a0($);if(K&&(K.type==="root"||K.type==="tree"||K.type==="blob"&&!K.path?.includes("."))){let V=await J1($);if(V.ok){let Y=N0(V.content,Z);return{url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:V.title,snippet:Y.slice(0,320),content:Y,contentChars:Y.length,source:"github-api",...V.tree&&{tree:V.tree},duration:Date.now()-X}}process.stderr.write(`[greedysearch] GitHub API fetch failed, trying HTTP: ${V.error}
273
- `)}}if(O2($)?.type==="post"){process.stderr.write(`[greedysearch] Using Reddit JSON API for: ${$.slice(0,60)}...
274
- `);let K=await G2($,Z);if(K.ok){let V=N0(K.markdown,Z);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:V,contentChars:V.length,source:"reddit-api",duration:Date.now()-X}}process.stderr.write(`[greedysearch] Reddit API fetch failed, falling back to HTTP: ${K.error}
275
- `)}let W=await Z1($,{timeoutMs:1e4});if(W.ok){let K=N0(W.markdown,Z);return{url:$,finalUrl:W.finalUrl,status:W.status,contentType:"text/markdown",lastModified:W.lastModified||"",publishedTime:W.publishedTime||"",byline:W.byline||"",siteName:W.siteName||"",lang:W.lang||"",title:W.title,snippet:W.excerpt,content:K,contentChars:K.length,source:"http",duration:Date.now()-X}}if(W.needsBrowser)try{let K=await j0();try{let V=await U6(K,$,Z);if(V.content&&V.content.length>100)return V}finally{await O0(K)}}catch{}return process.stderr.write(`[greedysearch] HTTP failed for ${$.slice(0,60)}, trying browser...
276
- `),await _6($,Z)}async function _6($,Z=8000){let X=Date.now(),J;try{J=await j0()}catch(W){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:`openNewTab failed: ${W.message}`,source:"browser",duration:Date.now()-X}}try{await q(["nav",J,$],30000),await new Promise((Y)=>setTimeout(Y,800));let W=await q(["eval",J,String.raw`
272
+ ${K}`,pages:W.total}}catch(X){return{error:X.message||String(X)}}}function I($="",Z=240){let X=String($).replaceAll(/\s+/g," ").trim();if(X.length<=Z)return X;let J=X.slice(0,Z),W=J.lastIndexOf(" ");return W>0?`${J.slice(0,W)}...`:`${J}...`}function V1($=""){let Z=I($,180);if(!Z)return"";if(/^https?:\/\//i.test(Z))return"";let X=Z.split(/\s+/).filter(Boolean).length,J=/[A-Z]/.test(Z),W=/\d/.test(Z);return Z===Z.toLowerCase()&&X<=4&&!J&&!W?"":Z}function Y1($="",Z=""){let X=V1($),J=V1(Z);if(!J)return X;if(!X)return J;let W=/^https?:\/\//i.test(X),K=/^https?:\/\//i.test(J);if(W&&!K)return J;if(!W&&K)return X;return J.length>X.length?J:X}function $0($){if(!$)return null;try{let Z=new URL($);if(!["http:","https:"].includes(Z.protocol))return null;if(Z.hash="",Z.hostname=Z.hostname.toLowerCase(),Z.protocol==="https:"&&Z.port==="443"||Z.protocol==="http:"&&Z.port==="80")Z.port="";for(let W of[...Z.searchParams.keys()]){let K=W.toLowerCase();if(j6.includes(K)||K.startsWith("utm_"))Z.searchParams.delete(W)}Z.searchParams.sort();let X=Z.pathname.replace(/\/{1,10}$/,"")||"/";Z.pathname=X;let J=Z.toString();return X==="/"?J.replace(/\/$/,""):J}catch{return null}}function H6($){try{return new URL($).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function s0($,Z){return Z.some((X)=>$===X||$.endsWith(`.${X}`))}function j1($,Z="",X=""){let J=Z.toLowerCase(),W=X.toLowerCase();if($==="github.com"||$==="gitlab.com")return"repo";if($==="arxiv.org"||$==="doi.org"||$==="semanticscholar.org"||$.endsWith(".semanticscholar.org")||W.includes("/paper/")||W.includes("/pdf/"))return"academic";if(s0($,z2))return"social";if(s0($,Q6))return"community";if(s0($,B6))return"news";if($.startsWith("docs.")||$.startsWith("developer.")||$.startsWith("developers.")||$.startsWith("api.")||J.includes("documentation")||J.includes("docs")||J.includes("reference")||W.includes("/docs/")||W.includes("/reference/")||W.includes("/api/"))return"official-docs";if($.startsWith("blog.")||W.includes("/blog/"))return"maintainer-blog";return"website"}function M6($){switch($){case"official-docs":return 5;case"repo":return 4;case"academic":return 4;case"maintainer-blog":return 3;case"website":return 2;case"community":return 1;case"news":return 0;case"social":return-6;default:return 0}}function G6($){let Z=Object.values($.perEngine||{}).map((X)=>X?.rank||99);return Z.length?Math.min(...Z):99}function w0($){return $.smartScore*3+$.engineCount*5+M6($.sourceType)*2+Math.max(0,7-G6($))}function N6($){let Z=$.toLowerCase(),X=[];if(Z.includes("openai")||Z.includes("gpt")||Z.includes("chatgpt"))X.push("openai.com","platform.openai.com","help.openai.com");if(Z.includes("anthropic")||Z.includes("claude"))X.push("anthropic.com","docs.anthropic.com");if(Z.includes("bun"))X.push("bun.sh","bun.com");if(Z.includes("next.js")||Z.includes("nextjs"))X.push("nextjs.org","vercel.com");if(Z.includes("playwright"))X.push("playwright.dev");if(Z.includes("supabase"))X.push("supabase.com","supabase.io");if(Z.includes("prisma"))X.push("prisma.io");if(Z.includes("tailwind"))X.push("tailwindcss.com");if(Z.includes("vite"))X.push("vitejs.dev","vite.dev");if(Z.includes("astro"))X.push("astro.build");if(Z.includes("svelte"))X.push("svelte.dev");if(Z.includes("solid"))X.push("solidjs.com");if(Z.includes("vue")||Z.includes("nuxt"))X.push("vuejs.org","nuxt.com");if(Z.includes("react")||Z.includes("react native"))X.push("react.dev","reactnative.dev");if(Z.includes("angular"))X.push("angular.io","angular.dev");if(Z.includes("node.js")||Z.includes("nodejs"))X.push("nodejs.org","nodejs.dev","npmjs.com");if(/\bgo\b/.test(Z)||Z.includes("golang"))X.push("go.dev","golang.org","pkg.go.dev");if(Z.includes("deno"))X.push("deno.land","deno.com");if(Z.includes("fresh"))X.push("fresh.deno.dev");if(Z.includes("typescript")||Z.includes("ts"))X.push("typescriptlang.org");if(Z.includes("python"))X.push("python.org","docs.python.org");if(Z.includes("rust"))X.push("rust-lang.org","docs.rs","crates.io");if(Z.includes("zig"))X.push("ziglang.org");if(Z.includes("docker"))X.push("docker.com","docs.docker.com","hub.docker.com");if(Z.includes("kubernetes")||Z.includes("k8s"))X.push("kubernetes.io","k8s.io");if(Z.includes("postgres")||Z.includes("postgresql"))X.push("postgresql.org","neon.tech","supabase.com");if(Z.includes("redis"))X.push("redis.io");if(Z.includes("sqlite"))X.push("sqlite.org");if(Z.includes("cloudflare"))X.push("developers.cloudflare.com","cloudflare.com");if(Z.includes("vercel"))X.push("vercel.com","nextjs.org");if(Z.includes("netlify"))X.push("netlify.com","docs.netlify.com");if(Z.includes("stripe"))X.push("stripe.com","docs.stripe.com");if(Z.includes("github"))X.push("github.com","docs.github.com");if(Z.includes("gitlab"))X.push("gitlab.com","docs.gitlab.com");if(Z.includes("aws"))X.push("aws.amazon.com","docs.aws.amazon.com");if(Z.includes("azure"))X.push("azure.microsoft.com","learn.microsoft.com");if(Z.includes("gcp")||Z.includes("google cloud"))X.push("cloud.google.com","developers.google.com");if(Z.includes("gemini")||Z.includes("google ai"))X.push("ai.google.dev","developers.google.com");for(let J of z2){let W=J.replace(/\.com$/,"");if(Z.includes(W))X.push(J)}return[...new Set(X)]}function D2($,Z){return $===Z||$.endsWith(`.${Z}`)}function g0($,Z=""){let X=new Map,J=Object.keys($||{}).filter((Q)=>!Q.startsWith("_")),W=N6(Z);for(let Q of J){let B=$[Q];if(!B?.sources)continue;for(let H=0;H<B.sources.length;H++){let O=B.sources[H],G=$0(O.url);if(!G||G.length<10)continue;let D=V1(O.title||""),z=H6(G),M=j1(z,D,G),A=0;if(W.some((f)=>D2(z,f)))A+=10;if(M==="official-docs")A+=3;let b=G.toLowerCase();if(/\/docs\/|\/documentation\/|\.dev\/|\/api\/|\/reference\//.test(b))A+=2;let P=W.some((f)=>D2(z,f));if(M==="social"&&!P)A-=20;if(W.length>0){if(s0(z,O6))A-=3;else if(M==="community"&&!s0(z,["stackoverflow.com","stackexchange.com"]))A-=1}let w=X.get(G)||{id:"",canonicalUrl:G,displayUrl:O.url||G,domain:z,title:"",engines:[],engineCount:0,perEngine:{},sourceType:M,isOfficial:M==="official-docs",smartScore:0};if(w.title=Y1(w.title,D),w.displayUrl=w.displayUrl||O.url||G,w.sourceType=w.sourceType||M,w.isOfficial=w.isOfficial||M==="official-docs",w.smartScore=Math.max(w.smartScore,A),!w.engines.includes(Q))w.engines.push(Q);w.perEngine[Q]={rank:H+1,title:Y1(w.perEngine[Q]?.title||"",D)},X.set(G,w)}}let K=Array.from(X.values()).map((Q)=>({...Q,engineCount:Q.engines.length})),V=K.filter((Q)=>Q.sourceType!=="social"),Y=K.filter((Q)=>Q.sourceType==="social");return V.sort((Q,B)=>{let H=w0(B)-w0(Q);if(H!==0)return H;return Q.domain.localeCompare(B.domain)}),Y.sort((Q,B)=>{let H=w0(B)-w0(Q);if(H!==0)return H;return Q.domain.localeCompare(B.domain)}),[...V,...Y].slice(0,12).map((Q,B)=>({...Q,id:`S${B+1}`,title:Q.title||Q.domain||Q.canonicalUrl}))}function L$($,Z){let X=new Map(Z.map((J)=>[J.id,J]));return $.map((J)=>{let W=X.get(J.id);if(!W)return J;let K=Y1(J.title,W.title||"");return{...J,title:K||J.title,fetch:{attempted:!0,ok:!W.error&&W.contentChars>100,status:W.status||null,finalUrl:W.finalUrl||W.url||J.canonicalUrl,contentType:W.contentType||"",lastModified:W.lastModified||"",publishedTime:W.publishedTime||"",byline:W.byline||"",siteName:W.siteName||"",lang:W.lang||"",title:W.title||"",snippet:W.snippet||"",contentChars:W.contentChars||0,source:W.source||"unknown",duration:W.duration||0,error:W.error||""}}})}var j6,Q6,B6,z2,O6;var y0=c(()=>{j6=["fbclid","gclid","ref","ref_src","ref_url","source","utm_campaign","utm_content","utm_medium","utm_source","utm_term"],Q6=["dev.to","hashnode.com","medium.com","reddit.com","stackoverflow.com","stackexchange.com","substack.com"],B6=["arstechnica.com","techcrunch.com","theverge.com","venturebeat.com","wired.com","zdnet.com"],z2=["facebook.com","instagram.com","linkedin.com","pinterest.com","tiktok.com","twitter.com","x.com"];O6=["reddit.com","news.ycombinator.com","lobste.rs"]});var _2={};p0(_2,{fetchTopSource:()=>t0,fetchSourceContent:()=>A2,fetchMultipleSources:()=>Q1});async function D6($,Z,X=8000){let J=Date.now();try{let K=(await q(["evalraw",$,"Page.getFrameTree","{}"]).then((D)=>JSON.parse(D)).catch(()=>null))?.frameTree?.frame?.id||void 0,V=await q(["evalraw",$,"Network.loadNetworkResource",JSON.stringify({frameId:K,url:Z,options:{disableCache:!0,includeCredentials:!1}})],20000),j=JSON.parse(V).resource;if(!j?.success||!j.httpStatusCode)return{url:Z,error:j?.netErrorName||j?.netError||"loadNetworkResource failed",source:"chrome",duration:Date.now()-J,needsFallback:!0};let Q="";if(j.stream)try{let D=await q(["evalraw",$,"IO.read",JSON.stringify({handle:j.stream})],1e4);Q=JSON.parse(D).data||"",await q(["evalraw",$,"IO.close",JSON.stringify({handle:j.stream})]).catch(()=>{})}catch{}if(!Q||Q.length<100)return{url:Z,error:"Empty response body from Network.loadNetworkResource",source:"chrome",duration:Date.now()-J,needsFallback:!0};let B=A$(j.httpStatusCode,Q,Z,Z);if(B.blocked)return{url:Z,status:j.httpStatusCode,error:`Blocked: ${B.reason}`,source:"chrome",duration:Date.now()-J,needsBrowser:!0};let H=_$(Q,Z),O=P$(H);if(!O.ok)return{url:Z,status:j.httpStatusCode,error:`Low quality: ${O.reason}`,source:"chrome",duration:Date.now()-J,needsBrowser:!0};let G=N0(H.markdown,X);return{url:Z,finalUrl:Z,status:j.httpStatusCode,contentType:"text/markdown",lastModified:"",publishedTime:H.publishedTime||"",byline:H.byline||"",siteName:H.siteName||"",lang:H.lang||"",title:H.title||Z,snippet:H.excerpt,content:G,contentChars:G.length,source:"chrome",duration:Date.now()-J}}catch(W){return{url:Z,error:W.message,source:"chrome",duration:Date.now()-J,needsFallback:!0}}}function U2($){try{return new URL($).pathname.toLowerCase().endsWith(".pdf")}catch{return!1}}async function z6($,Z=8000){let X=U$($);if(X.blocked)return{url:$,finalUrl:$,status:403,error:`Blocked: ${X.reason}`,source:"pdf-http"};let J=new AbortController,W=setTimeout(()=>J.abort(),20000),K=Date.now();try{let V=await fetch($,{method:"GET",redirect:"follow",signal:J.signal,headers:e$({accept:"application/pdf,application/octet-stream;q=0.9,*/*;q=0.5"})});clearTimeout(W);let Y=V.headers.get("content-type")||"",j=V.url||$,Q=Number.parseInt(V.headers.get("content-length")||"0",10);if(V.status>=400)return{url:$,finalUrl:j,status:V.status,error:`HTTP ${V.status}`,source:"pdf-http",duration:Date.now()-K};if(!Y.toLowerCase().includes("application/pdf")&&!U2(j))return null;if(Q>31457280)return{url:$,finalUrl:j,status:V.status,error:`PDF too large: ${Q} bytes`,source:"pdf-http",duration:Date.now()-K};let B=Buffer.from(await V.arrayBuffer()),H=await N2(B,j);if(!H||H.error)return{url:$,finalUrl:j,status:V.status,error:H?.error||"PDF text extraction failed",source:"pdf-http",duration:Date.now()-K};let O=N0(H.content,Z);return{url:$,finalUrl:j,status:V.status,contentType:"application/pdf",lastModified:V.headers.get("last-modified")||"",title:H.title,snippet:I(O,320),content:O,contentChars:O.length,pages:H.pages,source:"pdf-http",duration:Date.now()-K}}catch(V){return clearTimeout(W),{url:$,finalUrl:$,error:V.message||String(V),source:"pdf-http",duration:Date.now()-K}}}async function A2($,Z=8000){let X=Date.now();if(U2($)){let K=await z6($,Z);if(K?.content||K?.status===403)return K}if(a0($)){let K=a0($);if(K&&(K.type==="root"||K.type==="tree"||K.type==="blob"&&!K.path?.includes("."))){let V=await X1($);if(V.ok){let Y=N0(V.content,Z);return{url:$,finalUrl:$,status:200,contentType:"text/markdown",lastModified:"",title:V.title,snippet:Y.slice(0,320),content:Y,contentChars:Y.length,source:"github-api",...V.tree&&{tree:V.tree},duration:Date.now()-X}}process.stderr.write(`[greedysearch] GitHub API fetch failed, trying HTTP: ${V.error}
273
+ `)}}if(H2($)?.type==="post"){process.stderr.write(`[greedysearch] Using Reddit JSON API for: ${$.slice(0,60)}...
274
+ `);let K=await M2($,Z);if(K.ok){let V=N0(K.markdown,Z);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:V,contentChars:V.length,source:"reddit-api",duration:Date.now()-X}}process.stderr.write(`[greedysearch] Reddit API fetch failed, falling back to HTTP: ${K.error}
275
+ `)}let W=await $1($,{timeoutMs:1e4});if(W.ok){let K=N0(W.markdown,Z);return{url:$,finalUrl:W.finalUrl,status:W.status,contentType:"text/markdown",lastModified:W.lastModified||"",publishedTime:W.publishedTime||"",byline:W.byline||"",siteName:W.siteName||"",lang:W.lang||"",title:W.title,snippet:W.excerpt,content:K,contentChars:K.length,source:"http",duration:Date.now()-X}}if(W.needsBrowser)try{let K=await Q0();try{let V=await D6(K,$,Z);if(V.content&&V.content.length>100)return V}finally{await G0(K)}}catch{}return process.stderr.write(`[greedysearch] HTTP failed for ${$.slice(0,60)}, trying browser...
276
+ `),await U6($,Z)}async function U6($,Z=8000){let X=Date.now(),J;try{J=await Q0()}catch(W){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:`openNewTab failed: ${W.message}`,source:"browser",duration:Date.now()-X}}try{await q(["nav",J,$],30000),await new Promise((Y)=>setTimeout(Y,800));let W=await q(["eval",J,String.raw`
277
277
  (function(){
278
278
  var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
279
279
  var text = (el || document.body).innerText;
@@ -283,19 +283,19 @@ ${K}`,pages:W.total}}catch(X){return{error:X.message||String(X)}}}function I($="
283
283
  url: location.href
284
284
  });
285
285
  })()
286
- `]),K=JSON.parse(W),V=N0(K.content,Z);return{url:$,finalUrl:K.url||$,status:200,contentType:"text/plain",lastModified:"",title:K.title,snippet:I(V,320),content:V,contentChars:V.length,source:"browser",duration:Date.now()-X}}catch(W){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:W.message,source:"browser",duration:Date.now()-X}}finally{await O0(J)}}async function B1($,Z=5,X=8000,J=m$){let W=$.slice(0,Z);if(W.length===0)return[];let K=Math.min(W.length,Math.max(1,Number.parseInt(String(J),10)||m$));process.stderr.write(`[greedysearch] Fetching content from ${W.length} sources via HTTP (concurrency ${K})...
287
- `);let V=Array(W.length),Y=0,j=0;async function Q(){while(!0){let O=Y++;if(O>=W.length)return;let z=W[O],D=z.canonicalUrl||z.url;process.stderr.write(`[greedysearch] [${O+1}/${W.length}] Fetching: ${D.slice(0,60)}...
288
- `);let M=await P2(D,X).catch((A)=>({url:D,title:"",content:null,snippet:"",contentChars:0,error:A.message,source:"error",duration:0}));if(V[O]={id:z.id,...M},M.content&&M.content.length>100)process.stderr.write(`[greedysearch] ✓ ${M.source}: ${M.content.length} chars
286
+ `]),K=JSON.parse(W),V=N0(K.content,Z);return{url:$,finalUrl:K.url||$,status:200,contentType:"text/plain",lastModified:"",title:K.title,snippet:I(V,320),content:V,contentChars:V.length,source:"browser",duration:Date.now()-X}}catch(W){return{url:$,title:"",content:null,snippet:"",contentChars:0,error:W.message,source:"browser",duration:Date.now()-X}}finally{await G0(J)}}async function Q1($,Z=5,X=8000,J=d$){let W=$.slice(0,Z);if(W.length===0)return[];let K=Math.min(W.length,Math.max(1,Number.parseInt(String(J),10)||d$));process.stderr.write(`[greedysearch] Fetching content from ${W.length} sources via HTTP (concurrency ${K})...
287
+ `);let V=Array(W.length),Y=0,j=0;async function Q(){while(!0){let G=Y++;if(G>=W.length)return;let D=W[G],z=D.canonicalUrl||D.url;process.stderr.write(`[greedysearch] [${G+1}/${W.length}] Fetching: ${z.slice(0,60)}...
288
+ `);let M=await A2(z,X).catch((A)=>({url:z,title:"",content:null,snippet:"",contentChars:0,error:A.message,source:"error",duration:0}));if(V[G]={id:D.id,...M},M.content&&M.content.length>100)process.stderr.write(`[greedysearch] ✓ ${M.source}: ${M.content.length} chars
289
289
  `);else if(M.error)process.stderr.write(`[greedysearch] ✗ ${M.error.slice(0,80)}
290
290
  `);j+=1,process.stderr.write(`PROGRESS:fetch:${j}/${W.length}
291
- `)}}await Promise.all(Array.from({length:K},()=>Q()));let B=V.filter((O)=>O.content&&O.content.length>100),H=V.filter((O)=>O.source==="http").length,G=V.filter((O)=>O.source==="browser").length;return process.stderr.write(`[greedysearch] Fetched ${B.length}/${V.length} sources (HTTP: ${H}, Browser: ${G})
292
- `),V}async function t0($){let Z=await j0();await q(["list"]);try{await q(["nav",Z,$],30000),await new Promise((J)=>setTimeout(J,800));let X=await q(["eval",Z,String.raw`
291
+ `)}}await Promise.all(Array.from({length:K},()=>Q()));let B=V.filter((G)=>G.content&&G.content.length>100),H=V.filter((G)=>G.source==="http").length,O=V.filter((G)=>G.source==="browser").length;return process.stderr.write(`[greedysearch] Fetched ${B.length}/${V.length} sources (HTTP: ${H}, Browser: ${O})
292
+ `),V}async function t0($){let Z=await Q0();await q(["list"]);try{await q(["nav",Z,$],30000),await new Promise((J)=>setTimeout(J,800));let X=await q(["eval",Z,String.raw`
293
293
  (function(){
294
294
  var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
295
295
  var text = (el || document.body).innerText;
296
296
  return text.replace(/\s+/g, ' ').trim();
297
297
  })()
298
- `]);return{url:$,content:X}}catch(X){return{url:$,content:null,error:X.message}}finally{await O0(Z)}}var H1=c(()=>{X1();k$();z2();e$();V0();S0()});var F2={};y0(F2,{writeSourcesToFiles:()=>M1});import{mkdirSync as P6,writeFileSync as k6}from"node:fs";import{join as L2}from"node:path";function M1($,Z=L6){return P6(Z,{recursive:!0}),$.map((X)=>{if(!X.content||X.content.length<10)return X;let J=String(X.id||"unknown").replace(/[^a-zA-Z0-9_-]/g,""),W=(X.canonicalUrl||X.url||"").replace(/^https?:\/\//,"").replace(/[^a-zA-Z0-9]/g,"-").slice(0,40),K=`${J}-${W}.md`,V=L2(Z,K),Y=`---
298
+ `]);return{url:$,content:X}}catch(X){return{url:$,content:null,error:X.message}}finally{await G0(Z)}}var B1=c(()=>{Z1();k$();O2();r$();Y0();y0()});var k2={};p0(k2,{writeSourcesToFiles:()=>H1});import{mkdirSync as A6,writeFileSync as _6}from"node:fs";import{join as P2}from"node:path";function H1($,Z=P6){return A6(Z,{recursive:!0}),$.map((X)=>{if(!X.content||X.content.length<10)return X;let J=String(X.id||"unknown").replace(/[^a-zA-Z0-9_-]/g,""),W=(X.canonicalUrl||X.url||"").replace(/^https?:\/\//,"").replace(/[^a-zA-Z0-9]/g,"-").slice(0,40),K=`${J}-${W}.md`,V=P2(Z,K),Y=`---
299
299
  url: ${X.finalUrl||X.url}
300
300
  title: ${X.title||""}
301
301
  source: ${X.source||"unknown"}
@@ -303,19 +303,19 @@ status: ${X.status||""}
303
303
  chars: ${X.contentChars||X.content.length}
304
304
  ---
305
305
 
306
- `;k6(V,Y+X.content,"utf8");let{content:j,...Q}=X;return{...Q,contentPath:V,contentChars:X.contentChars||j.length}})}var L6;var O1=c(()=>{L6=L2(process.cwd(),".dm","greedysearch-sources")});e$();V0();import{appendFileSync as v9,existsSync as E$,readFileSync as f9}from"node:fs";import{homedir as x9}from"node:os";import{join as l2}from"node:path";h0();V0();import{spawn as c8}from"node:child_process";import{existsSync as J2}from"node:fs";import{dirname as d8,join as z$}from"node:path";import{fileURLToPath as l8}from"node:url";function D$($){return l8(new URL(".",$)).replace(/^\/([A-Z]:)/,"$1")}function u8($,Z=J2){let X=new Set;for(let J of $.filter(Boolean)){if(X.has(J))continue;if(X.add(J),Z(J))return J}return $.filter(Boolean).at(-1)}function v0($,{moduleDir:Z,entrypoint:X=process.argv[1],env:J=process.env,exists:W=J2}={}){let K=X?d8(X):null,V=J.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null,Y=[Z?z$(Z,"..","..","extractors",$):null,Z?z$(Z,"..","extractors",$):null,V?z$(V,"extractors",$):null,K?z$(K,"..","extractors",$):null];return u8(Y,W)}var n8=D$(import.meta.url);function f0($,Z,X=null,J=!1,W=null,K=null){if(W===null)W=$.includes("logically")?120000:$.includes("chatgpt")?80000:$.includes("gemini")?70000:60000;let V=[...X?["--tab",X]:[],...J?["--short"]:[],...K?["--locale",K]:[]],Y=v0($,{moduleDir:n8});return new Promise((j,Q)=>{let B=c8(M0(),[Y,"--stdin",...V],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:n}});B.stdin.write(Z),B.stdin.end();let H="",G="";B.stdout.on("data",(z)=>H+=z),B.stderr.on("data",(z)=>{if(G+=z,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(z)});let O=setTimeout(()=>{B.kill();let z=(A,b=20)=>String(A??"").split(/\r?\n/).filter(Boolean).slice(-b).join(`
307
- `),D=null;try{let A=JSON.parse(H.trim());if(A._envelope)D=A._envelope}catch{}let M=Error(`${$} timed out after ${W/1000}s`+(D?.lastStage?` (last stage: ${D.lastStage})`:""));M.engineScript=$,M.lastStage=D?.lastStage||null,M.partialErr=z(G),M.partialOut=z(H),Q(M)},W);B.on("close",(z)=>{if(clearTimeout(O),z===0)try{j(JSON.parse(H.trim()))}catch{Q(Error(`bad JSON from ${$}: ${H.slice(0,100)}`))}else{let D=null;try{let b=JSON.parse(H.trim());if(b._envelope)D=b._envelope}catch{}let M=G.trim()||`extractor exit ${z}`,A=Error(M);if(D)A.envelope=D;Q(A)}})})}H1();O1();import{mkdirSync as F6,readdirSync as w6,rmSync as T6,statSync as C6,writeFileSync as G1}from"node:fs";import{join as F$}from"node:path";var R6=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function I6($){return $.toLowerCase().replaceAll(/[^a-z0-9]+/g,"-").replaceAll(/^-|-$/g,"").slice(0,60)}var E6=604800000,b6=10;function q6($){try{let Z=w6($).filter((J)=>J.endsWith(".json")||J.endsWith(".md")).map((J)=>({f:J,mtime:C6(F$($,J)).mtimeMs})).sort((J,W)=>W.mtime-J.mtime),X=Date.now()-E6;for(let J=b6;J<Z.length;J++)if(Z[J].mtime<X)T6(F$($,Z[J].f),{force:!0})}catch{}}function v6(){let $=F$(R6,"..","..","results");return F6($,{recursive:!0}),q6($),$}function g0($,Z,{inline:X=!1,synthesize:J=!1,query:W=""}={}){let K=`${JSON.stringify($,null,2)}
306
+ `;_6(V,Y+X.content,"utf8");let{content:j,...Q}=X;return{...Q,contentPath:V,contentChars:X.contentChars||j.length}})}var P6;var M1=c(()=>{P6=P2(process.cwd(),".dm","greedysearch-sources")});r$();Y0();import{appendFileSync as E9,existsSync as E$,readFileSync as b9}from"node:fs";import{homedir as q9}from"node:os";import{join as b$}from"node:path";E0();Y0();import{spawn as l8}from"node:child_process";import{existsSync as Z2}from"node:fs";import{dirname as p8,join as z$}from"node:path";import{fileURLToPath as m8}from"node:url";function f0($){return m8(new URL(".",$)).replace(/^\/([A-Z]:)/,"$1")}function d8($,Z=Z2){let X=new Set;for(let J of $.filter(Boolean)){if(X.has(J))continue;if(X.add(J),Z(J))return J}return $.filter(Boolean).at(-1)}function x0($,{moduleDir:Z,entrypoint:X=process.argv[1],env:J=process.env,exists:W=Z2}={}){let K=X?p8(X):null,V=J.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null,Y=[Z?z$(Z,"..","..","extractors",$):null,Z?z$(Z,"..","extractors",$):null,V?z$(V,"extractors",$):null,K?z$(K,"..","extractors",$):null];return d8(Y,W)}var u8=f0(import.meta.url);function S0($,Z,X=null,J=!1,W=null,K=null){if(W===null)W=$.includes("logically")?120000:$.includes("chatgpt")?80000:$.includes("gemini")?70000:60000;let V=[...X?["--tab",X]:[],...J?["--short"]:[],...K?["--locale",K]:[]],Y=x0($,{moduleDir:u8});return new Promise((j,Q)=>{let B=l8(Z0(),[Y,"--stdin",...V],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:r}});B.stdin.write(Z),B.stdin.end();let H="",O="";B.stdout.on("data",(D)=>H+=D),B.stderr.on("data",(D)=>{if(O+=D,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(D)});let G=setTimeout(()=>{B.kill();let D=(A,b=20)=>String(A??"").split(/\r?\n/).filter(Boolean).slice(-b).join(`
307
+ `),z=null;try{let A=JSON.parse(H.trim());if(A._envelope)z=A._envelope}catch{}let M=Error(`${$} timed out after ${W/1000}s`+(z?.lastStage?` (last stage: ${z.lastStage})`:""));M.engineScript=$,M.lastStage=z?.lastStage||null,M.partialErr=D(O),M.partialOut=D(H),Q(M)},W);B.on("close",(D)=>{if(clearTimeout(G),D===0)try{j(JSON.parse(H.trim()))}catch{Q(Error(`bad JSON from ${$}: ${H.slice(0,100)}`))}else{let z=null;try{let b=JSON.parse(H.trim());if(b._envelope)z=b._envelope}catch{}let M=O.trim()||`extractor exit ${D}`,A=Error(M);if(z)A.envelope=z;Q(A)}})})}B1();M1();import{mkdirSync as k6,readdirSync as L6,rmSync as F6,statSync as w6,writeFileSync as G1}from"node:fs";import{join as F$}from"node:path";var T6=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function C6($){return $.toLowerCase().replaceAll(/[^a-z0-9]+/g,"-").replaceAll(/^-|-$/g,"").slice(0,60)}var R6=604800000,I6=10;function E6($){try{let Z=L6($).filter((J)=>J.endsWith(".json")||J.endsWith(".md")).map((J)=>({f:J,mtime:w6(F$($,J)).mtimeMs})).sort((J,W)=>W.mtime-J.mtime),X=Date.now()-R6;for(let J=I6;J<Z.length;J++)if(Z[J].mtime<X)F6(F$($,Z[J].f),{force:!0})}catch{}}function b6(){let $=F$(T6,"..","..","results");return k6($,{recursive:!0}),E6($),$}function h0($,Z,{inline:X=!1,synthesize:J=!1,query:W=""}={}){let K=`${JSON.stringify($,null,2)}
308
308
  `;if(Z){G1(Z,K,"utf8"),process.stderr.write(`Results written to ${Z}
309
- `);return}if(X){process.stdout.write(K);return}let V=new Date().toISOString().replaceAll("T","_").replaceAll(/[:.]/g,"-").slice(0,19),Y=I6(W),j=F$(v6(),`${V}_${Y}`);if(G1(`${j}.json`,K,"utf8"),J&&$._synthesis?.answer)G1(`${j}-synthesis.md`,$._synthesis.answer,"utf8"),process.stdout.write(`${j}-synthesis.md
309
+ `);return}if(X){process.stdout.write(K);return}let V=new Date().toISOString().replaceAll("T","_").replaceAll(/[:.]/g,"-").slice(0,19),Y=C6(W),j=F$(b6(),`${V}_${Y}`);if(G1(`${j}.json`,K,"utf8"),J&&$._synthesis?.answer)G1(`${j}-synthesis.md`,$._synthesis.answer,"utf8"),process.stdout.write(`${j}-synthesis.md
310
310
  `);else process.stdout.write(`${j}.json
311
- `)}var f6=["perplexity","bing","chatgpt","semantic-scholar","logically"],x6=/timed out|timeout|verification|captcha|cloudflare|turnstile|input not found|ask-input|clipboard|copy button hidden|sign.in|login required/i,S6=/needs-human|verification required|please solve|captcha|cloudflare|turnstile|could not be completed automatically|manual intervention|sign.in|login required/i;function w2($){return x6.test(String($||""))}function N1($){return S6.test(String($||""))}function T2($){return f6.filter((Z)=>{let X=$?.[Z];if(!X)return!1;if(X._envelope?.blockedBy)return!0;if(X._envelope?.verificationResult==="needs-human")return!0;let J=X.error;return J&&w2(J)})}function C2($){if(!$)return!1;let Z=$.envelope;if(Z?.blockedBy)return!0;if(Z?.verificationResult==="needs-human")return!0;return w2($.message)}S0();V0();S0();function g6($){let Z="",X=!1,J=!1;for(let W of String($)){if(J){Z+=W,J=!1;continue}if(W==="\\"){Z+=W,J=!0;continue}if(W==='"'){X=!X,Z+=W;continue}if(X&&W===`
312
- `)Z+="\\n";else if(X&&W==="\r")Z+="\\r";else if(X&&W==="\t")Z+="\\t";else Z+=W}return Z}function r0($){if(!$)return null;let Z=String($).trim(),X=Z.indexOf("BEGIN_JSON"),J=Z.indexOf("END_JSON");if(X!==-1&&J!==-1&&X<J)Z=Z.slice(X+10,J).trim();else{let Y=Z.indexOf("{");if(Y>0)Z=Z.slice(Y)}let W=[Z,Z.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],K=Z.indexOf("{"),V=Z.lastIndexOf("}");if(K!==-1&&V!==-1&&K<V)W.push(Z.slice(K,V+1));for(let Y of[...W]){let j=g6(Y);if(j!==Y)W.push(j)}for(let Y of W)try{return JSON.parse(Y)}catch{}return null}function R2($,Z,X=""){let J=new Set(Z.map((j)=>j.id)),W=["high","medium","low","mixed","conflicting"].includes($?.agreement?.level)?$.agreement.level:"mixed",K=Array.isArray($?.claims)?$.claims.map((j)=>({claim:I(j?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(j?.support)?j.support:"moderate",sourceIds:Array.isArray(j?.sourceIds)?j.sourceIds.filter((Q)=>J.has(Q)):[]})).filter((j)=>j.claim):[],V=Array.isArray($?.recommendedSources)?$.recommendedSources.filter((j)=>J.has(j)).slice(0,6):[],Y="";if(X){let j=X.indexOf("{"),Q=X.lastIndexOf("}");if(j!==-1&&Q!==-1&&j<Q)Y=X.slice(j,Q+1);else Y=X}return{answer:I($?.answer||Y||X,4000),agreement:{level:W,summary:I($?.agreement?.summary||"",280)},differences:Array.isArray($?.differences)?$.differences.map((j)=>I(j,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray($?.caveats)?$.caveats.map((j)=>I(j,220)).filter(Boolean).slice(0,5):[],claims:K,recommendedSources:V}}function I2($,Z,X,{grounded:J=!1}={}){let W={};for(let Y of["perplexity","bing","google"]){let j=Z[Y];if(!j)continue;if(j.error){W[Y]={status:"error",error:String(j.error)};continue}W[Y]={status:"ok",answer:I(j.answer||"",J?4500:2200),sourceIds:X.filter((Q)=>Q.engines.includes(Y)).sort((Q,B)=>(Q.perEngine[Y]?.rank||99)-(B.perEngine[Y]?.rank||99)).map((Q)=>Q.id).slice(0,6)}}let K=J?700:300,V=X.slice(0,J?10:8).map((Y)=>({id:Y.id,title:Y.title,domain:Y.domain,canonicalUrl:Y.canonicalUrl,sourceType:Y.sourceType,isOfficial:Y.isOfficial,engines:Y.engines,engineCount:Y.engineCount,fetch:Y.fetch?.attempted?{ok:Y.fetch.ok,publishedTime:Y.fetch.publishedTime||"",byline:Y.fetch.byline||"",snippet:I(Y.fetch.snippet||"",K)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${$}`,"",`Engine summaries:
311
+ `)}var q6=["perplexity","bing","chatgpt","semantic-scholar","logically"],v6=/timed out|timeout|verification|captcha|cloudflare|turnstile|input not found|ask-input|clipboard|copy button hidden|sign.in|login required/i,f6=/needs-human|verification required|please solve|captcha|cloudflare|turnstile|could not be completed automatically|manual intervention|sign.in|login required/i;function L2($){return v6.test(String($||""))}function O1($){return f6.test(String($||""))}function F2($){return q6.filter((Z)=>{let X=$?.[Z];if(!X)return!1;if(X._envelope?.blockedBy)return!0;if(X._envelope?.verificationResult==="needs-human")return!0;let J=X.error;return J&&L2(J)})}function w2($){if(!$)return!1;let Z=$.envelope;if(Z?.blockedBy)return!0;if(Z?.verificationResult==="needs-human")return!0;return L2($.message)}y0();Y0();y0();function x6($){let Z="",X=!1,J=!1;for(let W of String($)){if(J){Z+=W,J=!1;continue}if(W==="\\"){Z+=W,J=!0;continue}if(W==='"'){X=!X,Z+=W;continue}if(X&&W===`
312
+ `)Z+="\\n";else if(X&&W==="\r")Z+="\\r";else if(X&&W==="\t")Z+="\\t";else Z+=W}return Z}function r0($){if(!$)return null;let Z=String($).trim(),X=Z.indexOf("BEGIN_JSON"),J=Z.indexOf("END_JSON");if(X!==-1&&J!==-1&&X<J)Z=Z.slice(X+10,J).trim();else{let Y=Z.indexOf("{");if(Y>0)Z=Z.slice(Y)}let W=[Z,Z.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],K=Z.indexOf("{"),V=Z.lastIndexOf("}");if(K!==-1&&V!==-1&&K<V)W.push(Z.slice(K,V+1));for(let Y of[...W]){let j=x6(Y);if(j!==Y)W.push(j)}for(let Y of W)try{return JSON.parse(Y)}catch{}return null}function T2($,Z,X=""){let J=new Set(Z.map((j)=>j.id)),W=["high","medium","low","mixed","conflicting"].includes($?.agreement?.level)?$.agreement.level:"mixed",K=Array.isArray($?.claims)?$.claims.map((j)=>({claim:I(j?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(j?.support)?j.support:"moderate",sourceIds:Array.isArray(j?.sourceIds)?j.sourceIds.filter((Q)=>J.has(Q)):[]})).filter((j)=>j.claim):[],V=Array.isArray($?.recommendedSources)?$.recommendedSources.filter((j)=>J.has(j)).slice(0,6):[],Y="";if(X){let j=X.indexOf("{"),Q=X.lastIndexOf("}");if(j!==-1&&Q!==-1&&j<Q)Y=X.slice(j,Q+1);else Y=X}return{answer:I($?.answer||Y||X,4000),agreement:{level:W,summary:I($?.agreement?.summary||"",280)},differences:Array.isArray($?.differences)?$.differences.map((j)=>I(j,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray($?.caveats)?$.caveats.map((j)=>I(j,220)).filter(Boolean).slice(0,5):[],claims:K,recommendedSources:V}}function C2($,Z,X,{grounded:J=!1}={}){let W={};for(let Y of["perplexity","bing","google"]){let j=Z[Y];if(!j)continue;if(j.error){W[Y]={status:"error",error:String(j.error)};continue}W[Y]={status:"ok",answer:I(j.answer||"",J?4500:2200),sourceIds:X.filter((Q)=>Q.engines.includes(Y)).sort((Q,B)=>(Q.perEngine[Y]?.rank||99)-(B.perEngine[Y]?.rank||99)).map((Q)=>Q.id).slice(0,6)}}let K=J?700:300,V=X.slice(0,J?10:8).map((Y)=>({id:Y.id,title:Y.title,domain:Y.domain,canonicalUrl:Y.canonicalUrl,sourceType:Y.sourceType,isOfficial:Y.isOfficial,engines:Y.engines,engineCount:Y.engineCount,fetch:Y.fetch?.attempted?{ok:Y.fetch.ok,publishedTime:Y.fetch.publishedTime||"",byline:Y.fetch.byline||"",snippet:I(Y.fetch.snippet||"",K)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${$}`,"",`Engine summaries:
313
313
  ${JSON.stringify(W,null,2)}`,"",`Source registry:
314
314
  ${JSON.stringify(V,null,2)}`,"","Instructions:","- Write a clear, direct answer in markdown (use headers/bullets where they help readability)","- Cite sources inline as [S1], [S2] etc. when making specific claims","- Prefer sources with content (fetch.ok=true and non-empty snippet) for citations","- Note where the engines agree or meaningfully disagree","- List any important caveats or limitations","- recommendedSources: the 2-4 source IDs most worth reading for this query","","Respond ONLY with a JSON object wrapped in BEGIN_JSON / END_JSON markers:","","BEGIN_JSON",JSON.stringify({answer:"<your markdown answer here>",agreement:{level:"high|medium|mixed|conflicting",summary:"<one sentence>"},differences:["<notable difference between engines, if any>"],caveats:["<important caveat or limitation>"],recommendedSources:["S1","S2"]},null,2),"END_JSON"].join(`
315
- `)}function E2($){let Z=Array.isArray($._sources)?$._sources:[],X=Z.length>0?Z[0]?.engineCount||0:0,J=Z.filter((Q)=>Q.isOfficial).length,W=Z.filter((Q)=>Q.isOfficial||Q.sourceType==="maintainer-blog").length,K=Z.filter((Q)=>Q.fetch?.attempted).length,V=Z.filter((Q)=>Q.fetch?.ok).length,Y=Z.reduce((Q,B)=>{return Q[B.sourceType]=(Q[B.sourceType]||0)+1,Q},{}),j=$._synthesis?.agreement?.level;return{sourcesCount:Z.length,topSourceConsensus:X,agreementLevel:j||(X>=3?"high":X>=2?"medium":"low"),enginesResponded:e.filter((Q)=>$[Q]?.answer&&!$[Q]?.error),enginesFailed:e.filter((Q)=>$[Q]?.error),officialSourceCount:J,firstPartySourceCount:W,fetchedSourceSuccessRate:K>0?Number((V/K).toFixed(2)):0,sourceTypeBreakdown:Y}}V0();import{spawn as y6}from"node:child_process";S0();var h6=D$(import.meta.url),p6={gemini:"gemini.mjs",chatgpt:"chatgpt.mjs"},m6={gemini:"https://gemini.google.com/app",chatgpt:"https://chatgpt.com/"};function e0($="gemini"){let Z=String($||"gemini").toLowerCase();if(Z==="gem")return"gemini";if(Z==="gpt")return"chatgpt";return Z}function b2($="gemini"){return m6[e0($)]||"about:blank"}async function q2($,Z,{tabPrefix:X=null,timeoutMs:J=180000,visible:W=null}={}){let K=e0($),V=p6[K];if(!V||!p0.includes(K))throw Error(`Unsupported synthesizer "${$}". Supported: ${p0.join(", ")}`);return new Promise((Y,j)=>{let Q=X?["--tab",String(X)]:[],B=v0(V,{moduleDir:h6}),H={...process.env,CDP_PROFILE_DIR:n};if(W!==!0)delete H.GREEDY_SEARCH_VISIBLE,delete H.GREEDY_SEARCH_ALWAYS_VISIBLE;else H.GREEDY_SEARCH_VISIBLE="1",H.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let G=y6(nodeRuntimeCommand(),[B,"--stdin",...Q],{stdio:["pipe","pipe","pipe"],env:H});G.stdin.write(Z),G.stdin.end();let O="",z="";G.stdout.on("data",(M)=>O+=M),G.stderr.on("data",(M)=>z+=M);let D=setTimeout(()=>{G.kill(),j(Error(`${K} prompt timed out after ${J/1000}s`))},J);G.on("close",(M)=>{if(clearTimeout(D),M!==0){j(Error(z.trim()||`${K} extractor failed`));return}try{Y(JSON.parse(O.trim()))}catch{j(Error(`bad JSON from ${K}: ${O.slice(0,100)}`))}})})}async function T0($,Z={}){return q2("gemini",$,Z)}async function v2($,Z,{grounded:X=!1,tabPrefix:J=null,visible:W=null,synthesizer:K="gemini"}={}){let V=e0(K),Y=Array.isArray(Z._sources)?Z._sources:x0(Z),j=I2($,Z,Y,{grounded:X}),Q=await q2(V,j,{tabPrefix:J,timeoutMs:180000,visible:W}),B=r0(Q.answer||""),G=B&&["answer","agreement","claims","differences","caveats"].some((z)=>(z in B));if(B&&["perplexity","bing","google","chatgpt","gemini"].some((z)=>(z in B))&&!G)B=null;return{...R2(B,Y,Q.answer||""),rawAnswer:Q.answer||"",synthesizedBy:V,synthesizerSources:Q.sources||[],geminiSources:V==="gemini"?Q.sources||[]:[]}}var d6=/^(can you |could you |please |would you mind |i need to (know|understand) |i want to (know|understand) |i('m| am) (looking for|wondering about|curious about) |i need (information|info) (about|on) |tell me )?(about |explain |describe |give me |help me understand |search for |look up |find |research )?(about |regarding |on |for )?(it|this|the following)?\s*/i,l6=/\b(latest|newest|current|recent|up-to-date|up to date)\b/i,u6=/\b\d+\.\d+|\bv\d+\b|\b20(2[0-9]|[3-9]\d)\b/i;function c6($){let Z=$.trim().replace(d6,"").trim();return Z.length>4?Z:$.trim()}function n6($,Z=new Date().getFullYear()){if(!l6.test($))return $;if(u6.test($))return $;return`${$.trimEnd()} ${Z}`}function w$($){if(!$?.trim())return $;let Z=c6($);return Z=n6(Z),Z||$}S0();import{spawn as i6}from"node:child_process";import{existsSync as o6,mkdirSync as z1,writeFileSync as i}from"node:fs";import{join as f}from"node:path";import{fileURLToPath as a6}from"node:url";V0();h0();var s6=a6(new URL(".",import.meta.url)).replace(/^\/([A-Z]:)/,"$1");function L1($=s6){let Z=[f($,"search.mjs"),f($,"..","bin","search.mjs"),f($,"..","..","bin","search.mjs")];for(let X of Z)if(o6(X))return X;return Z[Z.length-1]}var t6=L1(),r6=f(process.cwd(),".dm","greedysearch-research");function e6($){return String($||"research").toLowerCase().replaceAll(/[^a-z0-9]+/g,"-").replaceAll(/^-|-$/g,"").slice(0,60)||"research"}function Q0($,Z=1/0){let X=new Set,J=[];for(let W of $||[]){let K=I(String(W||""),1000);if(!K||X.has(K))continue;if(X.add(K),J.push(K),J.length>=Z)break}return J}async function $9(...$){let{fetchMultipleSources:Z}=await Promise.resolve().then(() => (H1(),k2));return Z(...$)}async function P1(...$){let{writeSourcesToFiles:Z}=await Promise.resolve().then(() => (O1(),F2));return Z(...$)}function Z9({breadth:$=3,iterations:Z=2,maxSources:X}){let J=D1($,1,5,3),W=D1(Z,1,3,2),K=D1(X??Math.max(5,J*W*2),3,12,8);return{breadth:J,iterations:W,maxSources:K}}function D1($,Z,X,J){let W=Number.parseInt(String($??""),10);if(!Number.isFinite(W))return J;return Math.min(X,Math.max(Z,W))}function X9($,Z,X,{expand:J=!0,includeOriginal:W=!0,exclude:K=[]}={}){let V=Array.isArray($?.queries)?$.queries:[],Y=[],j=new Set([...K].map((Q)=>X0(Q).toLowerCase()));for(let Q of V){let B=typeof Q==="string"?Q:Q?.query,H=typeof Q==="string"?"":Q?.researchGoal||"";U1(Y,B,H,{exclude:j})}if(W)U1(Y,Z,"Original user query",{prepend:!0,exclude:j});if(J){let Q=[{query:`${Z} official docs GitHub`,researchGoal:"Find primary project docs, repository details, and maintainer claims."},{query:`${Z} benchmarks limitations compatibility`,researchGoal:"Validate performance claims and uncover unsupported APIs or caveats."},{query:`${Z} alternatives comparison production use cases`,researchGoal:"Compare against conventional headless browsers and identify when to choose it."},{query:`${Z} anti bot detection Cloudflare screenshots visual rendering`,researchGoal:"Check automation risks, rendering gaps, screenshots, and bot-detection behavior."}];for(let B of Q){if(Y.length>=X)break;U1(Y,B.query,B.researchGoal,{exclude:j})}}return Y.slice(0,X)}function U1($,Z,X="",{prepend:J=!1,exclude:W=new Set}={}){if(!Z||typeof Z!=="string")return;let K=X0(Z);if(!K||W.has(K.toLowerCase())||$.some((Y)=>Y.query.toLowerCase()===K.toLowerCase()))return;let V={query:K,researchGoal:I(X,320)};if(J)$.unshift(V);else $.push(V)}function X0($){return W9(J9(String($)))}function J9($){let Z="",X=0;while(X<$.length){let J=$.indexOf("[",X);if(J===-1){Z+=$.slice(X);break}let W=$.indexOf("]",J+1);if(W===-1||$[W+1]!=="("||W===J+1){Z+=$.slice(X,J+1),X=J+1;continue}let K=$.indexOf(")",W+2);if(K===-1){Z+=$.slice(X,J+1),X=J+1;continue}let V=$.slice(W+2,K).trimStart();if(!V.startsWith("http://")&&!V.startsWith("https://")){Z+=$.slice(X,J+1),X=J+1;continue}Z+=$.slice(X,J),Z+=$.slice(J+1,W),X=K+1}return Z}function W9($){let Z="",X=!1;for(let J of $)if(J===" "||J==="\t"||J===`
316
- `||J==="\r"){if(!X)Z+=" ";X=!0}else Z+=J,X=!1;return Z.trim()}function f2($){return new Set(String($).toLowerCase().normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"").split(/[^\w]+/).filter((Z)=>Z.length>1))}function I$($,Z){let X=f2($),J=f2(Z),W=new Set([...X,...J]).size;if(W===0)return 1;let K=0;for(let V of X)if(J.has(V))K++;return K/W}function y2($,Z,{threshold:X=0.75,roundIndex:J=0,originalQuery:W=null}={}){let K=X0($).toLowerCase();if(Z.has(K))return!0;if(W&&J>0&&K===X0(W).toLowerCase())return!0;for(let V of Z)if(I$(K,V)>=X)return!0;return!1}function K9($,Z,X,J){let W=Z.map((K)=>({queries:K.queries?.map((V)=>V.query||"")||[],learnings:K.learnings||[],gaps:K.gaps||[]}));return["You are evaluating the quality of an iterative research run.","Assess coverage across: official sources, limitations/risks, benchmarks/performance, production usage, and counter-evidence.","Score each dimension 0-10. Overall score 0-10.","Identify remaining knowledge gaps.","Propose targeted next actions (search queries or direct URL fetches) that would most improve the research.","Decide whether to continue or stop.","terminationReason must be one of: quality_threshold | max_rounds | no_novel_actions | insufficient_evidence.","",`Original research question: ${$}`,`Rounds completed: ${JSON.stringify(W,null,2)}`,`Accumulated learnings: ${JSON.stringify(X.slice(0,12),null,2)}`,`Known gaps: ${JSON.stringify(J.slice(0,8),null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({score:7.5,coverage:{officialSources:8,limitations:5,benchmarks:7,productionUseCases:6,counterEvidence:4},knowledgeGaps:["specific gap or missing evidence"],shouldContinue:!0,terminationReason:"quality_threshold",nextActions:[{type:"search",query:"targeted search query"},{type:"fetchUrl",url:"https://example.com/primary-doc"}]},null,2),"END_JSON"].join(`
317
- `)}function V9($,Z,X,J,W){let K=[],V=[{template:(Y)=>`${Y} official documentation`,label:"official docs"},{template:(Y)=>`${Y} GitHub issues discussions`,label:"community signals"},{template:(Y)=>`${Y} benchmarks performance comparison`,label:"benchmarks"},{template:(Y)=>`${Y} limitations risks caveats`,label:"limitations"},{template:(Y)=>`${Y} production deployment experience`,label:"production usage"},{template:(Y)=>`${Z} ${Y} counter evidence`,label:"counter-evidence"}];for(let Y=0;Y<$.length&&K.length<J;Y++){let j=$[Y],Q=V[Y%V.length],B=Q.template(j);if(!y2(B,X,{roundIndex:W}))K.push({query:B,researchGoal:`Gap-driven: ${j} (${Q.label})`})}return K}async function Y9($,Z,X,J,W){try{let K=await T0(K9($,Z,X,J),{timeoutMs:120000}),V=$$(K,{}),Y=typeof V.score==="number"?Math.min(10,Math.max(0,V.score)):W.length>0?W[W.length-1]:5,j=Array.isArray(V.knowledgeGaps)?V.knowledgeGaps.map((G)=>String(G)).filter(Boolean).slice(0,6):[],Q=Array.isArray(V.nextActions)?V.nextActions.slice(0,5):[],B=typeof V.shouldContinue==="boolean"?V.shouldContinue:Y<8,H=V.terminationReason||null;return{score:Y,coverage:V.coverage||{},knowledgeGaps:j,shouldContinue:B,nextActions:Q,terminationReason:H||(Y>=8.5?"quality_threshold":null),evaluationError:""}}catch(K){return process.stderr.write(`[greedysearch] Quality evaluation failed: ${K.message}
318
- `),{score:W.length>0?W[W.length-1]:5,coverage:{},knowledgeGaps:[],shouldContinue:!0,nextActions:[],terminationReason:null,evaluationError:K.message}}}function j9($){let Z={};for(let X of Object.keys($||{}).filter((J)=>!J.startsWith("_"))){let J=$?.[X];if(!J)continue;Z[X]=J.error?{status:"error",error:String(J.error)}:{status:"ok",answer:I(J.answer||"",1400),sources:Array.isArray(J.sources)?J.sources.slice(0,5).map((W)=>({title:I(W.title||"",160),url:W.url||""})):[]}}return Z}function Q9($,Z,X=[],J=[],W=[]){let K=J.length>0?`
315
+ `)}function R2($){let Z=Array.isArray($._sources)?$._sources:[],X=Z.length>0?Z[0]?.engineCount||0:0,J=Z.filter((Q)=>Q.isOfficial).length,W=Z.filter((Q)=>Q.isOfficial||Q.sourceType==="maintainer-blog").length,K=Z.filter((Q)=>Q.fetch?.attempted).length,V=Z.filter((Q)=>Q.fetch?.ok).length,Y=Z.reduce((Q,B)=>{return Q[B.sourceType]=(Q[B.sourceType]||0)+1,Q},{}),j=$._synthesis?.agreement?.level;return{sourcesCount:Z.length,topSourceConsensus:X,agreementLevel:j||(X>=3?"high":X>=2?"medium":"low"),enginesResponded:e.filter((Q)=>$[Q]?.answer&&!$[Q]?.error),enginesFailed:e.filter((Q)=>$[Q]?.error),officialSourceCount:J,firstPartySourceCount:W,fetchedSourceSuccessRate:K>0?Number((V/K).toFixed(2)):0,sourceTypeBreakdown:Y}}E0();Y0();import{spawn as S6}from"node:child_process";y0();var g6=f0(import.meta.url),y6={gemini:"gemini.mjs",chatgpt:"chatgpt.mjs"},h6={gemini:"https://gemini.google.com/app",chatgpt:"https://chatgpt.com/"};function e0($="gemini"){let Z=String($||"gemini").toLowerCase();if(Z==="gem")return"gemini";if(Z==="gpt")return"chatgpt";return Z}function I2($="gemini"){return h6[e0($)]||"about:blank"}async function E2($,Z,{tabPrefix:X=null,timeoutMs:J=180000,visible:W=null}={}){let K=e0($),V=y6[K];if(!V||!m0.includes(K))throw Error(`Unsupported synthesizer "${$}". Supported: ${m0.join(", ")}`);let Y=x0(V,{moduleDir:g6});return new Promise((j,Q)=>{let B=X?["--tab",String(X)]:[],H={...process.env,CDP_PROFILE_DIR:r};if(W!==!0)delete H.GREEDY_SEARCH_VISIBLE,delete H.GREEDY_SEARCH_ALWAYS_VISIBLE;else H.GREEDY_SEARCH_VISIBLE="1",H.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let O=S6(Z0(),[Y,"--stdin",...B],{stdio:["pipe","pipe","pipe"],env:H});O.stdin.write(Z),O.stdin.end();let G="",D="";O.stdout.on("data",(M)=>G+=M),O.stderr.on("data",(M)=>D+=M);let z=setTimeout(()=>{O.kill(),Q(Error(`${K} prompt timed out after ${J/1000}s`))},J);O.on("close",(M)=>{if(clearTimeout(z),M!==0){Q(Error(D.trim()||`${K} extractor failed`));return}try{j(JSON.parse(G.trim()))}catch{Q(Error(`bad JSON from ${K}: ${G.slice(0,100)}`))}})})}async function T0($,Z={}){return E2("gemini",$,Z)}async function b2($,Z,{grounded:X=!1,tabPrefix:J=null,visible:W=null,synthesizer:K="gemini"}={}){let V=e0(K),Y=Array.isArray(Z._sources)?Z._sources:g0(Z),j=C2($,Z,Y,{grounded:X}),Q=await E2(V,j,{tabPrefix:J,timeoutMs:180000,visible:W}),B=r0(Q.answer||""),O=B&&["answer","agreement","claims","differences","caveats"].some((D)=>(D in B));if(B&&["perplexity","bing","google","chatgpt","gemini"].some((D)=>(D in B))&&!O)B=null;return{...T2(B,Y,Q.answer||""),rawAnswer:Q.answer||"",synthesizedBy:V,synthesizerSources:Q.sources||[],geminiSources:V==="gemini"?Q.sources||[]:[]}}var p6=/^(can you |could you |please |would you mind |i need to (know|understand) |i want to (know|understand) |i('m| am) (looking for|wondering about|curious about) |i need (information|info) (about|on) |tell me )?(about |explain |describe |give me |help me understand |search for |look up |find |research )?(about |regarding |on |for )?(it|this|the following)?\s*/i,m6=/\b(latest|newest|current|recent|up-to-date|up to date)\b/i,d6=/\b\d+\.\d+|\bv\d+\b|\b20(2[0-9]|[3-9]\d)\b/i;function l6($){let Z=$.trim().replace(p6,"").trim();return Z.length>4?Z:$.trim()}function u6($,Z=new Date().getFullYear()){if(!m6.test($))return $;if(d6.test($))return $;return`${$.trimEnd()} ${Z}`}function w$($){if(!$?.trim())return $;let Z=l6($);return Z=u6(Z),Z||$}y0();import{spawn as c6}from"node:child_process";import{mkdirSync as N1,writeFileSync as n}from"node:fs";import{join as x}from"node:path";import{fileURLToPath as n6}from"node:url";Y0();E0();var i6=n6(new URL(".",import.meta.url)).replace(/^\/([A-Z]:)/,"$1"),o6=x(i6,"..","..","bin","search.mjs"),a6=x(process.cwd(),".dm","greedysearch-research");function s6($){return String($||"research").toLowerCase().replaceAll(/[^a-z0-9]+/g,"-").replaceAll(/^-|-$/g,"").slice(0,60)||"research"}function B0($,Z=1/0){let X=new Set,J=[];for(let W of $||[]){let K=I(String(W||""),1000);if(!K||X.has(K))continue;if(X.add(K),J.push(K),J.length>=Z)break}return J}async function t6(...$){let{fetchMultipleSources:Z}=await Promise.resolve().then(() => (B1(),_2));return Z(...$)}async function _1(...$){let{writeSourcesToFiles:Z}=await Promise.resolve().then(() => (M1(),k2));return Z(...$)}function r6({breadth:$=3,iterations:Z=2,maxSources:X}){let J=D1($,1,5,3),W=D1(Z,1,3,2),K=D1(X??Math.max(5,J*W*2),3,12,8);return{breadth:J,iterations:W,maxSources:K}}function D1($,Z,X,J){let W=Number.parseInt(String($??""),10);if(!Number.isFinite(W))return J;return Math.min(X,Math.max(Z,W))}function e6($,Z,X,{expand:J=!0,includeOriginal:W=!0,exclude:K=[]}={}){let V=Array.isArray($?.queries)?$.queries:[],Y=[],j=new Set([...K].map((Q)=>J0(Q).toLowerCase()));for(let Q of V){let B=typeof Q==="string"?Q:Q?.query,H=typeof Q==="string"?"":Q?.researchGoal||"";z1(Y,B,H,{exclude:j})}if(W)z1(Y,Z,"Original user query",{prepend:!0,exclude:j});if(J){let Q=[{query:`${Z} official docs GitHub`,researchGoal:"Find primary project docs, repository details, and maintainer claims."},{query:`${Z} benchmarks limitations compatibility`,researchGoal:"Validate performance claims and uncover unsupported APIs or caveats."},{query:`${Z} alternatives comparison production use cases`,researchGoal:"Compare against conventional headless browsers and identify when to choose it."},{query:`${Z} anti bot detection Cloudflare screenshots visual rendering`,researchGoal:"Check automation risks, rendering gaps, screenshots, and bot-detection behavior."}];for(let B of Q){if(Y.length>=X)break;z1(Y,B.query,B.researchGoal,{exclude:j})}}return Y.slice(0,X)}function z1($,Z,X="",{prepend:J=!1,exclude:W=new Set}={}){if(!Z||typeof Z!=="string")return;let K=J0(Z);if(!K||W.has(K.toLowerCase())||$.some((Y)=>Y.query.toLowerCase()===K.toLowerCase()))return;let V={query:K,researchGoal:I(X,320)};if(J)$.unshift(V);else $.push(V)}function J0($){return Z9($9(String($)))}function $9($){let Z="",X=0;while(X<$.length){let J=$.indexOf("[",X);if(J===-1){Z+=$.slice(X);break}let W=$.indexOf("]",J+1);if(W===-1||$[W+1]!=="("||W===J+1){Z+=$.slice(X,J+1),X=J+1;continue}let K=$.indexOf(")",W+2);if(K===-1){Z+=$.slice(X,J+1),X=J+1;continue}let V=$.slice(W+2,K).trimStart();if(!V.startsWith("http://")&&!V.startsWith("https://")){Z+=$.slice(X,J+1),X=J+1;continue}Z+=$.slice(X,J),Z+=$.slice(J+1,W),X=K+1}return Z}function Z9($){let Z="",X=!1;for(let J of $)if(J===" "||J==="\t"||J===`
316
+ `||J==="\r"){if(!X)Z+=" ";X=!0}else Z+=J,X=!1;return Z.trim()}function q2($){return new Set(String($).toLowerCase().normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"").split(/[^\w]+/).filter((Z)=>Z.length>1))}function I$($,Z){let X=q2($),J=q2(Z),W=new Set([...X,...J]).size;if(W===0)return 1;let K=0;for(let V of X)if(J.has(V))K++;return K/W}function S2($,Z,{threshold:X=0.75,roundIndex:J=0,originalQuery:W=null}={}){let K=J0($).toLowerCase();if(Z.has(K))return!0;if(W&&J>0&&K===J0(W).toLowerCase())return!0;for(let V of Z)if(I$(K,V)>=X)return!0;return!1}function X9($,Z,X,J){let W=Z.map((K)=>({queries:K.queries?.map((V)=>V.query||"")||[],learnings:K.learnings||[],gaps:K.gaps||[]}));return["You are evaluating the quality of an iterative research run.","Assess coverage across: official sources, limitations/risks, benchmarks/performance, production usage, and counter-evidence.","Score each dimension 0-10. Overall score 0-10.","Identify remaining knowledge gaps.","Propose targeted next actions (search queries or direct URL fetches) that would most improve the research.","Decide whether to continue or stop.","terminationReason must be one of: quality_threshold | max_rounds | no_novel_actions | insufficient_evidence.","",`Original research question: ${$}`,`Rounds completed: ${JSON.stringify(W,null,2)}`,`Accumulated learnings: ${JSON.stringify(X.slice(0,12),null,2)}`,`Known gaps: ${JSON.stringify(J.slice(0,8),null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({score:7.5,coverage:{officialSources:8,limitations:5,benchmarks:7,productionUseCases:6,counterEvidence:4},knowledgeGaps:["specific gap or missing evidence"],shouldContinue:!0,terminationReason:"quality_threshold",nextActions:[{type:"search",query:"targeted search query"},{type:"fetchUrl",url:"https://example.com/primary-doc"}]},null,2),"END_JSON"].join(`
317
+ `)}function J9($,Z,X,J,W){let K=[],V=[{template:(Y)=>`${Y} official documentation`,label:"official docs"},{template:(Y)=>`${Y} GitHub issues discussions`,label:"community signals"},{template:(Y)=>`${Y} benchmarks performance comparison`,label:"benchmarks"},{template:(Y)=>`${Y} limitations risks caveats`,label:"limitations"},{template:(Y)=>`${Y} production deployment experience`,label:"production usage"},{template:(Y)=>`${Z} ${Y} counter evidence`,label:"counter-evidence"}];for(let Y=0;Y<$.length&&K.length<J;Y++){let j=$[Y],Q=V[Y%V.length],B=Q.template(j);if(!S2(B,X,{roundIndex:W}))K.push({query:B,researchGoal:`Gap-driven: ${j} (${Q.label})`})}return K}async function W9($,Z,X,J,W){try{let K=await T0(X9($,Z,X,J),{timeoutMs:120000}),V=$$(K,{}),Y=typeof V.score==="number"?Math.min(10,Math.max(0,V.score)):W.length>0?W[W.length-1]:5,j=Array.isArray(V.knowledgeGaps)?V.knowledgeGaps.map((O)=>String(O)).filter(Boolean).slice(0,6):[],Q=Array.isArray(V.nextActions)?V.nextActions.slice(0,5):[],B=typeof V.shouldContinue==="boolean"?V.shouldContinue:Y<8,H=V.terminationReason||null;return{score:Y,coverage:V.coverage||{},knowledgeGaps:j,shouldContinue:B,nextActions:Q,terminationReason:H||(Y>=8.5?"quality_threshold":null),evaluationError:""}}catch(K){return process.stderr.write(`[greedysearch] Quality evaluation failed: ${K.message}
318
+ `),{score:W.length>0?W[W.length-1]:5,coverage:{},knowledgeGaps:[],shouldContinue:!0,nextActions:[],terminationReason:null,evaluationError:K.message}}}function K9($){let Z={};for(let X of Object.keys($||{}).filter((J)=>!J.startsWith("_"))){let J=$?.[X];if(!J)continue;Z[X]=J.error?{status:"error",error:String(J.error)}:{status:"ok",answer:I(J.answer||"",1400),sources:Array.isArray(J.sources)?J.sources.slice(0,5).map((W)=>({title:I(W.title||"",160),url:W.url||""})):[]}}return Z}function V9($,Z,X=[],J=[],W=[]){let K=J.length>0?`
319
319
  Known knowledge gaps to target:
320
320
  ${J.map((Y)=>`- ${Y}`).join(`
321
321
  `)}`:"",V=W.length>0?`
@@ -325,78 +325,78 @@ ${W.map((Y)=>`- ${Y}`).join(`
325
325
  Prior learnings to build on:
326
326
  ${X.map((Y)=>`- ${Y}`).join(`
327
327
  `)}`:"",K,V,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({actions:[{type:"search",query:"specific search query",researchGoal:"what this action should clarify"},{type:"fetchUrl",url:"https://example.com/docs/relevant-page",researchGoal:"extract specific information from this page"}]},null,2),"END_JSON"].join(`
328
- `)}function h2($){if(!$||typeof $!=="object")return null;let Z=$.type,X=I($.researchGoal||"",320);if(Z==="search"){if($.query==null)return null;let J=X0($.query);return J?{type:"search",query:J,researchGoal:X}:null}if(Z==="fetchUrl"){if($.url==null)return null;let J=$0($.url);return J?{type:"fetchUrl",url:J,researchGoal:X}:null}return null}async function B9($,{locale:Z=null,short:X=!0,usedQueries:J,usedUrls:W,maxChars:K=8000}={}){if($.type==="search"){let V=X0($.query).toLowerCase();J.add(V);try{let Y=await L9($.query,{locale:Z,short:X}),j=x0(Y,$.query);return{ok:!0,action:$,result:Y,sources:j}}catch(Y){return{ok:!1,action:$,error:Y.message,sources:[]}}}if($.type==="fetchUrl"){let V=$0($.url);if(W.has(V))return{ok:!1,action:$,error:`URL already fetched: ${V}`,sources:[]};try{let Y=await H9(V,K);W.add(V);let j=O9(V),Q={id:"",canonicalUrl:Y.finalUrl||V,displayUrl:Y.url||V,domain:j,title:Y.title||V,engines:["fetch"],engineCount:1,perEngine:{},sourceType:Q1(j,Y.title||"",Y.finalUrl||V),isOfficial:!1,smartScore:0,fetch:{attempted:!0,ok:!Y.error&&(Y.contentChars||0)>100,status:Y.status||null,finalUrl:Y.finalUrl||V,content:Y.content||"",contentChars:Y.contentChars||0,snippet:Y.snippet||"",error:Y.error||""}};return{ok:!0,action:$,result:null,sources:[Q],fetchResult:{id:Q.id,url:V,finalUrl:Y.finalUrl||V,title:Y.title||"",content:Y.content||"",contentChars:Y.contentChars||0,snippet:Y.snippet||"",status:Y.status||null,error:Y.error||"",source:Y.source||"http",duration:Y.duration||0}}}catch(Y){return{ok:!1,action:$,error:Y.message,sources:[]}}}return{ok:!1,action:$,error:`Unknown action type: ${$.type}`,sources:[]}}async function H9($,Z){return await M9($,Z)}async function M9($,Z=8000){let X=Date.now();try{let{parseGitHubUrl:J,fetchGitHubContent:W}=await Promise.resolve().then(() => (k$(),W1)),K=J($);if(K&&(K.type==="root"||K.type==="tree"||K.type==="blob"&&!K.path?.includes("."))){let V=await W($);if(V.ok){let{trimContentHeadTail:Y}=await Promise.resolve().then(() => V1),j=Y(V.content,Z);return{url:$,finalUrl:$,status:200,title:V.title,snippet:j.slice(0,320),content:j,contentChars:j.length,source:"github-api",duration:Date.now()-X}}}}catch{}try{let{fetchSourceHttp:J}=await Promise.resolve().then(() => (X1(),Q2)),{trimContentHeadTail:W}=await Promise.resolve().then(() => V1),K=await J($,{timeoutMs:1e4});if(K.ok){let V=W(K.markdown,Z);return{url:$,finalUrl:K.finalUrl,status:K.status,title:K.title,snippet:K.excerpt,content:V,contentChars:V.length,source:"http",duration:Date.now()-X}}}catch{}return{url:$,title:"",content:"",contentChars:0,snippet:"",error:"HTTP fetch failed",source:"error",duration:Date.now()-X}}function O9($){try{return new URL($).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}async function G9($,Z){let X=[],{parseGitHubUrl:J}=await Promise.resolve().then(() => (k$(),W1));for(let W of $){if(W.type!=="fetchUrl"){X.push(W);continue}let K=J(W.url);if(!K||K.type!=="root"){X.push(W);continue}let{owner:V,repo:Y}=K,j=`https://github.com/${V}/${Y}`;if(Z.has(j))continue;let Q=[j],B=[`${j}/blob/main/CONTRIBUTING.md`,`${j}/blob/master/CONTRIBUTING.md`,`${j}/blob/main/CHANGELOG.md`,`${j}/blob/master/CHANGELOG.md`,`${j}/blob/main/docs/README.md`];for(let H of B){if(Q.length>=3)break;if(!Z.has(H))Q.push(H)}for(let H of Q)X.push({type:"fetchUrl",url:H,researchGoal:W.researchGoal||`Fetch GitHub content for ${V}/${Y}`})}return X}function N9($,Z){let X=r0($?.answer||"")||{},J=Array.isArray(X?.actions)?X.actions:[],W=[];for(let K of J){let V=h2(K);if(V&&W.length<Z)W.push(V)}return W}function z9($){return($||[]).map((Z)=>({type:"search",query:typeof Z==="string"?Z:Z.query,researchGoal:typeof Z==="string"?"":Z.researchGoal||""})).filter((Z)=>Z.query)}function R$($){return $0($?.finalUrl||$?.canonicalUrl||$?.url||"")||$?.id||""}function D9($,Z,X,J=new Set){let W=(Z||[]).filter((V)=>V.status!=="closed").slice(0,12).map((V)=>({id:V.id,question:V.question})),K=(X||[]).filter((V)=>V?.content||V?.snippet).filter((V)=>!J.has(R$(V))).slice(0,6).map((V,Y)=>({id:V.id||`F${Y+1}`,title:V.title||"",url:V.finalUrl||V.url||V.canonicalUrl||"",content:I(V.content||V.snippet||"",5000)}));return["You are doing goal-based evidence extraction for an iterative research run.","For each source, extract only information that helps answer the open questions.","Use original wording/details where useful. Do not invent answers; leave questions open if evidence is insufficient.","If a source answers one or more tracked questions, identify those question IDs explicitly.","Also propose genuinely new sub-questions discovered from the evidence.","",`Original research question: ${$}`,`Open question ledger: ${JSON.stringify(W,null,2)}`,`Fetched sources: ${JSON.stringify(K,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({extractions:[{sourceId:"S1",url:"https://example.com/source",rational:"why this source matters for the goal",evidence:"specific quoted/paraphrased evidence with numbers, dates, caveats",summary:"concise contribution to the research question",answers:[{id:"Q1",evidence:"brief evidence that closes the question"}],newQuestions:["new sub-question raised by this source"]}]},null,2),"END_JSON"].join(`
329
- `)}function U9($,Z){let X=Array.isArray($?.extractions)?$.extractions:[],J=new Map,W=new Map;for(let K of Z||[]){if(K?.id)W.set(String(K.id),K);let V=R$(K);if(V)J.set(V,K)}return X.map((K)=>{let V=W.get(String(K?.sourceId||""))||J.get($0(K?.url||"")||""),Y=String(K?.sourceId||V?.id||""),j=$0(K?.url||V?.finalUrl||V?.url||""),Q=Array.isArray(K?.answers)?K.answers.map((B)=>({id:String(B?.id||""),evidence:I(B?.evidence||"",500),sourceIds:[Y].filter(Boolean)})).filter((B)=>B.id):[];return{sourceId:Y,url:j,title:V?.title||K?.title||"",rational:I(K?.rational||"",700),evidence:I(K?.evidence||"",1600),summary:I(K?.summary||"",700),answers:Q,newQuestions:Q0(K?.newQuestions||[],6)}}).filter((K)=>K.sourceId||K.url||K.summary||K.evidence)}async function A9({query:$,questions:Z,fetchedSources:X,extractedSourceKeys:J}){let W=(X||[]).filter((K)=>(K?.content||K?.snippet)&&!J.has(R$(K)));if(W.length===0)return{evidence:[],error:""};try{let K=await T0(D9($,Z,W,J),{timeoutMs:120000}),V=$$(K,{extractions:[]}),Y=U9(V,W);for(let j of W){let Q=R$(j);if(Q)J.add(Q)}return{evidence:Y,error:""}}catch(K){return{evidence:[],error:K.message||String(K)}}}function _9($,Z,X,J,W=[],K=[]){let V=J.filter((Y)=>Y?.content||Y?.snippet).slice(0,10).map((Y,j)=>({id:`F${j+1}`,title:Y.title||"",url:Y.finalUrl||Y.url||"",snippet:I(Y.content||Y.snippet||"",3000)}));return["You are extracting compact research state from live multi-engine search results.","Create dense, non-overlapping learnings with exact names, numbers, dates, limitations, and caveats where available.","Also propose follow-up search queries that would most improve confidence or fill gaps.","",`Original research question: ${$}`,`Round queries: ${JSON.stringify(Z,null,2)}`,`Question ledger: ${JSON.stringify(W,null,2)}`,`Extracted source evidence: ${JSON.stringify(K.slice(-12),null,2)}`,`Engine summaries: ${JSON.stringify(X,null,2)}`,`Fetched source snippets: ${JSON.stringify(V,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({learnings:["concise, information-dense learning"],answeredQuestions:[{id:"Q1",evidence:"brief evidence that closes this question",sourceIds:["S1"]}],newQuestions:["new sub-question discovered from the evidence"],followUpQueries:["specific next search query"],gaps:["important uncertainty or missing evidence"]},null,2),"END_JSON"].join(`
330
- `)}function P9($,Z,X,J=[],W=[]){let K=Z.flatMap((j)=>j.learnings||[]),V=Z.flatMap((j)=>j.gaps||[]),Y=X.slice(0,12).map((j)=>({id:j.id,title:j.title,domain:j.domain,url:j.canonicalUrl,type:j.sourceType,engines:j.engines,fetch:j.fetch?.attempted?{ok:j.fetch.ok,snippet:I(j.fetch.snippet||"",1200),publishedTime:j.fetch.publishedTime||""}:void 0}));return["You are writing the final research report for an iterative deep-research run.","Produce a thorough markdown report organized into clear sections.","","Use the learnings and source registry below. Every substantive claim MUST be backed by an [S1] citation.",'Where engines disagree, surface the conflicting claims explicitly in the "differences" array.','Include a "Key Claims" structure that maps each distinct claim to its supporting source IDs.',"","Report structure:","1. ## Summary — A 2-4 sentence executive summary of findings","2. ## Key Findings — The main findings, organized by theme or question, each with inline citations","3. ## Areas of Disagreement — Where engines or sources conflict (if any)","4. ## Limitations & Caveats — Important qualifiers, gaps, or uncertainties","",`Original research question: ${$}`,`Learnings: ${JSON.stringify(K,null,2)}`,`Known gaps/caveats: ${JSON.stringify(V,null,2)}`,`Question ledger: ${JSON.stringify(J,null,2)}`,`Goal-based extracted evidence: ${JSON.stringify(W.slice(-20),null,2)}`,`Source registry: ${JSON.stringify(Y,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({answer:"markdown report with sections and inline [S1] citations",agreement:{level:"high|medium|low|mixed|conflicting",summary:"one-sentence confidence summary"},differences:["notable disagreement or conflict between sources"],caveats:["important caveat or qualification"],claims:[{claim:"specific factual statement from the research",support:"strong|moderate|weak|conflicting",sourceIds:["S1","S2"]}],recommendedSources:["S1","S2"]},null,2),"END_JSON"].join(`
331
- `)}function k9($,Z=[],X=[],J=[]){let W=Z.slice(0,12).map((j)=>({id:j.id,title:j.title,domain:j.domain,url:j.canonicalUrl,type:j.sourceType,engines:j.engines})),K=J.slice(-20),V=new Set;for(let j of K)for(let Q of j.answers||[])if(Q?.id)V.add(Q.id);let Y=(X||[]).filter((j)=>j.status!=="closed").map((j)=>({id:j.id,question:j.question}));return["You are writing the final research report from goal-based extracted evidence.","Per-round learnings were not produced, but the per-source evidence extraction step succeeded.","Synthesize a thorough markdown report using ONLY the evidence below. Every substantive claim MUST be backed by an [S1] citation.","","Report structure:","1. ## Summary — A 2-4 sentence executive summary of findings","2. ## Key Findings — The main findings, organized by theme or question, each with inline citations","3. ## Limitations & Caveats — Important qualifiers, gaps, or uncertainties","",`Original research question: ${$}`,`Per-source extracted evidence: ${JSON.stringify(K,null,2)}`,`Source registry: ${JSON.stringify(W,null,2)}`,`Questions already answered by the evidence: ${JSON.stringify(Array.from(V))}`,`Questions still open after this evidence: ${JSON.stringify(Y)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({answer:"markdown report with sections and inline [S1] citations",agreement:{level:"high|medium|low|mixed|conflicting",summary:"one-sentence confidence summary"},differences:["notable disagreement or conflict between sources"],caveats:["important caveat or qualification"],claims:[{claim:"specific factual statement supported by the evidence",support:"strong|moderate|weak|conflicting",sourceIds:["S1","S2"]}],recommendedSources:["S1","S2"]},null,2),"END_JSON"].join(`
332
- `)}async function L9($,{locale:Z=null,short:X=!0}={}){let J=[t6,"all","--inline","--stdin","--fast"];if(!X)J.push("--full");if(Z)J.push("--locale",Z);return new Promise((W,K)=>{let V=i6(M0(),J,{stdio:["pipe","pipe","pipe"],env:{...process.env,GREEDY_SEARCH_RESEARCH_CHILD:"1"}});V.stdin.write($),V.stdin.end();let Y="",j="",Q="";V.stdout.on("data",(H)=>Y+=H),V.stderr.on("data",(H)=>{j+=H,Q+=H.toString();let G=Q.split(`
333
- `);Q=G.pop()||"";for(let O of G)if(w9(O))process.stderr.write(`${O}
334
- `)});let B=setTimeout(()=>{V.kill(),K(Error(`research child search timed out for: ${$}`))},140000);V.on("close",(H)=>{if(clearTimeout(B),H!==0){K(Error(j.trim()||`search child exited with code ${H}`));return}try{W(JSON.parse(Y.trim()))}catch{K(Error(`Invalid JSON from research child: ${Y.slice(0,200)}`))}})})}function F9($){let Z=new Map;for(let X of $.flat()){let J=$0(X.canonicalUrl||X.url);if(!J)continue;let W=Z.get(J);if(!W){Z.set(J,{...X,canonicalUrl:J});continue}W.engines=[...new Set([...W.engines||[],...X.engines||[]])],W.engineCount=W.engines.length,W.smartScore=Math.max(W.smartScore||0,X.smartScore||0)}return Array.from(Z.values()).sort((X,J)=>{let W=w0(J)-w0(X);if(W!==0)return W;return(X.domain||"").localeCompare(J.domain||"")}).slice(0,12).map((X,J)=>({...X,id:`S${J+1}`}))}function w9($){return/^PROGRESS:/.test($)||/^\[greedysearch\]/.test($)||/^\[(bing|perplexity|google|gemini|chatgpt|logically|semantic-scholar)\]/.test($)||/^GreedySearch Chrome/.test($)||/^Launching GreedySearch Chrome/.test($)||/^Headless mode/.test($)||/^Ready\.?$/.test($)}function $$($,Z={}){return r0($?.answer||"")||Z}function T9($,Z){if(!$||!Array.isArray(Z))return{cited:[],missing:[],unfetched:[],ok:!0};let X=/\b[SF](\d+)\b/g,J=new Set,W;while((W=X.exec($))!==null)J.add(`S${W[1]}`),J.add(`F${W[1]}`);let K=new Map;for(let Q of Z){let B=Q?.id;if(B)K.set(B,Q)}let V=Array.from(J),Y=[],j=[];for(let Q of V){let B=K.get(Q);if(!B){let H=Q.match(/^(S|F)(\d+)$/);if(H){let G=parseInt(H[2],10)-1;if(G>=0&&G<Z.length){let O=Z[G];if(O){if(!(O.fetch?.ok||O.content&&O.content.length>100||O.contentChars&&O.contentChars>100))j.push(Q);continue}}}Y.push(Q)}else if(!(B.fetch?.ok||B.content&&B.content.length>100||B.contentChars&&B.contentChars>100))j.push(Q)}return{cited:V,missing:Y,unfetched:j,ok:Y.length===0}}function x2({sources:$=[],fetchedSources:Z=[],synthesis:X={},citationAudit:J=null,gaps:W=[],questions:K=[],rounds:V=[],qualityScore:Y=0,qualityThreshold:j=8.5,maxSources:Q=8,requireCitations:B=!0,requireQuestions:H=!0}={}){let G=Z.filter((x)=>x?.fetch?.ok||(x?.contentChars||0)>100||String(x?.content||"").length>100),O=$.filter((x)=>["official-docs","repo","maintainer-blog","academic"].includes(String(x?.sourceType||""))),z=Array.isArray(X?.claims)?X.claims:[],D=J?J.cited?.length||0:0,M=k1(K),A=(K||[]).filter((x)=>!x.createdRound||x.reason==="Original research question"),b=k1(A),P=Math.min(4,Math.max(2,Number(Q)||8)),F={roundsRun:V.length>=1,fetchedSources:G.length>=P,primarySources:O.length>=1,qualityScore:Y>=Math.min(j,8),claimsExtracted:!B||z.length>0,citationsPresent:!B||D>0,citationsValid:!B||J?.ok===!0,unfetchedCitations:!B||(J?.unfetched||[]).length===0,requiredQuestionsClosed:!H||b.open===0};return{floorMet:Object.values(F).every(Boolean),checks:F,metrics:{fetchedOk:G.length,primarySources:O.length,claims:z.length,cited:D,gaps:W.length,openQuestions:M.open,closedQuestions:M.closed,totalQuestions:M.total,openRequiredQuestions:b.open,closedRequiredQuestions:b.closed,totalRequiredQuestions:b.total,qualityScore:Y,minFetched:P}}}function S2($,Z){let X=new Map;for(let J of Z||[]){let W=$0(J?.canonicalUrl||J?.finalUrl||J?.url);if(W&&J?.id)X.set(W,J.id)}return($||[]).map((J,W)=>{let K=$0(J?.finalUrl||J?.canonicalUrl||J?.url);return{...J,id:J?.id||X.get(K)||`F${W+1}`}})}function C9($){return[{id:"Q1",question:I(X0($),320),status:"open",reason:"Original research question",evidence:[],sourceIds:[]}]}function R9($){let Z=0;for(let X of $||[]){let J=Number.parseInt(String(X.id||"").replace(/^Q/i,""),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return`Q${Z+1}`}function p2($,Z){let X=X0(Z).toLowerCase();return($||[]).find((J)=>J.question?.toLowerCase()===X||I$(J.question||"",X)>=0.82)}function A1($,Z,{reason:X="",round:J=null}={}){let W=I(X0(Z),320);if(!W)return null;let K=p2($,W);if(K)return K;let V={id:R9($),question:W,status:"open",reason:I(X,240),createdRound:J,evidence:[],sourceIds:[]};return $.push(V),V}function C$($,Z,{evidence:X="",sourceIds:J=[],round:W=null}={}){let K=$.find((V)=>V.id===Z)||p2($,Z);if(!K)return null;if(K.status="closed",K.closedRound=K.closedRound||W,X)K.evidence=Q0([...K.evidence||[],X],4);if(Array.isArray(J))K.sourceIds=Q0([...K.sourceIds||[],...J],8);return K}function k1($){let Z=$.length,X=$.filter((J)=>J.status==="closed").length;return{total:Z,closed:X,open:Math.max(0,Z-X)}}function T$($,{roundNumber:Z,actions:X=[],learningPayload:J={}}={}){for(let j of X){let Q=j?.action||j,B=Q?.researchGoal&&Q.researchGoal!=="Original user query"?Q.researchGoal:Q?.query||Q?.url||"";if(B)A1($,B,{reason:"Planned research action",round:Z})}let W=5,K=$.filter((j)=>j.status==="open"&&j.reason==="Discovered gap/follow-up");if(K.length>W){let j=K.sort((Q,B)=>(Q.createdRound||0)-(B.createdRound||0)).slice(0,K.length-W);for(let Q of j)Q.status="resolved",Q.closedRound=Z,Q.evidence=Q0([...Q.evidence||[],"Auto-resolved to cap open-question ledger"],4)}let V=Array.isArray(J.answeredQuestions)?J.answeredQuestions:[];for(let j of V){if(typeof j==="string"){C$($,j,{round:Z});continue}let Q=j?.id||j?.question;if(!Q&&j?.question){let B=A1($,j.question,{reason:"Answered during learning extraction",round:Z});if(B)C$($,B.id,{round:Z});continue}C$($,Q,{evidence:j?.evidence||j?.answer||"",sourceIds:Array.isArray(j?.sourceIds)?j.sourceIds:[],round:Z})}let Y=Array.isArray(J.newQuestions)?J.newQuestions:[];for(let j of Y)A1($,j,{reason:"Discovered gap/follow-up",round:Z});return $}function I9($,Z){if(!Array.isArray($)||$.length===0)return[];let X=["arxiv.org","semanticscholar.org","doi.org"],J=new Set,W=[];for(let K of $){let V=K?.canonicalUrl||K?.finalUrl||K?.url||"";if(!V)continue;let Y="";try{Y=new URL(V).hostname.toLowerCase().replace(/^www\./,"")}catch{continue}if(!X.some((Q)=>Y===Q||Y.endsWith(`.${Q}`)))continue;if(Z.has(V)||J.has(V))continue;J.add(V);let j=V.includes("/pdf/")?V.replace(/\/pdf\//,"/html/").replace(/\.pdf$/i,""):V;W.push({url:j,label:K?.title||K?.id||Y})}return W.slice(0,2)}function E9($,Z,X){if(!Z?.answer||X?.ok!==!0)return $;let J=Array.isArray(Z.claims)?Z.claims:[],W=Array.isArray(X.cited)?X.cited:[];if(J.length===0||W.length===0)return $;for(let K of $){if(K.status==="closed")continue;let V=null,Y=0;for(let j of J){let Q=I$(K.question||"",j.claim||"");if(Q>Y)Y=Q,V=j}if(K.id==="Q1"||Y>=0.18)C$($,K.id,{evidence:V?.claim||"Answered in final cited synthesis",sourceIds:Array.isArray(V?.sourceIds)?V.sourceIds:W.slice(0,4)})}return $}function b9($){if(!$.length)return"No tracked questions.";return $.map((Z)=>{let X=Z.sourceIds?.length?` (${Z.sourceIds.join(", ")})`:"";return`- [${Z.status==="closed"?"x":" "}] ${Z.id}: ${Z.question}${X}`}).join(`
335
- `)}function _1($,Z="None recorded."){let X=Q0($);return X.length?X.map((J)=>`- ${J}`).join(`
336
- `):Z}async function q9({query:$,rounds:Z,sources:X,fetchedSources:J,evidenceItems:W=[],synthesis:K,citationAudit:V,floor:Y,manifest:j,allGaps:Q=[],questions:B=[],outDir:H=null}){let G=new Date().toISOString().replaceAll(/[:.]/g,"-").slice(0,19),O=H||f(r6,`${G}_${e6($)}`),z=f(O,"reports"),D=f(O,"sources"),M=f(O,"data");z1(z,{recursive:!0}),z1(D,{recursive:!0}),z1(M,{recursive:!0});let A=await P1(J,D),b=Q0([...Q,...Z.flatMap((P)=>P.gaps||[])]);return i(f(O,"STATUS.md"),[Y.floorMet?"STATUS: DONE":"STATUS: PARTIAL","",`Query: ${$}`,`Stop reason: ${j.terminationReason||"max_rounds"}`,"","## Deterministic floor checks",...Object.entries(Y.checks).map(([P,F])=>`- [${F?"x":" "}] ${P}`),"","## Questions",b9(B),"","## Open gaps",_1(b),""].join(`
337
- `),"utf8"),i(f(O,"OUTLINE.md"),["# Research bundle outline","","- `reports/SUMMARY.md` — final cited report","- `reports/CLAIMS.md` — extracted claims with support/source IDs","- `reports/EVIDENCE.md` — goal-based source evidence","- `reports/GAPS.md` — remaining caveats and uncertainties","- `sources/` — fetched source markdown files","- `data/manifest.json` — machine-readable run metadata","- `data/rounds.json` — per-round actions/learnings/gaps","- `data/sources.json` — ranked source registry","- `data/questions.json` — open/closed question ledger",""].join(`
338
- `),"utf8"),i(f(z,"SUMMARY.md"),String(K.answer||""),"utf8"),i(f(z,"CLAIMS.md"),["# Key claims","",...Array.isArray(K.claims)&&K.claims.length?K.claims.map((P)=>{let F=Array.isArray(P.sourceIds)?P.sourceIds.join(", "):"";return`- ${P.claim||""} (${P.support||"support unknown"}${F?`; ${F}`:""})`}):["No structured claims were extracted."],""].join(`
339
- `),"utf8"),i(f(z,"EVIDENCE.md"),["# Extracted evidence","",...W.length?W.map((P)=>[`## ${P.sourceId||P.url||"Source"}`,P.url?`<${P.url}>`:"",P.rational?`**Rational:** ${P.rational}`:"",P.evidence?`**Evidence:** ${P.evidence}`:"",P.summary?`**Summary:** ${P.summary}`:"",""].filter(Boolean).join(`
328
+ `)}function g2($){if(!$||typeof $!=="object")return null;let Z=$.type,X=I($.researchGoal||"",320);if(Z==="search"){if($.query==null)return null;let J=J0($.query);return J?{type:"search",query:J,researchGoal:X}:null}if(Z==="fetchUrl"){if($.url==null)return null;let J=$0($.url);return J?{type:"fetchUrl",url:J,researchGoal:X}:null}return null}async function Y9($,{locale:Z=null,short:X=!0,usedQueries:J,usedUrls:W,maxChars:K=8000}={}){if($.type==="search"){let V=J0($.query).toLowerCase();J.add(V);try{let Y=await _9($.query,{locale:Z,short:X}),j=g0(Y,$.query);return{ok:!0,action:$,result:Y,sources:j}}catch(Y){return{ok:!1,action:$,error:Y.message,sources:[]}}}if($.type==="fetchUrl"){let V=$0($.url);if(W.has(V))return{ok:!1,action:$,error:`URL already fetched: ${V}`,sources:[]};try{let Y=await j9(V,K);W.add(V);let j=B9(V),Q={id:"",canonicalUrl:Y.finalUrl||V,displayUrl:Y.url||V,domain:j,title:Y.title||V,engines:["fetch"],engineCount:1,perEngine:{},sourceType:j1(j,Y.title||"",Y.finalUrl||V),isOfficial:!1,smartScore:0,fetch:{attempted:!0,ok:!Y.error&&(Y.contentChars||0)>100,status:Y.status||null,finalUrl:Y.finalUrl||V,content:Y.content||"",contentChars:Y.contentChars||0,snippet:Y.snippet||"",error:Y.error||""}};return{ok:!0,action:$,result:null,sources:[Q],fetchResult:{id:Q.id,url:V,finalUrl:Y.finalUrl||V,title:Y.title||"",content:Y.content||"",contentChars:Y.contentChars||0,snippet:Y.snippet||"",status:Y.status||null,error:Y.error||"",source:Y.source||"http",duration:Y.duration||0}}}catch(Y){return{ok:!1,action:$,error:Y.message,sources:[]}}}return{ok:!1,action:$,error:`Unknown action type: ${$.type}`,sources:[]}}async function j9($,Z){return await Q9($,Z)}async function Q9($,Z=8000){let X=Date.now();try{let{parseGitHubUrl:J,fetchGitHubContent:W}=await Promise.resolve().then(() => (k$(),J1)),K=J($);if(K&&(K.type==="root"||K.type==="tree"||K.type==="blob"&&!K.path?.includes("."))){let V=await W($);if(V.ok){let{trimContentHeadTail:Y}=await Promise.resolve().then(() => K1),j=Y(V.content,Z);return{url:$,finalUrl:$,status:200,title:V.title,snippet:j.slice(0,320),content:j,contentChars:j.length,source:"github-api",duration:Date.now()-X}}}}catch{}try{let{fetchSourceHttp:J}=await Promise.resolve().then(() => (Z1(),Y2)),{trimContentHeadTail:W}=await Promise.resolve().then(() => K1),K=await J($,{timeoutMs:1e4});if(K.ok){let V=W(K.markdown,Z);return{url:$,finalUrl:K.finalUrl,status:K.status,title:K.title,snippet:K.excerpt,content:V,contentChars:V.length,source:"http",duration:Date.now()-X}}}catch{}return{url:$,title:"",content:"",contentChars:0,snippet:"",error:"HTTP fetch failed",source:"error",duration:Date.now()-X}}function B9($){try{return new URL($).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}async function H9($,Z){let X=[],{parseGitHubUrl:J}=await Promise.resolve().then(() => (k$(),J1));for(let W of $){if(W.type!=="fetchUrl"){X.push(W);continue}let K=J(W.url);if(!K||K.type!=="root"){X.push(W);continue}let{owner:V,repo:Y}=K,j=`https://github.com/${V}/${Y}`;if(Z.has(j))continue;let Q=[j],B=[`${j}/blob/main/CONTRIBUTING.md`,`${j}/blob/master/CONTRIBUTING.md`,`${j}/blob/main/CHANGELOG.md`,`${j}/blob/master/CHANGELOG.md`,`${j}/blob/main/docs/README.md`];for(let H of B){if(Q.length>=3)break;if(!Z.has(H))Q.push(H)}for(let H of Q)X.push({type:"fetchUrl",url:H,researchGoal:W.researchGoal||`Fetch GitHub content for ${V}/${Y}`})}return X}function M9($,Z){let X=r0($?.answer||"")||{},J=Array.isArray(X?.actions)?X.actions:[],W=[];for(let K of J){let V=g2(K);if(V&&W.length<Z)W.push(V)}return W}function G9($){return($||[]).map((Z)=>({type:"search",query:typeof Z==="string"?Z:Z.query,researchGoal:typeof Z==="string"?"":Z.researchGoal||""})).filter((Z)=>Z.query)}function R$($){return $0($?.finalUrl||$?.canonicalUrl||$?.url||"")||$?.id||""}function O9($,Z,X,J=new Set){let W=(Z||[]).filter((V)=>V.status!=="closed").slice(0,12).map((V)=>({id:V.id,question:V.question})),K=(X||[]).filter((V)=>V?.content||V?.snippet).filter((V)=>!J.has(R$(V))).slice(0,6).map((V,Y)=>({id:V.id||`F${Y+1}`,title:V.title||"",url:V.finalUrl||V.url||V.canonicalUrl||"",content:I(V.content||V.snippet||"",5000)}));return["You are doing goal-based evidence extraction for an iterative research run.","For each source, extract only information that helps answer the open questions.","Use original wording/details where useful. Do not invent answers; leave questions open if evidence is insufficient.","If a source answers one or more tracked questions, identify those question IDs explicitly.","Also propose genuinely new sub-questions discovered from the evidence.","",`Original research question: ${$}`,`Open question ledger: ${JSON.stringify(W,null,2)}`,`Fetched sources: ${JSON.stringify(K,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({extractions:[{sourceId:"S1",url:"https://example.com/source",rational:"why this source matters for the goal",evidence:"specific quoted/paraphrased evidence with numbers, dates, caveats",summary:"concise contribution to the research question",answers:[{id:"Q1",evidence:"brief evidence that closes the question"}],newQuestions:["new sub-question raised by this source"]}]},null,2),"END_JSON"].join(`
329
+ `)}function N9($,Z){let X=Array.isArray($?.extractions)?$.extractions:[],J=new Map,W=new Map;for(let K of Z||[]){if(K?.id)W.set(String(K.id),K);let V=R$(K);if(V)J.set(V,K)}return X.map((K)=>{let V=W.get(String(K?.sourceId||""))||J.get($0(K?.url||"")||""),Y=String(K?.sourceId||V?.id||""),j=$0(K?.url||V?.finalUrl||V?.url||""),Q=Array.isArray(K?.answers)?K.answers.map((B)=>({id:String(B?.id||""),evidence:I(B?.evidence||"",500),sourceIds:[Y].filter(Boolean)})).filter((B)=>B.id):[];return{sourceId:Y,url:j,title:V?.title||K?.title||"",rational:I(K?.rational||"",700),evidence:I(K?.evidence||"",1600),summary:I(K?.summary||"",700),answers:Q,newQuestions:B0(K?.newQuestions||[],6)}}).filter((K)=>K.sourceId||K.url||K.summary||K.evidence)}async function D9({query:$,questions:Z,fetchedSources:X,extractedSourceKeys:J}){let W=(X||[]).filter((K)=>(K?.content||K?.snippet)&&!J.has(R$(K)));if(W.length===0)return{evidence:[],error:""};try{let K=await T0(O9($,Z,W,J),{timeoutMs:120000}),V=$$(K,{extractions:[]}),Y=N9(V,W);for(let j of W){let Q=R$(j);if(Q)J.add(Q)}return{evidence:Y,error:""}}catch(K){return{evidence:[],error:K.message||String(K)}}}function z9($,Z,X,J,W=[],K=[]){let V=J.filter((Y)=>Y?.content||Y?.snippet).slice(0,10).map((Y,j)=>({id:`F${j+1}`,title:Y.title||"",url:Y.finalUrl||Y.url||"",snippet:I(Y.content||Y.snippet||"",3000)}));return["You are extracting compact research state from live multi-engine search results.","Create dense, non-overlapping learnings with exact names, numbers, dates, limitations, and caveats where available.","Also propose follow-up search queries that would most improve confidence or fill gaps.","",`Original research question: ${$}`,`Round queries: ${JSON.stringify(Z,null,2)}`,`Question ledger: ${JSON.stringify(W,null,2)}`,`Extracted source evidence: ${JSON.stringify(K.slice(-12),null,2)}`,`Engine summaries: ${JSON.stringify(X,null,2)}`,`Fetched source snippets: ${JSON.stringify(V,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({learnings:["concise, information-dense learning"],answeredQuestions:[{id:"Q1",evidence:"brief evidence that closes this question",sourceIds:["S1"]}],newQuestions:["new sub-question discovered from the evidence"],followUpQueries:["specific next search query"],gaps:["important uncertainty or missing evidence"]},null,2),"END_JSON"].join(`
330
+ `)}function U9($,Z,X,J=[],W=[]){let K=Z.flatMap((j)=>j.learnings||[]),V=Z.flatMap((j)=>j.gaps||[]),Y=X.slice(0,12).map((j)=>({id:j.id,title:j.title,domain:j.domain,url:j.canonicalUrl,type:j.sourceType,engines:j.engines,fetch:j.fetch?.attempted?{ok:j.fetch.ok,snippet:I(j.fetch.snippet||"",1200),publishedTime:j.fetch.publishedTime||""}:void 0}));return["You are writing the final research report for an iterative deep-research run.","Produce a thorough markdown report organized into clear sections.","","Use the learnings and source registry below. Every substantive claim MUST be backed by an [S1] citation.",'Where engines disagree, surface the conflicting claims explicitly in the "differences" array.','Include a "Key Claims" structure that maps each distinct claim to its supporting source IDs.',"","Report structure:","1. ## Summary — A 2-4 sentence executive summary of findings","2. ## Key Findings — The main findings, organized by theme or question, each with inline citations","3. ## Areas of Disagreement — Where engines or sources conflict (if any)","4. ## Limitations & Caveats — Important qualifiers, gaps, or uncertainties","",`Original research question: ${$}`,`Learnings: ${JSON.stringify(K,null,2)}`,`Known gaps/caveats: ${JSON.stringify(V,null,2)}`,`Question ledger: ${JSON.stringify(J,null,2)}`,`Goal-based extracted evidence: ${JSON.stringify(W.slice(-20),null,2)}`,`Source registry: ${JSON.stringify(Y,null,2)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({answer:"markdown report with sections and inline [S1] citations",agreement:{level:"high|medium|low|mixed|conflicting",summary:"one-sentence confidence summary"},differences:["notable disagreement or conflict between sources"],caveats:["important caveat or qualification"],claims:[{claim:"specific factual statement from the research",support:"strong|moderate|weak|conflicting",sourceIds:["S1","S2"]}],recommendedSources:["S1","S2"]},null,2),"END_JSON"].join(`
331
+ `)}function A9($,Z=[],X=[],J=[]){let W=Z.slice(0,12).map((j)=>({id:j.id,title:j.title,domain:j.domain,url:j.canonicalUrl,type:j.sourceType,engines:j.engines})),K=J.slice(-20),V=new Set;for(let j of K)for(let Q of j.answers||[])if(Q?.id)V.add(Q.id);let Y=(X||[]).filter((j)=>j.status!=="closed").map((j)=>({id:j.id,question:j.question}));return["You are writing the final research report from goal-based extracted evidence.","Per-round learnings were not produced, but the per-source evidence extraction step succeeded.","Synthesize a thorough markdown report using ONLY the evidence below. Every substantive claim MUST be backed by an [S1] citation.","","Report structure:","1. ## Summary — A 2-4 sentence executive summary of findings","2. ## Key Findings — The main findings, organized by theme or question, each with inline citations","3. ## Limitations & Caveats — Important qualifiers, gaps, or uncertainties","",`Original research question: ${$}`,`Per-source extracted evidence: ${JSON.stringify(K,null,2)}`,`Source registry: ${JSON.stringify(W,null,2)}`,`Questions already answered by the evidence: ${JSON.stringify(Array.from(V))}`,`Questions still open after this evidence: ${JSON.stringify(Y)}`,"","Respond ONLY with JSON wrapped in BEGIN_JSON / END_JSON markers:","BEGIN_JSON",JSON.stringify({answer:"markdown report with sections and inline [S1] citations",agreement:{level:"high|medium|low|mixed|conflicting",summary:"one-sentence confidence summary"},differences:["notable disagreement or conflict between sources"],caveats:["important caveat or qualification"],claims:[{claim:"specific factual statement supported by the evidence",support:"strong|moderate|weak|conflicting",sourceIds:["S1","S2"]}],recommendedSources:["S1","S2"]},null,2),"END_JSON"].join(`
332
+ `)}async function _9($,{locale:Z=null,short:X=!0}={}){let J=[o6,"all","--inline","--stdin","--fast"];if(!X)J.push("--full");if(Z)J.push("--locale",Z);return new Promise((W,K)=>{let V=c6(Z0(),J,{stdio:["pipe","pipe","pipe"],env:{...process.env,GREEDY_SEARCH_RESEARCH_CHILD:"1"}});V.stdin.write($),V.stdin.end();let Y="",j="",Q="";V.stdout.on("data",(H)=>Y+=H),V.stderr.on("data",(H)=>{j+=H,Q+=H.toString();let O=Q.split(`
333
+ `);Q=O.pop()||"";for(let G of O)if(k9(G))process.stderr.write(`${G}
334
+ `)});let B=setTimeout(()=>{V.kill(),K(Error(`research child search timed out for: ${$}`))},140000);V.on("close",(H)=>{if(clearTimeout(B),H!==0){K(Error(j.trim()||`search child exited with code ${H}`));return}try{W(JSON.parse(Y.trim()))}catch{K(Error(`Invalid JSON from research child: ${Y.slice(0,200)}`))}})})}function P9($){let Z=new Map;for(let X of $.flat()){let J=$0(X.canonicalUrl||X.url);if(!J)continue;let W=Z.get(J);if(!W){Z.set(J,{...X,canonicalUrl:J});continue}W.engines=[...new Set([...W.engines||[],...X.engines||[]])],W.engineCount=W.engines.length,W.smartScore=Math.max(W.smartScore||0,X.smartScore||0)}return Array.from(Z.values()).sort((X,J)=>{let W=w0(J)-w0(X);if(W!==0)return W;return(X.domain||"").localeCompare(J.domain||"")}).slice(0,12).map((X,J)=>({...X,id:`S${J+1}`}))}function k9($){return/^PROGRESS:/.test($)||/^\[greedysearch\]/.test($)||/^\[(bing|perplexity|google|gemini|chatgpt|logically|semantic-scholar)\]/.test($)||/^GreedySearch Chrome/.test($)||/^Launching GreedySearch Chrome/.test($)||/^Headless mode/.test($)||/^Ready\.?$/.test($)}function $$($,Z={}){return r0($?.answer||"")||Z}function L9($,Z){if(!$||!Array.isArray(Z))return{cited:[],missing:[],unfetched:[],ok:!0};let X=/\b[SF](\d+)\b/g,J=new Set,W;while((W=X.exec($))!==null)J.add(`S${W[1]}`),J.add(`F${W[1]}`);let K=new Map;for(let Q of Z){let B=Q?.id;if(B)K.set(B,Q)}let V=Array.from(J),Y=[],j=[];for(let Q of V){let B=K.get(Q);if(!B){let H=Q.match(/^(S|F)(\d+)$/);if(H){let O=parseInt(H[2],10)-1;if(O>=0&&O<Z.length){let G=Z[O];if(G){if(!(G.fetch?.ok||G.content&&G.content.length>100||G.contentChars&&G.contentChars>100))j.push(Q);continue}}}Y.push(Q)}else if(!(B.fetch?.ok||B.content&&B.content.length>100||B.contentChars&&B.contentChars>100))j.push(Q)}return{cited:V,missing:Y,unfetched:j,ok:Y.length===0}}function v2({sources:$=[],fetchedSources:Z=[],synthesis:X={},citationAudit:J=null,gaps:W=[],questions:K=[],rounds:V=[],qualityScore:Y=0,qualityThreshold:j=8.5,maxSources:Q=8,requireCitations:B=!0,requireQuestions:H=!0}={}){let O=Z.filter((f)=>f?.fetch?.ok||(f?.contentChars||0)>100||String(f?.content||"").length>100),G=$.filter((f)=>["official-docs","repo","maintainer-blog","academic"].includes(String(f?.sourceType||""))),D=Array.isArray(X?.claims)?X.claims:[],z=J?J.cited?.length||0:0,M=P1(K),A=(K||[]).filter((f)=>!f.createdRound||f.reason==="Original research question"),b=P1(A),P=Math.min(4,Math.max(2,Number(Q)||8)),w={roundsRun:V.length>=1,fetchedSources:O.length>=P,primarySources:G.length>=1,qualityScore:Y>=Math.min(j,8),claimsExtracted:!B||D.length>0,citationsPresent:!B||z>0,citationsValid:!B||J?.ok===!0,unfetchedCitations:!B||(J?.unfetched||[]).length===0,requiredQuestionsClosed:!H||b.open===0};return{floorMet:Object.values(w).every(Boolean),checks:w,metrics:{fetchedOk:O.length,primarySources:G.length,claims:D.length,cited:z,gaps:W.length,openQuestions:M.open,closedQuestions:M.closed,totalQuestions:M.total,openRequiredQuestions:b.open,closedRequiredQuestions:b.closed,totalRequiredQuestions:b.total,qualityScore:Y,minFetched:P}}}function f2($,Z){let X=new Map;for(let J of Z||[]){let W=$0(J?.canonicalUrl||J?.finalUrl||J?.url);if(W&&J?.id)X.set(W,J.id)}return($||[]).map((J,W)=>{let K=$0(J?.finalUrl||J?.canonicalUrl||J?.url);return{...J,id:J?.id||X.get(K)||`F${W+1}`}})}function F9($){return[{id:"Q1",question:I(J0($),320),status:"open",reason:"Original research question",evidence:[],sourceIds:[]}]}function w9($){let Z=0;for(let X of $||[]){let J=Number.parseInt(String(X.id||"").replace(/^Q/i,""),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return`Q${Z+1}`}function y2($,Z){let X=J0(Z).toLowerCase();return($||[]).find((J)=>J.question?.toLowerCase()===X||I$(J.question||"",X)>=0.82)}function U1($,Z,{reason:X="",round:J=null}={}){let W=I(J0(Z),320);if(!W)return null;let K=y2($,W);if(K)return K;let V={id:w9($),question:W,status:"open",reason:I(X,240),createdRound:J,evidence:[],sourceIds:[]};return $.push(V),V}function C$($,Z,{evidence:X="",sourceIds:J=[],round:W=null}={}){let K=$.find((V)=>V.id===Z)||y2($,Z);if(!K)return null;if(K.status="closed",K.closedRound=K.closedRound||W,X)K.evidence=B0([...K.evidence||[],X],4);if(Array.isArray(J))K.sourceIds=B0([...K.sourceIds||[],...J],8);return K}function P1($){let Z=$.length,X=$.filter((J)=>J.status==="closed").length;return{total:Z,closed:X,open:Math.max(0,Z-X)}}function T$($,{roundNumber:Z,actions:X=[],learningPayload:J={}}={}){for(let j of X){let Q=j?.action||j,B=Q?.researchGoal&&Q.researchGoal!=="Original user query"?Q.researchGoal:Q?.query||Q?.url||"";if(B)U1($,B,{reason:"Planned research action",round:Z})}let W=5,K=$.filter((j)=>j.status==="open"&&j.reason==="Discovered gap/follow-up");if(K.length>W){let j=K.sort((Q,B)=>(Q.createdRound||0)-(B.createdRound||0)).slice(0,K.length-W);for(let Q of j)Q.status="resolved",Q.closedRound=Z,Q.evidence=B0([...Q.evidence||[],"Auto-resolved to cap open-question ledger"],4)}let V=Array.isArray(J.answeredQuestions)?J.answeredQuestions:[];for(let j of V){if(typeof j==="string"){C$($,j,{round:Z});continue}let Q=j?.id||j?.question;if(!Q&&j?.question){let B=U1($,j.question,{reason:"Answered during learning extraction",round:Z});if(B)C$($,B.id,{round:Z});continue}C$($,Q,{evidence:j?.evidence||j?.answer||"",sourceIds:Array.isArray(j?.sourceIds)?j.sourceIds:[],round:Z})}let Y=Array.isArray(J.newQuestions)?J.newQuestions:[];for(let j of Y)U1($,j,{reason:"Discovered gap/follow-up",round:Z});return $}function T9($,Z){if(!Array.isArray($)||$.length===0)return[];let X=["arxiv.org","semanticscholar.org","doi.org"],J=new Set,W=[];for(let K of $){let V=K?.canonicalUrl||K?.finalUrl||K?.url||"";if(!V)continue;let Y="";try{Y=new URL(V).hostname.toLowerCase().replace(/^www\./,"")}catch{continue}if(!X.some((Q)=>Y===Q||Y.endsWith(`.${Q}`)))continue;if(Z.has(V)||J.has(V))continue;J.add(V);let j=V.includes("/pdf/")?V.replace(/\/pdf\//,"/html/").replace(/\.pdf$/i,""):V;W.push({url:j,label:K?.title||K?.id||Y})}return W.slice(0,2)}function C9($,Z,X){if(!Z?.answer||X?.ok!==!0)return $;let J=Array.isArray(Z.claims)?Z.claims:[],W=Array.isArray(X.cited)?X.cited:[];if(J.length===0||W.length===0)return $;for(let K of $){if(K.status==="closed")continue;let V=null,Y=0;for(let j of J){let Q=I$(K.question||"",j.claim||"");if(Q>Y)Y=Q,V=j}if(K.id==="Q1"||Y>=0.18)C$($,K.id,{evidence:V?.claim||"Answered in final cited synthesis",sourceIds:Array.isArray(V?.sourceIds)?V.sourceIds:W.slice(0,4)})}return $}function R9($){if(!$.length)return"No tracked questions.";return $.map((Z)=>{let X=Z.sourceIds?.length?` (${Z.sourceIds.join(", ")})`:"";return`- [${Z.status==="closed"?"x":" "}] ${Z.id}: ${Z.question}${X}`}).join(`
335
+ `)}function A1($,Z="None recorded."){let X=B0($);return X.length?X.map((J)=>`- ${J}`).join(`
336
+ `):Z}async function I9({query:$,rounds:Z,sources:X,fetchedSources:J,evidenceItems:W=[],synthesis:K,citationAudit:V,floor:Y,manifest:j,allGaps:Q=[],questions:B=[],outDir:H=null}){let O=new Date().toISOString().replaceAll(/[:.]/g,"-").slice(0,19),G=H||x(a6,`${O}_${s6($)}`),D=x(G,"reports"),z=x(G,"sources"),M=x(G,"data");N1(D,{recursive:!0}),N1(z,{recursive:!0}),N1(M,{recursive:!0});let A=await _1(J,z),b=B0([...Q,...Z.flatMap((P)=>P.gaps||[])]);return n(x(G,"STATUS.md"),[Y.floorMet?"STATUS: DONE":"STATUS: PARTIAL","",`Query: ${$}`,`Stop reason: ${j.terminationReason||"max_rounds"}`,"","## Deterministic floor checks",...Object.entries(Y.checks).map(([P,w])=>`- [${w?"x":" "}] ${P}`),"","## Questions",R9(B),"","## Open gaps",A1(b),""].join(`
337
+ `),"utf8"),n(x(G,"OUTLINE.md"),["# Research bundle outline","","- `reports/SUMMARY.md` — final cited report","- `reports/CLAIMS.md` — extracted claims with support/source IDs","- `reports/EVIDENCE.md` — goal-based source evidence","- `reports/GAPS.md` — remaining caveats and uncertainties","- `sources/` — fetched source markdown files","- `data/manifest.json` — machine-readable run metadata","- `data/rounds.json` — per-round actions/learnings/gaps","- `data/sources.json` — ranked source registry","- `data/questions.json` — open/closed question ledger",""].join(`
338
+ `),"utf8"),n(x(D,"SUMMARY.md"),String(K.answer||""),"utf8"),n(x(D,"CLAIMS.md"),["# Key claims","",...Array.isArray(K.claims)&&K.claims.length?K.claims.map((P)=>{let w=Array.isArray(P.sourceIds)?P.sourceIds.join(", "):"";return`- ${P.claim||""} (${P.support||"support unknown"}${w?`; ${w}`:""})`}):["No structured claims were extracted."],""].join(`
339
+ `),"utf8"),n(x(D,"EVIDENCE.md"),["# Extracted evidence","",...W.length?W.map((P)=>[`## ${P.sourceId||P.url||"Source"}`,P.url?`<${P.url}>`:"",P.rational?`**Rational:** ${P.rational}`:"",P.evidence?`**Evidence:** ${P.evidence}`:"",P.summary?`**Summary:** ${P.summary}`:"",""].filter(Boolean).join(`
340
340
  `)):["No goal-based evidence was extracted."],""].join(`
341
- `),"utf8"),i(f(z,"GAPS.md"),["# Gaps and caveats","","## Caveats",_1(K.caveats||[]),"","## Research gaps",_1(b),""].join(`
342
- `),"utf8"),i(f(M,"manifest.json"),JSON.stringify({...j,floor:Y,citationAudit:V},null,2),"utf8"),i(f(M,"rounds.json"),JSON.stringify(Z,null,2),"utf8"),i(f(M,"sources.json"),JSON.stringify(X,null,2),"utf8"),i(f(M,"questions.json"),JSON.stringify(B,null,2),"utf8"),i(f(M,"evidence.json"),JSON.stringify(W,null,2),"utf8"),i(f(D,"index.md"),["# Source index","",...A.map((P)=>{let F=P.title||P.url,x=P.finalUrl||P.url,o=P.contentPath?` — ${P.contentPath}`:"";return`- ${P.id||"?"}: [${F}](${x})${o}`}),""].join(`
343
- `),"utf8"),{dir:O,statusPath:f(O,"STATUS.md"),summaryPath:f(z,"SUMMARY.md"),manifestPath:f(M,"manifest.json"),sourceCount:A.length,sourceFiles:A}}async function m2({query:$,breadth:Z=3,iterations:X=2,maxSources:J,locale:W=null,short:K=!1,qualityThreshold:V=8.5,writeBundle:Y=process.env.GREEDY_RESEARCH_BUNDLE!=="0",researchOutDir:j=null}={}){let Q=Z9({breadth:Z,iterations:X,maxSources:J}),B=[],H=[],G=[],O=C9($),z=null,D=[],M=[],A=[],b=new Set,P=new Set,F=new Set,x=[],o="max_rounds",C0=new Date().toISOString(),b$=Date.now(),X$=0,z0=0,B0=0,H0=[];process.stderr.write(`[greedysearch] Research mode: breadth ${Q.breadth}, iterations ${Q.iterations}, qualityThreshold ${V}, engines ${p$.join(",")}, synthesizer gemini
344
- `);for(let L=0;L<Q.iterations;L++){let T=L+1,_=Math.max(1,Math.ceil(Q.breadth/2**L));if(process.stderr.write(`PROGRESS:research:round-${T}:planning
345
- `),!z)try{let N=await T0(Q9($,_,H,G,[...F]),{timeoutMs:120000}),C=N9(N,_);if(L===0)C.unshift({type:"search",query:$,researchGoal:"Original user query"});C=await G9(C,F),z=C}catch(N){process.stderr.write(`[greedysearch] Action planning failed, using fallback queries: ${N.message}
346
- `);let C=X9(null,$,_,{includeOriginal:L===0,exclude:P});z=z9(C)}let k=(z||[]).filter((N)=>{if(N.type==="search"){let C=!y2(N.query,P,{roundIndex:L,originalQuery:$});if(!C)process.stderr.write(`[greedysearch] Novelty gate rejected search: ${N.query}
347
- `);return C}if(N.type==="fetchUrl"){let C=!F.has(N.url);if(!C)process.stderr.write(`[greedysearch] Novelty gate rejected fetch: ${N.url}
348
- `);return C}return!1}).slice(0,_),m=I9(D,F);if(!k.some((N)=>N.type==="fetchUrl")&&m.length>0){let N=m[0];k.push({type:"fetchUrl",url:N.url,researchGoal:`Direct fetch of known academic source: ${N.label||N.url}`}),process.stderr.write(`[greedysearch] Forced fetchUrl for academic source: ${N.url}
349
- `)}let g=[];for(let N=0;N<k.length;N++){let C=k[N];process.stderr.write(`PROGRESS:research:round-${T}:action-${N+1}/${k.length}
341
+ `),"utf8"),n(x(D,"GAPS.md"),["# Gaps and caveats","","## Caveats",A1(K.caveats||[]),"","## Research gaps",A1(b),""].join(`
342
+ `),"utf8"),n(x(M,"manifest.json"),JSON.stringify({...j,floor:Y,citationAudit:V},null,2),"utf8"),n(x(M,"rounds.json"),JSON.stringify(Z,null,2),"utf8"),n(x(M,"sources.json"),JSON.stringify(X,null,2),"utf8"),n(x(M,"questions.json"),JSON.stringify(B,null,2),"utf8"),n(x(M,"evidence.json"),JSON.stringify(W,null,2),"utf8"),n(x(z,"index.md"),["# Source index","",...A.map((P)=>{let w=P.title||P.url,f=P.finalUrl||P.url,i=P.contentPath?` — ${P.contentPath}`:"";return`- ${P.id||"?"}: [${w}](${f})${i}`}),""].join(`
343
+ `),"utf8"),{dir:G,statusPath:x(G,"STATUS.md"),summaryPath:x(D,"SUMMARY.md"),manifestPath:x(M,"manifest.json"),sourceCount:A.length,sourceFiles:A}}async function h2({query:$,breadth:Z=3,iterations:X=2,maxSources:J,locale:W=null,short:K=!1,qualityThreshold:V=8.5,writeBundle:Y=process.env.GREEDY_RESEARCH_BUNDLE!=="0",researchOutDir:j=null}={}){let Q=r6({breadth:Z,iterations:X,maxSources:J}),B=[],H=[],O=[],G=F9($),D=null,z=[],M=[],A=[],b=new Set,P=new Set,w=new Set,f=[],i="max_rounds",C0=new Date().toISOString(),q$=Date.now(),X$=0,D0=0,H0=0,M0=[];process.stderr.write(`[greedysearch] Research mode: breadth ${Q.breadth}, iterations ${Q.iterations}, qualityThreshold ${V}, engines ${m$.join(",")}, synthesizer gemini
344
+ `);for(let L=0;L<Q.iterations;L++){let F=L+1,_=Math.max(1,Math.ceil(Q.breadth/2**L));if(process.stderr.write(`PROGRESS:research:round-${F}:planning
345
+ `),!D)try{let N=await T0(V9($,_,H,O,[...w]),{timeoutMs:120000}),C=M9(N,_);if(L===0)C.unshift({type:"search",query:$,researchGoal:"Original user query"});C=await H9(C,w),D=C}catch(N){process.stderr.write(`[greedysearch] Action planning failed, using fallback queries: ${N.message}
346
+ `);let C=e6(null,$,_,{includeOriginal:L===0,exclude:P});D=G9(C)}let k=(D||[]).filter((N)=>{if(N.type==="search"){let C=!S2(N.query,P,{roundIndex:L,originalQuery:$});if(!C)process.stderr.write(`[greedysearch] Novelty gate rejected search: ${N.query}
347
+ `);return C}if(N.type==="fetchUrl"){let C=!w.has(N.url);if(!C)process.stderr.write(`[greedysearch] Novelty gate rejected fetch: ${N.url}
348
+ `);return C}return!1}).slice(0,_),m=T9(z,w);if(!k.some((N)=>N.type==="fetchUrl")&&m.length>0){let N=m[0];k.push({type:"fetchUrl",url:N.url,researchGoal:`Direct fetch of known academic source: ${N.label||N.url}`}),process.stderr.write(`[greedysearch] Forced fetchUrl for academic source: ${N.url}
349
+ `)}let g=[];for(let N=0;N<k.length;N++){let C=k[N];process.stderr.write(`PROGRESS:research:round-${F}:action-${N+1}/${k.length}
350
350
  `),process.stderr.write(`[greedysearch] Action ${N+1}/${k.length} [${C.type}]: ${(C.query||C.url).slice(0,80)}
351
- `);let W0=await B9(C,{locale:W,short:K,usedQueries:P,usedUrls:F,maxChars:8000});if(g.push(W0),X$++,C.type==="search")z0++;if(C.type==="fetchUrl")B0++;if(!W0.ok)H0.push({round:T,type:C.type,target:C.query||C.url,error:W0.error}),process.stderr.write(`[greedysearch] Action failed: ${W0.error}
352
- `)}let d=g.filter((N)=>N.action.type==="search"),W$=g.filter((N)=>N.action.type==="fetchUrl");T$(O,{roundNumber:T,actions:g}),D=F9([D,d.flatMap((N)=>N.sources||[]),W$.flatMap((N)=>N.sources||[])]);for(let N of W$)if(N.fetchResult)M.push(N.fetchResult);M=g2(M);let R=Math.max(0,Q.maxSources-M.filter((N)=>N?.content||N?.contentChars>100).length);if(R>0&&D.length>0){process.stderr.write(`PROGRESS:research:round-${T}:fetching
353
- `);let N=await $9(D,Math.min(R,D.length),8000,Math.min(3,R||1));M=g2([...M,...N]),D=L$(D,M)}M=S2(M,D),process.stderr.write(`PROGRESS:research:round-${T}:evidence
354
- `);let t=await A9({query:$,questions:O,fetchedSources:M,extractedSourceKeys:b});if(t.error)process.stderr.write(`[greedysearch] Evidence extraction failed: ${t.error}
355
- `);A=[...A,...t.evidence];for(let N of t.evidence)T$(O,{roundNumber:T,learningPayload:{answeredQuestions:N.answers||[],newQuestions:N.newQuestions||[]}});let h=g.map((N)=>({query:N.action.query||N.action.url||"",researchGoal:N.action.researchGoal||""}));process.stderr.write(`PROGRESS:research:round-${T}:learning
356
- `);let r={learnings:[],followUpQueries:[],gaps:[]},I0="";try{let N=await T0(_9($,h,d.map((C)=>({query:C.action.query,researchGoal:C.action.researchGoal,error:C.error||"",engines:j9(C.result)})),M,O,A),{timeoutMs:120000});r={...r,...$$(N,r)}}catch(N){I0=N.message,process.stderr.write(`[greedysearch] Learning extraction failed: ${N.message}
357
- `)}let w1=Array.isArray(r.learnings)?r.learnings.map((N)=>String(N)).filter(Boolean).slice(0,8):[],v$=Array.isArray(r.gaps)?r.gaps.map((N)=>String(N)).filter(Boolean).slice(0,6):[];H=Q0([...H,...w1]),G=Q0([...G,...v$]),T$(O,{roundNumber:T,actions:[],learningPayload:r,gaps:v$}),B.push({round:T,actions:g.map((N)=>({type:N.action.type,query:N.action.query||"",url:N.action.url||"",researchGoal:N.action.researchGoal||"",error:N.error||"",sourceCount:N.sources?.length||0})),learnings:w1,gaps:v$,evidence:t.evidence,evidenceError:t.error,learningError:I0}),process.stderr.write(`PROGRESS:research:round-${T}:evaluating
358
- `);let u=await Y9($,B,H,G,x);x.push(u.score),G=Q0([...G,...u.knowledgeGaps||[]]),T$(O,{roundNumber:T,gaps:u.knowledgeGaps||[]});let T1=x2({sources:D,fetchedSources:M,gaps:G,questions:O,rounds:B,qualityScore:u.score,qualityThreshold:V,maxSources:Q.maxSources,requireCitations:!1,requireQuestions:!1});if(process.stderr.write(`[greedysearch] Quality score round ${T}: ${u.score.toFixed(1)} (shouldContinue: ${u.shouldContinue}, floor: ${T1.floorMet})
359
- `),u.score>=V&&T1.floorMet&&(!u.shouldContinue||u.terminationReason==="quality_threshold")){o=u.terminationReason||"quality_threshold",process.stderr.write(`[greedysearch] Research floor reached (score: ${u.score.toFixed(1)}). Terminating early.
360
- `);break}let U0=Math.max(1,Math.ceil(_/2)),J0=(r.followUpQueries||[]).map((N)=>({type:"search",query:X0(String(N)),researchGoal:"Follow-up from learning extraction"})).filter((N)=>N.query&&N.query.toLowerCase()!==$.toLowerCase()).slice(0,U0);if(J0.length<U0&&u.nextActions.length>0){let N=u.nextActions.map((W0)=>h2(W0)).filter(Boolean);J0=[...J0,...N].slice(0,U0)}if(J0.length<U0&&G.length>0){let N=V9(G,$,P,U0-J0.length,L+1),C=N.map((W0)=>({type:"search",query:W0.query,researchGoal:W0.researchGoal}));if(J0=[...J0,...C].slice(0,U0),N.length>0)process.stderr.write(`[greedysearch] Generated ${N.length} gap-driven fallback actions.
361
- `)}z=J0.length>=U0?J0:null}process.stderr.write(`PROGRESS:research:final-report
351
+ `);let K0=await Y9(C,{locale:W,short:K,usedQueries:P,usedUrls:w,maxChars:8000});if(g.push(K0),X$++,C.type==="search")D0++;if(C.type==="fetchUrl")H0++;if(!K0.ok)M0.push({round:F,type:C.type,target:C.query||C.url,error:K0.error}),process.stderr.write(`[greedysearch] Action failed: ${K0.error}
352
+ `)}let d=g.filter((N)=>N.action.type==="search"),W$=g.filter((N)=>N.action.type==="fetchUrl");T$(G,{roundNumber:F,actions:g}),z=P9([z,d.flatMap((N)=>N.sources||[]),W$.flatMap((N)=>N.sources||[])]);for(let N of W$)if(N.fetchResult)M.push(N.fetchResult);M=x2(M);let R=Math.max(0,Q.maxSources-M.filter((N)=>N?.content||N?.contentChars>100).length);if(R>0&&z.length>0){process.stderr.write(`PROGRESS:research:round-${F}:fetching
353
+ `);let N=await t6(z,Math.min(R,z.length),8000,Math.min(3,R||1));M=x2([...M,...N]),z=L$(z,M)}M=f2(M,z),process.stderr.write(`PROGRESS:research:round-${F}:evidence
354
+ `);let s=await D9({query:$,questions:G,fetchedSources:M,extractedSourceKeys:b});if(s.error)process.stderr.write(`[greedysearch] Evidence extraction failed: ${s.error}
355
+ `);A=[...A,...s.evidence];for(let N of s.evidence)T$(G,{roundNumber:F,learningPayload:{answeredQuestions:N.answers||[],newQuestions:N.newQuestions||[]}});let h=g.map((N)=>({query:N.action.query||N.action.url||"",researchGoal:N.action.researchGoal||""}));process.stderr.write(`PROGRESS:research:round-${F}:learning
356
+ `);let t={learnings:[],followUpQueries:[],gaps:[]},I0="";try{let N=await T0(z9($,h,d.map((C)=>({query:C.action.query,researchGoal:C.action.researchGoal,error:C.error||"",engines:K9(C.result)})),M,G,A),{timeoutMs:120000});t={...t,...$$(N,t)}}catch(N){I0=N.message,process.stderr.write(`[greedysearch] Learning extraction failed: ${N.message}
357
+ `)}let L1=Array.isArray(t.learnings)?t.learnings.map((N)=>String(N)).filter(Boolean).slice(0,8):[],f$=Array.isArray(t.gaps)?t.gaps.map((N)=>String(N)).filter(Boolean).slice(0,6):[];H=B0([...H,...L1]),O=B0([...O,...f$]),T$(G,{roundNumber:F,actions:[],learningPayload:t,gaps:f$}),B.push({round:F,actions:g.map((N)=>({type:N.action.type,query:N.action.query||"",url:N.action.url||"",researchGoal:N.action.researchGoal||"",error:N.error||"",sourceCount:N.sources?.length||0})),learnings:L1,gaps:f$,evidence:s.evidence,evidenceError:s.error,learningError:I0}),process.stderr.write(`PROGRESS:research:round-${F}:evaluating
358
+ `);let u=await W9($,B,H,O,f);f.push(u.score),O=B0([...O,...u.knowledgeGaps||[]]),T$(G,{roundNumber:F,gaps:u.knowledgeGaps||[]});let F1=v2({sources:z,fetchedSources:M,gaps:O,questions:G,rounds:B,qualityScore:u.score,qualityThreshold:V,maxSources:Q.maxSources,requireCitations:!1,requireQuestions:!1});if(process.stderr.write(`[greedysearch] Quality score round ${F}: ${u.score.toFixed(1)} (shouldContinue: ${u.shouldContinue}, floor: ${F1.floorMet})
359
+ `),u.score>=V&&F1.floorMet&&(!u.shouldContinue||u.terminationReason==="quality_threshold")){i=u.terminationReason||"quality_threshold",process.stderr.write(`[greedysearch] Research floor reached (score: ${u.score.toFixed(1)}). Terminating early.
360
+ `);break}let U0=Math.max(1,Math.ceil(_/2)),W0=(t.followUpQueries||[]).map((N)=>({type:"search",query:J0(String(N)),researchGoal:"Follow-up from learning extraction"})).filter((N)=>N.query&&N.query.toLowerCase()!==$.toLowerCase()).slice(0,U0);if(W0.length<U0&&u.nextActions.length>0){let N=u.nextActions.map((K0)=>g2(K0)).filter(Boolean);W0=[...W0,...N].slice(0,U0)}if(W0.length<U0&&O.length>0){let N=J9(O,$,P,U0-W0.length,L+1),C=N.map((K0)=>({type:"search",query:K0.query,researchGoal:K0.researchGoal}));if(W0=[...W0,...C].slice(0,U0),N.length>0)process.stderr.write(`[greedysearch] Generated ${N.length} gap-driven fallback actions.
361
+ `)}D=W0.length>=U0?W0:null}process.stderr.write(`PROGRESS:research:final-report
362
362
  `);let S={answer:H.length?H.map((L)=>`- ${L}`).join(`
363
- `):"Research completed, but no structured learnings were extracted.",agreement:{level:"mixed",summary:"Research synthesis fallback."},differences:[],caveats:[],claims:[],recommendedSources:D.slice(0,4).map((L)=>L.id),synthesized:!1};try{let L=await T0(P9($,B,D,O,A),{timeoutMs:180000}),T=$$(L,{}),_=Array.isArray(T?.claims)&&T.claims.length>0;S={...S,...T,rawAnswer:L.answer||"",geminiSources:L.sources||[],synthesized:_}}catch(L){process.stderr.write(`[greedysearch] Final report failed: ${L.message}
363
+ `):"Research completed, but no structured learnings were extracted.",agreement:{level:"mixed",summary:"Research synthesis fallback."},differences:[],caveats:[],claims:[],recommendedSources:z.slice(0,4).map((L)=>L.id),synthesized:!1};try{let L=await T0(U9($,B,z,G,A),{timeoutMs:180000}),F=$$(L,{}),_=Array.isArray(F?.claims)&&F.claims.length>0;S={...S,...F,rawAnswer:L.answer||"",geminiSources:L.sources||[],synthesized:_}}catch(L){process.stderr.write(`[greedysearch] Final report failed: ${L.message}
364
364
  `),S.error=L.message}if(!(S.synthesized===!0&&Array.isArray(S.claims)&&S.claims.length>0)&&A.length>0){process.stderr.write(`[greedysearch] Falling back to evidence-based synthesis (no per-round learnings).
365
- `);try{let L=k9($,D,O,A),T=await T0(L,{timeoutMs:180000}),_=$$(T,{});S={...S,..._,rawAnswer:T.answer||S.answer||"",geminiSources:T.sources||S.geminiSources||[],synthesized:!0,synthesisMode:"evidence_fallback"}}catch(L){process.stderr.write(`[greedysearch] Evidence-based synthesis failed: ${L.message}
366
- `),S.evidenceFallbackError=L.message}}let a=new Date().toISOString(),J$=Date.now()-b$,D0=x.at(-1)||0;M=S2(M,D),process.stderr.write(`PROGRESS:research:audit-citations
367
- `);let R0=T9(S.answer||"",D);E9(O,S,R0);let v=x2({sources:D,fetchedSources:M,synthesis:S,citationAudit:R0,gaps:G,questions:O,rounds:B,qualityScore:D0,qualityThreshold:V,maxSources:Q.maxSources});if(v.floorMet&&o==="max_rounds")o="done_floor_met";else if(!v.floorMet&&o==="quality_threshold")o="max_rounds_floor_unmet";let s={startedAt:C0,finishedAt:a,durationMs:J$,engines:p$,synthesizer:"gemini",rounds:B.length,actionsRun:X$,searches:z0,fetches:B0,sourcesFetched:M.filter((L)=>L?.contentChars>100).length,engineFailures:H0,terminationReason:o,floorMet:v.floorMet},U=null,w;if(Y){process.stderr.write(`PROGRESS:research:bundle
368
- `);try{U=await q9({query:$,rounds:B,sources:D,fetchedSources:M,evidenceItems:A,synthesis:S,citationAudit:R0,floor:v,manifest:s,allGaps:G,questions:O,outDir:j}),w=U.sourceFiles,delete U.sourceFiles}catch(L){U={error:L.message||String(L)},w=await P1(M)}}else w=await P1(M);return process.stderr.write(`PROGRESS:research:done
369
- `),{query:$,_research:{mode:"iterative",breadth:Q.breadth,iterations:Q.iterations,maxSources:Q.maxSources,rounds:B,learnings:H,gaps:G,evidence:A,questions:O,questionProgress:k1(O),qualityHistory:x,terminationReason:o,qualityThreshold:V,floor:v,bundle:U,manifest:s},_citationAudit:R0,_sources:D,_fetchedSources:w,_synthesis:S,_confidence:{sourcesCount:D.length,fetchedSourceSuccessRate:M.length>0?Number((M.filter((L)=>L.contentChars>100).length/M.length).toFixed(2)):0,agreementLevel:S.agreement?.level||"mixed",floorMet:v.floorMet}}}function g2($){let Z=new Map;for(let J of $){let W=J?.id||$0(J?.finalUrl||J?.url||"");if(!W)continue;let K=Z.get(W);if(!K||(J.contentChars||0)>(K.contentChars||0))Z.set(W,J)}let X=[];for(let J of Z.values()){let W=String(J.content||J.snippet||""),K=X.findIndex((V)=>{let Y=String(V.content||V.snippet||"");if(W.length<400||Y.length<400)return!1;return I$(W.slice(0,4000),Y.slice(0,4000))>=0.9});if(K===-1){X.push(J);continue}if((J.contentChars||0)>(X[K].contentChars||0))X[K]=J}return X}var S9=l2(x9(),".config","greedysearch"),d2=l2(S9,"config.json");function g9(){try{if(E$(d2))return JSON.parse(f9(d2,"utf8"))}catch{}return{}}function Z$($){try{v9(q1,`${JSON.stringify({at:new Date().toISOString(),...$})}
370
- `,"utf8")}catch{}}async function y9(){return new Promise(($)=>{let Z="";if(process.stdin.setEncoding("utf8"),process.stdin.on("data",(X)=>Z+=X),process.stdin.on("end",()=>$(Z.trim())),process.stdin.isTTY)$("")})}async function h9(){let $=process.argv.slice(2);if($[0]==="--dm-print-helper-paths"){let U=t$(),w=L1(),L=v0("perplexity.mjs");console.log(JSON.stringify({launchScript:U,launchScriptExists:E$(U),searchScript:w,searchScriptExists:E$(w),perplexityExtractor:L,perplexityExtractorExists:E$(L)}));return}if($.length<2||$[0]==="--help")process.stderr.write(`${['Usage: node search.mjs <engine> "<query>"',"","Engines: all, perplexity (p), google (g), chatgpt (gpt), gemini (gem), semantic-scholar (s2), logically (log), bing (b)","","Flags:"," --synthesize For engine=all: synthesize fetched sources"," --synthesizer <engine> Synthesis engine (default from ~/.dm/greedyconfig)"," --fast Legacy quick mode: no source fetching or synthesis"," --depth <mode> Legacy: fast|standard|deep aliases, or research"," --deep-research Deprecated alias for --research"," --research Iterative query/learnings loop (alias: --depth research)"," --breadth <n> Research mode query breadth, 1-5 (default: 3)"," --iterations <n> Research mode rounds, 1-3 (default: 2)"," --max-sources <n> Research mode fetched source cap, 3-12"," --research-out-dir <dir> Write research bundle to a specific directory"," --no-research-bundle Disable the default .dm/greedysearch-research bundle"," --fetch-top-source Fetch content from top source"," --inline Output JSON to stdout (for piping)"," --locale <lang> Force results language (en, de, fr, etc.)"," --visible Always use visible Chrome for this search"," --always-visible Alias for --visible"," --stdin Read query from stdin (avoids command-line leakage)","","Environment:"," GREEDY_SEARCH_VISIBLE Set to 1 to show Chrome window (disables headless)"," GREEDY_SEARCH_ALWAYS_VISIBLE Set to 1 to force visible mode for all runs"," GREEDY_SEARCH_LOCALE Default locale (default: en)","","Examples:",' node search.mjs all "Node.js streams" # Grounded: engines + fetched sources',' node search.mjs all "Node.js streams" --synthesize # Add Gemini synthesis',' node search.mjs all "quick check" --fast # Legacy fast: no sources/synthesis',' node search.mjs all "browser automation" --research --breadth 3 --iterations 2',' node search.mjs p "what is memoization" # Single engine search'].join(`
365
+ `);try{let L=A9($,z,G,A),F=await T0(L,{timeoutMs:180000}),_=$$(F,{});S={...S,..._,rawAnswer:F.answer||S.answer||"",geminiSources:F.sources||S.geminiSources||[],synthesized:!0,synthesisMode:"evidence_fallback"}}catch(L){process.stderr.write(`[greedysearch] Evidence-based synthesis failed: ${L.message}
366
+ `),S.evidenceFallbackError=L.message}}let o=new Date().toISOString(),J$=Date.now()-q$,z0=f.at(-1)||0;M=f2(M,z),process.stderr.write(`PROGRESS:research:audit-citations
367
+ `);let R0=L9(S.answer||"",z);C9(G,S,R0);let v=v2({sources:z,fetchedSources:M,synthesis:S,citationAudit:R0,gaps:O,questions:G,rounds:B,qualityScore:z0,qualityThreshold:V,maxSources:Q.maxSources});if(v.floorMet&&i==="max_rounds")i="done_floor_met";else if(!v.floorMet&&i==="quality_threshold")i="max_rounds_floor_unmet";let a={startedAt:C0,finishedAt:o,durationMs:J$,engines:m$,synthesizer:"gemini",rounds:B.length,actionsRun:X$,searches:D0,fetches:H0,sourcesFetched:M.filter((L)=>L?.contentChars>100).length,engineFailures:M0,terminationReason:i,floorMet:v.floorMet},U=null,T;if(Y){process.stderr.write(`PROGRESS:research:bundle
368
+ `);try{U=await I9({query:$,rounds:B,sources:z,fetchedSources:M,evidenceItems:A,synthesis:S,citationAudit:R0,floor:v,manifest:a,allGaps:O,questions:G,outDir:j}),T=U.sourceFiles,delete U.sourceFiles}catch(L){U={error:L.message||String(L)},T=await _1(M)}}else T=await _1(M);return process.stderr.write(`PROGRESS:research:done
369
+ `),{query:$,_research:{mode:"iterative",breadth:Q.breadth,iterations:Q.iterations,maxSources:Q.maxSources,rounds:B,learnings:H,gaps:O,evidence:A,questions:G,questionProgress:P1(G),qualityHistory:f,terminationReason:i,qualityThreshold:V,floor:v,bundle:U,manifest:a},_citationAudit:R0,_sources:z,_fetchedSources:T,_synthesis:S,_confidence:{sourcesCount:z.length,fetchedSourceSuccessRate:M.length>0?Number((M.filter((L)=>L.contentChars>100).length/M.length).toFixed(2)):0,agreementLevel:S.agreement?.level||"mixed",floorMet:v.floorMet}}}function x2($){let Z=new Map;for(let J of $){let W=J?.id||$0(J?.finalUrl||J?.url||"");if(!W)continue;let K=Z.get(W);if(!K||(J.contentChars||0)>(K.contentChars||0))Z.set(W,J)}let X=[];for(let J of Z.values()){let W=String(J.content||J.snippet||""),K=X.findIndex((V)=>{let Y=String(V.content||V.snippet||"");if(W.length<400||Y.length<400)return!1;return I$(W.slice(0,4000),Y.slice(0,4000))>=0.9});if(K===-1){X.push(J);continue}if((J.contentChars||0)>(X[K].contentChars||0))X[K]=J}return X}var v9=b$(q9(),".config","greedysearch"),p2=b$(v9,"config.json");function f9(){try{if(E$(p2))return JSON.parse(b9(p2,"utf8"))}catch{}return{}}function Z$($){try{E9(E1,`${JSON.stringify({at:new Date().toISOString(),...$})}
370
+ `,"utf8")}catch{}}async function x9(){return new Promise(($)=>{let Z="";if(process.stdin.setEncoding("utf8"),process.stdin.on("data",(X)=>Z+=X),process.stdin.on("end",()=>$(Z.trim())),process.stdin.isTTY)$("")})}async function S9(){let $=process.argv.slice(2);if($[0]==="--dm-print-helper-paths"){let U=f0(import.meta.url),T=b$(U,"launch.mjs"),L=b$(U,"search.mjs"),F=x0("perplexity.mjs");console.log(JSON.stringify({launchScript:T,launchScriptExists:E$(T),searchScript:L,searchScriptExists:E$(L),perplexityExtractor:F,perplexityExtractorExists:E$(F)}));return}if($.length<2||$[0]==="--help")process.stderr.write(`${['Usage: node search.mjs <engine> "<query>"',"","Engines: all, perplexity (p), google (g), chatgpt (gpt), gemini (gem), semantic-scholar (s2), logically (log), bing (b)","","Flags:"," --synthesize For engine=all: synthesize fetched sources"," --synthesizer <engine> Synthesis engine (default from ~/.dm/greedyconfig)"," --fast Legacy quick mode: no source fetching or synthesis"," --depth <mode> Legacy: fast|standard|deep aliases, or research"," --deep-research Deprecated alias for --research"," --research Iterative query/learnings loop (alias: --depth research)"," --breadth <n> Research mode query breadth, 1-5 (default: 3)"," --iterations <n> Research mode rounds, 1-3 (default: 2)"," --max-sources <n> Research mode fetched source cap, 3-12"," --research-out-dir <dir> Write research bundle to a specific directory"," --no-research-bundle Disable the default .dm/greedysearch-research bundle"," --fetch-top-source Fetch content from top source"," --inline Output JSON to stdout (for piping)"," --locale <lang> Force results language (en, de, fr, etc.)"," --visible Always use visible Chrome for this search"," --always-visible Alias for --visible"," --stdin Read query from stdin (avoids command-line leakage)","","Environment:"," GREEDY_SEARCH_VISIBLE Set to 1 to show Chrome window (disables headless)"," GREEDY_SEARCH_ALWAYS_VISIBLE Set to 1 to force visible mode for all runs"," GREEDY_SEARCH_LOCALE Default locale (default: en)","","Examples:",' node search.mjs all "Node.js streams" # Grounded: engines + fetched sources',' node search.mjs all "Node.js streams" --synthesize # Add Gemini synthesis',' node search.mjs all "quick check" --fast # Legacy fast: no sources/synthesis',' node search.mjs all "browser automation" --research --breadth 3 --iterations 2',' node search.mjs p "what is memoization" # Single engine search'].join(`
371
371
  `)}
372
- `),process.exit(1);if($.includes("--visible")||$.includes("--always-visible")||process.env.GREEDY_SEARCH_ALWAYS_VISIBLE==="1")process.env.GREEDY_SEARCH_VISIBLE="1",process.env.GREEDY_SEARCH_ALWAYS_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS;else if(process.env.GREEDY_SEARCH_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await o0(),G$();let X=$.indexOf("--depth"),J=X!==-1&&$[X+1]?$[X+1].toLowerCase():null,W=$.find((U)=>!U.startsWith("--"))?.toLowerCase(),K=$.includes("--research")||$.includes("--deep-research")||J==="research",V=$.includes("--fast")||J==="fast",Y=J==="standard"||J==="deep"||$.includes("--deep"),j=W==="all"&&!V,Q=W==="all"&&!V&&($.includes("--synthesize")||Y),B=J==="deep"||$.includes("--deep");if($.includes("--deep-research"))process.stderr.write(`[greedysearch] --deep-research is deprecated; use --research or --depth research
372
+ `),process.exit(1);if($.includes("--visible")||$.includes("--always-visible")||process.env.GREEDY_SEARCH_ALWAYS_VISIBLE==="1")process.env.GREEDY_SEARCH_VISIBLE="1",process.env.GREEDY_SEARCH_ALWAYS_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS;else if(process.env.GREEDY_SEARCH_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await o0(),N$();let X=$.indexOf("--depth"),J=X!==-1&&$[X+1]?$[X+1].toLowerCase():null,W=$.find((U)=>!U.startsWith("--"))?.toLowerCase(),K=$.includes("--research")||$.includes("--deep-research")||J==="research",V=$.includes("--fast")||J==="fast",Y=J==="standard"||J==="deep"||$.includes("--deep"),j=W==="all"&&!V,Q=W==="all"&&!V&&($.includes("--synthesize")||Y),B=J==="deep"||$.includes("--deep");if($.includes("--deep-research"))process.stderr.write(`[greedysearch] --deep-research is deprecated; use --research or --depth research
373
373
  `);if(Y)process.stderr.write(`[greedysearch] depth fast|standard|deep is deprecated; use default grounded search plus --synthesize when needed
374
- `);let H=$.indexOf("--synthesizer"),G=e0(H===-1?v1:$[H+1]),z=!$.includes("--full"),D=$.includes("--fetch-top-source"),M=$.includes("--inline"),A=$.indexOf("--breadth"),b=$.indexOf("--iterations"),P=$.indexOf("--max-sources"),F=A===-1?void 0:$[A+1],x=b===-1?void 0:$[b+1],o=P===-1?void 0:$[P+1],C0=$.indexOf("--research-out-dir"),b$=C0===-1?void 0:$[C0+1],X$=!$.includes("--no-research-bundle"),z0=$.indexOf("--out"),B0=z0===-1?null:$[z0+1],H0=$.indexOf("--locale"),S=process.env.GREEDY_SEARCH_LOCALE,q$=g9(),a="en";if(H0!==-1&&$[H0+1])a=$[H0+1];else if(S)a=S;else if(q$.locale)a=q$.locale;let J$=$.filter((U,w)=>U!=="--full"&&U!=="--short"&&U!=="--fast"&&U!=="--fetch-top-source"&&U!=="--synthesize"&&U!=="--deep-research"&&U!=="--deep"&&U!=="--research"&&U!=="--inline"&&U!=="--stdin"&&U!=="--headless"&&U!=="--visible"&&U!=="--always-visible"&&U!=="--depth"&&U!=="--synthesizer"&&U!=="--out"&&U!=="--locale"&&U!=="--breadth"&&U!=="--iterations"&&U!=="--max-sources"&&U!=="--research-out-dir"&&U!=="--no-research-bundle"&&U!=="--help"&&(X===-1||w!==X+1)&&(H===-1||w!==H+1)&&(z0===-1||w!==z0+1)&&(H0===-1||w!==H0+1)&&(A===-1||w!==A+1)&&(b===-1||w!==b+1)&&(P===-1||w!==P+1)&&(C0===-1||w!==C0+1)),D0=J$[0]?.toLowerCase(),R0=$.includes("--stdin"),v;if(R0)v=await y9();else v=J$.slice(1).join(" ");if(K){if(D0!=="all")process.stderr.write(`[greedysearch] Research mode uses all engines; ignoring engine "${D0}".
375
- `);let U=await m2({query:w$(v),breadth:F,iterations:x,maxSources:o,locale:a,short:z,writeBundle:X$,researchOutDir:b$});g0(U,B0,{inline:M,synthesize:!0,query:v});return}if(D0==="all"){await q(["list"]);let U={perplexity:"https://www.perplexity.ai/",google:"https://www.google.com/","semantic-scholar":"https://www.semanticscholar.org/",semanticscholar:"https://www.semanticscholar.org/",s2:"https://www.semanticscholar.org/",logically:"https://logically.app/research-assistant/"},w=await Promise.all(e.map((T)=>j0(U[T])));await q(["list"]);let L=(T)=>{if(!V)return 70000;return T==="chatgpt"?60000:35000};try{let T=await Promise.allSettled(e.map((k,m)=>f0(Z0[k],w$(v),w[m],z,L(k),a).then((l)=>{return process.stderr.write(`PROGRESS:${k}:done
376
- `),{engine:k,...l}}).catch((l)=>{throw l}))),_={};for(let k=0;k<T.length;k++){let m=T[k];if(m.status==="fulfilled")_[m.value.engine]=m.value;else{let l=m.reason,g=l?.message||"unknown error";if(_[e[k]]={error:g},l?.lastStage)process.stderr.write(`[greedysearch] ${e[k]} failed at stage '${l.lastStage}': ${g}
374
+ `);let H=$.indexOf("--synthesizer"),O=e0(H===-1?b1:$[H+1]),D=!$.includes("--full"),z=$.includes("--fetch-top-source"),M=$.includes("--inline"),A=$.indexOf("--breadth"),b=$.indexOf("--iterations"),P=$.indexOf("--max-sources"),w=A===-1?void 0:$[A+1],f=b===-1?void 0:$[b+1],i=P===-1?void 0:$[P+1],C0=$.indexOf("--research-out-dir"),q$=C0===-1?void 0:$[C0+1],X$=!$.includes("--no-research-bundle"),D0=$.indexOf("--out"),H0=D0===-1?null:$[D0+1],M0=$.indexOf("--locale"),S=process.env.GREEDY_SEARCH_LOCALE,v$=f9(),o="en";if(M0!==-1&&$[M0+1])o=$[M0+1];else if(S)o=S;else if(v$.locale)o=v$.locale;let J$=$.filter((U,T)=>U!=="--full"&&U!=="--short"&&U!=="--fast"&&U!=="--fetch-top-source"&&U!=="--synthesize"&&U!=="--deep-research"&&U!=="--deep"&&U!=="--research"&&U!=="--inline"&&U!=="--stdin"&&U!=="--headless"&&U!=="--visible"&&U!=="--always-visible"&&U!=="--depth"&&U!=="--synthesizer"&&U!=="--out"&&U!=="--locale"&&U!=="--breadth"&&U!=="--iterations"&&U!=="--max-sources"&&U!=="--research-out-dir"&&U!=="--no-research-bundle"&&U!=="--help"&&(X===-1||T!==X+1)&&(H===-1||T!==H+1)&&(D0===-1||T!==D0+1)&&(M0===-1||T!==M0+1)&&(A===-1||T!==A+1)&&(b===-1||T!==b+1)&&(P===-1||T!==P+1)&&(C0===-1||T!==C0+1)),z0=J$[0]?.toLowerCase(),R0=$.includes("--stdin"),v;if(R0)v=await x9();else v=J$.slice(1).join(" ");if(K){if(z0!=="all")process.stderr.write(`[greedysearch] Research mode uses all engines; ignoring engine "${z0}".
375
+ `);let U=await h2({query:w$(v),breadth:w,iterations:f,maxSources:i,locale:o,short:D,writeBundle:X$,researchOutDir:q$});h0(U,H0,{inline:M,synthesize:!0,query:v});return}if(z0==="all"){await q(["list"]);let U={perplexity:"https://www.perplexity.ai/",google:"https://www.google.com/","semantic-scholar":"https://www.semanticscholar.org/",semanticscholar:"https://www.semanticscholar.org/",s2:"https://www.semanticscholar.org/",logically:"https://logically.app/research-assistant/"},T=await Promise.all(e.map((F)=>Q0(U[F])));await q(["list"]);let L=(F)=>{if(!V)return 70000;return F==="chatgpt"?60000:35000};try{let F=await Promise.allSettled(e.map((k,m)=>S0(X0[k],w$(v),T[m],D,L(k),o).then((l)=>{return process.stderr.write(`PROGRESS:${k}:done
376
+ `),{engine:k,...l}}).catch((l)=>{throw l}))),_={};for(let k=0;k<F.length;k++){let m=F[k];if(m.status==="fulfilled")_[m.value.engine]=m.value;else{let l=m.reason,g=l?.message||"unknown error";if(_[e[k]]={error:g},l?.lastStage)process.stderr.write(`[greedysearch] ${e[k]} failed at stage '${l.lastStage}': ${g}
377
377
  `);if(l?.partialErr)process.stderr.write(`[greedysearch] ${e[k]} tail stderr:
378
378
  ${l.partialErr}
379
- `)}}let E=T2(_);if(E.length>0&&process.env.GREEDY_SEARCH_VISIBLE!=="1"){Z$({scope:"all",phase:"start",engines:E,reasons:Object.fromEntries(E.map((g)=>[g,{error:_[g]?.error||null,envelope:_[g]?._envelope||null}]))}),process.stderr.write(`[greedysearch] \uD83D\uDD13 Headless ${E.join(", ")} search hit timeout/verification/antibot signals — retrying visible to establish cookies...
379
+ `)}}let E=F2(_);if(E.length>0&&process.env.GREEDY_SEARCH_VISIBLE!=="1"){Z$({scope:"all",phase:"start",engines:E,reasons:Object.fromEntries(E.map((g)=>[g,{error:_[g]?.error||null,envelope:_[g]?._envelope||null}]))}),process.stderr.write(`[greedysearch] \uD83D\uDD13 Headless ${E.join(", ")} search hit timeout/verification/antibot signals — retrying visible to establish cookies...
380
380
  `);for(let g of E)process.stderr.write(`[greedysearch] ${g} recovery starting in visible mode...
381
- `);await N$(w),await F0(),process.env.GREEDY_SEARCH_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS,await o0(),await q(["list"]);let k=[],m=!1,l=0;for(let g=0;g<E.length;g++){let d=await j0();k.push(d)}try{let g=await Promise.allSettled(E.map((R,t)=>f0(Z0[R],v,k[t],z,null,a).then((h)=>({engine:R,...h})).catch((h)=>({engine:R,error:h.message})))),d=[],W$=[];for(let R of g)if(R.status==="fulfilled"&&!R.value.error)_[R.value.engine]=R.value,l++,process.stderr.write(`PROGRESS:${R.value.engine}:done
382
- `);else if(R.status==="fulfilled"){if(_[R.value.engine]=R.value,d.push(R.value.engine),N1(R.value.error))W$.push(R.value.engine)}if(l>0)process.stderr.write(`[greedysearch] ✅ ${l}/${E.length} engine(s) recovered — cookies cached for future headless runs.
381
+ `);await D$(T),await F0(),process.env.GREEDY_SEARCH_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS,await o0(),await q(["list"]);let k=[],m=!1,l=0;for(let g=0;g<E.length;g++){let d=await Q0();k.push(d)}try{let g=await Promise.allSettled(E.map((R,s)=>S0(X0[R],v,k[s],D,null,o).then((h)=>({engine:R,...h})).catch((h)=>({engine:R,error:h.message})))),d=[],W$=[];for(let R of g)if(R.status==="fulfilled"&&!R.value.error)_[R.value.engine]=R.value,l++,process.stderr.write(`PROGRESS:${R.value.engine}:done
382
+ `);else if(R.status==="fulfilled"){if(_[R.value.engine]=R.value,d.push(R.value.engine),O1(R.value.error))W$.push(R.value.engine)}if(l>0)process.stderr.write(`[greedysearch] ✅ ${l}/${E.length} engine(s) recovered — cookies cached for future headless runs.
383
383
  `);else process.stderr.write(`[greedysearch] ⚠️ Recovery attempt did not extract an answer — ${E.join(", ")} may still need manual verification or a DOM fallback.
384
384
  `);if(d.length>0){process.stderr.write(`[greedysearch] Second visible retry for ${d.join(", ")} — Turnstile may have resolved on first attempt...
385
- `);let R=await Promise.allSettled(d.map((h)=>{let r=E.indexOf(h);return f0(Z0[h],v,k[r],z,null,a).then((I0)=>({engine:h,...I0})).catch((I0)=>({engine:h,error:I0.message}))})),t=[];for(let h of R)if(h.status==="fulfilled"&&!h.value.error)_[h.value.engine]=h.value,l++,process.stderr.write(`PROGRESS:${h.value.engine}:done
385
+ `);let R=await Promise.allSettled(d.map((h)=>{let t=E.indexOf(h);return S0(X0[h],v,k[t],D,null,o).then((I0)=>({engine:h,...I0})).catch((I0)=>({engine:h,error:I0.message}))})),s=[];for(let h of R)if(h.status==="fulfilled"&&!h.value.error)_[h.value.engine]=h.value,l++,process.stderr.write(`PROGRESS:${h.value.engine}:done
386
386
  `),process.stderr.write(`[greedysearch] ✅ ${h.value.engine} recovered on second visible retry.
387
- `);else t.push(h.value?.engine||"unknown");d.length=0,d.push(...t)}if(Z$({scope:"all",phase:d.length>0?"needs-human":"success",engines:E,results:Object.fromEntries(E.map((R)=>[R,{mode:_[R]?._envelope?.mode||null,durationMs:_[R]?._envelope?.durationMs||null,lastStage:_[R]?._envelope?.lastStage||null,error:_[R]?.error||null}]))}),d.length>0){for(let R of d)process.stderr.write(`PROGRESS:${R}:needs-human
387
+ `);else s.push(h.value?.engine||"unknown");d.length=0,d.push(...s)}if(Z$({scope:"all",phase:d.length>0?"needs-human":"success",engines:E,results:Object.fromEntries(E.map((R)=>[R,{mode:_[R]?._envelope?.mode||null,durationMs:_[R]?._envelope?.durationMs||null,lastStage:_[R]?._envelope?.lastStage||null,error:_[R]?.error||null}]))}),d.length>0){for(let R of d)process.stderr.write(`PROGRESS:${R}:needs-human
388
388
  `);m=!0,_._needsHumanVerification={engines:d,message:"Visible Chrome is open with the engine page loaded. Solve the Turnstile checkbox or other challenge in the visible window to store cookies. Cookies persist for future runs."},process.stderr.write(`[greedysearch] \uD83D\uDD13 ${d.join(", ")} still blocked — keeping visible Chrome open. Solve the challenge in the window to store cookies, then rerun.
389
- `)}}finally{if(m)F1().catch(()=>{});else await N$(k),process.stderr.write(`[greedysearch] Switching back to headless Chrome...
390
- `),await F0(),delete process.env.GREEDY_SEARCH_VISIBLE,process.env.GREEDY_SEARCH_HEADLESS="1",await o0(),await q(["list"])}w.length=0}for(let k of e){if(!_[k]?.error)continue;if(E.includes(k)){if(process.env.GREEDY_SEARCH_VISIBLE==="1")process.stderr.write(`PROGRESS:${k}:${N1(_[k].error)?"needs-human":"error"}
389
+ `)}}finally{if(m)k1().catch(()=>{});else await D$(k),process.stderr.write(`[greedysearch] Switching back to headless Chrome...
390
+ `),await F0(),delete process.env.GREEDY_SEARCH_VISIBLE,process.env.GREEDY_SEARCH_HEADLESS="1",await o0(),await q(["list"])}T.length=0}for(let k of e){if(!_[k]?.error)continue;if(E.includes(k)){if(process.env.GREEDY_SEARCH_VISIBLE==="1")process.stderr.write(`PROGRESS:${k}:${O1(_[k].error)?"needs-human":"error"}
391
391
  `);continue}process.stderr.write(`PROGRESS:${k}:error
392
- `)}if(_._sources=x0(_,v),j&&_._sources.length>0){process.stderr.write(`PROGRESS:source-fetch:start
393
- `);let k=await B1(_._sources,5,8000);_._sources=L$(_._sources,k),_._fetchedSources=M1(k),process.stderr.write(`PROGRESS:source-fetch:done
392
+ `)}if(_._sources=g0(_,v),j&&_._sources.length>0){process.stderr.write(`PROGRESS:source-fetch:start
393
+ `);let k=await Q1(_._sources,5,8000);_._sources=L$(_._sources,k),_._fetchedSources=H1(k),process.stderr.write(`PROGRESS:source-fetch:done
394
394
  `)}if(Q){process.stderr.write(`PROGRESS:synthesis:start
395
- `),process.stderr.write(`[greedysearch] Synthesizing results with ${G}...
396
- `);let k=null;try{k=await j0(b2(G));let m=await v2(v,_,{grounded:B,tabPrefix:k,visible:process.env.GREEDY_SEARCH_VISIBLE==="1",synthesizer:G});_._synthesis={...m,synthesized:!0},process.stderr.write(`PROGRESS:synthesis:done
395
+ `),process.stderr.write(`[greedysearch] Synthesizing results with ${O}...
396
+ `);let k=null;try{k=await Q0(I2(O));let m=await b2(v,_,{grounded:B,tabPrefix:k,visible:process.env.GREEDY_SEARCH_VISIBLE==="1",synthesizer:O});_._synthesis={...m,synthesized:!0},process.stderr.write(`PROGRESS:synthesis:done
397
397
  `)}catch(m){process.stderr.write(`[greedysearch] Synthesis failed: ${m.message}
398
- `),_._synthesis={error:m.message,synthesized:!1,synthesizedBy:G}}finally{if(k)await O0(k)}}if(D){let k=p9(_);if(k)_._topSource=await t0(k.canonicalUrl||k.url)}if(!V)_._confidence=E2(_);g0(_,B0,{inline:M,synthesize:Q,query:v});return}finally{await N$(w)}}let s=Z0[D0];if(!s)process.stderr.write(`Unknown engine: "${D0}"
399
- Available: ${Object.keys(Z0).join(", ")}
400
- `),process.exit(1);try{let U=await f0(s,w$(v),null,z,null,a);if(D&&U.sources?.length>0)U.topSource=await t0(U.sources[0].url);g0(U,B0,{inline:M,synthesize:!1,query:v})}catch(U){let w=s.includes("bing")?"bing":s.includes("perplexity")?"perplexity":s.includes("chatgpt")?"chatgpt":s.includes("semantic-scholar")?"semantic-scholar":s.includes("logically")?"logically":null;if(w&&process.env.GREEDY_SEARCH_VISIBLE!=="1"&&C2(U)){Z$({scope:"single",phase:"start",engines:[w],reasons:{[w]:{error:U.message||null,envelope:U.envelope||null,lastStage:U.lastStage||null}}}),process.stderr.write(`[greedysearch] \uD83D\uDD13 ${w} blocked in headless — retrying visible to establish cookies...
401
- `),await F0(),process.env.GREEDY_SEARCH_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS,await o0(),await q(["list"]);let T=await j0(),_=!1;try{let E=await f0(s,v,T,z,null,a);if(Z$({scope:"single",phase:"success",engines:[w],result:{engine:w,mode:E._envelope?.mode||null,durationMs:E._envelope?.durationMs||null,lastStage:E._envelope?.lastStage||null}}),D&&E.sources?.length>0)E.topSource=await t0(E.sources[0].url);g0(E,B0,{inline:M,synthesize:!1,query:v});return}catch(E){Z$({scope:"single",phase:"needs-human",engines:[w],result:{engine:w,error:E.message||String(E),envelope:E.envelope||null}}),_=!0,g0({query:v,error:E.message,_needsHumanVerification:{engines:[w],message:"Visible Chrome is open with the engine page loaded. Solve the Turnstile checkbox or other challenge to store cookies. Cookies persist for future runs."}},B0,{inline:M,synthesize:!1,query:v});return}finally{if(!_)await O0(T),await F0(),delete process.env.GREEDY_SEARCH_VISIBLE,process.env.GREEDY_SEARCH_HEADLESS="1";else F1().catch(()=>{})}}process.stderr.write(`Error: ${U.message}
402
- `),process.exit(1)}}function p9($){if(Array.isArray($._sources)&&$._sources.length>0)return $._sources[0];for(let Z of["perplexity","google","bing"]){let X=$[Z];if(X?.sources?.length>0)return X.sources[0]}return null}async function F1(){if(process.env.GREEDY_SEARCH_HEADLESS==="1")return;try{let $=await import("node:http"),X=(await new Promise((Y,j)=>{$.get("http://localhost:9222/json/version",(Q)=>{let B="";Q.on("data",(H)=>B+=H),Q.on("end",()=>Y(JSON.parse(B)))}).on("error",j)})).webSocketDebuggerUrl,J=globalThis.WebSocket;if(!J)return;let W=new J(X),K=0,V=new Map;W.onopen=()=>{let Y=++K;V.set(Y,{resolve:(j)=>{let B=(j.targetInfos||[]).find((G)=>G.type==="page");if(!B){W.close();return}let H=++K;V.set(H,{resolve:(G)=>{let O=G.windowId,z=++K;V.set(z,{resolve:()=>{},reject:()=>{}}),W.send(JSON.stringify({id:z,method:"Browser.setWindowBounds",params:{windowId:O,bounds:{windowState:"minimized"}}})),setTimeout(()=>W.close(),500)},reject:()=>W.close()}),W.send(JSON.stringify({id:H,method:"Browser.getWindowForTarget",params:{targetId:B.targetId}}))},reject:()=>W.close()}),W.send(JSON.stringify({id:Y,method:"Target.getTargets",params:{}}))},W.onmessage=(Y)=>{let j=JSON.parse(Y.data);if(j.id&&V.has(j.id)){let{resolve:Q,reject:B}=V.get(j.id);if(V.delete(j.id),j.error)B?.(j.error);else Q?.(j.result)}},setTimeout(()=>W.close(),3000)}catch{}}h9().finally(async()=>{G$(),F1().catch(()=>{})});
398
+ `),_._synthesis={error:m.message,synthesized:!1,synthesizedBy:O}}finally{if(k)await G0(k)}}if(z){let k=g9(_);if(k)_._topSource=await t0(k.canonicalUrl||k.url)}if(!V)_._confidence=R2(_);h0(_,H0,{inline:M,synthesize:Q,query:v});return}finally{await D$(T)}}let a=X0[z0];if(!a)process.stderr.write(`Unknown engine: "${z0}"
399
+ Available: ${Object.keys(X0).join(", ")}
400
+ `),process.exit(1);try{let U=await S0(a,w$(v),null,D,null,o);if(z&&U.sources?.length>0)U.topSource=await t0(U.sources[0].url);h0(U,H0,{inline:M,synthesize:!1,query:v})}catch(U){let T=a.includes("bing")?"bing":a.includes("perplexity")?"perplexity":a.includes("chatgpt")?"chatgpt":a.includes("semantic-scholar")?"semantic-scholar":a.includes("logically")?"logically":null;if(T&&process.env.GREEDY_SEARCH_VISIBLE!=="1"&&w2(U)){Z$({scope:"single",phase:"start",engines:[T],reasons:{[T]:{error:U.message||null,envelope:U.envelope||null,lastStage:U.lastStage||null}}}),process.stderr.write(`[greedysearch] \uD83D\uDD13 ${T} blocked in headless — retrying visible to establish cookies...
401
+ `),await F0(),process.env.GREEDY_SEARCH_VISIBLE="1",delete process.env.GREEDY_SEARCH_HEADLESS,await o0(),await q(["list"]);let F=await Q0(),_=!1;try{let E=await S0(a,v,F,D,null,o);if(Z$({scope:"single",phase:"success",engines:[T],result:{engine:T,mode:E._envelope?.mode||null,durationMs:E._envelope?.durationMs||null,lastStage:E._envelope?.lastStage||null}}),z&&E.sources?.length>0)E.topSource=await t0(E.sources[0].url);h0(E,H0,{inline:M,synthesize:!1,query:v});return}catch(E){Z$({scope:"single",phase:"needs-human",engines:[T],result:{engine:T,error:E.message||String(E),envelope:E.envelope||null}}),_=!0,h0({query:v,error:E.message,_needsHumanVerification:{engines:[T],message:"Visible Chrome is open with the engine page loaded. Solve the Turnstile checkbox or other challenge to store cookies. Cookies persist for future runs."}},H0,{inline:M,synthesize:!1,query:v});return}finally{if(!_)await G0(F),await F0(),delete process.env.GREEDY_SEARCH_VISIBLE,process.env.GREEDY_SEARCH_HEADLESS="1";else k1().catch(()=>{})}}process.stderr.write(`Error: ${U.message}
402
+ `),process.exit(1)}}function g9($){if(Array.isArray($._sources)&&$._sources.length>0)return $._sources[0];for(let Z of["perplexity","google","bing"]){let X=$[Z];if(X?.sources?.length>0)return X.sources[0]}return null}async function k1(){if(process.env.GREEDY_SEARCH_HEADLESS==="1")return;try{let $=await import("node:http"),X=(await new Promise((Y,j)=>{$.get("http://localhost:9222/json/version",(Q)=>{let B="";Q.on("data",(H)=>B+=H),Q.on("end",()=>Y(JSON.parse(B)))}).on("error",j)})).webSocketDebuggerUrl,J=globalThis.WebSocket;if(!J)return;let W=new J(X),K=0,V=new Map;W.onopen=()=>{let Y=++K;V.set(Y,{resolve:(j)=>{let B=(j.targetInfos||[]).find((O)=>O.type==="page");if(!B){W.close();return}let H=++K;V.set(H,{resolve:(O)=>{let G=O.windowId,D=++K;V.set(D,{resolve:()=>{},reject:()=>{}}),W.send(JSON.stringify({id:D,method:"Browser.setWindowBounds",params:{windowId:G,bounds:{windowState:"minimized"}}})),setTimeout(()=>W.close(),500)},reject:()=>W.close()}),W.send(JSON.stringify({id:H,method:"Browser.getWindowForTarget",params:{targetId:B.targetId}}))},reject:()=>W.close()}),W.send(JSON.stringify({id:Y,method:"Target.getTargets",params:{}}))},W.onmessage=(Y)=>{let j=JSON.parse(Y.data);if(j.id&&V.has(j.id)){let{resolve:Q,reject:B}=V.get(j.id);if(V.delete(j.id),j.error)B?.(j.error);else Q?.(j.result)}},setTimeout(()=>W.close(),3000)}catch{}}S9().finally(async()=>{N$(),k1().catch(()=>{})});