@duckmind/dm-darwin-x64 0.48.5 → 0.49.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.
Files changed (97) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +159 -220
  3. package/extensions/dm-9router-ext/package.json +0 -6
  4. package/extensions/dm-9router-ext/src/index.js +1 -1
  5. package/extensions/dm-ask-user/package.json +0 -4
  6. package/extensions/dm-caveman/extensions/caveman.js +29 -0
  7. package/extensions/dm-caveman/package.json +20 -0
  8. package/extensions/dm-cli-anything/index.js +5 -5
  9. package/extensions/dm-cli-anything/package.json +0 -7
  10. package/extensions/dm-cli-anything/skills/cli-anything/SKILL.md +1 -3
  11. package/extensions/dm-context/package.json +0 -1
  12. package/extensions/dm-cua/package.json +0 -7
  13. package/extensions/dm-fff/package.json +0 -6
  14. package/extensions/dm-goal/package.json +0 -8
  15. package/extensions/dm-grill-me/index.js +2 -2
  16. package/extensions/dm-grill-me/package.json +0 -7
  17. package/extensions/dm-image2/package.json +0 -8
  18. package/extensions/dm-subagents/.m/artifacts/shell/shell_output_1783845384621_9cf9262bf674.txt +1336 -0
  19. package/extensions/dm-subagents/.m/artifacts/shell/shell_output_1783846154938_6a41cefee0bf.txt +1336 -0
  20. package/extensions/dm-subagents/package.json +0 -11
  21. package/extensions/dm-subagents/src/extension/doctor.js +10 -10
  22. package/extensions/dm-subagents/src/extension/fanout-child.js +97 -97
  23. package/extensions/dm-subagents/src/extension/index.js +121 -121
  24. package/extensions/dm-subagents/src/extension/rpc.js +5 -5
  25. package/extensions/dm-subagents/src/extension/schemas.js +1 -1
  26. package/extensions/dm-subagents/src/extension/tool-description.js +2 -2
  27. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -5
  28. package/extensions/dm-subagents/src/runs/background/async-execution.js +19 -19
  29. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +9 -9
  30. package/extensions/dm-subagents/src/runs/background/async-resume.js +5 -5
  31. package/extensions/dm-subagents/src/runs/background/async-status.js +8 -8
  32. package/extensions/dm-subagents/src/runs/background/fleet-view.js +13 -13
  33. package/extensions/dm-subagents/src/runs/background/result-watcher.js +5 -5
  34. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +3 -3
  35. package/extensions/dm-subagents/src/runs/background/run-status.js +19 -19
  36. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +7 -7
  37. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +35 -35
  38. package/extensions/dm-subagents/src/runs/background/wait.js +7 -7
  39. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +32 -32
  40. package/extensions/dm-subagents/src/runs/foreground/execution.js +26 -26
  41. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +96 -96
  42. package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -1
  43. package/extensions/dm-subagents/src/runs/shared/nested-events.js +6 -6
  44. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -13
  45. package/extensions/dm-subagents/src/shared/fork-context.js +4 -4
  46. package/extensions/dm-tasks/package.json +0 -7
  47. package/extensions/dm-usage/package.json +0 -7
  48. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +1 -8
  49. package/extensions/greedysearch-dm/bin/gschrome.mjs +3 -3
  50. package/extensions/greedysearch-dm/bin/launch-visible.mjs +3 -3
  51. package/extensions/greedysearch-dm/bin/launch.mjs +4 -4
  52. package/extensions/greedysearch-dm/bin/search.mjs +103 -103
  53. package/extensions/greedysearch-dm/extractors/consensus.mjs +35 -35
  54. package/extensions/greedysearch-dm/extractors/gemini.mjs +38 -38
  55. package/extensions/greedysearch-dm/extractors/logically.mjs +35 -35
  56. package/extensions/greedysearch-dm/package.json +0 -10
  57. package/extensions/greedysearch-dm/src/search/chrome.mjs +23 -23
  58. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +35 -35
  59. package/extensions/greedysearch-dm/src/search/research.mjs +61 -61
  60. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +4 -4
  61. package/package.json +1 -1
  62. package/extensions/dm-9router-ext/README.md +0 -142
  63. package/extensions/dm-9router-ext/tsconfig.json +0 -17
  64. package/extensions/dm-ask-user/README.md +0 -226
  65. package/extensions/dm-cli-anything/LICENSE +0 -201
  66. package/extensions/dm-cli-anything/README.md +0 -33
  67. package/extensions/dm-cli-anything/vendor/UPSTREAM.md +0 -14
  68. package/extensions/dm-context/AGENTS.md +0 -41
  69. package/extensions/dm-context/README.md +0 -18
  70. package/extensions/dm-context/tsconfig.json +0 -16
  71. package/extensions/dm-cua/README.md +0 -24
  72. package/extensions/dm-fff/README.md +0 -36
  73. package/extensions/dm-fff/tsconfig.json +0 -13
  74. package/extensions/dm-goal/CHANGELOG.md +0 -12
  75. package/extensions/dm-goal/LICENSE +0 -21
  76. package/extensions/dm-goal/README.md +0 -29
  77. package/extensions/dm-goal/tsconfig.json +0 -15
  78. package/extensions/dm-grill-me/DESIGN.md +0 -301
  79. package/extensions/dm-grill-me/LICENSE +0 -21
  80. package/extensions/dm-grill-me/README.md +0 -82
  81. package/extensions/dm-grill-me/tsconfig.json +0 -17
  82. package/extensions/dm-image2/README.md +0 -33
  83. package/extensions/dm-subagents/CHANGELOG.md +0 -1211
  84. package/extensions/dm-subagents/README.md +0 -29
  85. package/extensions/dm-subagents/banner.png +0 -0
  86. package/extensions/dm-subagents/biome.json +0 -26
  87. package/extensions/dm-subagents/tsconfig.json +0 -18
  88. package/extensions/dm-tasks/LICENSE +0 -21
  89. package/extensions/dm-tasks/README.md +0 -30
  90. package/extensions/dm-tasks/biome.json +0 -26
  91. package/extensions/dm-tasks/tsconfig.json +0 -14
  92. package/extensions/dm-usage/LICENSE +0 -21
  93. package/extensions/dm-usage/README.md +0 -29
  94. package/extensions/dm-usage/insights-screenshot.png +0 -0
  95. package/extensions/dm-usage/screenshot.png +0 -0
  96. package/extensions/greedysearch-dm/LICENSE +0 -21
  97. package/extensions/greedysearch-dm/README.md +0 -222
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_process";import{dirname as ue,join as le}from"node:path";import{fileURLToPath as ae}from"node:url";import{basename as fe}from"node:path";function ce(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=fe(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}var ge=ue(ae(import.meta.url)),se=le(ge,"..","bin","cdp.mjs");function g(t,e=30000){return G(t,null,e)}function G(t,e=null,n=30000){return new Promise((r,i)=>{let o=oe(ce(),[se,...t],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)o.stdin.write(e),o.stdin.end();let u="",a="";o.stdout.on("data",(f)=>u+=f),o.stderr.on("data",(f)=>a+=f);let l=setTimeout(()=>{o.kill(),i(Error(`cdp timeout: ${t[0]}`))},n);o.on("close",(f)=>{if(clearTimeout(l),f===0)r(u.trim());else i(Error(a.trim()||`cdp exit ${f}`))})})}async function bt(t){if(t)return t;let e=(await g(["list"])).split(`
3
- `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await g(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),{targetId:r}=JSON.parse(n);await g(["list"]);let i=r.slice(0,8);try{await yt(i)}catch(o){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${o.message}
4
- `)}return i}async function ht(t,e){let n=`
2
+ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_process";import{dirname as oe,join as ue}from"node:path";import{fileURLToPath as le}from"node:url";import{basename as ae}from"node:path";function fe(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=ae(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}var ce=oe(le(import.meta.url)),ge=ue(ce,"..","bin","cdp.mjs");function g(t,e=30000){return G(t,null,e)}function G(t,e=null,n=30000){return new Promise((r,i)=>{let o=ie(fe(),[ge,...t],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)o.stdin.write(e),o.stdin.end();let u="",a="";o.stdout.on("data",(f)=>u+=f),o.stderr.on("data",(f)=>a+=f);let l=setTimeout(()=>{o.kill(),i(Error(`cdp timeout: ${t[0]}`))},n);o.on("close",(f)=>{if(clearTimeout(l),f===0)r(u.trim());else i(Error(a.trim()||`cdp exit ${f}`))})})}async function st(t){if(t)return t;let e=(await g(["list"])).split(`
3
+ `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await g(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),{targetId:r}=JSON.parse(n);await g(["list"]);let i=r.slice(0,8);try{await ht(i)}catch(o){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${o.message}
4
+ `)}return i}async function bt(t,e){let n=`
5
5
  (() => {
6
6
  window.${e} = null;
7
7
  const _clipboard = navigator.clipboard;
@@ -38,7 +38,7 @@ import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_proc
38
38
  catch (_) { return undefined; }
39
39
  };
40
40
  })();
41
- `;await g(["eval",t,n])}async function yt(t){await g(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
41
+ `;await g(["eval",t,n])}async function ht(t){await g(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
42
42
  (function() {
43
43
  // ── Runtime.enable / CDP detection masking ──────────────
44
44
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -246,7 +246,7 @@ import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_proc
246
246
  };
247
247
  } catch(_) {}
248
248
  })();
249
- `})])}function wt(t){if(!t)return[];let e=[],n=0;while(n<t.length&&e.length<10){let r=t.indexOf("[",n);if(r===-1)break;let i=t.indexOf("](",r);if(i===-1)break;let o=i+2,u=-1;for(let a=o;a<t.length;a++){let l=t[a];if(l===")"){u=a;break}if(/\s/.test(l))break}if(u!==-1){let a=t.slice(r+1,i),l=t.slice(o,u);if(/^https?:\/\//i.test(l)&&a){if(!e.some((f)=>f.url===l))e.push({title:a,url:l})}n=u+1}else n=r+1}return e}var M={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function B(t){let e=t*0.4,n=ie(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function mt(t,e={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:o="document.body",minLength:u=0}=e,a=String.raw`
249
+ `})])}function yt(t){if(!t)return[];let e=[],n=0;while(n<t.length&&e.length<10){let r=t.indexOf("[",n);if(r===-1)break;let i=t.indexOf("](",r);if(i===-1)break;let o=i+2,u=-1;for(let a=o;a<t.length;a++){let l=t[a];if(l===")"){u=a;break}if(/\s/.test(l))break}if(u!==-1){let a=t.slice(r+1,i),l=t.slice(o,u);if(/^https?:\/\//i.test(l)&&a){if(!e.some((f)=>f.url===l))e.push({title:a,url:l})}n=u+1}else n=r+1}return e}var T={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function B(t){let e=t*0.4,n=re(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function wt(t,e={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:o="document.body",minLength:u=0}=e,a=String.raw`
250
250
  new Promise((resolve, reject) => {
251
251
  const _deadline = Date.now() + ${n};
252
252
  const _baseInterval = ${r};
@@ -284,7 +284,7 @@ import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_proc
284
284
 
285
285
  _poll();
286
286
  })
287
- `,l=await g(["eval",t,a],n+1e4),f=parseInt(l,10)||0;if(f>=u)return f;throw Error(`Generation did not stabilise within ${n}ms`)}async function vt(t,e,n=15000,r=500){let i=String.raw`
287
+ `,l=await g(["eval",t,a],n+1e4),f=parseInt(l,10)||0;if(f>=u)return f;throw Error(`Generation did not stabilise within ${n}ms`)}async function mt(t,e,n=15000,r=500){let i=String.raw`
288
288
  new Promise((resolve) => {
289
289
  const _deadline = Date.now() + ${n};
290
290
  const _baseInterval = ${r};
@@ -303,27 +303,27 @@ import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_proc
303
303
 
304
304
  _poll();
305
305
  })
306
- `;return await g(["eval",t,i],n+5000)==="true"}async function pt(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((i)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(u)=>o+=u),process.stdin.on("end",()=>i(o.trim()))}),r=[...t];return r[e]=n,r}function xt(t){let e=t.includes("--short"),n=t.filter((a)=>a!=="--short"),r=n.indexOf("--tab"),i=r===-1?null:n[r+1];if(r!==-1)n=n.filter((a,l)=>l!==r&&l!==r+1);let o=n.indexOf("--locale"),u=o===-1?null:n[o+1];if(o!==-1)n=n.filter((a,l)=>l!==o&&l!==o+1);return{query:n.join(" "),tabPrefix:i,short:e,locale:u}}function $t(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function Jt(t,e,n=300){if(!e||t.length<=n)return t;let r=t.slice(0,n),i=r.lastIndexOf(" ");return i>0?`${r.slice(0,i)}…`:`${r}…`}function kt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
307
- `)}function Wt(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
306
+ `;return await g(["eval",t,i],n+5000)==="true"}async function vt(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((i)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(u)=>o+=u),process.stdin.on("end",()=>i(o.trim()))}),r=[...t];return r[e]=n,r}function pt(t){let e=t.includes("--short"),n=t.filter((a)=>a!=="--short"),r=n.indexOf("--tab"),i=r===-1?null:n[r+1];if(r!==-1)n=n.filter((a,l)=>l!==r&&l!==r+1);let o=n.indexOf("--locale"),u=o===-1?null:n[o+1];if(o!==-1)n=n.filter((a,l)=>l!==o&&l!==o+1);return{query:n.join(" "),tabPrefix:i,short:e,locale:u}}function xt(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function $t(t,e,n=300){if(!e||t.length<=n)return t;let r=t.slice(0,n),i=r.lastIndexOf(" ");return i>0?`${r.slice(0,i)}…`:`${r}…`}function Jt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
307
+ `)}function kt(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
308
308
  `)}process.stderr.write(`Error: ${t.message}
309
- `),process.exit(1)}import{spawn as Ye,execFileSync as St,execSync as ut}from"node:child_process";import{existsSync as T,readFileSync as P,renameSync as ze,unlinkSync as x,writeFileSync as S}from"node:fs";import lt from"node:http";import{platform as at,tmpdir as de}from"node:os";import{join as it}from"node:path";import{basename as be}from"node:path";function Nt(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=be(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}import{existsSync as Xt}from"node:fs";import{platform as he}from"node:os";import{join as $}from"node:path";function y(t){let e=he()==="win32",n=process.env.SystemRoot||"C:\\Windows",r={win32:{powershell:$(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:$(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:$(n,"System32","netstat.exe"),taskkill:$(n,"System32","taskkill.exe"),tasklist:$(n,"System32","tasklist.exe"),cmd:$(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=e?r.win32:r.unix,o=t.toLowerCase();if(i[o]&&Xt(i[o]))return i[o];if(e&&o==="netstat"){let u=$(n,"Sysnative","netstat.exe");if(Xt(u))return u}return t}import{existsSync as U,mkdirSync as ye,readFileSync as Qt,writeFileSync as we}from"node:fs";import{homedir as me}from"node:os";import{join as jt}from"node:path";import{tmpdir as K}from"node:os";var h=9222,p=`${K().replaceAll("\\","/")}/greedysearch-chrome-profile`,X=`${p}/DevToolsActivePort`,ve=`${K().replaceAll("\\","/")}/cdp-pages.json`,J=`${K().replaceAll("\\","/")}/greedysearch-chrome-mode`,_n=`${K().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,I=jt(me(),".dm"),v=jt(I,"greedyconfig"),F=["perplexity","google","chatgpt"],E="gemini";function pe(){try{if(U(v)){let t=Qt(v,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((i)=>L[i]),r=e.engines.filter((i)=>!L[i]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${v}: ${r.join(", ")}
309
+ `),process.exit(1)}import{spawn as Ce,execFileSync as zt,execSync as ot}from"node:child_process";import{existsSync as R,readFileSync as S,renameSync as de,unlinkSync as p,writeFileSync as z}from"node:fs";import ut from"node:http";import{platform as lt,tmpdir as Ye}from"node:os";import{join as ze}from"node:path";import{basename as se}from"node:path";function Wt(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=se(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}import{existsSync as Nt}from"node:fs";import{platform as be}from"node:os";import{join as x}from"node:path";function y(t){let e=be()==="win32",n=process.env.SystemRoot||"C:\\Windows",r={win32:{powershell:x(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:x(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:x(n,"System32","netstat.exe"),taskkill:x(n,"System32","taskkill.exe"),tasklist:x(n,"System32","tasklist.exe"),cmd:x(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=e?r.win32:r.unix,o=t.toLowerCase();if(i[o]&&Nt(i[o]))return i[o];if(e&&o==="netstat"){let u=x(n,"Sysnative","netstat.exe");if(Nt(u))return u}return t}import{existsSync as M,mkdirSync as he,readFileSync as qt,writeFileSync as ye}from"node:fs";import{homedir as we}from"node:os";import{join as Qt}from"node:path";import{tmpdir as U}from"node:os";var h=9222,$=`${U().replaceAll("\\","/")}/greedysearch-chrome-profile`,X=`${$}/DevToolsActivePort`,me=`${U().replaceAll("\\","/")}/cdp-pages.json`,J=`${U().replaceAll("\\","/")}/greedysearch-chrome-mode`,On=`${U().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,I=Qt(we(),".dm"),v=Qt(I,"greedyconfig"),F=["perplexity","google","chatgpt"],E="gemini";function ve(){try{if(M(v)){let t=qt(v,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((i)=>L[i]),r=e.engines.filter((i)=>!L[i]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${v}: ${r.join(", ")}
310
310
  [greedysearch] Available engines: ${Object.keys(L).join(", ")}
311
311
  `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${v}, falling back to defaults: ${F.join(", ")}
312
- `)}}}catch{}return F}function xe(){try{if(!U(I))ye(I,{recursive:!0});if(!U(v))we(v,JSON.stringify({engines:F,synthesizer:E},null,2)+`
313
- `,"utf8")}catch{}}xe();var qt=["gemini","chatgpt"];function $e(){try{if(U(v)){let t=Qt(v,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(qt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${v}
314
- [greedysearch] Available synthesizers: ${qt.join(", ")}
312
+ `)}}}catch{}return F}function pe(){try{if(!M(I))he(I,{recursive:!0});if(!M(v))ye(v,JSON.stringify({engines:F,synthesizer:E},null,2)+`
313
+ `,"utf8")}catch{}}pe();var Xt=["gemini","chatgpt"];function xe(){try{if(M(v)){let t=qt(v,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(Xt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${v}
314
+ [greedysearch] Available synthesizers: ${Xt.join(", ")}
315
315
  [greedysearch] Falling back to default: ${E}
316
- `)}}}catch{}return E}var L={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"},An=pe();var Tn=$e(),Mn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{existsSync as Cn,mkdirSync as Je,readFileSync as Zt,renameSync as ke,unlinkSync as We,writeFileSync as Ht}from"node:fs";import Ne from"node:http";import{platform as Vt}from"node:os";import{dirname as Xe}from"node:path";var Ot=[9222,9223],qe=/^(0|false|no|off)$/i;function Qe(t){return[...new Set(t.filter(Boolean))]}function Bt(t,e="explicit"){let n=new URL(t),r=n.protocol==="wss:"?"wss:":"ws:",i=n.port?Number.parseInt(n.port,10):r==="wss:"?443:80;return{source:e,wsUrl:`${r}//${n.host}${n.pathname}${n.search}`,host:n.hostname,port:i,path:`${n.pathname}${n.search}`,httpUrl:`http://${n.hostname}:${i}`}}function _t(t=process.env){return![t.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,t.DM_CUA_REUSE_EXISTING_BROWSER].some((e)=>e!==void 0&&qe.test(String(e)))}function tt(t){let e=Number.parseInt(String(t??""),10);return Number.isInteger(e)&&e>0&&e<65536?e:null}function je(t){if(!t)return null;let e=String(t).trim();if(!e)return null;let n=new URL(e.includes("://")?e:`http://${e}`),r=tt(n.port)||(n.protocol==="https:"?443:80);return{host:n.hostname,port:r,source:`env:${e}`}}function Be(t){if(!t)return[];return String(t).split(/[,\s]+/).map(tt).filter(Boolean)}function Ze({env:t=process.env,platformName:e=Vt(),procVersionText:n=null}={}){if(e!=="linux")return!1;if(t.WSL_DISTRO_NAME||t.WSL_INTEROP)return!0;let r=n??(()=>{try{return Zt("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(r)}function He({env:t=process.env,platformName:e=Vt(),procVersionText:n=null,resolvConfText:r=null}={}){let i=["localhost","127.0.0.1"];if(Ze({env:t,platformName:e,procVersionText:n})){let u=(r??(()=>{try{return Zt("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(u)i.push(u[1]);i.push("host.docker.internal")}return Qe(i)}function Ve({env:t=process.env,hosts:e=He({env:t}),autoPorts:n=Ot,excludePorts:r=[]}={}){let i=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(t[l])i.push({wsUrl:t[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let f=je(t[l]);if(f)i.push(f)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let f=tt(t[l]);if(!f)continue;for(let c of e)i.push({host:c,port:f,source:`env:${l}`})}let o=Be(t.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of o)for(let f of e)i.push({host:f,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let u=new Set(r.filter(Boolean));if(_t(t))for(let l of n){if(u.has(l))continue;for(let f of e)i.push({host:f,port:l,source:"auto"})}let a=new Set;return i.filter((l)=>{let f=l.wsUrl||`${l.host}:${l.port}`;if(a.has(f))return!1;return a.add(f),!0})}async function Oe(t,{timeoutMs:e=700}={}){if(t.wsUrl)return Bt(t.wsUrl,t.source);let n=t.host||"localhost",r=t.port;if(!r)return null;let i=await new Promise((o)=>{let u=Ne.get({host:n,port:r,path:"/json/version",timeout:e},(a)=>{let l="";a.setEncoding("utf8"),a.on("data",(f)=>l+=f),a.on("end",()=>o(a.statusCode===200?l:null))});u.on("error",()=>o(null)),u.setTimeout(e,()=>{u.destroy(),o(null)})});if(!i)return null;try{let o=JSON.parse(i);if(!o.webSocketDebuggerUrl)return null;let u=Bt(o.webSocketDebuggerUrl,t.source),a=u.path||new URL(o.webSocketDebuggerUrl).pathname;return{...u,host:n,port:r,httpUrl:`http://${n}:${r}`,wsUrl:`ws://${n}:${r}${a}`,path:a}}catch{return null}}async function _e(t={}){for(let e of Ve(t)){let n=await Oe(e,t);if(n)return n}return null}function Ae(t){if(!t)throw Error("missing CDP endpoint");let e=new URL(t.wsUrl);return`${e.host}
316
+ `)}}}catch{}return E}var L={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=ve();var An=xe(),Tn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=$;import{existsSync as Kn,mkdirSync as $e,readFileSync as Bt,renameSync as Je,unlinkSync as ke,writeFileSync as Zt}from"node:fs";import We from"node:http";import{platform as Ht}from"node:os";import{dirname as Ne}from"node:path";var Vt=[9222,9223],Xe=/^(0|false|no|off)$/i;function qe(t){return[...new Set(t.filter(Boolean))]}function jt(t,e="explicit"){let n=new URL(t),r=n.protocol==="wss:"?"wss:":"ws:",i=n.port?Number.parseInt(n.port,10):r==="wss:"?443:80;return{source:e,wsUrl:`${r}//${n.host}${n.pathname}${n.search}`,host:n.hostname,port:i,path:`${n.pathname}${n.search}`,httpUrl:`http://${n.hostname}:${i}`}}function Ot(t=process.env){return![t.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,t.DM_CUA_REUSE_EXISTING_BROWSER].some((e)=>e!==void 0&&Xe.test(String(e)))}function tt(t){let e=Number.parseInt(String(t??""),10);return Number.isInteger(e)&&e>0&&e<65536?e:null}function Qe(t){if(!t)return null;let e=String(t).trim();if(!e)return null;let n=new URL(e.includes("://")?e:`http://${e}`),r=tt(n.port)||(n.protocol==="https:"?443:80);return{host:n.hostname,port:r,source:`env:${e}`}}function je(t){if(!t)return[];return String(t).split(/[,\s]+/).map(tt).filter(Boolean)}function Be({env:t=process.env,platformName:e=Ht(),procVersionText:n=null}={}){if(e!=="linux")return!1;if(t.WSL_DISTRO_NAME||t.WSL_INTEROP)return!0;let r=n??(()=>{try{return Bt("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(r)}function Ze({env:t=process.env,platformName:e=Ht(),procVersionText:n=null,resolvConfText:r=null}={}){let i=["localhost","127.0.0.1"];if(Be({env:t,platformName:e,procVersionText:n})){let u=(r??(()=>{try{return Bt("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(u)i.push(u[1]);i.push("host.docker.internal")}return qe(i)}function He({env:t=process.env,hosts:e=Ze({env:t}),autoPorts:n=Vt,excludePorts:r=[]}={}){let i=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(t[l])i.push({wsUrl:t[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let f=Qe(t[l]);if(f)i.push(f)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let f=tt(t[l]);if(!f)continue;for(let c of e)i.push({host:c,port:f,source:`env:${l}`})}let o=je(t.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of o)for(let f of e)i.push({host:f,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let u=new Set(r.filter(Boolean));if(Ot(t))for(let l of n){if(u.has(l))continue;for(let f of e)i.push({host:f,port:l,source:"auto"})}let a=new Set;return i.filter((l)=>{let f=l.wsUrl||`${l.host}:${l.port}`;if(a.has(f))return!1;return a.add(f),!0})}async function Ve(t,{timeoutMs:e=700}={}){if(t.wsUrl)return jt(t.wsUrl,t.source);let n=t.host||"localhost",r=t.port;if(!r)return null;let i=await new Promise((o)=>{let u=We.get({host:n,port:r,path:"/json/version",timeout:e},(a)=>{let l="";a.setEncoding("utf8"),a.on("data",(f)=>l+=f),a.on("end",()=>o(a.statusCode===200?l:null))});u.on("error",()=>o(null)),u.setTimeout(e,()=>{u.destroy(),o(null)})});if(!i)return null;try{let o=JSON.parse(i);if(!o.webSocketDebuggerUrl)return null;let u=jt(o.webSocketDebuggerUrl,t.source),a=u.path||new URL(o.webSocketDebuggerUrl).pathname;return{...u,host:n,port:r,httpUrl:`http://${n}:${r}`,wsUrl:`ws://${n}:${r}${a}`,path:a}}catch{return null}}async function Oe(t={}){for(let e of He(t)){let n=await Ve(e,t);if(n)return n}return null}function _e(t){if(!t)throw Error("missing CDP endpoint");let e=new URL(t.wsUrl);return`${e.host}
317
317
  ${e.pathname}${e.search}
318
- `}function Te(t,e){Je(Xe(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;Ht(n,Ae(e),"utf8");try{We(t)}catch{}ke(n,t)}async function At({activePortFile:t,modeFile:e,env:n=process.env,excludePorts:r=[],autoPorts:i=Ot}={}){if(!_t(n))return null;let o=await _e({env:n,excludePorts:r,autoPorts:i});if(!o)return null;if(Te(t,o),e)Ht(e,"existing","utf8");return o}import{execFileSync as Tt,execSync as et}from"node:child_process";import{existsSync as C,mkdirSync as Me,readFileSync as q,unlinkSync as W,writeFileSync as N}from"node:fs";import{platform as nt,tmpdir as Dt}from"node:os";var V=Dt().replaceAll("\\","/"),D=`${V}/greedysearch-chrome-metadata.json`,k=`${V}/greedysearch-chrome-launch.lock`,Ue=15000,Y=`${V}/greedysearch-chrome.pid`,z=`${V}/greedysearch-chrome-mode`,Z=`${V}/greedysearch-chrome-last-activity`;function H(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Ke(t){if(!H(t))return null;try{if(nt()==="win32")return Tt(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Tt(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Ce(t,e,n=h){if(!t)return!1;let r=(u)=>String(u||"").replaceAll("\\","/").toLowerCase(),i=r(t),o=r(e);return i.includes(o)&&i.includes(`--remote-debugging-port=${n}`)&&!i.includes("--type=")}function Mt(t,e,n=h){return Ce(Ke(t),e,n)}function De(t=h){try{if(nt()==="win32"){let n=et(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),r=new RegExp(String.raw`TCP\s+\S+:${t}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),i=n.match(r);return i?Number.parseInt(i[1],10):null}let e=et(`${y("lsof")} -i :${t} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${t} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
319
- `)[0],10):null}catch{return null}}function Ut(t){try{if(nt()==="win32")et(`${y("taskkill")} /F /T /PID ${t}`,{stdio:"ignore"});else{try{process.kill(-t,"SIGKILL")}catch{}try{process.kill(t,"SIGKILL")}catch{}}return!0}catch{return!1}}function O(){try{if(C(D)){let t=q(D,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{let t=C(Y)?Number.parseInt(q(Y,"utf8").trim(),10)||void 0:void 0,e=C(z)?q(z,"utf8").trim()==="visible"?"visible":"headless":"headless",n=C(Z)?Number.parseInt(q(Z,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:h,tempDir:p,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function d(t){try{N(D,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)N(Y,String(t.browserPid),"utf8")}catch{}try{N(z,t.sessionMode,"utf8")}catch{}try{N(Z,String(t.lastActivity),"utf8")}catch{}}function Kt(){try{W(D)}catch{}try{W(Y)}catch{}try{W(z)}catch{}try{W(Z)}catch{}}function Yt(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>H(n)||n===process.pid))]};return d(e),e}function rt(t){let e=Date.now();try{if(t)d({...t,lastActivity:e});else N(Z,String(e),"utf8")}catch{}}var In=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ct=!1;function zt(){if(Ct)return;Ct=!0;let t=O();if(!t)return;if(t.browserPid){if(!H(t.browserPid)){Ut(t.browserPid),Kt();return}if(!Mt(t.browserPid,t.tempDir,t.debugPort))Kt();else d({...t,clientPids:t.clientPids.filter((i)=>H(i))})}let e=De();if(e&&e!==t.browserPid)if(Mt(e,p,h))d({browserPid:e,debugPort:h,tempDir:p,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Ut(e)}function dt(){Me(Dt(),{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=q(k,"utf8");if(JSON.parse(e).pid===process.pid)W(k)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=q(k,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!H(e.pid)||n>Ue){try{W(k)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{W(k)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Se=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function Pe(t=Se){let e=[it(t,"launch.mjs"),it(t,"..","bin","launch.mjs"),it(t,"..","..","bin","launch.mjs")];for(let n of e)if(T(n))return n;return e[e.length-1]}var Rt=de().replaceAll("\\","/"),_=`${Rt}/greedysearch-chrome.pid`,A=`${Rt}/greedysearch-chrome-last-activity`,Re=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Ge=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Le(t,e=h){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Gt(){try{let t=ft(),e=t?Fe(t):null,n=Le(e);if(n!==null){try{S(J,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!T(J))return!0;return P(J,"utf8").trim()==="headless"}catch{return!0}}function Ie(){try{S(A,String(Date.now()),"utf8")}catch{}try{let t=O();if(t)rt(t)}catch{}}function Fe(t){try{if(at()==="win32")return St(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return St(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function ft(){try{if(at()==="win32"){let e=ut(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),n=new RegExp(String.raw`TCP\s+\S+:${h}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),r=e.match(n);return r?Number.parseInt(r[1],10):null}let t=ut(`${y("lsof")} -i :${h} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${h} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
320
- `)[0],10):null}catch{return null}}async function Ee(t=1500){try{let n=await new Promise((i,o)=>{let u=lt.get(`http://localhost:${h}/json/version`,(a)=>{let l="";a.on("data",(f)=>l+=f),a.on("end",()=>{try{i(JSON.parse(l))}catch{o(Error("bad JSON"))}})});u.on("error",o),u.setTimeout(1000,()=>{u.destroy(),o(Error("timeout"))})}),r=new globalThis.WebSocket(n.webSocketDebuggerUrl);await new Promise((i)=>{r.onopen=()=>{r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),i()},200)},r.onerror=()=>i(),setTimeout(i,1000)})}catch{}let e=Date.now()+t;while(Date.now()<e){if(!ft())return!0;await new Promise((r)=>setTimeout(r,150))}return tn()}function tn(){try{let t=ft();if(!t&&T(_))t=Number.parseInt(P(_,"utf8").trim(),10)||null;if(!t)return!1;if(at()==="win32")ut(`${y("taskkill")} /F /PID ${t}`,{stdio:"ignore"});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Lt(){if(!await Q(500)){try{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}return!1}let e=await Ee(1500);try{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
- `);return e}var Pt=Lt;async function en(){let e=Gt()?Re:Ge;if(e<=0)return!1;if(!T(A))return Ie(),!1;try{let n=Number.parseInt(P(A,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Lt()}catch{}return!1}function Q(t=3000){return new Promise((e)=>{let n=lt.get(`http://localhost:${h}/json/version`,(r)=>{r.resume(),e(r.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function ot(){let t=`${X}.lock`,e=`${X}.tmp`,n=5000,r=1000,i=await new Promise((o)=>{let u=Date.now(),a=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});S(t,l,{encoding:"utf8",flag:"wx"}),o(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-u<1000)setTimeout(a,50);else o(!1);return}try{let f=P(t,"utf8").trim(),c=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},b=Number(c?.ts)||0;if(b>0&&Date.now()-b>5000)try{x(t)}catch{}if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}catch{if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}}};a()});try{let o=await new Promise((f,c)=>{let b=lt.get(`http://localhost:${h}/json/version`,(s)=>{let m="";s.on("data",(R)=>m+=R),s.on("end",()=>f(m))});b.on("error",c),b.setTimeout(3000,()=>{b.destroy(),c(Error("timeout"))})}),{webSocketDebuggerUrl:u}=JSON.parse(o),a=new URL(u),l=`${a.pathname}${a.search}`;if(i){S(e,`localhost:${h}
322
- ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}async function It(){let t=T(_)||!!O(),e=await At({activePortFile:X,modeFile:J,excludePorts:t?[h]:[]});if(e){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${e.httpUrl} (${e.source}).
323
- `);return}zt();let n=await en(),r=n?!1:await Q();if(!r&&!n)await new Promise((a)=>setTimeout(a,500)),r=await Q();let i=!1;if(r){let a=Gt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
- `),await Pt(),await new Promise((f)=>setTimeout(f,1000)),i=!0;else if(l&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
325
- `),await Pt(),await new Promise((f)=>setTimeout(f,1000)),i=!0}if(i?!1:await Q()){await ot();try{let a=O();if(a)rt(a),Yt(a)}catch{}return}let u=dt();if(!u.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await Q(5000)){await ot();return}}try{if(await Q(1000)){await ot();return}process.stderr.write(`GreedySearch Chrome not running on port ${h} — auto-launching...
326
- `);let l=[Pe()];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((f,c)=>{Ye(Nt(),l,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:p,GREEDY_SEARCH_PROFILE_DIR:p}}).on("close",(s)=>s===0?f():c(Error("launch.mjs failed")))})}finally{u.release()}}import{randomInt as nn}from"node:crypto";import{existsSync as rn,readFileSync as on}from"node:fs";import un from"node:http";var ln=`
318
+ `}function Ae(t,e){$e(Ne(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;Zt(n,_e(e),"utf8");try{ke(t)}catch{}Je(n,t)}async function _t({activePortFile:t,modeFile:e,env:n=process.env,excludePorts:r=[],autoPorts:i=Vt}={}){if(!Ot(n))return null;let o=await Oe({env:n,excludePorts:r,autoPorts:i});if(!o)return null;if(Ae(t,o),e)Zt(e,"existing","utf8");return o}import{execFileSync as At,execSync as et}from"node:child_process";import{existsSync as K,mkdirSync as Te,readFileSync as q,unlinkSync as W,writeFileSync as N}from"node:fs";import{platform as nt,tmpdir as Dt}from"node:os";var V=Dt().replaceAll("\\","/"),D=`${V}/greedysearch-chrome-metadata.json`,k=`${V}/greedysearch-chrome-launch.lock`,Me=15000,C=`${V}/greedysearch-chrome.pid`,d=`${V}/greedysearch-chrome-mode`,Z=`${V}/greedysearch-chrome-last-activity`;function H(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Ue(t){if(!H(t))return null;try{if(nt()==="win32")return At(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return At(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Ke(t,e,n=h){if(!t)return!1;let r=(u)=>String(u||"").replaceAll("\\","/").toLowerCase(),i=r(t),o=r(e);return i.includes(o)&&i.includes(`--remote-debugging-port=${n}`)&&!i.includes("--type=")}function Tt(t,e,n=h){return Ke(Ue(t),e,n)}function De(t=h){try{if(nt()==="win32"){let n=et(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),r=new RegExp(String.raw`TCP\s+\S+:${t}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),i=n.match(r);return i?Number.parseInt(i[1],10):null}let e=et(`${y("lsof")} -i :${t} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${t} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
319
+ `)[0],10):null}catch{return null}}function Mt(t){try{if(nt()==="win32")et(`${y("taskkill")} /F /T /PID ${t}`,{stdio:"ignore"});else{try{process.kill(-t,"SIGKILL")}catch{}try{process.kill(t,"SIGKILL")}catch{}}return!0}catch{return!1}}function O(){try{if(K(D)){let t=q(D,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{let t=K(C)?Number.parseInt(q(C,"utf8").trim(),10)||void 0:void 0,e=K(d)?q(d,"utf8").trim()==="visible"?"visible":"headless":"headless",n=K(Z)?Number.parseInt(q(Z,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:h,tempDir:$,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function Y(t){try{N(D,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)N(C,String(t.browserPid),"utf8")}catch{}try{N(d,t.sessionMode,"utf8")}catch{}try{N(Z,String(t.lastActivity),"utf8")}catch{}}function Ut(){try{W(D)}catch{}try{W(C)}catch{}try{W(d)}catch{}try{W(Z)}catch{}}function Ct(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>H(n)||n===process.pid))]};return Y(e),e}function rt(t){let e=Date.now();try{if(t)Y({...t,lastActivity:e});else N(Z,String(e),"utf8")}catch{}}var Ln=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Kt=!1;function dt(){if(Kt)return;Kt=!0;let t=O();if(!t)return;if(t.browserPid){if(!H(t.browserPid)){Mt(t.browserPid),Ut();return}if(!Tt(t.browserPid,t.tempDir,t.debugPort))Ut();else Y({...t,clientPids:t.clientPids.filter((i)=>H(i))})}let e=De();if(e&&e!==t.browserPid)if(Tt(e,$,h))Y({browserPid:e,debugPort:h,tempDir:$,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Mt(e)}function Yt(){Te(Dt(),{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=q(k,"utf8");if(JSON.parse(e).pid===process.pid)W(k)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=q(k,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!H(e.pid)||n>Me){try{W(k)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{W(k)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Re=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),St=Ye().replaceAll("\\","/"),_=`${St}/greedysearch-chrome.pid`,A=`${St}/greedysearch-chrome-last-activity`,Se=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Pe=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Ge(t,e=h){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Pt(){try{let t=at(),e=t?Ie(t):null,n=Ge(e);if(n!==null){try{z(J,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!R(J))return!0;return S(J,"utf8").trim()==="headless"}catch{return!0}}function Le(){try{z(A,String(Date.now()),"utf8")}catch{}try{let t=O();if(t)rt(t)}catch{}}function Ie(t){try{if(lt()==="win32")return zt(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return zt(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function at(){try{if(lt()==="win32"){let e=ot(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),n=new RegExp(String.raw`TCP\s+\S+:${h}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),r=e.match(n);return r?Number.parseInt(r[1],10):null}let t=ot(`${y("lsof")} -i :${h} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${h} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
320
+ `)[0],10):null}catch{return null}}async function Fe(t=1500){try{let n=await new Promise((i,o)=>{let u=ut.get(`http://localhost:${h}/json/version`,(a)=>{let l="";a.on("data",(f)=>l+=f),a.on("end",()=>{try{i(JSON.parse(l))}catch{o(Error("bad JSON"))}})});u.on("error",o),u.setTimeout(1000,()=>{u.destroy(),o(Error("timeout"))})}),r=new globalThis.WebSocket(n.webSocketDebuggerUrl);await new Promise((i)=>{r.onopen=()=>{r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),i()},200)},r.onerror=()=>i(),setTimeout(i,1000)})}catch{}let e=Date.now()+t;while(Date.now()<e){if(!at())return!0;await new Promise((r)=>setTimeout(r,150))}return Ee()}function Ee(){try{let t=at();if(!t&&R(_))t=Number.parseInt(S(_,"utf8").trim(),10)||null;if(!t)return!1;if(lt()==="win32")ot(`${y("taskkill")} /F /PID ${t}`,{stdio:"ignore"});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Gt(){if(!await Q(500)){try{p(_)}catch{}try{p(A)}catch{}try{p(J)}catch{}return!1}let e=await Fe(1500);try{p(_)}catch{}try{p(A)}catch{}try{p(J)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
+ `);return e}var Rt=Gt;async function tn(){let e=Pt()?Se:Pe;if(e<=0)return!1;if(!R(A))return Le(),!1;try{let n=Number.parseInt(S(A,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Gt()}catch{}return!1}function Q(t=3000){return new Promise((e)=>{let n=ut.get(`http://localhost:${h}/json/version`,(r)=>{r.resume(),e(r.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function it(){let t=`${X}.lock`,e=`${X}.tmp`,n=5000,r=1000,i=await new Promise((o)=>{let u=Date.now(),a=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});z(t,l,{encoding:"utf8",flag:"wx"}),o(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-u<1000)setTimeout(a,50);else o(!1);return}try{let f=S(t,"utf8").trim(),c=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},b=Number(c?.ts)||0;if(b>0&&Date.now()-b>5000)try{p(t)}catch{}if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}catch{if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}}};a()});try{let o=await new Promise((f,c)=>{let b=ut.get(`http://localhost:${h}/json/version`,(s)=>{let m="";s.on("data",(P)=>m+=P),s.on("end",()=>f(m))});b.on("error",c),b.setTimeout(3000,()=>{b.destroy(),c(Error("timeout"))})}),{webSocketDebuggerUrl:u}=JSON.parse(o),a=new URL(u),l=`${a.pathname}${a.search}`;if(i){z(e,`localhost:${h}
322
+ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}async function Lt(){let t=R(_)||!!O(),e=await _t({activePortFile:X,modeFile:J,excludePorts:t?[h]:[]});if(e){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${e.httpUrl} (${e.source}).
323
+ `);return}dt();let n=await tn(),r=n?!1:await Q();if(!r&&!n)await new Promise((a)=>setTimeout(a,500)),r=await Q();let i=!1;if(r){let a=Pt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
+ `),await Rt(),await new Promise((f)=>setTimeout(f,1000)),i=!0;else if(l&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
325
+ `),await Rt(),await new Promise((f)=>setTimeout(f,1000)),i=!0}if(i?!1:await Q()){await it();try{let a=O();if(a)rt(a),Ct(a)}catch{}return}let u=Yt();if(!u.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await Q(5000)){await it();return}}try{if(await Q(1000)){await it();return}process.stderr.write(`GreedySearch Chrome not running on port ${h} — auto-launching...
326
+ `);let l=[ze(Re,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((f,c)=>{Ce(Wt(),l,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(s)=>s===0?f():c(Error("launch.mjs failed")))})}finally{u.release()}}import{randomInt as en}from"node:crypto";import{existsSync as nn,readFileSync as rn}from"node:fs";import on from"node:http";var un=`
327
327
  (function() {
328
328
  // Google consent page (consent.google.com)
329
329
  var g = document.querySelector('#L2AGLb, button[jsname="b3VHJd"], .tHlp8d');
@@ -340,7 +340,7 @@ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
340
340
 
341
341
  return null;
342
342
  })()
343
- `,an=`
343
+ `,ln=`
344
344
  (function() {
345
345
  var url = document.location.href;
346
346
 
@@ -410,7 +410,7 @@ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
410
410
 
411
411
  return null;
412
412
  })()
413
- `,fn=`
413
+ `,an=`
414
414
  (function() {
415
415
  var url = document.location.href;
416
416
  var isVerifyPage = url.includes('/sorry/') ||
@@ -444,26 +444,26 @@ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
444
444
 
445
445
  return 'still-verifying';
446
446
  })()
447
- `;async function Et(t,e){let n=await e(["eval",t,ln]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function w(t,e){return nn(t*1000,e*1000)/1000}async function cn(t,e){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!rn(r))return;let i=on(r,"utf8").trim().split(`
448
- `)[0],o=await new Promise((l,f)=>{let c=un.get(`http://localhost:${i}/json/version`,(b)=>{let s="";b.on("data",(m)=>s+=m),b.on("end",()=>{try{l(JSON.parse(s))}catch{f(Error("bad JSON"))}})});c.on("error",f),c.setTimeout(1000,()=>{c.destroy(),f(Error("timeout"))})}),u=new globalThis.WebSocket(o.webSocketDebuggerUrl),a=0;await new Promise((l)=>{u.onopen=async()=>{let f=(s,m)=>new Promise((R)=>{let gt=++a,st=(re)=>{if(JSON.parse(re.data).id===gt)u.removeEventListener("message",st),R()};u.addEventListener("message",st),u.send(JSON.stringify({id:gt,method:s,params:m}))}),c=t+w(-2,2),b=e+w(-2,2);await f("Input.dispatchMouseEvent",{type:"mouseMoved",x:c,y:b,button:"none"}),await new Promise((s)=>setTimeout(s,w(80,160))),await f("Input.dispatchMouseEvent",{type:"mousePressed",x:c,y:b,button:"left",clickCount:1}),await new Promise((s)=>setTimeout(s,w(30,80))),await f("Input.dispatchMouseEvent",{type:"mouseReleased",x:c+w(-1,1),y:b+w(-1,1),button:"left",clickCount:1}),setTimeout(()=>{u.close(),l()},200)},u.onerror=()=>l(),setTimeout(l,3000)})}async function te(t,e,n,r){let i=Number.parseFloat(n),o=Number.parseFloat(r);if(Number.isNaN(i)||Number.isNaN(o))throw Error(`humanClickXY: invalid coordinates (${n}, ${r})`);let u={button:"left",clickCount:1,modifiers:0},a=i+w(-3,3),l=o+w(-3,3);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseMoved",x:a,y:l})]),await new Promise((m)=>setTimeout(m,w(80,180)));let f=i+w(-2,2),c=o+w(-2,2);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mousePressed",x:f,y:c})]),await new Promise((m)=>setTimeout(m,w(30,90)));let b=f+w(-1,1),s=c+w(-1,1);return await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseReleased",x:b,y:s})]),await cn(i,o).catch(()=>{}),await new Promise((m)=>setTimeout(m,w(100,300))),`human-clicked at (${i.toFixed(0)}, ${o.toFixed(0)})`}async function gn(t,e,n){let r=await e(["eval",t,`(function() {
447
+ `;async function Ft(t,e){let n=await e(["eval",t,un]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function w(t,e){return en(t*1000,e*1000)/1000}async function fn(t,e){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!nn(r))return;let i=rn(r,"utf8").trim().split(`
448
+ `)[0],o=await new Promise((l,f)=>{let c=on.get(`http://localhost:${i}/json/version`,(b)=>{let s="";b.on("data",(m)=>s+=m),b.on("end",()=>{try{l(JSON.parse(s))}catch{f(Error("bad JSON"))}})});c.on("error",f),c.setTimeout(1000,()=>{c.destroy(),f(Error("timeout"))})}),u=new globalThis.WebSocket(o.webSocketDebuggerUrl),a=0;await new Promise((l)=>{u.onopen=async()=>{let f=(s,m)=>new Promise((P)=>{let ct=++a,gt=(ne)=>{if(JSON.parse(ne.data).id===ct)u.removeEventListener("message",gt),P()};u.addEventListener("message",gt),u.send(JSON.stringify({id:ct,method:s,params:m}))}),c=t+w(-2,2),b=e+w(-2,2);await f("Input.dispatchMouseEvent",{type:"mouseMoved",x:c,y:b,button:"none"}),await new Promise((s)=>setTimeout(s,w(80,160))),await f("Input.dispatchMouseEvent",{type:"mousePressed",x:c,y:b,button:"left",clickCount:1}),await new Promise((s)=>setTimeout(s,w(30,80))),await f("Input.dispatchMouseEvent",{type:"mouseReleased",x:c+w(-1,1),y:b+w(-1,1),button:"left",clickCount:1}),setTimeout(()=>{u.close(),l()},200)},u.onerror=()=>l(),setTimeout(l,3000)})}async function Et(t,e,n,r){let i=Number.parseFloat(n),o=Number.parseFloat(r);if(Number.isNaN(i)||Number.isNaN(o))throw Error(`humanClickXY: invalid coordinates (${n}, ${r})`);let u={button:"left",clickCount:1,modifiers:0},a=i+w(-3,3),l=o+w(-3,3);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseMoved",x:a,y:l})]),await new Promise((m)=>setTimeout(m,w(80,180)));let f=i+w(-2,2),c=o+w(-2,2);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mousePressed",x:f,y:c})]),await new Promise((m)=>setTimeout(m,w(30,90)));let b=f+w(-1,1),s=c+w(-1,1);return await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseReleased",x:b,y:s})]),await fn(i,o).catch(()=>{}),await new Promise((m)=>setTimeout(m,w(100,300))),`human-clicked at (${i.toFixed(0)}, ${o.toFixed(0)})`}async function cn(t,e,n){let r=await e(["eval",t,`(function() {
449
449
  var el = document.querySelector('${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}');
450
450
  if (!el) return 'null';
451
451
  var r = el.getBoundingClientRect();
452
452
  return JSON.stringify({x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height});
453
- })()`]).catch(()=>"null");if(!r||r==="null")return null;let i=JSON.parse(r);if(i.w===0||i.h===0||i.x===0&&i.y===0)return null;let{x:o,y:u}=i;return te(t,e,o,u)}async function Ft(t,e,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying")return!1;try{let r=JSON.parse(n);if(r.t==="sel"&&r.s)return process.stderr.write(`[greedysearch] Human-clicking "${r.txt}" via CDP...
454
- `),await gn(t,e,r.s)!==null;if(r.t==="xy"){if(!r.x&&!r.y)return!1;return process.stderr.write(`[greedysearch] Human-clicking at (${r.x.toFixed(0)}, ${r.y.toFixed(0)})...
455
- `),await te(t,e,r.x,r.y),!0}}catch{}return!1}async function sn(t,e){let n=await e(["eval",t,an]).catch(()=>null);return n&&n!=="null"?n:null}async function ee(t,e,n=30000){let r=await sn(t,e);if(!r)return"clear";if(r==="sorry-page"){process.stderr.write(`[greedysearch] Google CAPTCHA detected — please solve it in the browser window (waiting up to ${Math.floor(n/1000)}s)...
456
- `);let i=Date.now()+n;while(Date.now()<i)if(await new Promise((o)=>setTimeout(o,2000)),!(await e(["eval",t,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}if(await Ft(t,e,r)){await new Promise((o)=>setTimeout(o,2000));let i=Date.now()+n;while(Date.now()<i){let o=await e(["eval",t,fn]).catch(()=>null);if(o==="cleared"||!o||o==="null")return process.stderr.write(`[greedysearch] Verification cleared.
457
- `),"clicked";if(o!=="still-verifying")await Ft(t,e,o),await new Promise((u)=>setTimeout(u,2000));else await new Promise((u)=>setTimeout(u,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
458
- `),"needs-human"}return"clear"}var ne={perplexity:{input:"#ask-input",copyButton:null,sourceItem:"[data-pplx-citation-url]",sourceLink:"a",consent:"#onetrust-accept-btn-handler"},bing:{input:"#userInput",copyButton:'button[data-testid="copy-ai-message-button"]',sourceLink:'a[href^="http"][target="_blank"]',sourceExclude:"copilot.microsoft.com",consent:"#onetrust-accept-btn-handler"},google:{answerContainer:".pWvJNd",sourceLink:'a[href^="http"]',sourceExclude:["google.","gstatic","googleapis"],sourceHeadingParent:"[data-snhf]",consent:'#L2AGLb, button[jsname="b3VHJd"], .tHlp8d'},gemini:{input:"rich-textarea .ql-editor",copyButton:'button:has(mat-icon[data-mat-icon-name="copy"])',sendButton:'button:has(mat-icon[data-mat-icon-name="arrow_upward"]), [data-test-id="send-button"], .send-button',sourcesSidebarButton:"button.legacy-sources-sidebar-button",sourcesExclude:["gemini.google","gstatic","google.com/search"],citationButtonPattern:'button[aria-label*="citation from"]',citationNameRegex:/from\s{1,20}([^.]{1,200})\.\s/}};var j=ne.gemini,ct="__geminiClipboard";async function bn(t,e){if(await g(["click",t,j.input]),await new Promise((r)=>setTimeout(r,B(200))),await G(["type",t,"--stdin"],e),await new Promise((r)=>setTimeout(r,B(300))),await g(["eval",t,`(function() {
453
+ })()`]).catch(()=>"null");if(!r||r==="null")return null;let i=JSON.parse(r);if(i.w===0||i.h===0||i.x===0&&i.y===0)return null;let{x:o,y:u}=i;return Et(t,e,o,u)}async function It(t,e,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying")return!1;try{let r=JSON.parse(n);if(r.t==="sel"&&r.s)return process.stderr.write(`[greedysearch] Human-clicking "${r.txt}" via CDP...
454
+ `),await cn(t,e,r.s)!==null;if(r.t==="xy"){if(!r.x&&!r.y)return!1;return process.stderr.write(`[greedysearch] Human-clicking at (${r.x.toFixed(0)}, ${r.y.toFixed(0)})...
455
+ `),await Et(t,e,r.x,r.y),!0}}catch{}return!1}async function gn(t,e){let n=await e(["eval",t,ln]).catch(()=>null);return n&&n!=="null"?n:null}async function te(t,e,n=30000){let r=await gn(t,e);if(!r)return"clear";if(r==="sorry-page"){process.stderr.write(`[greedysearch] Google CAPTCHA detected — please solve it in the browser window (waiting up to ${Math.floor(n/1000)}s)...
456
+ `);let i=Date.now()+n;while(Date.now()<i)if(await new Promise((o)=>setTimeout(o,2000)),!(await e(["eval",t,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}if(await It(t,e,r)){await new Promise((o)=>setTimeout(o,2000));let i=Date.now()+n;while(Date.now()<i){let o=await e(["eval",t,an]).catch(()=>null);if(o==="cleared"||!o||o==="null")return process.stderr.write(`[greedysearch] Verification cleared.
457
+ `),"clicked";if(o!=="still-verifying")await It(t,e,o),await new Promise((u)=>setTimeout(u,2000));else await new Promise((u)=>setTimeout(u,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
458
+ `),"needs-human"}return"clear"}var ee={perplexity:{input:"#ask-input",copyButton:null,sourceItem:"[data-pplx-citation-url]",sourceLink:"a",consent:"#onetrust-accept-btn-handler"},bing:{input:"#userInput",copyButton:'button[data-testid="copy-ai-message-button"]',sourceLink:'a[href^="http"][target="_blank"]',sourceExclude:"copilot.microsoft.com",consent:"#onetrust-accept-btn-handler"},google:{answerContainer:".pWvJNd",sourceLink:'a[href^="http"]',sourceExclude:["google.","gstatic","googleapis"],sourceHeadingParent:"[data-snhf]",consent:'#L2AGLb, button[jsname="b3VHJd"], .tHlp8d'},gemini:{input:"rich-textarea .ql-editor",copyButton:'button:has(mat-icon[data-mat-icon-name="copy"])',sendButton:'button:has(mat-icon[data-mat-icon-name="arrow_upward"]), [data-test-id="send-button"], .send-button',sourcesSidebarButton:"button.legacy-sources-sidebar-button",sourcesExclude:["gemini.google","gstatic","google.com/search"],citationButtonPattern:'button[aria-label*="citation from"]',citationNameRegex:/from\s{1,20}([^.]{1,200})\.\s/}};var j=ee.gemini,ft="__geminiClipboard";async function sn(t,e){if(await g(["click",t,j.input]),await new Promise((r)=>setTimeout(r,B(200))),await G(["type",t,"--stdin"],e),await new Promise((r)=>setTimeout(r,B(300))),await g(["eval",t,`(function() {
459
459
  var el = document.querySelector('${j.input}');
460
460
  if (!el) return false;
461
461
  var content = el.innerText || el.textContent || '';
462
462
  return content.trim().length >= ${Math.floor(e.length*0.8)};
463
- })()`])!=="true")throw Error("Gemini input field did not accept text — input verification failed")}async function hn(t){await g(["eval",t,`(function() {
463
+ })()`])!=="true")throw Error("Gemini input field did not accept text — input verification failed")}async function bn(t){await g(["eval",t,`(function() {
464
464
  const chat = document.querySelector('chat-window, [role="main"], main') || document.body;
465
465
  chat.scrollTo ? chat.scrollTo({ top: chat.scrollHeight, behavior: 'smooth' }) : window.scrollTo(0, document.body.scrollHeight);
466
- })()`])}async function yn(t){let e=await g(["eval",t,String.raw`
466
+ })()`])}async function hn(t){let e=await g(["eval",t,String.raw`
467
467
  (() => {
468
468
  // The model-response element is a custom element <model-response>.
469
469
  // Its innerText starts with the "Gemini said" label in the
@@ -491,7 +491,7 @@ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
491
491
  }
492
492
  return JSON.stringify({ answer, sources });
493
493
  })()
494
- `]);try{return JSON.parse(e)}catch{return{answer:"",sources:[]}}}async function wn(t,e=""){let n=e.toLowerCase().trim(),r=!1,i=Date.now()+12000;while(Date.now()<i){if(await g(["eval",t,String.raw`(() => {
494
+ `]);try{return JSON.parse(e)}catch{return{answer:"",sources:[]}}}async function yn(t,e=""){let n=e.toLowerCase().trim(),r=!1,i=Date.now()+12000;while(Date.now()<i){if(await g(["eval",t,String.raw`(() => {
495
495
  const r = document.querySelector('model-response');
496
496
  if (!r) return false;
497
497
  const t = (r.innerText || '').trim();
@@ -506,12 +506,12 @@ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
506
506
  if (!btn) return 'no-copy-button';
507
507
  btn.click();
508
508
  return 'clicked';
509
- })()`]),await new Promise((c)=>setTimeout(c,600));let o=await g(["eval",t,`window.${ct} || ''`]);if(o&&n&&(o.toLowerCase().trim()===n||o.trim().length<n.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),await g(["eval",t,`(() => {
509
+ })()`]),await new Promise((c)=>setTimeout(c,600));let o=await g(["eval",t,`window.${ft} || ''`]);if(o&&n&&(o.toLowerCase().trim()===n||o.trim().length<n.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),await g(["eval",t,`(() => {
510
510
  const resp = document.querySelector('model-response');
511
511
  if (!resp) return 'no-model-response';
512
512
  const btn = resp.querySelector('${j.copyButton}');
513
513
  if (!btn) return 'no-copy-button';
514
514
  btn.click();
515
515
  return 'clicked';
516
- })()`]),await new Promise((c)=>setTimeout(c,600)),o=await g(["eval",t,`window.${ct} || ''`]);let u=null;if(!o||n&&(o.toLowerCase().trim()===n||o.trim().length<n.length)){if(u=await yn(t),u.answer)o=u.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let a=wt(o),l=new Map;for(let c of[...u?.sources||[],...a])if(c?.url&&!l.has(c.url))l.set(c.url,c);let f=Array.from(l.values()).slice(0,10);return{answer:o.trim(),sources:f}}var mn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
517
- `;async function vn(){let t=await pt(process.argv.slice(2));$t(t,mn);let{query:e,tabPrefix:n,short:r}=xt(t);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await It();try{await g(["list"]);let i=await bt(n),o=await g(["eval",i,"document.location.href"]).catch(()=>""),u=!1;try{let s=new URL(o).hostname.toLowerCase();u=s==="gemini.google.com"||s.endsWith(".gemini.google.com")}catch{}if(!u)await g(["nav",i,"https://gemini.google.com/app"],20000),await new Promise((s)=>setTimeout(s,600));await Et(i,g),await ee(i,g,1e4),await vt(i,j.input,8000,M.inputPoll),await new Promise((s)=>setTimeout(s,B(M.postClick))),await ht(i,ct),await bn(i,e),await new Promise((s)=>setTimeout(s,B(M.postType))),await g(["eval",i,`document.querySelector('${j.sendButton}')?.click()`]);let a=0,l=setInterval(()=>{if(++a%10===0)hn(i).catch(()=>null)},6000);try{await mt(i,{timeout:45000,minLength:50})}finally{clearInterval(l)}let{answer:f,sources:c}=await wn(i,e);if(!f)throw Error("No answer captured from Gemini clipboard");let b=await g(["eval",i,"document.location.href"]).catch(()=>"https://gemini.google.com/app");kt({query:e,url:b,answer:Jt(f,r),sources:c})}catch(i){Wt(i)}}vn();
516
+ })()`]),await new Promise((c)=>setTimeout(c,600)),o=await g(["eval",t,`window.${ft} || ''`]);let u=null;if(!o||n&&(o.toLowerCase().trim()===n||o.trim().length<n.length)){if(u=await hn(t),u.answer)o=u.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let a=yt(o),l=new Map;for(let c of[...u?.sources||[],...a])if(c?.url&&!l.has(c.url))l.set(c.url,c);let f=Array.from(l.values()).slice(0,10);return{answer:o.trim(),sources:f}}var wn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
517
+ `;async function mn(){let t=await vt(process.argv.slice(2));xt(t,wn);let{query:e,tabPrefix:n,short:r}=pt(t);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await Lt();try{await g(["list"]);let i=await st(n),o=await g(["eval",i,"document.location.href"]).catch(()=>""),u=!1;try{let s=new URL(o).hostname.toLowerCase();u=s==="gemini.google.com"||s.endsWith(".gemini.google.com")}catch{}if(!u)await g(["nav",i,"https://gemini.google.com/app"],20000),await new Promise((s)=>setTimeout(s,600));await Ft(i,g),await te(i,g,1e4),await mt(i,j.input,8000,T.inputPoll),await new Promise((s)=>setTimeout(s,B(T.postClick))),await bt(i,ft),await sn(i,e),await new Promise((s)=>setTimeout(s,B(T.postType))),await g(["eval",i,`document.querySelector('${j.sendButton}')?.click()`]);let a=0,l=setInterval(()=>{if(++a%10===0)bn(i).catch(()=>null)},6000);try{await wt(i,{timeout:45000,minLength:50})}finally{clearInterval(l)}let{answer:f,sources:c}=await yn(i,e);if(!f)throw Error("No answer captured from Gemini clipboard");let b=await g(["eval",i,"document.location.href"]).catch(()=>"https://gemini.google.com/app");Jt({query:e,url:b,answer:$t(f,r),sources:c})}catch(i){kt(i)}}mn();