@duckmind/dm-darwin-arm64 0.52.3 → 0.52.6
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 +6 -3
- package/extensions/greedysearch-dm/bin/gschrome.mjs +5 -7
- package/extensions/greedysearch-dm/bin/launch-visible.mjs +2 -4
- package/extensions/greedysearch-dm/bin/launch.mjs +11 -5
- package/extensions/greedysearch-dm/bin/search.mjs +122 -120
- package/extensions/greedysearch-dm/extractors/consensus.mjs +43 -43
- package/extensions/greedysearch-dm/extractors/gemini.mjs +44 -44
- package/extensions/greedysearch-dm/extractors/logically.mjs +41 -41
- package/extensions/greedysearch-dm/index.js +18 -18
- package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +8 -9
- package/extensions/greedysearch-dm/src/search/chrome.mjs +25 -25
- package/extensions/greedysearch-dm/src/search/constants.mjs +8 -8
- package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
- package/extensions/greedysearch-dm/src/search/fetch-source.mjs +49 -49
- package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +3 -0
- package/extensions/greedysearch-dm/src/search/partial-output.mjs +1 -0
- package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -0
- package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
- package/extensions/greedysearch-dm/src/search/research.mjs +101 -101
- package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +11 -11
- package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
- package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +18 -18
- package/extensions/greedysearch-dm/src/tools/shared.js +9 -9
- package/package.json +1 -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 ${E}, falling back to defaults: ${
|
|
4
|
-
`)}}}catch{}return
|
|
5
|
-
`,"utf8")}catch{}}
|
|
6
|
-
[greedysearch] Available synthesizers: ${
|
|
7
|
-
[greedysearch] Falling back to default: ${
|
|
8
|
-
`)}}}catch{}return
|
|
9
|
-
`)e+="\\n";else if(i&&
|
|
10
|
-
${JSON.stringify(
|
|
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}
|
|
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:
|
|
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
|
|
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};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{existsSync as m,mkdirSync as C,readFileSync 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{}}
|
|
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
|
|
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(", ")}
|
|
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:
|
|
10
10
|
${JSON.stringify(n,null,2)}`,"",`Source registry:
|
|
11
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
|
|
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};
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import{Type as
|
|
2
|
-
`:`*Synthesized by ${
|
|
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
3
|
`),r.join(`
|
|
4
|
-
`).trim()}for(let[
|
|
5
|
-
## ${
|
|
6
|
-
`).trim()}function
|
|
7
|
-
`).trim()}function
|
|
8
|
-
Sources:`);for(let c of
|
|
9
|
-
[greedysearch] Available engines: ${Object.keys(
|
|
10
|
-
`);if(
|
|
11
|
-
`)}}}catch{}return
|
|
12
|
-
`,"utf8")}catch{}}
|
|
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
13
|
[greedysearch] Available synthesizers: ${W.join(", ")}
|
|
14
|
-
[greedysearch] Falling back to default: ${
|
|
15
|
-
`)}}}catch{}return
|
|
16
|
-
`)){let
|
|
17
|
-
`).flatMap((
|
|
18
|
-
`).map((
|
|
19
|
-
`);return new
|
|
20
|
-
${
|
|
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,9 +1,9 @@
|
|
|
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 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};
|