@duckmind/dm-darwin-x64 0.52.6 → 0.53.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +14 -10
  3. package/extensions/dm-cua/bin/browser-cua.mjs +6 -6
  4. package/extensions/dm-cua/index.js +5 -5
  5. package/extensions/dm-cua/src/browser-cua-lib.mjs +2 -2
  6. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +8 -1
  7. package/extensions/greedysearch-dm/bin/cdp-headless.mjs +1 -1
  8. package/extensions/greedysearch-dm/bin/cdp-visible.mjs +1 -1
  9. package/extensions/greedysearch-dm/bin/cdp.mjs +29 -20
  10. package/extensions/greedysearch-dm/bin/gschrome.mjs +1 -8
  11. package/extensions/greedysearch-dm/bin/kill-visible.mjs +1 -1
  12. package/extensions/greedysearch-dm/bin/launch-visible.mjs +1 -2
  13. package/extensions/greedysearch-dm/bin/launch.mjs +9 -11
  14. package/extensions/greedysearch-dm/bin/mcp.mjs +375 -0
  15. package/extensions/greedysearch-dm/bin/search.mjs +309 -157
  16. package/extensions/greedysearch-dm/bin/visible.mjs +1 -1
  17. package/extensions/greedysearch-dm/extractors/bing-copilot.mjs +205 -68
  18. package/extensions/greedysearch-dm/extractors/chatgpt.mjs +229 -140
  19. package/extensions/greedysearch-dm/extractors/common.mjs +160 -50
  20. package/extensions/greedysearch-dm/extractors/consensus.mjs +226 -93
  21. package/extensions/greedysearch-dm/extractors/consent.mjs +44 -17
  22. package/extensions/greedysearch-dm/extractors/gemini.mjs +277 -138
  23. package/extensions/greedysearch-dm/extractors/google-ai.mjs +172 -64
  24. package/extensions/greedysearch-dm/extractors/logically.mjs +183 -69
  25. package/extensions/greedysearch-dm/extractors/perplexity.mjs +331 -65
  26. package/extensions/greedysearch-dm/extractors/semantic-scholar.mjs +118 -41
  27. package/extensions/greedysearch-dm/index.js +23 -20
  28. package/extensions/greedysearch-dm/package.json +8 -3
  29. package/extensions/greedysearch-dm/skills/greedy-search/skill.md +8 -8
  30. package/extensions/greedysearch-dm/src/fetcher.mjs +2 -2
  31. package/extensions/greedysearch-dm/src/formatters/results.js +8 -6
  32. package/extensions/greedysearch-dm/src/github.mjs +7 -7
  33. package/extensions/greedysearch-dm/src/reddit.mjs +1 -1
  34. package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +10 -8
  35. package/extensions/greedysearch-dm/src/search/challenge-detect.mjs +48 -0
  36. package/extensions/greedysearch-dm/src/search/chrome.mjs +130 -54
  37. package/extensions/greedysearch-dm/src/search/constants.mjs +6 -6
  38. package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
  39. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +160 -83
  40. package/extensions/greedysearch-dm/src/search/minimize.mjs +1 -0
  41. package/extensions/greedysearch-dm/src/search/paths.mjs +1 -1
  42. package/extensions/greedysearch-dm/src/search/pdf.mjs +1 -1
  43. package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -1
  44. package/extensions/greedysearch-dm/src/search/progress.mjs +2 -0
  45. package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
  46. package/extensions/greedysearch-dm/src/search/research.mjs +262 -167
  47. package/extensions/greedysearch-dm/src/search/scale-aware.mjs +11 -0
  48. package/extensions/greedysearch-dm/src/search/simple-research.mjs +827 -0
  49. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +9 -9
  50. package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
  51. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +23 -20
  52. package/extensions/greedysearch-dm/src/tools/shared.js +10 -9
  53. package/extensions/greedysearch-dm/src/utils/node-runtime.mjs +1 -1
  54. package/package.json +1 -1
  55. package/extensions/greedysearch-dm/src/search/cdp-endpoint.mjs +0 -3
  56. package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +0 -3
  57. package/extensions/greedysearch-dm/src/search/partial-output.mjs +0 -1
  58. package/extensions/greedysearch-dm/src/utils/browser-executable.mjs +0 -1
