@duckmind/dm-darwin-x64 0.52.6 → 0.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dm +0 -0
- package/extensions/.dm-extensions.json +14 -10
- package/extensions/dm-cua/bin/browser-cua.mjs +6 -6
- package/extensions/dm-cua/index.js +5 -5
- package/extensions/dm-cua/src/browser-cua-lib.mjs +2 -2
- package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +8 -1
- package/extensions/greedysearch-dm/bin/cdp-headless.mjs +1 -1
- package/extensions/greedysearch-dm/bin/cdp-visible.mjs +1 -1
- package/extensions/greedysearch-dm/bin/cdp.mjs +29 -20
- package/extensions/greedysearch-dm/bin/gschrome.mjs +1 -8
- package/extensions/greedysearch-dm/bin/kill-visible.mjs +1 -1
- package/extensions/greedysearch-dm/bin/launch-visible.mjs +1 -2
- package/extensions/greedysearch-dm/bin/launch.mjs +9 -11
- package/extensions/greedysearch-dm/bin/mcp.mjs +375 -0
- package/extensions/greedysearch-dm/bin/search.mjs +309 -157
- package/extensions/greedysearch-dm/bin/visible.mjs +1 -1
- package/extensions/greedysearch-dm/extractors/bing-copilot.mjs +205 -68
- package/extensions/greedysearch-dm/extractors/chatgpt.mjs +229 -140
- package/extensions/greedysearch-dm/extractors/common.mjs +160 -50
- package/extensions/greedysearch-dm/extractors/consensus.mjs +226 -93
- package/extensions/greedysearch-dm/extractors/consent.mjs +44 -17
- package/extensions/greedysearch-dm/extractors/gemini.mjs +277 -138
- package/extensions/greedysearch-dm/extractors/google-ai.mjs +172 -64
- package/extensions/greedysearch-dm/extractors/logically.mjs +183 -69
- package/extensions/greedysearch-dm/extractors/perplexity.mjs +331 -65
- package/extensions/greedysearch-dm/extractors/semantic-scholar.mjs +118 -41
- package/extensions/greedysearch-dm/index.js +23 -20
- package/extensions/greedysearch-dm/package.json +8 -3
- package/extensions/greedysearch-dm/skills/greedy-search/skill.md +8 -8
- package/extensions/greedysearch-dm/src/fetcher.mjs +2 -2
- package/extensions/greedysearch-dm/src/formatters/results.js +8 -6
- package/extensions/greedysearch-dm/src/github.mjs +7 -7
- package/extensions/greedysearch-dm/src/reddit.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +10 -8
- package/extensions/greedysearch-dm/src/search/challenge-detect.mjs +48 -0
- package/extensions/greedysearch-dm/src/search/chrome.mjs +130 -54
- package/extensions/greedysearch-dm/src/search/constants.mjs +6 -6
- package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
- package/extensions/greedysearch-dm/src/search/fetch-source.mjs +160 -83
- package/extensions/greedysearch-dm/src/search/minimize.mjs +1 -0
- package/extensions/greedysearch-dm/src/search/paths.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/pdf.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/progress.mjs +2 -0
- package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/research.mjs +262 -167
- package/extensions/greedysearch-dm/src/search/scale-aware.mjs +11 -0
- package/extensions/greedysearch-dm/src/search/simple-research.mjs +827 -0
- package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +9 -9
- package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
- package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +23 -20
- package/extensions/greedysearch-dm/src/tools/shared.js +10 -9
- package/extensions/greedysearch-dm/src/utils/node-runtime.mjs +1 -1
- package/package.json +1 -1
- package/extensions/greedysearch-dm/src/search/cdp-endpoint.mjs +0 -3
- package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +0 -3
- package/extensions/greedysearch-dm/src/search/partial-output.mjs +0 -1
- package/extensions/greedysearch-dm/src/utils/browser-executable.mjs +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
[greedysearch] Available engines: ${Object.keys(
|
|
3
|
-
`);if(i.length>0)return i;process.stderr.write(`[greedysearch] Warning: no valid engines in ${
|
|
4
|
-
`)}}}catch{}return
|
|
5
|
-
`,"utf8")}catch{}}
|
|
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: ${
|
|
8
|
-
`)}}}catch{}return
|
|
9
|
-
`)e+="\\n";else if(i&&o==="\r")e+="\\r";else if(i&&o==="\t")e+="\\t";else e+=o}return e}function
|
|
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
|
-
`)}
|
|
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
|
|
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 ${
|
|
4
|
-
`)}}}catch{}return E}function
|
|
5
|
-
`,"utf8")}catch{}}
|
|
6
|
-
[greedysearch] Available synthesizers: ${
|
|
7
|
-
[greedysearch] Falling back to default: ${
|
|
8
|
-
`)}}}catch{}return
|
|
9
|
-
`)e+="\\n";else if(i&&n==="\r")e+="\\r";else if(i&&n==="\t")e+="\\t";else e+=n}return e}function
|
|
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(
|
|
12
|
-
`)}function
|
|
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
|
|
2
|
-
|
|
3
|
-
`),r.join(`
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`).trim()}
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`);if(n.length>0)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
[
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`)
|
|
18
|
-
`).
|
|
19
|
-
`);return
|
|
20
|
-
${
|
|
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
|
|
2
|
-
[greedysearch] Available engines: ${Object.keys(
|
|
3
|
-
`);if(
|
|
4
|
-
`)}}}catch{}return
|
|
5
|
-
`,"utf8")}catch{}}
|
|
6
|
-
[greedysearch] Available synthesizers: ${
|
|
7
|
-
[greedysearch] Falling back to default: ${
|
|
8
|
-
`)}}}catch{}return
|
|
9
|
-
`)){let
|
|
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
|
|
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,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};
|