@@ -1,12 +1,12 @@
1
- import{spawn as _e}from"node:child_process";import{basename as B}from"node:path";function W(t=process.env,e=process.execPath){let i=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(i?.trim())return i.trim();let n=B(e||"").toLowerCase();if(n==="node"||n==="node.exe")return e;return"node"}import{existsSync as O,mkdirSync as V,readFileSync as H,writeFileSync as F}from"node:fs";import{homedir as z}from"node:os";import{join as G}from"node:path";import{tmpdir as j}from"node:os";function ee(t,e=9222){let i=Number.parseInt(String(t??""),10);return Number.isInteger(i)&&i>1024&&i<65535?i:e}var we=ee(process.env.GREEDY_SEARCH_PORT,9222),T=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${j().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),Le=`${T}/DevToolsActivePort`,Ue=`${j().replaceAll("\\","/")}/cdp-pages.json`,Ie=process.env.GREEDY_SEARCH_MODE_FILE||`${j().replaceAll("\\","/")}/greedysearch-chrome-mode`,We=`${j().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,y=G(z(),".dm"),E=G(y,"greedyconfig"),w=["perplexity","google","chatgpt"],L="gemini";function ie(){try{if(O(E)){let t=H(E,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((i)=>typeof i==="string")){let i=e.engines.filter((o)=>$[o]),n=e.engines.filter((o)=>!$[o]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${E}: ${n.join(", ")}
2
- [greedysearch] Available engines: ${Object.keys($).join(", ")}
3
- `);if(i.length>0)return i;process.stderr.write(`[greedysearch] Warning: no valid engines in ${E}, falling back to defaults: ${w.join(", ")}
4
- `)}}}catch{}return w}function te(){try{if(!O(y))V(y,{recursive:!0});if(!O(E))F(E,JSON.stringify({engines:w,synthesizer:L},null,2)+`
5
- `,"utf8")}catch{}}te();var R=["gemini","chatgpt"];function ne(){try{if(O(E)){let t=H(E,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let i=e.synthesizer.toLowerCase();if(R.includes(i))return i;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${E}
1
+ import{spawn as Ce}from"node:child_process";import{basename as X}from"node:path";function Y(t=process.env,e=process.execPath){let i=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(i?.trim())return i.trim();let s=X(e||"").toLowerCase();if(s==="node"||s==="node.exe")return e;return"node"}import{existsSync as T,mkdirSync as V,readFileSync as G,writeFileSync as B}from"node:fs";import{homedir as F}from"node:os";import{join as H}from"node:path";import{tmpdir as z}from"node:os";function ee(t,e=9222){let i=Number.parseInt(String(t??""),10);return Number.isInteger(i)&&i>1024&&i<65535?i:e}var ie=z().replaceAll("\\","/"),Ne=ee(process.env.GREEDY_SEARCH_PORT),h=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${ie}/greedysearch-chrome-profile`).replaceAll("\\","/"),Ae=`${h}/DevToolsActivePort`,Ye=process.env.GREEDY_SEARCH_PID_FILE||`${h}/browser.pid`,Ge=process.env.CDP_PAGES_CACHE||`${h}/cdp-pages.json`,He=process.env.GREEDY_SEARCH_MODE_FILE||`${h}/browser-mode`,Ue=process.env.GREEDY_SEARCH_METADATA_FILE||`${h}/browser-metadata.json`,ye=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${h}/browser-launch.lock`,Se=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${h}/browser-last-activity`,ke=(process.env.CDP_SOCKET_DIR||`${h}/cdp-sockets`).replaceAll("\\","/"),Pe=`${h}/visible-recovery.jsonl`,w=H(F(),".dm"),d=H(w,"greedyconfig"),b=["perplexity","google","chatgpt","gemini"],$="gemini";function te(){try{if(T(d)){let t=G(d,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((i)=>typeof i==="string")){let i=e.engines.filter((o)=>j[o]),s=e.engines.filter((o)=>!j[o]);if(s.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${d}: ${s.join(", ")}
2
+ [greedysearch] Available engines: ${Object.keys(j).join(", ")}
3
+ `);if(i.length>0)return i;process.stderr.write(`[greedysearch] Warning: no valid engines in ${d}, falling back to defaults: ${b.join(", ")}
4
+ `)}}}catch{}return b}function ne(){try{if(!T(w))V(w,{recursive:!0});if(!T(d))B(d,JSON.stringify({engines:b,synthesizer:$},null,2)+`
5
+ `,"utf8")}catch{}}ne();var R=["gemini","chatgpt"];function se(){try{if(T(d)){let t=G(d,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let i=e.synthesizer.toLowerCase();if(R.includes(i))return i;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${d}
6
6
  [greedysearch] Available synthesizers: ${R.join(", ")}
7
- [greedysearch] Falling back to default: ${L}
8
- `)}}}catch{}return L}var $={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"},se=ie();var He=ne(),Ge=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=T;var oe=["fbclid","gclid","ref","ref_src","ref_url","source","utm_campaign","utm_content","utm_medium","utm_source","utm_term"],le=["dev.to","hashnode.com","medium.com","reddit.com","stackoverflow.com","stackexchange.com","substack.com"],ce=["arstechnica.com","techcrunch.com","theverge.com","venturebeat.com","wired.com","zdnet.com"],k=["facebook.com","instagram.com","linkedin.com","pinterest.com","tiktok.com","twitter.com","x.com"];function v(t="",e=240){let i=String(t).replaceAll(/\s+/g," ").trim();if(i.length<=e)return i;let n=i.slice(0,e),o=n.lastIndexOf(" ");return o>0?`${n.slice(0,o)}...`:`${n}...`}function U(t=""){let e=v(t,180);if(!e)return"";if(/^https?:\/\//i.test(e))return"";let i=e.split(/\s+/).filter(Boolean).length,n=/[A-Z]/.test(e),o=/\d/.test(e);return e===e.toLowerCase()&&i<=4&&!n&&!o?"":e}function A(t="",e=""){let i=U(t),n=U(e);if(!n)return i;if(!i)return n;let o=/^https?:\/\//i.test(i),r=/^https?:\/\//i.test(n);if(o&&!r)return n;if(!o&&r)return i;return n.length>i.length?n:i}function re(t){if(!t)return null;try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))return null;if(e.hash="",e.hostname=e.hostname.toLowerCase(),e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")e.port="";for(let o of[...e.searchParams.keys()]){let r=o.toLowerCase();if(oe.includes(r)||r.startsWith("utm_"))e.searchParams.delete(o)}e.searchParams.sort();let i=e.pathname.replace(/\/{1,10}$/,"")||"/";e.pathname=i;let n=e.toString();return i==="/"?n.replace(/\/$/,""):n}catch{return null}}function ae(t){try{return new URL(t).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function C(t,e){return e.some((i)=>t===i||t.endsWith(`.${i}`))}function fe(t,e="",i=""){let n=e.toLowerCase(),o=i.toLowerCase();if(t==="github.com"||t==="gitlab.com")return"repo";if(t==="arxiv.org"||t==="doi.org"||t==="semanticscholar.org"||t.endsWith(".semanticscholar.org")||o.includes("/paper/")||o.includes("/pdf/"))return"academic";if(C(t,k))return"social";if(C(t,le))return"community";if(C(t,ce))return"news";if(t.startsWith("docs.")||t.startsWith("developer.")||t.startsWith("developers.")||t.startsWith("api.")||n.includes("documentation")||n.includes("docs")||n.includes("reference")||o.includes("/docs/")||o.includes("/reference/")||o.includes("/api/"))return"official-docs";if(t.startsWith("blog.")||o.includes("/blog/"))return"maintainer-blog";return"website"}function ge(t){switch(t){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 pe(t){let e=Object.values(t.perEngine||{}).map((i)=>i?.rank||99);return e.length?Math.min(...e):99}var ue=["reddit.com","news.ycombinator.com","lobste.rs"];function N(t){return t.smartScore*3+t.engineCount*5+ge(t.sourceType)*2+Math.max(0,7-pe(t))}function me(t){let e=t.toLowerCase(),i=[];if(e.includes("openai")||e.includes("gpt")||e.includes("chatgpt"))i.push("openai.com","platform.openai.com","help.openai.com");if(e.includes("anthropic")||e.includes("claude"))i.push("anthropic.com","docs.anthropic.com");if(e.includes("bun"))i.push("bun.sh","bun.com");if(e.includes("next.js")||e.includes("nextjs"))i.push("nextjs.org","vercel.com");if(e.includes("playwright"))i.push("playwright.dev");if(e.includes("supabase"))i.push("supabase.com","supabase.io");if(e.includes("prisma"))i.push("prisma.io");if(e.includes("tailwind"))i.push("tailwindcss.com");if(e.includes("vite"))i.push("vitejs.dev","vite.dev");if(e.includes("astro"))i.push("astro.build");if(e.includes("svelte"))i.push("svelte.dev");if(e.includes("solid"))i.push("solidjs.com");if(e.includes("vue")||e.includes("nuxt"))i.push("vuejs.org","nuxt.com");if(e.includes("react")||e.includes("react native"))i.push("react.dev","reactnative.dev");if(e.includes("angular"))i.push("angular.io","angular.dev");if(e.includes("node.js")||e.includes("nodejs"))i.push("nodejs.org","nodejs.dev","npmjs.com");if(/\bgo\b/.test(e)||e.includes("golang"))i.push("go.dev","golang.org","pkg.go.dev");if(e.includes("deno"))i.push("deno.land","deno.com");if(e.includes("fresh"))i.push("fresh.deno.dev");if(e.includes("typescript")||e.includes("ts"))i.push("typescriptlang.org");if(e.includes("python"))i.push("python.org","docs.python.org");if(e.includes("rust"))i.push("rust-lang.org","docs.rs","crates.io");if(e.includes("zig"))i.push("ziglang.org");if(e.includes("docker"))i.push("docker.com","docs.docker.com","hub.docker.com");if(e.includes("kubernetes")||e.includes("k8s"))i.push("kubernetes.io","k8s.io");if(e.includes("postgres")||e.includes("postgresql"))i.push("postgresql.org","neon.tech","supabase.com");if(e.includes("redis"))i.push("redis.io");if(e.includes("sqlite"))i.push("sqlite.org");if(e.includes("cloudflare"))i.push("developers.cloudflare.com","cloudflare.com");if(e.includes("vercel"))i.push("vercel.com","nextjs.org");if(e.includes("netlify"))i.push("netlify.com","docs.netlify.com");if(e.includes("stripe"))i.push("stripe.com","docs.stripe.com");if(e.includes("github"))i.push("github.com","docs.github.com");if(e.includes("gitlab"))i.push("gitlab.com","docs.gitlab.com");if(e.includes("aws"))i.push("aws.amazon.com","docs.aws.amazon.com");if(e.includes("azure"))i.push("azure.microsoft.com","learn.microsoft.com");if(e.includes("gcp")||e.includes("google cloud"))i.push("cloud.google.com","developers.google.com");if(e.includes("gemini")||e.includes("google ai"))i.push("ai.google.dev","developers.google.com");for(let n of k){let o=n.replace(/\.com$/,"");if(e.includes(o))i.push(n)}return[...new Set(i)]}function Y(t,e){return t===e||t.endsWith(`.${e}`)}function M(t,e=""){let i=new Map,n=Object.keys(t||{}).filter((s)=>!s.startsWith("_")),o=me(e);for(let s of n){let c=t[s];if(!c?.sources)continue;for(let a=0;a<c.sources.length;a++){let h=c.sources[a],g=re(h.url);if(!g||g.length<10)continue;let _=U(h.title||""),u=ae(g),d=fe(u,_,g),m=0;if(o.some((D)=>Y(u,D)))m+=10;if(d==="official-docs")m+=3;let q=g.toLowerCase();if(/\/docs\/|\/documentation\/|\.dev\/|\/api\/|\/reference\//.test(q))m+=2;let Q=o.some((D)=>Y(u,D));if(d==="social"&&!Q)m-=20;if(o.length>0){if(C(u,ue))m-=3;else if(d==="community"&&!C(u,["stackoverflow.com","stackexchange.com"]))m-=1}let p=i.get(g)||{id:"",canonicalUrl:g,displayUrl:h.url||g,domain:u,title:"",engines:[],engineCount:0,perEngine:{},sourceType:d,isOfficial:d==="official-docs",smartScore:0};if(p.title=A(p.title,_),p.displayUrl=p.displayUrl||h.url||g,p.sourceType=p.sourceType||d,p.isOfficial=p.isOfficial||d==="official-docs",p.smartScore=Math.max(p.smartScore,m),!p.engines.includes(s))p.engines.push(s);p.perEngine[s]={rank:a+1,title:A(p.perEngine[s]?.title||"",_)},i.set(g,p)}}let r=Array.from(i.values()).map((s)=>({...s,engineCount:s.engines.length})),f=r.filter((s)=>s.sourceType!=="social"),l=r.filter((s)=>s.sourceType==="social");return f.sort((s,c)=>{let a=N(c)-N(s);if(a!==0)return a;return s.domain.localeCompare(c.domain)}),l.sort((s,c)=>{let a=N(c)-N(s);if(a!==0)return a;return s.domain.localeCompare(c.domain)}),[...f,...l].slice(0,12).map((s,c)=>({...s,id:`S${c+1}`,title:s.title||s.domain||s.canonicalUrl}))}function he(t){let e="",i=!1,n=!1;for(let o of String(t)){if(n){e+=o,n=!1;continue}if(o==="\\"){e+=o,n=!0;continue}if(o==='"'){i=!i,e+=o;continue}if(i&&o===`
9
- `)e+="\\n";else if(i&&o==="\r")e+="\\r";else if(i&&o==="\t")e+="\\t";else e+=o}return e}function S(t){if(!t)return null;let e=String(t).trim(),i=e.indexOf("BEGIN_JSON"),n=e.indexOf("END_JSON");if(i!==-1&&n!==-1&&i<n)e=e.slice(i+10,n).trim();else{let l=e.indexOf("{");if(l>0)e=e.slice(l)}let o=[e,e.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],r=e.indexOf("{"),f=e.lastIndexOf("}");if(r!==-1&&f!==-1&&r<f)o.push(e.slice(r,f+1));for(let l of[...o]){let s=he(l);if(s!==l)o.push(s)}for(let l of o)try{return JSON.parse(l)}catch{}return null}function J(t,e,i=""){let n=new Set(e.map((s)=>s.id)),o=["high","medium","low","mixed","conflicting"].includes(t?.agreement?.level)?t.agreement.level:"mixed",r=Array.isArray(t?.claims)?t.claims.map((s)=>({claim:v(s?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(s?.support)?s.support:"moderate",sourceIds:Array.isArray(s?.sourceIds)?s.sourceIds.filter((c)=>n.has(c)):[]})).filter((s)=>s.claim):[],f=Array.isArray(t?.recommendedSources)?t.recommendedSources.filter((s)=>n.has(s)).slice(0,6):[],l="";if(i){let s=i.indexOf("{"),c=i.lastIndexOf("}");if(s!==-1&&c!==-1&&s<c)l=i.slice(s,c+1);else l=i}return{answer:v(t?.answer||l||i,4000),agreement:{level:o,summary:v(t?.agreement?.summary||"",280)},differences:Array.isArray(t?.differences)?t.differences.map((s)=>v(s,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray(t?.caveats)?t.caveats.map((s)=>v(s,220)).filter(Boolean).slice(0,5):[],claims:r,recommendedSources:f}}function P(t,e,i,{grounded:n=!1}={}){let o={};for(let l of["perplexity","bing","google"]){let s=e[l];if(!s)continue;if(s.error){o[l]={status:"error",error:String(s.error)};continue}o[l]={status:"ok",answer:v(s.answer||"",n?4500:2200),sourceIds:i.filter((c)=>c.engines.includes(l)).sort((c,a)=>(c.perEngine[l]?.rank||99)-(a.perEngine[l]?.rank||99)).map((c)=>c.id).slice(0,6)}}let r=n?700:300,f=i.slice(0,n?10:8).map((l)=>({id:l.id,title:l.title,domain:l.domain,canonicalUrl:l.canonicalUrl,sourceType:l.sourceType,isOfficial:l.isOfficial,engines:l.engines,engineCount:l.engineCount,fetch:l.fetch?.attempted?{ok:l.fetch.ok,publishedTime:l.fetch.publishedTime||"",byline:l.fetch.byline||"",snippet:v(l.fetch.snippet||"",r)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${t}`,"",`Engine summaries:
7
+ [greedysearch] Falling back to default: ${$}
8
+ `)}}}catch{}return $}var j={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"},oe=te();var We=se(),Me=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=h;import{existsSync as U}from"node:fs";import{dirname as le,join as O}from"node:path";import{fileURLToPath as re}from"node:url";function y(t){return re(new URL(".",t)).replace(/^\/([A-Z]:)/,"$1")}function ce(t,e=U){let i=new Set;for(let s of t.filter(Boolean)){if(i.has(s))continue;if(i.add(s),e(s))return s}return t.filter(Boolean).at(-1)}function S(t,{moduleDir:e,entrypoint:i=process.argv[1],env:s=process.env,exists:o=U}={}){let c=i?le(i):null,f=s.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return ce([e?O(e,"..","..","extractors",t):null,e?O(e,"..","extractors",t):null,f?O(f,"extractors",t):null,c?O(c,"..","extractors",t):null],o)}var ae=["fbclid","gclid","ref","ref_src","ref_url","source","utm_campaign","utm_content","utm_medium","utm_source","utm_term"],fe=["dev.to","hashnode.com","medium.com","reddit.com","stackoverflow.com","stackexchange.com","substack.com"],pe=["arstechnica.com","techcrunch.com","theverge.com","venturebeat.com","wired.com","zdnet.com"],W=["facebook.com","instagram.com","linkedin.com","pinterest.com","tiktok.com","twitter.com","x.com"];function v(t="",e=240){let i=String(t).replaceAll(/\s+/g," ").trim();if(i.length<=e)return i;let s=i.slice(0,e),o=s.lastIndexOf(" ");return o>0?`${s.slice(0,o)}...`:`${s}...`}function N(t=""){let e=v(t,180);if(!e)return"";if(/^https?:\/\//i.test(e))return"";let i=e.split(/\s+/).filter(Boolean).length,s=/[A-Z]/.test(e),o=/\d/.test(e);return e===e.toLowerCase()&&i<=4&&!s&&!o?"":e}function k(t="",e=""){let i=N(t),s=N(e);if(!s)return i;if(!i)return s;let o=/^https?:\/\//i.test(i),c=/^https?:\/\//i.test(s);if(o&&!c)return s;if(!o&&c)return i;return s.length>i.length?s:i}function ge(t){if(!t)return null;try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))return null;if(e.hash="",e.hostname=e.hostname.toLowerCase(),e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")e.port="";for(let o of[...e.searchParams.keys()]){let c=o.toLowerCase();if(ae.includes(c)||c.startsWith("utm_"))e.searchParams.delete(o)}e.searchParams.sort();let i=e.pathname.replace(/\/{1,10}$/,"")||"/";e.pathname=i;let s=e.toString();return i==="/"?s.replace(/\/$/,""):s}catch{return null}}function ue(t){try{return new URL(t).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function D(t,e){return e.some((i)=>t===i||t.endsWith(`.${i}`))}function me(t,e="",i=""){let s=e.toLowerCase(),o=i.toLowerCase();if(t==="github.com"||t==="gitlab.com")return"repo";if(t==="arxiv.org"||t==="doi.org"||t==="semanticscholar.org"||t.endsWith(".semanticscholar.org")||o.includes("/paper/")||o.includes("/pdf/"))return"academic";if(D(t,W))return"social";if(D(t,fe))return"community";if(D(t,pe))return"news";if(t.startsWith("docs.")||t.startsWith("developer.")||t.startsWith("developers.")||t.startsWith("api.")||s.includes("documentation")||s.includes("docs")||s.includes("reference")||o.includes("/docs/")||o.includes("/reference/")||o.includes("/api/"))return"official-docs";if(t.startsWith("blog.")||o.includes("/blog/"))return"maintainer-blog";return"website"}function he(t){switch(t){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 Ee(t){let e=Object.values(t.perEngine||{}).map((i)=>i?.rank||99);return e.length?Math.min(...e):99}var _e=["reddit.com","news.ycombinator.com","lobste.rs"];function I(t){return t.smartScore*3+t.engineCount*5+he(t.sourceType)*2+Math.max(0,7-Ee(t))}function de(t){let e=t.toLowerCase(),i=[];if(e.includes("openai")||e.includes("gpt")||e.includes("chatgpt"))i.push("openai.com","platform.openai.com","help.openai.com");if(e.includes("anthropic")||e.includes("claude"))i.push("anthropic.com","docs.anthropic.com");if(e.includes("bun"))i.push("bun.sh","bun.com");if(e.includes("next.js")||e.includes("nextjs"))i.push("nextjs.org","vercel.com");if(e.includes("playwright"))i.push("playwright.dev");if(e.includes("supabase"))i.push("supabase.com","supabase.io");if(e.includes("prisma"))i.push("prisma.io");if(e.includes("tailwind"))i.push("tailwindcss.com");if(e.includes("vite"))i.push("vitejs.dev","vite.dev");if(e.includes("astro"))i.push("astro.build");if(e.includes("svelte"))i.push("svelte.dev");if(e.includes("solid"))i.push("solidjs.com");if(e.includes("vue")||e.includes("nuxt"))i.push("vuejs.org","nuxt.com");if(e.includes("react")||e.includes("react native"))i.push("react.dev","reactnative.dev");if(e.includes("angular"))i.push("angular.io","angular.dev");if(e.includes("node.js")||e.includes("nodejs"))i.push("nodejs.org","nodejs.dev","npmjs.com");if(/\bgo\b/.test(e)||e.includes("golang"))i.push("go.dev","golang.org","pkg.go.dev");if(e.includes("deno"))i.push("deno.land","deno.com");if(e.includes("fresh"))i.push("fresh.deno.dev");if(e.includes("typescript")||e.includes("ts"))i.push("typescriptlang.org");if(e.includes("python"))i.push("python.org","docs.python.org");if(e.includes("rust"))i.push("rust-lang.org","docs.rs","crates.io");if(e.includes("zig"))i.push("ziglang.org");if(e.includes("docker"))i.push("docker.com","docs.docker.com","hub.docker.com");if(e.includes("kubernetes")||e.includes("k8s"))i.push("kubernetes.io","k8s.io");if(e.includes("postgres")||e.includes("postgresql"))i.push("postgresql.org","neon.tech","supabase.com");if(e.includes("redis"))i.push("redis.io");if(e.includes("sqlite"))i.push("sqlite.org");if(e.includes("cloudflare"))i.push("developers.cloudflare.com","cloudflare.com");if(e.includes("vercel"))i.push("vercel.com","nextjs.org");if(e.includes("netlify"))i.push("netlify.com","docs.netlify.com");if(e.includes("stripe"))i.push("stripe.com","docs.stripe.com");if(e.includes("github"))i.push("github.com","docs.github.com");if(e.includes("gitlab"))i.push("gitlab.com","docs.gitlab.com");if(e.includes("aws"))i.push("aws.amazon.com","docs.aws.amazon.com");if(e.includes("azure"))i.push("azure.microsoft.com","learn.microsoft.com");if(e.includes("gcp")||e.includes("google cloud"))i.push("cloud.google.com","developers.google.com");if(e.includes("gemini")||e.includes("google ai"))i.push("ai.google.dev","developers.google.com");for(let s of W){let o=s.replace(/\.com$/,"");if(e.includes(o))i.push(s)}return[...new Set(i)]}function P(t,e){return t===e||t.endsWith(`.${e}`)}function M(t,e=""){let i=new Map,s=Object.keys(t||{}).filter((n)=>!n.startsWith("_")),o=de(e);for(let n of s){let r=t[n];if(!r?.sources)continue;for(let a=0;a<r.sources.length;a++){let E=r.sources[a],p=ge(E.url);if(!p||p.length<10)continue;let C=N(E.title||""),u=ue(p),_=me(u,C,p),m=0;if(o.some((L)=>P(u,L)))m+=10;if(_==="official-docs")m+=3;let Q=p.toLowerCase();if(/\/docs\/|\/documentation\/|\.dev\/|\/api\/|\/reference\//.test(Q))m+=2;let q=o.some((L)=>P(u,L));if(_==="social"&&!q)m-=20;if(o.length>0){if(D(u,_e))m-=3;else if(_==="community"&&!D(u,["stackoverflow.com","stackexchange.com"]))m-=1}let g=i.get(p)||{id:"",canonicalUrl:p,displayUrl:E.url||p,domain:u,title:"",engines:[],engineCount:0,perEngine:{},sourceType:_,isOfficial:_==="official-docs",smartScore:0};if(g.title=k(g.title,C),g.displayUrl=g.displayUrl||E.url||p,g.sourceType=g.sourceType||_,g.isOfficial=g.isOfficial||_==="official-docs",g.smartScore=Math.max(g.smartScore,m),!g.engines.includes(n))g.engines.push(n);g.perEngine[n]={rank:a+1,title:k(g.perEngine[n]?.title||"",C)},i.set(p,g)}}let c=Array.from(i.values()).map((n)=>({...n,engineCount:n.engines.length})),f=c.filter((n)=>n.sourceType!=="social"),l=c.filter((n)=>n.sourceType==="social");return f.sort((n,r)=>{let a=I(r)-I(n);if(a!==0)return a;return n.domain.localeCompare(r.domain)}),l.sort((n,r)=>{let a=I(r)-I(n);if(a!==0)return a;return n.domain.localeCompare(r.domain)}),[...f,...l].slice(0,12).map((n,r)=>({...n,id:`S${r+1}`,title:n.title||n.domain||n.canonicalUrl}))}function ve(t){let e="",i=!1,s=!1;for(let o of String(t)){if(s){e+=o,s=!1;continue}if(o==="\\"){e+=o,s=!0;continue}if(o==='"'){i=!i,e+=o;continue}if(i&&o===`
9
+ `)e+="\\n";else if(i&&o==="\r")e+="\\r";else if(i&&o==="\t")e+="\\t";else e+=o}return e}function J(t){if(!t)return null;let e=String(t).trim(),i=e.indexOf("BEGIN_JSON"),s=e.indexOf("END_JSON");if(i!==-1&&s!==-1&&i<s)e=e.slice(i+10,s).trim();else{let l=e.indexOf("{");if(l>0)e=e.slice(l)}let o=[e,e.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],c=e.indexOf("{"),f=e.lastIndexOf("}");if(c!==-1&&f!==-1&&c<f)o.push(e.slice(c,f+1));for(let l of[...o]){let n=ve(l);if(n!==l)o.push(n)}for(let l of o)try{return JSON.parse(l)}catch{}return null}function Z(t,e,i=""){let s=new Set(e.map((n)=>n.id)),o=["high","medium","low","mixed","conflicting"].includes(t?.agreement?.level)?t.agreement.level:"mixed",c=Array.isArray(t?.claims)?t.claims.map((n)=>({claim:v(n?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(n?.support)?n.support:"moderate",sourceIds:Array.isArray(n?.sourceIds)?n.sourceIds.filter((r)=>s.has(r)):[]})).filter((n)=>n.claim):[],f=Array.isArray(t?.recommendedSources)?t.recommendedSources.filter((n)=>s.has(n)).slice(0,6):[],l="";if(i){let n=i.indexOf("{"),r=i.lastIndexOf("}");if(n!==-1&&r!==-1&&n<r)l=i.slice(n,r+1);else l=i}return{answer:v(t?.answer||l||i,4000),agreement:{level:o,summary:v(t?.agreement?.summary||"",280)},differences:Array.isArray(t?.differences)?t.differences.map((n)=>v(n,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray(t?.caveats)?t.caveats.map((n)=>v(n,220)).filter(Boolean).slice(0,5):[],claims:c,recommendedSources:f}}function x(t,e,i,{grounded:s=!1}={}){let o={};for(let l of["perplexity","bing","google"]){let n=e[l];if(!n)continue;if(n.error){o[l]={status:"error",error:String(n.error)};continue}o[l]={status:"ok",answer:v(n.answer||"",s?4500:2200),sourceIds:i.filter((r)=>r.engines.includes(l)).sort((r,a)=>(r.perEngine[l]?.rank||99)-(a.perEngine[l]?.rank||99)).map((r)=>r.id).slice(0,6)}}let c=s?700:300,f=i.slice(0,s?10:8).map((l)=>({id:l.id,title:l.title,domain:l.domain,canonicalUrl:l.canonicalUrl,sourceType:l.sourceType,isOfficial:l.isOfficial,engines:l.engines,engineCount:l.engineCount,fetch:l.fetch?.attempted?{ok:l.fetch.ok,publishedTime:l.fetch.publishedTime||"",byline:l.fetch.byline||"",snippet:v(l.fetch.snippet||"",c)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${t}`,"",`Engine summaries:
10
10
  ${JSON.stringify(o,null,2)}`,"",`Source registry:
11
11
  ${JSON.stringify(f,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(`
12
- `)}import{existsSync as Z}from"node:fs";import{dirname as de,join as b}from"node:path";import{fileURLToPath as Ee}from"node:url";function x(t){return Ee(new URL(".",t)).replace(/^\/([A-Z]:)/,"$1")}function ve(t,e=Z){let i=new Set;for(let n of t.filter(Boolean)){if(i.has(n))continue;if(i.add(n),e(n))return n}return t.filter(Boolean).at(-1)}function K(t,{moduleDir:e,entrypoint:i=process.argv[1],env:n=process.env,exists:o=Z}={}){let r=i?de(i):null,f=n.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null,l=[e?b(e,"..","..","extractors",t):null,e?b(e,"..","extractors",t):null,f?b(f,"extractors",t):null,r?b(r,"..","extractors",t):null];return ve(l,o)}var Re=x(import.meta.url),Ce={gemini:"gemini.mjs",chatgpt:"chatgpt.mjs"},Oe={gemini:"https://gemini.google.com/app",chatgpt:"https://chatgpt.com/"};function I(t="gemini"){let e=String(t||"gemini").toLowerCase();if(e==="gem")return"gemini";if(e==="gpt")return"chatgpt";return e}function Fe(t="gemini"){return Oe[I(t)]||"about:blank"}async function X(t,e,{tabPrefix:i=null,timeoutMs:n=180000,visible:o=null}={}){let r=I(t),f=Ce[r];if(!f||!R.includes(r))throw Error(`Unsupported synthesizer "${t}". Supported: ${R.join(", ")}`);let l=K(f,{moduleDir:Re});return new Promise((s,c)=>{let a=i?["--tab",String(i)]:[],h={...process.env,CDP_PROFILE_DIR:T};if(o!==!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=_e(W(),[l,"--stdin",...a],{stdio:["pipe","pipe","pipe"],env:h});g.stdin.write(e),g.stdin.end();let _="",u="";g.stdout.on("data",(m)=>_+=m),g.stderr.on("data",(m)=>u+=m);let d=setTimeout(()=>{g.kill(),c(Error(`${r} prompt timed out after ${n/1000}s`))},n);g.on("close",(m)=>{if(clearTimeout(d),m!==0){c(Error(u.trim()||`${r} extractor failed`));return}try{s(JSON.parse(_.trim()))}catch{c(Error(`bad JSON from ${r}: ${_.slice(0,100)}`))}})})}async function ze(t,e={}){return X("gemini",t,e)}async function je(t,e,{grounded:i=!1,tabPrefix:n=null,visible:o=null,synthesizer:r="gemini"}={}){let f=I(r),l=Array.isArray(e._sources)?e._sources:M(e),s=P(t,e,l,{grounded:i}),c=await X(f,s,{tabPrefix:n,timeoutMs:180000,visible:o}),a=S(c.answer||""),g=a&&["answer","agreement","claims","differences","caveats"].some((u)=>(u in a));if(a&&["perplexity","bing","google","chatgpt","gemini"].some((u)=>(u in a))&&!g)a=null;return{...J(a,l,c.answer||""),rawAnswer:c.answer||"",synthesizedBy:f,synthesizerSources:c.sources||[],geminiSources:f==="gemini"?c.sources||[]:[]}}async function ei(t,e,i={}){return je(t,e,{...i,synthesizer:"gemini"})}export{ei as synthesizeWithGemini,je as synthesizeResults,X as runSynthesisPrompt,ze as runGeminiPrompt,I as normalizeSynthesizer,Fe as getSynthesisStartUrl};
12
+ `)}var Re=y(import.meta.url),De={gemini:"gemini.mjs",chatgpt:"chatgpt.mjs"},Te={gemini:"https://gemini.google.com/app",chatgpt:"https://chatgpt.com/"};function A(t="gemini"){let e=String(t||"gemini").toLowerCase();if(e==="gem")return"gemini";if(e==="gpt")return"chatgpt";return e}function si(t="gemini"){return Te[A(t)]||"about:blank"}async function K(t,e,{tabPrefix:i=null,timeoutMs:s=180000,visible:o=null}={}){let c=A(t),f=De[c];if(!f||!R.includes(c))throw Error(`Unsupported synthesizer "${t}". Supported: ${R.join(", ")}`);return new Promise((l,n)=>{let r=S(f,{moduleDir:Re}),a=i?["--tab",String(i)]:[],E={...process.env,CDP_PROFILE_DIR:h};if(o!==!0)delete E.GREEDY_SEARCH_VISIBLE,delete E.GREEDY_SEARCH_ALWAYS_VISIBLE;else E.GREEDY_SEARCH_VISIBLE="1",E.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let p=Ce(Y(),[r,"--stdin",...a],{stdio:["pipe","pipe","pipe"],env:E});p.stdin.write(e),p.stdin.end();let C="",u="";p.stdout.on("data",(m)=>C+=m),p.stderr.on("data",(m)=>u+=m);let _=setTimeout(()=>{p.kill(),n(Error(`${c} prompt timed out after ${s/1000}s`))},s);p.on("close",(m)=>{if(clearTimeout(_),m!==0){n(Error(u.trim()||`${c} extractor failed`));return}try{l(JSON.parse(C.trim()))}catch{n(Error(`bad JSON from ${c}: ${C.slice(0,100)}`))}})})}async function oi(t,e={}){return K("gemini",t,e)}async function Oe(t,e,{grounded:i=!1,tabPrefix:s=null,visible:o=null,synthesizer:c="gemini"}={}){let f=A(c),l=Array.isArray(e._sources)?e._sources:M(e),n=x(t,e,l,{grounded:i}),r=await K(f,n,{tabPrefix:s,timeoutMs:180000,visible:o}),a=J(r.answer||""),p=a&&["answer","agreement","claims","differences","caveats"].some((u)=>(u in a));if(a&&["perplexity","bing","google","chatgpt","gemini"].some((u)=>(u in a))&&!p)a=null;return{...Z(a,l,r.answer||""),rawAnswer:r.answer||"",synthesizedBy:f,synthesizerSources:r.sources||[],geminiSources:f==="gemini"?r.sources||[]:[]}}async function li(t,e,i={}){return Oe(t,e,{...i,synthesizer:"gemini"})}export{li as synthesizeWithGemini,Oe as synthesizeResults,K as runSynthesisPrompt,oi as runGeminiPrompt,A as normalizeSynthesizer,si as getSynthesisStartUrl};
@@ -1,12 +1,12 @@
1
- import{existsSync as m,mkdirSync as C,readFileSync as R,writeFileSync as O}from"node:fs";import{homedir as S}from"node:os";import{join as j}from"node:path";import{tmpdir as g}from"node:os";function T(t,e=9222){let i=Number.parseInt(String(t??""),10);return Number.isInteger(i)&&i>1024&&i<65535?i:e}var k=T(process.env.GREEDY_SEARCH_PORT,9222),b=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${g().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),z=`${b}/DevToolsActivePort`,M=`${g().replaceAll("\\","/")}/cdp-pages.json`,H=process.env.GREEDY_SEARCH_MODE_FILE||`${g().replaceAll("\\","/")}/greedysearch-chrome-mode`,W=`${g().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,d=j(S(),".dm"),p=j(d,"greedyconfig"),E=["perplexity","google","chatgpt"],v="gemini";function w(){try{if(m(p)){let t=R(p,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((i)=>typeof i==="string")){let i=e.engines.filter((n)=>h[n]),l=e.engines.filter((n)=>!h[n]);if(l.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${p}: ${l.join(", ")}
1
+ import{existsSync as g,mkdirSync as T,readFileSync as C,writeFileSync as b}from"node:fs";import{homedir as D}from"node:os";import{join as y}from"node:path";import{tmpdir as S}from"node:os";function j(t,e=9222){let i=Number.parseInt(String(t??""),10);return Number.isInteger(i)&&i>1024&&i<65535?i:e}var O=S().replaceAll("\\","/"),G=j(process.env.GREEDY_SEARCH_PORT),a=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${O}/greedysearch-chrome-profile`).replaceAll("\\","/"),H=`${a}/DevToolsActivePort`,U=process.env.GREEDY_SEARCH_PID_FILE||`${a}/browser.pid`,k=process.env.CDP_PAGES_CACHE||`${a}/cdp-pages.json`,M=process.env.GREEDY_SEARCH_MODE_FILE||`${a}/browser-mode`,z=process.env.GREEDY_SEARCH_METADATA_FILE||`${a}/browser-metadata.json`,W=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${a}/browser-launch.lock`,x=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${a}/browser-last-activity`,J=(process.env.CDP_SOCKET_DIR||`${a}/cdp-sockets`).replaceAll("\\","/"),Z=`${a}/visible-recovery.jsonl`,d=y(D(),".dm"),u=y(d,"greedyconfig"),E=["perplexity","google","chatgpt","gemini"],_="gemini";function I(){try{if(g(u)){let t=C(u,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((i)=>typeof i==="string")){let i=e.engines.filter((n)=>h[n]),l=e.engines.filter((n)=>!h[n]);if(l.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${u}: ${l.join(", ")}
2
2
  [greedysearch] Available engines: ${Object.keys(h).join(", ")}
3
- `);if(i.length>0)return i;process.stderr.write(`[greedysearch] Warning: no valid engines in ${p}, falling back to defaults: ${E.join(", ")}
4
- `)}}}catch{}return E}function N(){try{if(!m(d))C(d,{recursive:!0});if(!m(p))O(p,JSON.stringify({engines:E,synthesizer:v},null,2)+`
5
- `,"utf8")}catch{}}N();var _=["gemini","chatgpt"];function D(){try{if(m(p)){let t=R(p,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let i=e.synthesizer.toLowerCase();if(_.includes(i))return i;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${p}
6
- [greedysearch] Available synthesizers: ${_.join(", ")}
7
- [greedysearch] Falling back to default: ${v}
8
- `)}}}catch{}return v}var h={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"},y=w();var Y=D(),x=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=b;function u(t="",e=240){let i=String(t).replaceAll(/\s+/g," ").trim();if(i.length<=e)return i;let l=i.slice(0,e),n=l.lastIndexOf(" ");return n>0?`${l.slice(0,n)}...`:`${l}...`}function P(t){let e="",i=!1,l=!1;for(let n of String(t)){if(l){e+=n,l=!1;continue}if(n==="\\"){e+=n,l=!0;continue}if(n==='"'){i=!i,e+=n;continue}if(i&&n===`
9
- `)e+="\\n";else if(i&&n==="\r")e+="\\r";else if(i&&n==="\t")e+="\\t";else e+=n}return e}function q(t){if(!t)return null;let e=String(t).trim(),i=e.indexOf("BEGIN_JSON"),l=e.indexOf("END_JSON");if(i!==-1&&l!==-1&&i<l)e=e.slice(i+10,l).trim();else{let s=e.indexOf("{");if(s>0)e=e.slice(s)}let n=[e,e.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],c=e.indexOf("{"),a=e.lastIndexOf("}");if(c!==-1&&a!==-1&&c<a)n.push(e.slice(c,a+1));for(let s of[...n]){let r=P(s);if(r!==s)n.push(r)}for(let s of n)try{return JSON.parse(s)}catch{}return null}function K(t,e,i=""){let l=new Set(e.map((r)=>r.id)),n=["high","medium","low","mixed","conflicting"].includes(t?.agreement?.level)?t.agreement.level:"mixed",c=Array.isArray(t?.claims)?t.claims.map((r)=>({claim:u(r?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(r?.support)?r.support:"moderate",sourceIds:Array.isArray(r?.sourceIds)?r.sourceIds.filter((o)=>l.has(o)):[]})).filter((r)=>r.claim):[],a=Array.isArray(t?.recommendedSources)?t.recommendedSources.filter((r)=>l.has(r)).slice(0,6):[],s="";if(i){let r=i.indexOf("{"),o=i.lastIndexOf("}");if(r!==-1&&o!==-1&&r<o)s=i.slice(r,o+1);else s=i}return{answer:u(t?.answer||s||i,4000),agreement:{level:n,summary:u(t?.agreement?.summary||"",280)},differences:Array.isArray(t?.differences)?t.differences.map((r)=>u(r,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray(t?.caveats)?t.caveats.map((r)=>u(r,220)).filter(Boolean).slice(0,5):[],claims:c,recommendedSources:a}}function Q(t,e,i,{grounded:l=!1}={}){let n={};for(let s of["perplexity","bing","google"]){let r=e[s];if(!r)continue;if(r.error){n[s]={status:"error",error:String(r.error)};continue}n[s]={status:"ok",answer:u(r.answer||"",l?4500:2200),sourceIds:i.filter((o)=>o.engines.includes(s)).sort((o,f)=>(o.perEngine[s]?.rank||99)-(f.perEngine[s]?.rank||99)).map((o)=>o.id).slice(0,6)}}let c=l?700:300,a=i.slice(0,l?10:8).map((s)=>({id:s.id,title:s.title,domain:s.domain,canonicalUrl:s.canonicalUrl,sourceType:s.sourceType,isOfficial:s.isOfficial,engines:s.engines,engineCount:s.engineCount,fetch:s.fetch?.attempted?{ok:s.fetch.ok,publishedTime:s.fetch.publishedTime||"",byline:s.fetch.byline||"",snippet:u(s.fetch.snippet||"",c)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${t}`,"",`Engine summaries:
3
+ `);if(i.length>0)return i;process.stderr.write(`[greedysearch] Warning: no valid engines in ${u}, falling back to defaults: ${E.join(", ")}
4
+ `)}}}catch{}return E}function w(){try{if(!g(d))T(d,{recursive:!0});if(!g(u))b(u,JSON.stringify({engines:E,synthesizer:_},null,2)+`
5
+ `,"utf8")}catch{}}w();var R=["gemini","chatgpt"];function L(){try{if(g(u)){let t=C(u,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let i=e.synthesizer.toLowerCase();if(R.includes(i))return i;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${u}
6
+ [greedysearch] Available synthesizers: ${R.join(", ")}
7
+ [greedysearch] Falling back to default: ${_}
8
+ `)}}}catch{}return _}var h={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"},v=I();var K=L(),q=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=a;function m(t="",e=240){let i=String(t).replaceAll(/\s+/g," ").trim();if(i.length<=e)return i;let l=i.slice(0,e),n=l.lastIndexOf(" ");return n>0?`${l.slice(0,n)}...`:`${l}...`}function N(t){let e="",i=!1,l=!1;for(let n of String(t)){if(l){e+=n,l=!1;continue}if(n==="\\"){e+=n,l=!0;continue}if(n==='"'){i=!i,e+=n;continue}if(i&&n===`
9
+ `)e+="\\n";else if(i&&n==="\r")e+="\\r";else if(i&&n==="\t")e+="\\t";else e+=n}return e}function B(t){if(!t)return null;let e=String(t).trim(),i=e.indexOf("BEGIN_JSON"),l=e.indexOf("END_JSON");if(i!==-1&&l!==-1&&i<l)e=e.slice(i+10,l).trim();else{let s=e.indexOf("{");if(s>0)e=e.slice(s)}let n=[e,e.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/```$/i,"").trim()],c=e.indexOf("{"),p=e.lastIndexOf("}");if(c!==-1&&p!==-1&&c<p)n.push(e.slice(c,p+1));for(let s of[...n]){let r=N(s);if(r!==s)n.push(r)}for(let s of n)try{return JSON.parse(s)}catch{}return null}function ee(t,e,i=""){let l=new Set(e.map((r)=>r.id)),n=["high","medium","low","mixed","conflicting"].includes(t?.agreement?.level)?t.agreement.level:"mixed",c=Array.isArray(t?.claims)?t.claims.map((r)=>({claim:m(r?.claim||"",260),support:["strong","moderate","weak","conflicting"].includes(r?.support)?r.support:"moderate",sourceIds:Array.isArray(r?.sourceIds)?r.sourceIds.filter((o)=>l.has(o)):[]})).filter((r)=>r.claim):[],p=Array.isArray(t?.recommendedSources)?t.recommendedSources.filter((r)=>l.has(r)).slice(0,6):[],s="";if(i){let r=i.indexOf("{"),o=i.lastIndexOf("}");if(r!==-1&&o!==-1&&r<o)s=i.slice(r,o+1);else s=i}return{answer:m(t?.answer||s||i,4000),agreement:{level:n,summary:m(t?.agreement?.summary||"",280)},differences:Array.isArray(t?.differences)?t.differences.map((r)=>m(r,220)).filter(Boolean).slice(0,5):[],caveats:Array.isArray(t?.caveats)?t.caveats.map((r)=>m(r,220)).filter(Boolean).slice(0,5):[],claims:c,recommendedSources:p}}function ie(t,e,i,{grounded:l=!1}={}){let n={};for(let s of["perplexity","bing","google"]){let r=e[s];if(!r)continue;if(r.error){n[s]={status:"error",error:String(r.error)};continue}n[s]={status:"ok",answer:m(r.answer||"",l?4500:2200),sourceIds:i.filter((o)=>o.engines.includes(s)).sort((o,f)=>(o.perEngine[s]?.rank||99)-(f.perEngine[s]?.rank||99)).map((o)=>o.id).slice(0,6)}}let c=l?700:300,p=i.slice(0,l?10:8).map((s)=>({id:s.id,title:s.title,domain:s.domain,canonicalUrl:s.canonicalUrl,sourceType:s.sourceType,isOfficial:s.isOfficial,engines:s.engines,engineCount:s.engineCount,fetch:s.fetch?.attempted?{ok:s.fetch.ok,publishedTime:s.fetch.publishedTime||"",byline:s.fetch.byline||"",snippet:m(s.fetch.snippet||"",c)}:void 0}));return["You are a research synthesizer. Combine these search engine results into a single authoritative answer.","",`Query: ${t}`,"",`Engine summaries:
10
10
  ${JSON.stringify(n,null,2)}`,"",`Source registry:
11
- ${JSON.stringify(a,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(`
12
- `)}function X(t){let e=Array.isArray(t._sources)?t._sources:[],i=e.length>0?e[0]?.engineCount||0:0,l=e.filter((o)=>o.isOfficial).length,n=e.filter((o)=>o.isOfficial||o.sourceType==="maintainer-blog").length,c=e.filter((o)=>o.fetch?.attempted).length,a=e.filter((o)=>o.fetch?.ok).length,s=e.reduce((o,f)=>{return o[f.sourceType]=(o[f.sourceType]||0)+1,o},{}),r=t._synthesis?.agreement?.level;return{sourcesCount:e.length,topSourceConsensus:i,agreementLevel:r||(i>=3?"high":i>=2?"medium":"low"),enginesResponded:y.filter((o)=>t[o]?.answer&&!t[o]?.error),enginesFailed:y.filter((o)=>t[o]?.error),officialSourceCount:l,firstPartySourceCount:n,fetchedSourceSuccessRate:c>0?Number((a/c).toFixed(2)):0,sourceTypeBreakdown:s}}export{q as parseStructuredJson,K as normalizeSynthesisPayload,Q as buildSynthesisPrompt,X as buildConfidence};
11
+ ${JSON.stringify(p,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(`
12
+ `)}function te(t){let e=Array.isArray(t._sources)?t._sources:[],i=e.length>0?e[0]?.engineCount||0:0,l=e.filter((o)=>o.isOfficial).length,n=e.filter((o)=>o.isOfficial||o.sourceType==="maintainer-blog").length,c=e.filter((o)=>o.fetch?.attempted).length,p=e.filter((o)=>o.fetch?.ok).length,s=e.reduce((o,f)=>{return o[f.sourceType]=(o[f.sourceType]||0)+1,o},{}),r=t._synthesis?.agreement?.level;return{sourcesCount:e.length,topSourceConsensus:i,agreementLevel:r||(i>=3?"high":i>=2?"medium":"low"),enginesResponded:v.filter((o)=>t[o]?.answer&&!t[o]?.error),enginesFailed:v.filter((o)=>t[o]?.error),officialSourceCount:l,firstPartySourceCount:n,fetchedSourceSuccessRate:c>0?Number((p/c).toFixed(2)):0,sourceTypeBreakdown:s}}export{B as parseStructuredJson,ee as normalizeSynthesisPayload,ie as buildSynthesisPrompt,te as buildConfidence};
@@ -1,20 +1,23 @@
1
- import{Type as l}from"@sinclair/typebox";function L(i){return{bing:"Bing Copilot",google:"Google AI",gemini:"Gemini",copilot:"Copilot",perplexity:"Perplexity"}[i]??i.charAt(0).toUpperCase()+i.slice(1)}function w(i){if(!i)return"";if(i==="official-docs")return"official docs";return i.replace(/-/g," ")}function a(i){if(!i)return"Mixed";return i.charAt(0).toUpperCase()+i.slice(1)}function J(i){return String(i.displayUrl||i.canonicalUrl||i.url||"")}function G(i){return String(i.title||i.domain||J(i)||"Untitled source")}function x(i){if(typeof i.engineCount==="number")return i.engineCount;return(Array.isArray(i.engines)?i.engines:[]).length}function T(i){return new Map(i.map((r)=>[String(r.id||""),r]).filter(([r])=>r))}function q(i){let r=String(i.id||"?"),n=J(i),o=G(i),c=String(i.domain||""),t=Array.isArray(i.engines)?i.engines:[],u=x(i),e=w(String(i.sourceType||"")),s=i.fetch,g=s?.ok?`fetched ${s.status||200}`:s?.attempted?"fetch failed":"";return`- ${[`${r} - [${o}](${n})`,c,e,t.length?`cited by ${t.map(L).join(", ")} (${u}/3)`:`${u}/3`,g].filter(Boolean).join(" - ")}`}function ii(i,r=[],n=6){if(!i.length)return[];let o=T(i),c=r.map((t)=>o.get(t)).filter((t)=>Boolean(t));if(c.length>0)return c.slice(0,n);return i.slice(0,n)}function ri(i,r,n,o=6){if(r.answer)i.push("## Answer"),i.push(String(r.answer)),i.push("");let c=r.agreement,t=String(c?.summary||"").trim(),u=String(c?.level||"").trim();if(t||u)i.push("## Consensus"),i.push(`- ${a(u)}${t?` - ${t}`:""}`),i.push("");let e=Array.isArray(r.differences)?r.differences:[];if(e.length>0){i.push("## Where Engines Differ");for(let $ of e)i.push(`- ${$}`);i.push("")}let s=Array.isArray(r.caveats)?r.caveats:[];if(s.length>0){i.push("## Caveats");for(let $ of s)i.push(`- ${$}`);i.push("")}let g=Array.isArray(r.claims)?r.claims:[];if(g.length>0){i.push("## Key Claims");for(let $ of g){let E=Array.isArray($.sourceIds)?$.sourceIds:[],_=String($.support||"moderate");i.push(`- ${String($.claim||"")} [${_}${E.length?`; ${E.join(", ")}`:""}]`)}i.push("")}let A=Array.isArray(r.recommendedSources)?r.recommendedSources:[],h=ii(n,A,o);if(h.length>0){i.push("## Top Sources");for(let $ of h)i.push(q($));i.push("")}}function K(i,r){let n=[];if(i==="all")return ni(r,n);return ci(r,n)}function ni(i,r){let{_synthesis:n,_sources:o,_needsHumanVerification:c,_research:t}=i;if(c){let u=Array.isArray(c.engines)?c.engines.join(", "):"one or more engines";r.push("## Manual verification required"),r.push(String(c.message||"Visible Chrome is open. Solve the verification challenge, then rerun the same search.")),r.push(`Engines: ${u}`),r.push("")}if(n?.answer){if(t?.mode==="iterative")oi(r,t);ri(r,n,o||[],6);let u=String(n.synthesizedBy||"configured synthesizer");return r.push(t?.mode==="iterative"?`*Research mode: iterative planning, source fetching, citation audit, and bundle output*
2
- `:`*Synthesized by ${u} from multi-engine results and fetched sources*
3
- `),r.join(`
4
- `).trim()}for(let[u,e]of Object.entries(i)){if(u.startsWith("_"))continue;r.push(`
5
- ## ${L(u)}`),Q(e,r,3)}return r.join(`
6
- `).trim()}function oi(i,r){let n=r.floor,o=n?.metrics,c=r.bundle,t=r.manifest;if(i.push("## Research Run"),i.push(`- Status: ${n?.floorMet?"floor met":"partial / floor unmet"}`),t?.terminationReason)i.push(`- Stop reason: ${String(t.terminationReason)}`);if(o)i.push(`- Evidence: ${o.fetchedOk||0} fetched sources, ${o.primarySources||0} primary/official, ${o.claims||0} claims, ${o.cited||0} citations`),i.push(`- Questions: ${o.closedQuestions||0}/${o.totalQuestions||0} closed${o.openQuestions?`, ${o.openQuestions} open`:""}`);if(c?.dir)i.push(`- Bundle: ${String(c.dir)}`);i.push("")}function ci(i,r){let n=i._needsHumanVerification;if(n){let o=Array.isArray(n.engines)?n.engines.join(", "):"this engine";r.push("## Manual verification required"),r.push(String(n.message||"Visible Chrome is open. Solve the verification challenge, then rerun the same search.")),r.push(`Engines: ${o}`),r.push("")}return Q(i,r,5),r.join(`
7
- `).trim()}function Q(i,r,n){if(i.error){r.push(`Error: ${i.error}`);return}if(i.answer)r.push(String(i.answer));let o=i.sources;if(Array.isArray(o)&&o.length>0){r.push(`
8
- Sources:`);for(let c of o.slice(0,n))r.push(`- [${c.title||c.url}](${c.url})`)}}import{spawn as Ei}from"node:child_process";import{existsSync as Ai}from"node:fs";import{join as hi}from"node:path";import{basename as ti}from"node:path";function B(i=process.env,r=process.execPath){let n=i.GREEDY_SEARCH_NODE||i.NODE_BINARY||i.NODE;if(n?.trim())return n.trim();let o=ti(r||"").toLowerCase();if(o==="node"||o==="node.exe")return r;return"node"}function H(i){let r=String(i??"").trim();if(!r)return null;let n=[r],o=r.indexOf("{"),c=r.lastIndexOf("}");if(o>=0&&c>o)n.push(r.slice(o,c+1));for(let t of n)try{let u=JSON.parse(t);if(u&&typeof u==="object"&&!Array.isArray(u))return u}catch{}return null}function U(i,r={}){let n=H(i);if(!n)return null;return{...n,_process:{...n._process&&typeof n._process==="object"?n._process:{},status:"partial",...r}}}import{existsSync as N,mkdirSync as ui,readFileSync as z,writeFileSync as ei}from"node:fs";import{homedir as fi}from"node:os";import{join as Z}from"node:path";import{tmpdir as Y}from"node:os";function li(i,r=9222){let n=Number.parseInt(String(i??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:r}var Yi=li(process.env.GREEDY_SEARCH_PORT,9222),X=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Y().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),Hi=`${X}/DevToolsActivePort`,bi=`${Y().replaceAll("\\","/")}/cdp-pages.json`,mi=process.env.GREEDY_SEARCH_MODE_FILE||`${Y().replaceAll("\\","/")}/greedysearch-chrome-mode`,vi=`${Y().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,m=Z(fi(),".dm"),I=Z(m,"greedyconfig"),v=["perplexity","google","chatgpt"],V="gemini";function gi(){try{if(N(I)){let i=z(I,"utf8"),r=JSON.parse(i);if(Array.isArray(r.engines)&&r.engines.length>0&&r.engines.every((n)=>typeof n==="string")){let n=r.engines.filter((c)=>b[c]),o=r.engines.filter((c)=>!b[c]);if(o.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${I}: ${o.join(", ")}
9
- [greedysearch] Available engines: ${Object.keys(b).join(", ")}
10
- `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${I}, falling back to defaults: ${v.join(", ")}
11
- `)}}}catch{}return v}function si(){try{if(!N(m))ui(m,{recursive:!0});if(!N(I))ei(I,JSON.stringify({engines:v,synthesizer:V},null,2)+`
12
- `,"utf8")}catch{}}si();var W=["gemini","chatgpt"];function $i(){try{if(N(I)){let i=z(I,"utf8"),r=JSON.parse(i);if(typeof r.synthesizer==="string"){let n=r.synthesizer.toLowerCase();if(W.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${r.synthesizer}" in ${I}
13
- [greedysearch] Available synthesizers: ${W.join(", ")}
14
- [greedysearch] Falling back to default: ${V}
15
- `)}}}catch{}return V}var b={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"},D=gi();var Vi=$i(),Di=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=X;function F(i){return i.replace(/^"|"$/g,"")}function k(i){return Ai(hi(i,"bin","cdp.mjs"))}function p(){return{content:[{type:"text",text:"cdp.mjs missing — try reinstalling: Rebuild or reinstall DM to refresh the bundled GreedySearch asset."}],details:{}}}function M(i,r){let n=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`${i}: ${n}`}],details:{}}}function d(i,r,n,o,c,t,u={}){return new Promise((e,s)=>{let{headless:g=!0}=u,A=[...n];if(g!==!1&&process.env.GREEDY_SEARCH_VISIBLE!=="1")A.push("--headless");if(g===!1)A.push("--always-visible");let h={...process.env};if(g===!1)h.GREEDY_SEARCH_VISIBLE="1",h.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let $=Ei(B(),[o,i,"--inline","--stdin",...A],{stdio:["pipe","pipe","pipe"],env:h});$.stdin.write(r),$.stdin.end();let E="",_="",O=()=>{$.kill("SIGTERM"),s(Error("Aborted"))};c?.addEventListener("abort",O,{once:!0}),$.stderr.on("data",(S)=>{_+=S;let f=/^PROGRESS:(perplexity|google|chatgpt|bing|gemini|semantic-scholar|semanticscholar|s2|logically):(done|error|needs-human)$/;for(let C of S.toString().split(`
16
- `)){let j=C.match(f);if(j&&t)t(j[1],j[2]);let y=C.match(/^PROGRESS:synthesis:(done|error|skipped)$/);if(y&&t)t("synthesis",y[1])}}),$.stdout.on("data",(S)=>E+=S),$.on("close",(S)=>{if(c?.removeEventListener("abort",O),S!==0){let f=_.trim()||`search.mjs exited with code ${S}`,C=U(E,{code:S,error:f});if(C){e(C);return}s(Error(f))}else{let f=H(E);if(f)e(f);else s(Error(`Invalid JSON from search.mjs: ${E.slice(0,200)}`))}})})}function P(i,r,n,o){let c=new Map;return(t,u)=>{c.set(t,u);let e=[];for(let s of i){let g=c.get(s);if(g==="done")e.push(`✅ ${s} done`);else if(g==="error")e.push(`❌ ${s} failed`);else if(g==="needs-human")e.push(`\uD83D\uDD13 ${s} needs manual verification`);else e.push(`⏳ ${s}`)}if(o&&c.size>=i.length){let s=c.get("synthesis");if(s==="done")e.push("✅ synthesized");else if(s==="error")e.push("❌ synthesis failed");else if(s==="needs-human")e.push("⏭️ synthesis skipped");else e.push("\uD83D\uDD04 synthesizing")}r?.({content:[{type:"text",text:`**${n}...** ${e.join(" · ")}`}],details:{_progress:!0}})}}class R{text;paddingX;paddingY;constructor(i,r=0,n=0){this.text=i;this.paddingX=r;this.paddingY=n}render(i){let r=" ".repeat(this.paddingX),n="",o=Math.max(1,i-this.paddingX*2),c=this.text.split(`
17
- `).flatMap((t)=>{if(t.length<=o)return[`${r}${t}`];let u=[];for(let e=0;e<t.length;e+=o)u.push(`${r}${t.slice(e,e+o)}`);return u});return[...Array.from({length:this.paddingY},()=>""),...c,...Array.from({length:this.paddingY},()=>"")]}invalidate(){}}function ki(i,r){i.registerTool({name:"greedy_search",label:"Greedy Search",description:"WEB/RESEARCH SEARCH ONLY — searches live web via Perplexity, Google AI, ChatGPT, and Gemini, plus opt-in research through Semantic Scholar and Logically. "+"Research mode reuses the configured ~/.dm/greedyconfig engines for child searches and Gemini for planning/final synthesis. Research mode is the centerpiece: it plans follow-up actions, fetches sources, audits citations, and writes a structured research bundle on disk. Use for: library docs, recent framework changes, error messages, best practices, current events. Reports streaming progress as each engine completes.",promptSnippet:"Multi-engine AI web search with streaming progress",parameters:l.Object({query:l.String({description:"The search query"}),engine:l.String({description:'Engine to use: "all" (default), "perplexity", "google", "chatgpt", "gemini", "gem". Research engines: "semantic-scholar" (alias "s2") and "logically". "all" fans out to the configured engines and fetches top sources. Customize via ~/.dm/greedyconfig. Bing Copilot is still available as "bing" for signed-in users.',default:"all"}),synthesize:l.Optional(l.Boolean({description:'Only for engine="all": synthesize the multi-engine results and fetched sources. Default: false.',default:!1})),synthesizer:l.Optional(l.String({description:'Synthesis engine for synthesize=true. Defaults to ~/.dm/greedyconfig synthesizer (currently "gemini" by default). Supported: "gemini", "chatgpt".'})),depth:l.Optional(l.String({description:'Deprecated except "research". Use depth="research" for the iterative research workflow. Research child searches use ~/.dm/greedyconfig engines; Gemini handles research planning/final synthesis. Legacy values: "fast" skips source fetching; "standard"/"deep" alias synthesize=true.'})),breadth:l.Optional(l.Number({description:'Only for depth="research": number of parallel research directions per round, 1-5 (default: 3).',default:3})),iterations:l.Optional(l.Number({description:'Only for depth="research": number of iterative research rounds, 1-3 (default: 2).',default:2})),maxSources:l.Optional(l.Number({description:'Only for depth="research": maximum fetched sources for the final report, 3-12.'})),researchOutDir:l.Optional(l.String({description:'Only for depth="research": optional directory for the structured research bundle. Defaults to .dm/greedysearch-research/<timestamp>_<query>.'})),writeResearchBundle:l.Optional(l.Boolean({description:'Only for depth="research": write the structured research bundle to disk (default true).',default:!0})),fullAnswer:l.Optional(l.Boolean({description:"When true, returns the complete answer instead of a truncated preview (default: false, answers are shortened to ~300 chars to save tokens).",default:!1})),headless:l.Optional(l.Boolean({description:"Set to false to show Chrome window (headless is the default). Set GREEDY_SEARCH_VISIBLE=1 to disable headless globally.",default:!0})),visible:l.Optional(l.Boolean({description:"Set to true to always use visible Chrome for this search. Alias for headless: false.",default:!1})),alwaysVisible:l.Optional(l.Boolean({description:"Set to true to keep GreedySearch in visible Chrome mode for this search. Alias for visible: true.",default:!1}))}),execute:async(n,o,c,t)=>{let{query:u,fullAnswer:e}=o,s=F(o.engine??"all")||"all",g=F(o.depth??""),A=g==="research",h=g==="fast",$=g==="standard"||g==="deep",E=s==="all"&&!h&&(o.synthesize===!0||$),_=A?"all":s,S=!(o.visible===!0||o.alwaysVisible===!0||o.headless===!1||process.env.GREEDY_SEARCH_VISIBLE==="1"||process.env.GREEDY_SEARCH_ALWAYS_VISIBLE==="1");if(!k(r))return p();let f=[];if(e??_!=="all")f.push("--full");if(A){if(f.push("--depth","research"),typeof o.breadth==="number")f.push("--breadth",String(o.breadth));if(typeof o.iterations==="number")f.push("--iterations",String(o.iterations));if(typeof o.maxSources==="number")f.push("--max-sources",String(o.maxSources));if(typeof o.researchOutDir==="string")f.push("--research-out-dir",o.researchOutDir);if(o.writeResearchBundle===!1)f.push("--no-research-bundle")}else if(h)f.push("--fast");else if(g==="deep")f.push("--depth","deep");else if(E)f.push("--synthesize");if(E&&typeof o.synthesizer==="string")f.push("--synthesizer",o.synthesizer);let j=_==="all"?P(D,t,A?"Researching":"Searching",E):void 0;try{let y=await d(_,u,f,`${r}/bin/search.mjs`,c,j,{headless:S});return{content:[{type:"text",text:K(_,y)||"No results returned."}],details:{raw:y}}}catch(y){return M("Search failed",y)}},renderCall(n,o){let c=(n.query||"").slice(0,60),t=c.length<(n.query||"").length?`${c}...`:c,u=n.engine&&n.engine!=="all"?o.fg("dim",` (${n.engine})`):"";return new R(`${o.fg("toolTitle",o.bold("greedy_search"))} "${o.fg("accent",t)}"${u}`,0,0)},renderResult(n,{expanded:o,isPartial:c},t){if(c){let g=n.content.find((h)=>h.type==="text")?.text,A=g?g.replace(/\*\*/g,""):"Searching...";return new R(t.fg("warning",A),0,0)}let u=n.content.find((g)=>g.type==="text"),e=n.details?.raw;if(!o){if(e?._needsHumanVerification)return new R(t.fg("warning"," Manual verification required"),0,0);let A=e?._synthesis,h=e?._sources;if(A){let O=Array.isArray(h)?h.length:0,S=A.agreement?.level,f=" → Synthesized";if(O>0)f+=` · ${O} source${O>1?"s":""}`;if(S)f+=` · ${S}`;return new R(t.fg("muted",f),0,0)}let $=Object.keys(e||{}).filter((O)=>!O.startsWith("_")),E=0;for(let O of $){let f=e?.[O]?.sources;if(Array.isArray(f))E+=f.length}if(E>0)return new R(t.fg("muted",` → ${E} source${E>1?"s":""}`),0,0);let _=u?.text;if(_)return new R(t.fg("warning",` ${_.slice(0,80)}`),0,0);return new R(t.fg("muted"," → Done"),0,0)}if(!u||u.type!=="text")return new R("",0,0);let s=u.text.split(`
18
- `).map((g)=>t.fg("toolOutput",g)).join(`
19
- `);return new R(`
20
- ${s}`,0,0)}})}export{ki as registerGreedySearchTool};
1
+ import{Type as $}from"@sinclair/typebox";function s(i){return{bing:"Bing Copilot",google:"Google AI",gemini:"Gemini",copilot:"Copilot",perplexity:"Perplexity"}[i]??i.charAt(0).toUpperCase()+i.slice(1)}function ri(i){if(!i)return"";if(i==="official-docs")return"official docs";return i.replace(/-/g," ")}function ci(i){if(!i)return"Mixed";return i.charAt(0).toUpperCase()+i.slice(1)}function w(i){return String(i.displayUrl||i.canonicalUrl||i.url||"")}function ui(i){return String(i.title||i.domain||w(i)||"Untitled source")}function Ei(i){if(typeof i.engineCount==="number")return i.engineCount;return(Array.isArray(i.engines)?i.engines:[]).length}function oi(i){return new Map(i.map((n)=>[String(n.id||""),n]).filter(([n])=>n))}function fi(i){let n=String(i.id||"?"),c=w(i),r=ui(i),o=String(i.domain||""),u=Array.isArray(i.engines)?i.engines:[],l=Ei(i),A=ri(String(i.sourceType||"")),t=i.fetch,f=t?.ok?`fetched ${t.status||200}`:t?.attempted?"fetch failed":"";return`- ${[`${n} - [${r}](${c})`,o,A,u.length?`cited by ${u.map(s).join(", ")} (${l}/3)`:`${l}/3`,f].filter(Boolean).join(" - ")}`}function li(i,n=[],c=6){if(!i.length)return[];let r=oi(i),o=n.map((u)=>r.get(u)).filter((u)=>Boolean(u));if(o.length>0)return o.slice(0,c);return i.slice(0,c)}function _i(i,n,c,r=6){if(n.answer)i.push("## Answer"),i.push(String(n.answer)),i.push("");let o=n.agreement,u=String(o?.summary||"").trim(),l=String(o?.level||"").trim();if(u||l)i.push("## Consensus"),i.push(`- ${ci(l)}${u?` - ${u}`:""}`),i.push("");let A=Array.isArray(n.differences)?n.differences:[];if(A.length>0){i.push("## Where Engines Differ");for(let E of A)i.push(`- ${E}`);i.push("")}let t=Array.isArray(n.caveats)?n.caveats:[];if(t.length>0){i.push("## Caveats");for(let E of t)i.push(`- ${E}`);i.push("")}let f=Array.isArray(n.claims)?n.claims:[];if(f.length>0){i.push("## Key Claims");for(let E of f){let C=Array.isArray(E.sourceIds)?E.sourceIds:[],I=String(E.support||"moderate");i.push(`- ${String(E.claim||"")} [${I}${C.length?`; ${C.join(", ")}`:""}]`)}i.push("")}let S=Array.isArray(n.recommendedSources)?n.recommendedSources:[],_=li(c,S,r);if(_.length>0){i.push("## Top Sources");for(let E of _)i.push(fi(E));i.push("")}}var W=800;function X(i){return i.split(`
2
+ `).map((n)=>n.length>W?n.slice(0,W-1)+"…":n).join(`
3
+ `)}function p(i,n){let c=[];if(i==="all")return X($i(n,c));return X(Si(n,c))}function $i(i,n){let{_synthesis:c,_sources:r,_needsHumanVerification:o,_research:u}=i;if(o){let l=Array.isArray(o.engines)?o.engines.join(", "):"one or more engines";n.push("## Manual verification required"),n.push(String(o.message||"Visible Chrome is open. Solve the verification challenge, then rerun the same search.")),n.push(`Engines: ${l}`),n.push("")}if(c?.answer){if(u?.mode==="iterative")Ai(n,u);_i(n,c,r||[],6);let l=String(c.synthesizedBy||"configured synthesizer");return n.push(u?.mode==="iterative"?`*Research mode: iterative planning, source fetching, citation audit, and bundle output*
4
+ `:`*Synthesized by ${l} from multi-engine results and fetched sources*
5
+ `),n.join(`
6
+ `).trim()}for(let[l,A]of Object.entries(i)){if(l.startsWith("_"))continue;n.push(`
7
+ ## ${s(l)}`),G(A,n,3)}return n.join(`
8
+ `).trim()}function Ai(i,n){let c=n.floor,r=c?.metrics,o=n.bundle,u=n.manifest;if(i.push("## Research Run"),i.push(`- Status: ${c?.floorMet?"floor met":"partial / floor unmet"}`),u?.terminationReason)i.push(`- Stop reason: ${String(u.terminationReason)}`);if(r)i.push(`- Evidence: ${r.fetchedOk||0} fetched sources, ${r.primarySources||0} primary/official, ${r.claims||0} claims, ${r.cited||0} citations`),i.push(`- Questions: ${r.closedQuestions||0}/${r.totalQuestions||0} closed${r.openQuestions?`, ${r.openQuestions} open`:""}`);if(o?.dir)i.push(`- Bundle: ${String(o.dir)}`);i.push("")}function Si(i,n){let c=i._needsHumanVerification;if(c){let r=Array.isArray(c.engines)?c.engines.join(", "):"this engine";n.push("## Manual verification required"),n.push(String(c.message||"Visible Chrome is open. Solve the verification challenge, then rerun the same search.")),n.push(`Engines: ${r}`),n.push("")}return G(i,n,5),n.join(`
9
+ `).trim()}function G(i,n,c){if(i.error){n.push(`Error: ${i.error}`);return}if(i.answer)n.push(String(i.answer));let r=i.sources;if(Array.isArray(r)&&r.length>0){n.push(`
10
+ Sources:`);for(let o of r.slice(0,c))n.push(`- [${o.title||o.url}](${o.url})`)}}import{spawn as vi}from"node:child_process";import{basename as Ci}from"node:path";function M(i=process.env,n=process.execPath){let c=i.GREEDY_SEARCH_NODE||i.NODE_BINARY||i.NODE;if(c?.trim())return c.trim();let r=Ci(n||"").toLowerCase();if(r==="node"||r==="node.exe")return n;return"node"}import{existsSync as ji}from"node:fs";import{join as Li}from"node:path";import{existsSync as y,mkdirSync as Ii,readFileSync as e,writeFileSync as Ri}from"node:fs";import{homedir as ti}from"node:os";import{join as x}from"node:path";import{tmpdir as Oi}from"node:os";function gi(i,n=9222){let c=Number.parseInt(String(i??""),10);return Number.isInteger(c)&&c>1024&&c<65535?c:n}var Yi=Oi().replaceAll("\\","/"),Zi=gi(process.env.GREEDY_SEARCH_PORT),Y=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Yi}/greedysearch-chrome-profile`).replaceAll("\\","/"),ki=`${Y}/DevToolsActivePort`,mi=process.env.GREEDY_SEARCH_PID_FILE||`${Y}/browser.pid`,zi=process.env.CDP_PAGES_CACHE||`${Y}/cdp-pages.json`,Bi=process.env.GREEDY_SEARCH_MODE_FILE||`${Y}/browser-mode`,Wi=process.env.GREEDY_SEARCH_METADATA_FILE||`${Y}/browser-metadata.json`,Xi=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${Y}/browser-launch.lock`,si=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${Y}/browser-last-activity`,wi=(process.env.CDP_SOCKET_DIR||`${Y}/cdp-sockets`).replaceAll("\\","/"),pi=`${Y}/visible-recovery.jsonl`,Q=x(ti(),".dm"),D=x(Q,"greedyconfig"),J=["perplexity","google","chatgpt","gemini"],U="gemini";function hi(){try{if(y(D)){let i=e(D,"utf8"),n=JSON.parse(i);if(Array.isArray(n.engines)&&n.engines.length>0&&n.engines.every((c)=>typeof c==="string")){let c=n.engines.filter((o)=>K[o]),r=n.engines.filter((o)=>!K[o]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${D}: ${r.join(", ")}
11
+ [greedysearch] Available engines: ${Object.keys(K).join(", ")}
12
+ `);if(c.length>0)return c;process.stderr.write(`[greedysearch] Warning: no valid engines in ${D}, falling back to defaults: ${J.join(", ")}
13
+ `)}}}catch{}return J}function Di(){try{if(!y(Q))Ii(Q,{recursive:!0});if(!y(D))Ri(D,JSON.stringify({engines:J,synthesizer:U},null,2)+`
14
+ `,"utf8")}catch{}}Di();var P=["gemini","chatgpt"];function Hi(){try{if(y(D)){let i=e(D,"utf8"),n=JSON.parse(i);if(typeof n.synthesizer==="string"){let c=n.synthesizer.toLowerCase();if(P.includes(c))return c;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${n.synthesizer}" in ${D}
15
+ [greedysearch] Available synthesizers: ${P.join(", ")}
16
+ [greedysearch] Falling back to default: ${U}
17
+ `)}}}catch{}return U}var K={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"},Z=hi();var Gi=Hi(),Mi=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=Y;function k(i){return i.replace(/^"|"$/g,"")}function T(i){return ji(Li(i,"bin","cdp.mjs"))}function d(){return{content:[{type:"text",text:"cdp.mjs missing try reinstalling: pi install git:github.com/apmantza/greedysearch-dm"}],details:{}}}function q(i,n){let c=n instanceof Error?n.message:String(n);return{content:[{type:"text",text:`${i}: ${c}`}],details:{}}}function a(i,n,c,r,o,u,l={}){return new Promise((A,t)=>{let{headless:f=!0}=l,S=[...c];if(f!==!1&&process.env.GREEDY_SEARCH_VISIBLE!=="1")S.push("--headless");if(f===!1)S.push("--always-visible");let _={...process.env};if(f===!1)_.GREEDY_SEARCH_VISIBLE="1",_.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let E=vi(M(),[r,i,"--inline","--stdin",...S],{stdio:["pipe","pipe","pipe"],env:_});E.stdin.write(n),E.stdin.end();let C="",I="",g=51200,O=!1,R=900000,F=parseInt(process.env.GREEDY_SEARCH_TIMEOUT_MS||"",10),L=Number.isNaN(F)?R:F,H=setTimeout(()=>{if(O)return;if(O=!0,o?.removeEventListener("abort",N),process.platform==="win32")E.kill();else E.kill("SIGTERM");t(Error(`greedy-search child timed out after ${L}ms (watchdog)`))},L);H.unref();let N=()=>{if(O)return;O=!0,clearTimeout(H),E.kill("SIGTERM"),t(Error("Aborted"))};o?.addEventListener("abort",N,{once:!0}),E.stderr.on("data",(v)=>{if(I+=v,I.length>g)I=I.slice(-g);let ni=/^PROGRESS:(perplexity|google|chatgpt|bing|gemini|semantic-scholar|semanticscholar|s2|logically):(done|error|needs-human)$/;for(let j of v.toString().split(`
18
+ `)){let V=j.match(ni);if(V&&u)u({type:"engine",engine:V[1],status:V[2]});let m=j.match(/^PROGRESS:synthesis:(done|error|skipped)$/);if(m&&u)u({type:"engine",engine:"synthesis",status:m[1]});let z=j.match(/^PROGRESS:research:(.+)$/);if(z&&u)u({type:"text",text:z[1]});let B=j.match(/^\[greedysearch\] (\[.+?\] .+)$/);if(B&&u)u({type:"text",text:B[1]});let b=j.match(/^\[(perplexity|google|chatgpt|bing|gemini|semantic-scholar|logically)\] stage: (.+) \(\+\d+ms\)$/);if(b&&u)u({type:"text",text:`${b[1]}: ${b[2]}`})}}),E.stdout.on("data",(v)=>C+=v),E.on("close",(v)=>{if(O)return;if(O=!0,clearTimeout(H),o?.removeEventListener("abort",N),v!==0)t(Error(I.trim()||`search.mjs exited with code ${v}`));else{if(u&&i!=="all")u({type:"engine",engine:i,status:"done"});try{A(JSON.parse(C.trim()))}catch{t(Error(`Invalid JSON from search.mjs: ${C.slice(0,200)}`))}}})})}function Ni(i,n){if(n<=0)return"";let c=16,r=Math.round(i/n*c);return"["+"█".repeat(Math.min(r,c))+"░".repeat(Math.max(0,c-r))+"]"}function yi(i){if(i<1000)return"—";let n=Math.round(i/1000);if(n<60)return`${n}s`;return`${Math.floor(n/60)}m ${n%60}s`}function ii(i,n,c,r,o){let u=Date.now(),l=new Map,A="";function t(){let f=[];f.push(`**${c}...** ${o||""}`.trim());let S=l.size;if(i.length>1&&S>0&&!A){let E=Date.now()-u,C=Math.min(1,S/i.length),I=C>0.01?Math.round(E/C-E):null,g=Ni(S,i.length),O=I!=null&&I>0?yi(I):"—";f.push(`${g} ${S}/${i.length} engines (ETA ${O})`)}if(A)f.push(A);let _=[];for(let E of i){let C=l.get(E);if(C==="done")_.push(`✅ ${E} done`);else if(C==="error")_.push(`❌ ${E} failed`);else if(C==="needs-human")_.push(`\uD83D\uDD13 ${E} needs manual verification`);else _.push(`⏳ ${E}`)}if(r&&S>=i.length){let E=l.get("synthesis");if(E==="done")_.push("✅ synthesized");else if(E==="error")_.push("❌ synthesis failed");else if(E==="needs-human")_.push("⏭️ synthesis skipped");else _.push("\uD83D\uDD04 synthesizing")}if(_.length>0){let E=_.join(" · ");f.push(E.length>90?E.slice(0,88)+"…":E)}n?.({content:[{type:"text",text:f.join(`
19
+ `)}],details:{_progress:!0}})}return(f)=>{if(f.type==="text"){if(f.text.startsWith("["))A=f.text;t();return}let{engine:S,status:_}=f;l.set(S,_),t()}}class h{text;paddingX;paddingY;constructor(i,n=0,c=0){this.text=i;this.paddingX=n;this.paddingY=c}render(i){let n=" ".repeat(this.paddingX),c="",r=Math.max(1,i-this.paddingX*2),o=this.text.split(`
20
+ `).flatMap((u)=>{if(u.length<=r)return[`${n}${u}`];let l=[];for(let A=0;A<u.length;A+=r)l.push(`${n}${u.slice(A,A+r)}`);return l});return[...Array.from({length:this.paddingY},()=>""),...o,...Array.from({length:this.paddingY},()=>"")]}invalidate(){}}function un(i,n){i.registerTool({name:"greedy_search",label:"Greedy Search",description:"WEB/RESEARCH SEARCH ONLY — searches live web via Perplexity, Google AI, ChatGPT, and Gemini, plus opt-in research through Semantic Scholar and Logically. "+"Research mode reuses the configured ~/.dm/greedyconfig engines for child searches and Gemini for planning/final synthesis. Research mode is the centerpiece: it plans follow-up actions, fetches sources, audits citations, and writes a structured research bundle on disk. Scale-aware: simple queries auto-classify and use a fast single-pass path. Use for: library docs, recent framework changes, error messages, best practices, current events. Reports streaming progress as each engine completes.",promptSnippet:"Multi-engine AI web search with streaming progress",parameters:$.Object({query:$.String({description:"The search query"}),engine:$.String({description:'Engine to use: "all" (default), "perplexity", "google", "chatgpt", "gemini", "gem". Research engines: "semantic-scholar" (alias "s2") and "logically". "all" fans out to the configured engines and fetches top sources. Customize via ~/.dm/greedyconfig. Bing Copilot is still available as "bing" for signed-in users.',default:"all"}),synthesize:$.Optional($.Boolean({description:'Only for engine="all": synthesize the multi-engine results and fetched sources. Default: false.',default:!1})),synthesizer:$.Optional($.String({description:'Synthesis engine for synthesize=true. Defaults to ~/.dm/greedyconfig synthesizer (currently "gemini" by default). Supported: "gemini", "chatgpt".'})),depth:$.Optional($.String({description:'Deprecated except "research". Use depth="research" for the iterative research workflow. Research child searches use ~/.dm/greedyconfig engines; Gemini handles research planning/final synthesis. Legacy values: "fast" skips source fetching; "standard"/"deep" alias synthesize=true.'})),breadth:$.Optional($.Number({description:'Only for depth="research": number of parallel research directions per round, 1-5 (default: 3).',default:3})),iterations:$.Optional($.Number({description:'Only for depth="research": number of iterative research rounds, 1-3 (default: 2).',default:2})),maxSources:$.Optional($.Number({description:'Only for depth="research": maximum fetched sources for the final report, 3-12.'})),researchOutDir:$.Optional($.String({description:'Only for depth="research": optional directory for the structured research bundle. Defaults to .dm/greedysearch-research/<timestamp>_<query>.'})),writeResearchBundle:$.Optional($.Boolean({description:'Only for depth="research": write the structured research bundle to disk (default true).',default:!0})),fullAnswer:$.Optional($.Boolean({description:"When true, returns the complete answer instead of a truncated preview (default: false, answers are shortened to ~300 chars to save tokens).",default:!1})),headless:$.Optional($.Boolean({description:"Set to false to show Chrome window (headless is the default). Set GREEDY_SEARCH_VISIBLE=1 to disable headless globally.",default:!0})),visible:$.Optional($.Boolean({description:"Set to true to always use visible Chrome for this search. Alias for headless: false.",default:!1})),alwaysVisible:$.Optional($.Boolean({description:"Set to true to keep GreedySearch in visible Chrome mode for this search. Alias for visible: true.",default:!1}))}),execute:async(c,r,o,u)=>{let{query:l,fullAnswer:A}=r,t=k(r.engine??"all")||"all",f=k(r.depth??""),S=f==="research",_=f==="fast",E=f==="standard"||f==="deep",C=t==="all"&&!_&&(r.synthesize===!0||E),I=S?"all":t,O=!(r.visible===!0||r.alwaysVisible===!0||r.headless===!1||process.env.GREEDY_SEARCH_VISIBLE==="1"||process.env.GREEDY_SEARCH_ALWAYS_VISIBLE==="1");if(!T(n))return d();let R=[];if(A??I!=="all")R.push("--full");if(S){if(R.push("--depth","research"),typeof r.breadth==="number")R.push("--breadth",String(r.breadth));if(typeof r.iterations==="number")R.push("--iterations",String(r.iterations));if(typeof r.maxSources==="number")R.push("--max-sources",String(r.maxSources));if(typeof r.researchOutDir==="string")R.push("--research-out-dir",r.researchOutDir);if(r.writeResearchBundle===!1)R.push("--no-research-bundle")}else if(_)R.push("--fast");else if(f==="deep")R.push("--depth","deep");else if(C)R.push("--synthesize");if(C&&typeof r.synthesizer==="string")R.push("--synthesizer",r.synthesizer);let L=ii(I==="all"?Z:[I],u,S?"Researching":"Searching",C&&I==="all",l);try{let H=await a(I,l,R,`${n}/bin/search.mjs`,o,L,{headless:O});return{content:[{type:"text",text:p(I,H)||"No results returned."}],details:{raw:H}}}catch(H){return q("Search failed",H)}},renderCall(c,r){let o=(c.query||"").slice(0,60),u=o.length<(c.query||"").length?`${o}...`:o,l=c.engine&&c.engine!=="all"?r.fg("dim",` (${c.engine})`):"";return new h(`${r.fg("toolTitle",r.bold("greedy_search"))} "${r.fg("accent",u)}"${l}`,0,0)},renderResult(c,{expanded:r,isPartial:o},u){if(o){let f=c.content.find((_)=>_.type==="text")?.text,S=f?f.replace(/\*\*/g,""):"Searching...";return new h(u.fg("warning",S),0,0)}let l=c.content.find((f)=>f.type==="text"),A=c.details?.raw;if(!r){if(A?._needsHumanVerification)return new h(u.fg("warning"," → Manual verification required"),0,0);let S=A?._synthesis,_=A?._sources;if(S){let g=Array.isArray(_)?_.length:0,O=S.agreement?.level,R=" → Synthesized";if(g>0)R+=` · ${g} source${g>1?"s":""}`;if(O)R+=` · ${O}`;return new h(u.fg("muted",R),0,0)}let E=Object.keys(A||{}).filter((g)=>!g.startsWith("_")),C=0;for(let g of E){let R=A?.[g]?.sources;if(Array.isArray(R))C+=R.length}if(C>0)return new h(u.fg("muted",` → ${C} source${C>1?"s":""}`),0,0);let I=l?.text;if(I)return new h(u.fg("warning",` → ${I.slice(0,80)}`),0,0);return new h(u.fg("muted"," → Done"),0,0)}if(!l||l.type!=="text")return new h("",0,0);let t=l.text.split(`
21
+ `).map((f)=>u.fg("toolOutput",f)).join(`
22
+ `);return new h(`
23
+ ${t}`,0,0)}})}export{un as registerGreedySearchTool};
@@ -1,9 +1,10 @@
1
- import{spawn as V}from"node:child_process";import{existsSync as w}from"node:fs";import{join as K}from"node:path";import{basename as z}from"node:path";function H(l=process.env,i=process.execPath){let r=l.GREEDY_SEARCH_NODE||l.NODE_BINARY||l.NODE;if(r?.trim())return r.trim();let E=z(i||"").toLowerCase();if(E==="node"||E==="node.exe")return i;return"node"}function N(l){let i=String(l??"").trim();if(!i)return null;let r=[i],E=i.indexOf("{"),c=i.lastIndexOf("}");if(E>=0&&c>E)r.push(i.slice(E,c+1));for(let y of r)try{let a=JSON.parse(y);if(a&&typeof a==="object"&&!Array.isArray(a))return a}catch{}return null}function L(l,i={}){let r=N(l);if(!r)return null;return{...r,_process:{...r._process&&typeof r._process==="object"?r._process:{},status:"partial",...i}}}import{existsSync as O,mkdirSync as u,readFileSync as b,writeFileSync as k}from"node:fs";import{homedir as J}from"node:os";import{join as G}from"node:path";import{tmpdir as I}from"node:os";function W(l,i=9222){let r=Number.parseInt(String(l??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:i}var ii=W(process.env.GREEDY_SEARCH_PORT,9222),h=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${I().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),ri=`${h}/DevToolsActivePort`,li=`${I().replaceAll("\\","/")}/cdp-pages.json`,ci=process.env.GREEDY_SEARCH_MODE_FILE||`${I().replaceAll("\\","/")}/greedysearch-chrome-mode`,Ei=`${I().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,S=G(J(),".dm"),g=G(S,"greedyconfig"),D=["perplexity","google","chatgpt"],$="gemini";function Z(){try{if(O(g)){let l=b(g,"utf8"),i=JSON.parse(l);if(Array.isArray(i.engines)&&i.engines.length>0&&i.engines.every((r)=>typeof r==="string")){let r=i.engines.filter((c)=>n[c]),E=i.engines.filter((c)=>!n[c]);if(E.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${g}: ${E.join(", ")}
2
- [greedysearch] Available engines: ${Object.keys(n).join(", ")}
3
- `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${g}, falling back to defaults: ${D.join(", ")}
4
- `)}}}catch{}return D}function v(){try{if(!O(S))u(S,{recursive:!0});if(!O(g))k(g,JSON.stringify({engines:D,synthesizer:$},null,2)+`
5
- `,"utf8")}catch{}}v();var F=["gemini","chatgpt"];function x(){try{if(O(g)){let l=b(g,"utf8"),i=JSON.parse(l);if(typeof i.synthesizer==="string"){let r=i.synthesizer.toLowerCase();if(F.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${i.synthesizer}" in ${g}
6
- [greedysearch] Available synthesizers: ${F.join(", ")}
7
- [greedysearch] Falling back to default: ${$}
8
- `)}}}catch{}return $}var n={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"},U=Z();var ei=x(),ti=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=h;function oi(l){return l.replace(/^"|"$/g,"")}function fi(l){return w(K(l,"bin","cdp.mjs"))}function Oi(){return{content:[{type:"text",text:"cdp.mjs missing — try reinstalling: Rebuild or reinstall DM to refresh the bundled GreedySearch asset."}],details:{}}}function Ii(l,i){let r=i instanceof Error?i.message:String(i);return{content:[{type:"text",text:`${l}: ${r}`}],details:{}}}function pi(l,i,r,E,c,y,a={}){return new Promise((t,e)=>{let{headless:s=!0}=a,p=[...r];if(s!==!1&&process.env.GREEDY_SEARCH_VISIBLE!=="1")p.push("--headless");if(s===!1)p.push("--always-visible");let A={...process.env};if(s===!1)A.GREEDY_SEARCH_VISIBLE="1",A.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let R=V(H(),[E,l,"--inline","--stdin",...p],{stdio:["pipe","pipe","pipe"],env:A});R.stdin.write(i),R.stdin.end();let f="",j="",T=()=>{R.kill("SIGTERM"),e(Error("Aborted"))};c?.addEventListener("abort",T,{once:!0}),R.stderr.on("data",(m)=>{j+=m;let _=/^PROGRESS:(perplexity|google|chatgpt|bing|gemini|semantic-scholar|semanticscholar|s2|logically):(done|error|needs-human)$/;for(let o of m.toString().split(`
9
- `)){let C=o.match(_);if(C&&y)y(C[1],C[2]);let Y=o.match(/^PROGRESS:synthesis:(done|error|skipped)$/);if(Y&&y)y("synthesis",Y[1])}}),R.stdout.on("data",(m)=>f+=m),R.on("close",(m)=>{if(c?.removeEventListener("abort",T),m!==0){let _=j.trim()||`search.mjs exited with code ${m}`,o=L(f,{code:m,error:_});if(o){t(o);return}e(Error(_))}else{let _=N(f);if(_)t(_);else e(Error(`Invalid JSON from search.mjs: ${f.slice(0,200)}`))}})})}function Ai(l,i,r,E){let c=new Map;return(y,a)=>{c.set(y,a);let t=[];for(let e of l){let s=c.get(e);if(s==="done")t.push(`✅ ${e} done`);else if(s==="error")t.push(`❌ ${e} failed`);else if(s==="needs-human")t.push(`\uD83D\uDD13 ${e} needs manual verification`);else t.push(`⏳ ${e}`)}if(E&&c.size>=l.length){let e=c.get("synthesis");if(e==="done")t.push("✅ synthesized");else if(e==="error")t.push("❌ synthesis failed");else if(e==="needs-human")t.push("⏭️ synthesis skipped");else t.push("\uD83D\uDD04 synthesizing")}i?.({content:[{type:"text",text:`**${r}...** ${t.join(" · ")}`}],details:{_progress:!0}})}}export{oi as stripQuotes,pi as runSearch,Ai as makeProgressTracker,Ii as errorResult,Oi as cdpMissingResult,fi as cdpAvailable,U as ALL_ENGINES};
1
+ import{spawn as d}from"node:child_process";import{basename as x}from"node:path";function Z(E=process.env,_=process.execPath){let R=E.GREEDY_SEARCH_NODE||E.NODE_BINARY||E.NODE;if(R?.trim())return R.trim();let D=x(_||"").toLowerCase();if(D==="node"||D==="node.exe")return _;return"node"}import{existsSync as e}from"node:fs";import{join as EE}from"node:path";import{existsSync as g,mkdirSync as B,readFileSync as Q,writeFileSync as a}from"node:fs";import{homedir as h}from"node:os";import{join as q}from"node:path";import{tmpdir as P}from"node:os";function u(E,_=9222){let R=Number.parseInt(String(E??""),10);return Number.isInteger(R)&&R>1024&&R<65535?R:_}var M=P().replaceAll("\\","/"),AE=u(process.env.GREEDY_SEARCH_PORT),m=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${M}/greedysearch-chrome-profile`).replaceAll("\\","/"),mE=`${m}/DevToolsActivePort`,lE=process.env.GREEDY_SEARCH_PID_FILE||`${m}/browser.pid`,SE=process.env.CDP_PAGES_CACHE||`${m}/cdp-pages.json`,OE=process.env.GREEDY_SEARCH_MODE_FILE||`${m}/browser-mode`,YE=process.env.GREEDY_SEARCH_METADATA_FILE||`${m}/browser-metadata.json`,LE=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${m}/browser-launch.lock`,NE=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${m}/browser-last-activity`,GE=(process.env.CDP_SOCKET_DIR||`${m}/cdp-sockets`).replaceAll("\\","/"),$E=`${m}/visible-recovery.jsonl`,k=q(h(),".dm"),O=q(k,"greedyconfig"),z=["perplexity","google","chatgpt","gemini"],f="gemini";function o(){try{if(g(O)){let E=Q(O,"utf8"),_=JSON.parse(E);if(Array.isArray(_.engines)&&_.engines.length>0&&_.engines.every((R)=>typeof R==="string")){let R=_.engines.filter((l)=>b[l]),D=_.engines.filter((l)=>!b[l]);if(D.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${O}: ${D.join(", ")}
2
+ [greedysearch] Available engines: ${Object.keys(b).join(", ")}
3
+ `);if(R.length>0)return R;process.stderr.write(`[greedysearch] Warning: no valid engines in ${O}, falling back to defaults: ${z.join(", ")}
4
+ `)}}}catch{}return z}function t(){try{if(!g(k))B(k,{recursive:!0});if(!g(O))a(O,JSON.stringify({engines:z,synthesizer:f},null,2)+`
5
+ `,"utf8")}catch{}}t();var W=["gemini","chatgpt"];function s(){try{if(g(O)){let E=Q(O,"utf8"),_=JSON.parse(E);if(typeof _.synthesizer==="string"){let R=_.synthesizer.toLowerCase();if(W.includes(R))return R;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${_.synthesizer}" in ${O}
6
+ [greedysearch] Available synthesizers: ${W.join(", ")}
7
+ [greedysearch] Falling back to default: ${f}
8
+ `)}}}catch{}return f}var b={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},n=o();var HE=s(),FE=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=m;function kE(E){return E.replace(/^"|"$/g,"")}function zE(E){return e(EE(E,"bin","cdp.mjs"))}function fE(){return{content:[{type:"text",text:"cdp.mjs missing — try reinstalling: pi install git:github.com/apmantza/greedysearch-dm"}],details:{}}}function wE(E,_){let R=_ instanceof Error?_.message:String(_);return{content:[{type:"text",text:`${E}: ${R}`}],details:{}}}function VE(E,_,R,D,l,c,G={}){return new Promise(($,L)=>{let{headless:i=!0}=G,y=[...R];if(i!==!1&&process.env.GREEDY_SEARCH_VISIBLE!=="1")y.push("--headless");if(i===!1)y.push("--always-visible");let C={...process.env};if(i===!1)C.GREEDY_SEARCH_VISIBLE="1",C.GREEDY_SEARCH_ALWAYS_VISIBLE="1";let I=d(Z(),[D,E,"--inline","--stdin",...y],{stdio:["pipe","pipe","pipe"],env:C});I.stdin.write(_),I.stdin.end();let A="",S="",F=51200,Y=!1,X=900000,w=parseInt(process.env.GREEDY_SEARCH_TIMEOUT_MS||"",10),V=Number.isNaN(w)?X:w,T=setTimeout(()=>{if(Y)return;if(Y=!0,l?.removeEventListener("abort",v),process.platform==="win32")I.kill();else I.kill("SIGTERM");L(Error(`greedy-search child timed out after ${V}ms (watchdog)`))},V);T.unref();let v=()=>{if(Y)return;Y=!0,clearTimeout(T),I.kill("SIGTERM"),L(Error("Aborted"))};l?.addEventListener("abort",v,{once:!0}),I.stderr.on("data",(N)=>{if(S+=N,S.length>F)S=S.slice(-F);let r=/^PROGRESS:(perplexity|google|chatgpt|bing|gemini|semantic-scholar|semanticscholar|s2|logically):(done|error|needs-human)$/;for(let H of N.toString().split(`
9
+ `)){let p=H.match(r);if(p&&c)c({type:"engine",engine:p[1],status:p[2]});let K=H.match(/^PROGRESS:synthesis:(done|error|skipped)$/);if(K&&c)c({type:"engine",engine:"synthesis",status:K[1]});let J=H.match(/^PROGRESS:research:(.+)$/);if(J&&c)c({type:"text",text:J[1]});let U=H.match(/^\[greedysearch\] (\[.+?\] .+)$/);if(U&&c)c({type:"text",text:U[1]});let j=H.match(/^\[(perplexity|google|chatgpt|bing|gemini|semantic-scholar|logically)\] stage: (.+) \(\+\d+ms\)$/);if(j&&c)c({type:"text",text:`${j[1]}: ${j[2]}`})}}),I.stdout.on("data",(N)=>A+=N),I.on("close",(N)=>{if(Y)return;if(Y=!0,clearTimeout(T),l?.removeEventListener("abort",v),N!==0)L(Error(S.trim()||`search.mjs exited with code ${N}`));else{if(c&&E!=="all")c({type:"engine",engine:E,status:"done"});try{$(JSON.parse(A.trim()))}catch{L(Error(`Invalid JSON from search.mjs: ${A.slice(0,200)}`))}}})})}function _E(E,_){if(_<=0)return"";let R=16,D=Math.round(E/_*R);return"["+"█".repeat(Math.min(D,R))+"░".repeat(Math.max(0,R-D))+"]"}function RE(E){if(E<1000)return"—";let _=Math.round(E/1000);if(_<60)return`${_}s`;return`${Math.floor(_/60)}m ${_%60}s`}function KE(E,_,R,D,l){let c=Date.now(),G=new Map,$="";function L(){let i=[];i.push(`**${R}...** ${l||""}`.trim());let y=G.size;if(E.length>1&&y>0&&!$){let I=Date.now()-c,A=Math.min(1,y/E.length),S=A>0.01?Math.round(I/A-I):null,F=_E(y,E.length),Y=S!=null&&S>0?RE(S):"—";i.push(`${F} ${y}/${E.length} engines (ETA ${Y})`)}if($)i.push($);let C=[];for(let I of E){let A=G.get(I);if(A==="done")C.push(`✅ ${I} done`);else if(A==="error")C.push(`❌ ${I} failed`);else if(A==="needs-human")C.push(`\uD83D\uDD13 ${I} needs manual verification`);else C.push(`⏳ ${I}`)}if(D&&y>=E.length){let I=G.get("synthesis");if(I==="done")C.push("✅ synthesized");else if(I==="error")C.push("❌ synthesis failed");else if(I==="needs-human")C.push("⏭️ synthesis skipped");else C.push("\uD83D\uDD04 synthesizing")}if(C.length>0){let I=C.join(" · ");i.push(I.length>90?I.slice(0,88)+"…":I)}_?.({content:[{type:"text",text:i.join(`
10
+ `)}],details:{_progress:!0}})}return(i)=>{if(i.type==="text"){if(i.text.startsWith("["))$=i.text;L();return}let{engine:y,status:C}=i;G.set(y,C),L()}}export{kE as stripQuotes,VE as runSearch,KE as makeProgressTracker,wE as errorResult,fE as cdpMissingResult,zE as cdpAvailable,n as ALL_ENGINES};
@@ -1 +1 @@
1
- import{basename as E}from"node:path";function H(q=process.env,z=process.execPath){let A=q.GREEDY_SEARCH_NODE||q.NODE_BINARY||q.NODE;if(A?.trim())return A.trim();let B=E(z||"").toLowerCase();if(B==="node"||B==="node.exe")return z;return"node"}export{H as nodeRuntimeCommand};
1
+ import{basename as B}from"node:path";function E(k=process.env,q=process.execPath){let w=k.GREEDY_SEARCH_NODE||k.NODE_BINARY||k.NODE;if(w?.trim())return w.trim();let z=B(q||"").toLowerCase();if(z==="node"||z==="node.exe")return q;return"node"}export{E as nodeRuntimeCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duckmind/dm-darwin-x64",
3
- "version": "0.52.6",
3
+ "version": "0.53.4",
4
4
  "description": "DuckMind (dm) binary payload for darwin x64",
5
5
  "license": "MIT",
6
6
  "os": [
@@ -1,3 +0,0 @@
1
- import{existsSync as g,mkdirSync as N,readFileSync as $,renameSync as V,unlinkSync as D,writeFileSync as q}from"node:fs";import M from"node:http";import{platform as A}from"node:os";import{dirname as R}from"node:path";var B=[9222,9223],_=/^(0|false|no|off)$/i;function b(j){return[...new Set(j.filter(Boolean))]}function u(j,z="localhost"){let G=String(j||"").trim().split(/\r?\n/).map((Q)=>Q.trim()).filter(Boolean);if(G.length===0)throw Error("empty DevToolsActivePort");let[I,J=""]=G;if(/^wss?:\/\//i.test(I))return I;if(I.includes(":"))return`ws://${I}${J}`;return`ws://${z}:${I}${J}`}function W(j,z="explicit"){let G=new URL(j),I=G.protocol==="wss:"?"wss:":"ws:",J=G.port?Number.parseInt(G.port,10):I==="wss:"?443:80;return{source:z,wsUrl:`${I}//${G.host}${G.pathname}${G.search}`,host:G.hostname,port:J,path:`${G.pathname}${G.search}`,httpUrl:`http://${G.hostname}:${J}`}}function H(j=process.env){return![j.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,j.DM_CUA_REUSE_EXISTING_BROWSER].some((z)=>z!==void 0&&_.test(String(z)))}function O(j){let z=Number.parseInt(String(j??""),10);return Number.isInteger(z)&&z>0&&z<65536?z:null}function U(j){if(!j)return null;let z=String(j).trim();if(!z)return null;let G=new URL(z.includes("://")?z:`http://${z}`),I=O(G.port)||(G.protocol==="https:"?443:80);return{host:G.hostname,port:I,source:`env:${z}`}}function C(j){if(!j)return[];return String(j).split(/[,\s]+/).map(O).filter(Boolean)}function T({env:j=process.env,platformName:z=A(),procVersionText:G=null}={}){if(z!=="linux")return!1;if(j.WSL_DISTRO_NAME||j.WSL_INTEROP)return!0;let I=G??(()=>{try{return $("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(I)}function E({env:j=process.env,platformName:z=A(),procVersionText:G=null,resolvConfText:I=null}={}){let J=["localhost","127.0.0.1"];if(T({env:j,platformName:z,procVersionText:G})){let Y=(I??(()=>{try{return $("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(Y)J.push(Y[1]);J.push("host.docker.internal")}return b(J)}function S({env:j=process.env,hosts:z=E({env:j}),autoPorts:G=B,excludePorts:I=[]}={}){let J=[];for(let K of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(j[K])J.push({wsUrl:j[K],source:`env:${K}`});for(let K of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let X=U(j[K]);if(X)J.push(X)}catch{}for(let K of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let X=O(j[K]);if(!X)continue;for(let L of z)J.push({host:L,port:X,source:`env:${K}`})}let Q=C(j.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let K of Q)for(let X of z)J.push({host:X,port:K,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let Y=new Set(I.filter(Boolean));if(H(j))for(let K of G){if(Y.has(K))continue;for(let X of z)J.push({host:X,port:K,source:"auto"})}let Z=new Set;return J.filter((K)=>{let X=K.wsUrl||`${K.host}:${K.port}`;if(Z.has(X))return!1;return Z.add(X),!0})}async function k(j,{timeoutMs:z=700}={}){if(j.wsUrl)return W(j.wsUrl,j.source);let G=j.host||"localhost",I=j.port;if(!I)return null;let J=await new Promise((Q)=>{let Y=M.get({host:G,port:I,path:"/json/version",timeout:z},(Z)=>{let K="";Z.setEncoding("utf8"),Z.on("data",(X)=>K+=X),Z.on("end",()=>Q(Z.statusCode===200?K:null))});Y.on("error",()=>Q(null)),Y.setTimeout(z,()=>{Y.destroy(),Q(null)})});if(!J)return null;try{let Q=JSON.parse(J);if(!Q.webSocketDebuggerUrl)return null;let Y=W(Q.webSocketDebuggerUrl,j.source),Z=Y.path||new URL(Q.webSocketDebuggerUrl).pathname;return{...Y,host:G,port:I,httpUrl:`http://${G}:${I}`,wsUrl:`ws://${G}:${I}${Z}`,path:Z}}catch{return null}}async function w(j={}){for(let z of S(j)){let G=await k(z,j);if(G)return G}return null}function f(j){if(!j)throw Error("missing CDP endpoint");let z=new URL(j.wsUrl);return`${z.host}
2
- ${z.pathname}${z.search}
3
- `}function x(j,z){N(R(j),{recursive:!0});let G=`${j}.tmp-${process.pid}`;q(G,f(z),"utf8");try{D(j)}catch{}V(G,j)}async function v({activePortFile:j,modeFile:z,env:G=process.env,excludePorts:I=[],autoPorts:J=B}={}){if(!H(G))return null;let Q=await w({env:G,excludePorts:I,autoPorts:J});if(!Q)return null;if(x(j,Q),z)q(z,"existing","utf8");return Q}function y(j){return String(j||"").trim()==="existing"}function c(j,z){if(!z||!g(z))return!1;if(!y($(z,"utf8")))return!1;return!!j&&g(j)}export{x as writeActivePortFile,k as probeCdpEndpoint,u as parseActivePortText,T as isWslEnvironment,y as isExistingBrowserMode,H as isBrowserReuseEnabled,w as findExistingBrowserEndpoint,W as endpointFromWsUrl,E as cdpHostCandidates,S as cdpDiscoveryCandidates,f as activePortPayload,c as activePortFilePointsToExistingBrowser,v as activateExistingBrowserEndpoint};
@@ -1,3 +0,0 @@
1
- import{existsSync as H}from"node:fs";import{dirname as I,join as B}from"node:path";function J(b){let w=new Set;return b.filter((z)=>{if(!z||w.has(z))return!1;return w.add(z),!0})}function K({moduleDir:b,entrypoint:w=process.argv[1],env:z=process.env}={}){let A=w?I(w):null,E=z.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return J([E?B(E,"bin","launch.mjs"):null,b?B(b,"launch.mjs"):null,b?B(b,"..","bin","launch.mjs"):null,b?B(b,"..","..","bin","launch.mjs"):null,A?B(A,"launch.mjs"):null,A?B(A,"..","bin","launch.mjs"):null])}function N({moduleDir:b,entrypoint:w=process.argv[1],env:z=process.env,exists:A=H}={}){let E=K({moduleDir:b,entrypoint:w,env:z}),G=E.find((F)=>A(F));if(G)return G;throw Error(`GreedySearch launcher not found. Checked candidates:
2
- ${E.map((F)=>`- ${F}`).join(`
3
- `)}`)}export{N as resolveGreedySearchLauncherScript,K as launcherCandidates};
@@ -1 +0,0 @@
1
- function o(s){let r=String(s??"").trim();if(!r)return null;let e=[r],c=r.indexOf("{"),a=r.lastIndexOf("}");if(c>=0&&a>c)e.push(r.slice(c,a+1));for(let n of e)try{let t=JSON.parse(n);if(t&&typeof t==="object"&&!Array.isArray(t))return t}catch{}return null}function i(s,r={}){let e=o(s);if(!e)return null;return{...e,_process:{...e._process&&typeof e._process==="object"?e._process:{},status:"partial",...r}}}export{i as preservePartialSearchResult,o as parseSearchJsonOutput};
@@ -1 +0,0 @@
1
- import{existsSync as c}from"node:fs";import{platform as s}from"node:os";function C(o=s()){if(o==="win32")return{cloak:["C:/Program Files/CloakBrowser/CloakBrowser.exe","C:/Program Files (x86)/CloakBrowser/CloakBrowser.exe"],chrome:["C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"]};if(o==="darwin")return{cloak:["/Applications/CloakBrowser.app/Contents/MacOS/CloakBrowser","/Applications/Cloak Browser.app/Contents/MacOS/CloakBrowser"],chrome:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]};return{cloak:["/usr/bin/cloakbrowser","/usr/local/bin/cloakbrowser","/opt/CloakBrowser/CloakBrowser"],chrome:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"]}}function l(o,e=c){return o.find((r)=>r&&e(r))||null}function p(o,e){for(let r of e){let a=o[r]?.trim();if(a)return{key:r,path:a}}return null}function m(o,e){if(o==="chrome"||e==="CHROME_PATH")return"Chrome";if(o==="cloak"||e==="DM_CUA_CLOAK_PATH"||e==="CLOAKBROWSER_BINARY_PATH")return"CloakBrowser";return"browser"}function _({env:o=process.env,platformName:e=s(),exists:r=c}={}){let a=(o.GREEDY_SEARCH_BROWSER||o.DM_CUA_BROWSER||"auto").toLowerCase(),n=p(o,a==="chrome"?["GREEDY_SEARCH_BROWSER_PATH","DM_CUA_BROWSER_PATH","CHROME_PATH"]:["GREEDY_SEARCH_BROWSER_PATH","DM_CUA_BROWSER_PATH","DM_CUA_CLOAK_PATH","CLOAKBROWSER_BINARY_PATH","CHROME_PATH"]);if(n)return{path:n.path,label:m(a,n.key)};let t=C(e);if(a==="cloak")return{path:l(t.cloak,r),label:"CloakBrowser"};if(a==="chrome")return{path:l(t.chrome,r),label:"Chrome"};let i=l(t.cloak,r);return{path:i||l(t.chrome,r),label:i?"CloakBrowser":"Chrome"}}export{_ as resolveBrowser,l as firstExisting,C as browserCandidates};