@duckmind/dm-darwin-x64 0.52.6 → 0.53.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +14 -10
  3. package/extensions/dm-cua/bin/browser-cua.mjs +6 -6
  4. package/extensions/dm-cua/index.js +5 -5
  5. package/extensions/dm-cua/src/browser-cua-lib.mjs +2 -2
  6. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +8 -1
  7. package/extensions/greedysearch-dm/bin/cdp-headless.mjs +1 -1
  8. package/extensions/greedysearch-dm/bin/cdp-visible.mjs +1 -1
  9. package/extensions/greedysearch-dm/bin/cdp.mjs +29 -20
  10. package/extensions/greedysearch-dm/bin/gschrome.mjs +1 -8
  11. package/extensions/greedysearch-dm/bin/kill-visible.mjs +1 -1
  12. package/extensions/greedysearch-dm/bin/launch-visible.mjs +1 -2
  13. package/extensions/greedysearch-dm/bin/launch.mjs +9 -11
  14. package/extensions/greedysearch-dm/bin/mcp.mjs +375 -0
  15. package/extensions/greedysearch-dm/bin/search.mjs +309 -157
  16. package/extensions/greedysearch-dm/bin/visible.mjs +1 -1
  17. package/extensions/greedysearch-dm/extractors/bing-copilot.mjs +205 -68
  18. package/extensions/greedysearch-dm/extractors/chatgpt.mjs +229 -140
  19. package/extensions/greedysearch-dm/extractors/common.mjs +160 -50
  20. package/extensions/greedysearch-dm/extractors/consensus.mjs +226 -93
  21. package/extensions/greedysearch-dm/extractors/consent.mjs +44 -17
  22. package/extensions/greedysearch-dm/extractors/gemini.mjs +277 -138
  23. package/extensions/greedysearch-dm/extractors/google-ai.mjs +172 -64
  24. package/extensions/greedysearch-dm/extractors/logically.mjs +183 -69
  25. package/extensions/greedysearch-dm/extractors/perplexity.mjs +331 -65
  26. package/extensions/greedysearch-dm/extractors/semantic-scholar.mjs +118 -41
  27. package/extensions/greedysearch-dm/index.js +23 -20
  28. package/extensions/greedysearch-dm/package.json +8 -3
  29. package/extensions/greedysearch-dm/skills/greedy-search/skill.md +8 -8
  30. package/extensions/greedysearch-dm/src/fetcher.mjs +2 -2
  31. package/extensions/greedysearch-dm/src/formatters/results.js +8 -6
  32. package/extensions/greedysearch-dm/src/github.mjs +7 -7
  33. package/extensions/greedysearch-dm/src/reddit.mjs +1 -1
  34. package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +10 -8
  35. package/extensions/greedysearch-dm/src/search/challenge-detect.mjs +48 -0
  36. package/extensions/greedysearch-dm/src/search/chrome.mjs +130 -54
  37. package/extensions/greedysearch-dm/src/search/constants.mjs +6 -6
  38. package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
  39. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +160 -83
  40. package/extensions/greedysearch-dm/src/search/minimize.mjs +1 -0
  41. package/extensions/greedysearch-dm/src/search/paths.mjs +1 -1
  42. package/extensions/greedysearch-dm/src/search/pdf.mjs +1 -1
  43. package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -1
  44. package/extensions/greedysearch-dm/src/search/progress.mjs +2 -0
  45. package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
  46. package/extensions/greedysearch-dm/src/search/research.mjs +262 -167
  47. package/extensions/greedysearch-dm/src/search/scale-aware.mjs +11 -0
  48. package/extensions/greedysearch-dm/src/search/simple-research.mjs +827 -0
  49. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +9 -9
  50. package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
  51. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +23 -20
  52. package/extensions/greedysearch-dm/src/tools/shared.js +10 -9
  53. package/extensions/greedysearch-dm/src/utils/node-runtime.mjs +1 -1
  54. package/package.json +1 -1
  55. package/extensions/greedysearch-dm/src/search/cdp-endpoint.mjs +0 -3
  56. package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +0 -3
  57. package/extensions/greedysearch-dm/src/search/partial-output.mjs +0 -1
  58. package/extensions/greedysearch-dm/src/utils/browser-executable.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";import{existsSync as B,readFileSync as j,renameSync as gr,unlinkSync as m,writeFileSync as K}from"node:fs";import me from"node:http";import{platform as Ye,tmpdir as mr}from"node:os";import{spawn as ze}from"node:child_process";import{dirname as et,join as tt}from"node:path";import{fileURLToPath as rt}from"node:url";import{basename as nt}from"node:path";function it(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=nt(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}var at=et(rt(import.meta.url)),ot=tt(at,"..","bin","cdp.mjs");function L(e,t=30000){return st(e,null,t)}function st(e,t=null,r=30000){return new Promise((n,i)=>{let a=ze(it(),[ot,...e],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)a.stdin.write(t),a.stdin.end();let l="",s="";a.stdout.on("data",(u)=>l+=u),a.stderr.on("data",(u)=>s+=u);let o=setTimeout(()=>{a.kill(),i(Error(`cdp timeout: ${e[0]}`))},r);a.on("close",(u)=>{if(clearTimeout(o),u===0)n(l.trim());else i(Error(s.trim()||`cdp exit ${u}`))})})}async function G(e){await L(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
1
+ import{spawn as Jt,execFileSync as se,execSync as Zr}from"node:child_process";import{basename as Be}from"node:path";function pe(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let i=Be(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}import{existsSync as le,readFileSync as z,renameSync as Ht,unlinkSync as h,writeFileSync as V}from"node:fs";import ue from"node:http";import{platform as Je}from"node:os";import{join as qt}from"node:path";import{spawn as Ze}from"node:child_process";import{basename as Qe}from"node:path";import{dirname as Re,join as ze}from"node:path";import{fileURLToPath as Le}from"node:url";function Ve(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let i=Qe(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}var Ie=Re(Le(import.meta.url)),Ye=ze(Ie,"..","bin","cdp.mjs"),Ee=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function Ge(e){if(!Array.isArray(e)||e.length===0)throw Error("cdp: args must be a non-empty array");if(e[0]==="test")return e.map((t,r)=>ge(t,r));if(!Ee.has(e[0]))throw Error(`cdp: unknown subcommand '${e[0]}'`);return e.map((t,r)=>ge(t,r))}function ge(e,t){if(typeof e!=="string")throw Error(`cdp: argv[${t}] must be a string (got ${typeof e})`);if(e.includes("\x00"))throw Error(`cdp: argv[${t}] contains a null byte`);return e}function I(e,t=30000){return Fe(e,null,t)}function Fe(e,t=null,r=30000){let i=Ge(e);return new Promise((n,a)=>{let o=Ze(Ve(),[Ye,...i],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)o.stdin.write(t),o.stdin.end();let s="",l="";o.stdout.on("data",(u)=>s+=u),o.stderr.on("data",(u)=>l+=u);let f=setTimeout(()=>{o.kill(),a(Error(`cdp timeout: ${e[0]}`))},r);o.on("close",(u)=>{if(clearTimeout(f),u===0)n(s.trim());else a(Error(l.trim()||`cdp exit ${u}`))})})}async function Y(e){await I(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
2
2
  (function() {
3
3
  // ── Runtime.enable / CDP detection masking ──────────────
4
4
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -9,40 +9,62 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
9
9
  try { delete window._phantom; } catch(_) {}
10
10
  try { delete window.Buffer; } catch(_) {}
11
11
 
12
- // Real Chrome without automation does not expose a useful webdriver value.
13
- // A literal false value is itself a common stealth tell; prefer undefined and
14
- // make the descriptor configurable like native browser properties.
15
- Object.defineProperty(navigator, 'webdriver', { get: () => undefined, configurable: true });
12
+ // Real Chrome without automation should not expose navigator.webdriver at all.
13
+ // A literal false or an own-property getter returning undefined is itself a
14
+ // common stealth tell; remove both instance and prototype properties when the
15
+ // descriptor is configurable (as it is with --disable-blink-features).
16
+ try { delete navigator.webdriver; } catch(_) {}
17
+ try { delete Navigator.prototype.webdriver; } catch(_) {}
16
18
  Object.defineProperty(navigator, 'vendor', { get: () => 'Google Inc.', configurable: true });
17
19
  Object.defineProperty(navigator, 'platform', { get: () => 'Win32', configurable: true });
18
20
  Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0, configurable: true });
19
21
  Object.defineProperty(navigator, 'pdfViewerEnabled', { get: () => true, configurable: true });
22
+ Object.defineProperty(navigator, 'productSub', { get: () => '20030107', configurable: true });
23
+ Object.defineProperty(navigator, 'product', { get: () => 'Gecko', configurable: true });
24
+ var __greedyMimeTypes = null;
25
+ function __makeMimeTypes() {
26
+ var pdf = { type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null };
27
+ var textPdf = { type: 'text/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null };
28
+ try { Object.setPrototypeOf(pdf, MimeType.prototype); } catch(_) {}
29
+ try { Object.setPrototypeOf(textPdf, MimeType.prototype); } catch(_) {}
30
+ var m = [pdf, textPdf];
31
+ try { Object.setPrototypeOf(m, MimeTypeArray.prototype); } catch(_) {}
32
+ m.item = function item(i) { return this[i] || null; };
33
+ m.namedItem = function namedItem(name) { return Array.prototype.find.call(this, function(x) { return x && x.type === name; }) || null; };
34
+ return m;
35
+ }
20
36
  Object.defineProperty(navigator, 'plugins', {
21
37
  get: () => {
22
- var p = [
23
- { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
24
- { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '' },
25
- { name: 'Native Client', filename: 'internal-nacl-plugin', description: '' },
26
- ];
27
- p.length = 3;
38
+ __greedyMimeTypes = __greedyMimeTypes || __makeMimeTypes();
39
+ var plugin0 = { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format' };
40
+ var plugin1 = { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '' };
41
+ var plugin2 = { name: 'Native Client', filename: 'internal-nacl-plugin', description: '' };
42
+ try { Object.setPrototypeOf(plugin0, Plugin.prototype); } catch(_) {}
43
+ try { Object.setPrototypeOf(plugin1, Plugin.prototype); } catch(_) {}
44
+ try { Object.setPrototypeOf(plugin2, Plugin.prototype); } catch(_) {}
45
+ var p = [plugin0, plugin1, plugin2];
46
+ p.item = function item(i) { return this[i] || null; };
47
+ p.namedItem = function namedItem(name) { return Array.prototype.find.call(this, function(x) { return x && x.name === name; }) || null; };
48
+ p.refresh = function refresh() {};
49
+ try { Object.setPrototypeOf(p, PluginArray.prototype); } catch(_) {}
50
+ try {
51
+ __greedyMimeTypes[0].enabledPlugin = p[0];
52
+ __greedyMimeTypes[1].enabledPlugin = p[0];
53
+ } catch(_) {}
28
54
  return p;
29
55
  },
56
+ configurable: true,
30
57
  });
31
58
  Object.defineProperty(navigator, 'mimeTypes', {
32
59
  get: () => {
33
- var m = [
34
- { type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null },
35
- { type: 'text/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: null },
36
- ];
37
- m.item = function(i) { return m[i] || null; };
38
- m.namedItem = function(name) { return m.find(function(x) { return x.type === name; }) || null; };
39
- return m;
60
+ __greedyMimeTypes = __greedyMimeTypes || __makeMimeTypes();
61
+ return __greedyMimeTypes;
40
62
  },
41
63
  configurable: true,
42
64
  });
43
65
  Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'], configurable: true });
44
66
  try {
45
- Object.defineProperty(navigator, 'connection', { get: () => ({ effectiveType: '4g', rtt: 50, downlink: 10, saveData: false }), configurable: true });
67
+ Object.defineProperty(navigator, 'connection', { get: () => ({ effectiveType: '4g', rtt: 50, downlink: 10, downlinkMax: Infinity, saveData: false }), configurable: true });
46
68
  } catch(_) {}
47
69
  if (!navigator.mediaDevices) {
48
70
  Object.defineProperty(navigator, 'mediaDevices', {
@@ -58,6 +80,18 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
58
80
  configurable: true,
59
81
  });
60
82
  }
83
+ // ── Missing platform APIs (headless often lacks these) ─
84
+ try {
85
+ if (!navigator.share) {
86
+ navigator.share = function() { return Promise.reject(new Error('NotAllowedError')); };
87
+ }
88
+ } catch(_) {}
89
+ try {
90
+ if (!navigator.contentIndex) {
91
+ Object.defineProperty(navigator, 'contentIndex', { get: () => ({ add: function() {}, delete: function() {}, getAll: function() { return Promise.resolve([]); } }), configurable: true });
92
+ }
93
+ } catch(_) {}
94
+
61
95
  if (!window.chrome) {
62
96
  window.chrome = {
63
97
  app: { isInstalled: false, InstallState: {}, RunningState: {} },
@@ -65,8 +99,8 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
65
99
  OnInstalledReason: {}, OnRestartRequiredReason: {}, PlatformArch: {}, PlatformNaclArch: {}, PlatformOs: {}, RequestUpdateCheckStatus: {},
66
100
  connect: () => ({}), sendMessage: () => {}, onMessage: { addListener: () => {} }
67
101
  },
68
- loadTimes: () => ({}),
69
- csi: () => ({}),
102
+ loadTimes: function() { return { requestTime: 0, startLoadTime: Date.now() - 5000, commitLoadTime: Date.now() - 3000, finishDocumentLoadTime: Date.now() - 2000, finishLoadTime: Date.now() - 1000, firstPaintTime: Date.now() - 800, navigationType: 'Other', wasFetchedViaSpdy: true, wasNpnNegotiated: true, npnNegotiatedProtocol: 'h2', wasAlternateProtocolAvailable: false, connectionInfo: 'http/2' }; },
103
+ csi: function() { var t = Date.now(); return { onloadT: t - 2000, startE: t - 5000, pageT: 'back', tran: 2 }; },
70
104
  };
71
105
  }
72
106
  var __greedyNativeFns = [];
@@ -87,6 +121,19 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
87
121
  return getParam.call(this, p);
88
122
  });
89
123
  } catch(_) {}
124
+ // ── WebGL readPixels noise ──────────────────────────
125
+ // CreepJS and other fingerprinters draw content with WebGL and read back the
126
+ // rendered pixels. Adding subtle noise breaks rendering-based fingerprinting.
127
+ try {
128
+ var origReadPixels = WebGLRenderingContext.prototype.readPixels;
129
+ WebGLRenderingContext.prototype.readPixels = __markNative(function readPixels(x, y, width, height, format, type, pixels) {
130
+ var result = origReadPixels.call(this, x, y, width, height, format, type, pixels);
131
+ if (pixels && pixels.length > 0) {
132
+ pixels[0] ^= 1;
133
+ }
134
+ return result;
135
+ });
136
+ } catch(_) {}
90
137
  Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 8, configurable: true });
91
138
  Object.defineProperty(navigator, 'deviceMemory', { get: () => 8, configurable: true });
92
139
 
@@ -94,7 +141,7 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
94
141
  // Headless rendering engines produce slightly different canvas output
95
142
  // than headed Chrome. Subtle noise breaks hash-based fingerprinting.
96
143
  try {
97
- var __canvasNoise = ((Date.now() % 997) + Math.floor(Math.random() * 997)) & 1;
144
+ var __canvasNoise = ((Date.now() & 0xFF) | 1);
98
145
  var origFill = CanvasRenderingContext2D.prototype.fillText;
99
146
  CanvasRenderingContext2D.prototype.fillText = __markNative(function fillText() {
100
147
  this.globalAlpha = 0.9995;
@@ -113,15 +160,39 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
113
160
  HTMLCanvasElement.prototype.toDataURL = __markNative(function toDataURL() {
114
161
  var ctx = this.getContext('2d');
115
162
  if (ctx) {
116
- // Add 1px noise pixel in corner (invisible but changes hash)
117
- var imgData = ctx.getImageData(0, 0, 1, 1);
118
- if (imgData) imgData.data[0] ^= __canvasNoise;
119
- ctx.putImageData(imgData, 0, 0);
163
+ // Spread noise across canvas to break hash-based fingerprinting.
164
+ // Uses a deterministic pattern so it's consistent per page load
165
+ // but varies between sessions.
166
+ var w = this.width, h = this.height;
167
+ if (w > 0 && h > 0) {
168
+ var imgData = ctx.getImageData(0, 0, Math.min(w, 4), Math.min(h, 4));
169
+ if (imgData && imgData.data) {
170
+ for (var __i = 0; __i < imgData.data.length; __i += 4) {
171
+ imgData.data[__i] ^= (__canvasNoise + __i) & 0xFF;
172
+ }
173
+ ctx.putImageData(imgData, 0, 0);
174
+ }
175
+ }
120
176
  }
121
177
  return origToDataURL.apply(this, arguments);
122
178
  });
123
179
  } catch(_) {}
124
180
 
181
+ // ── AudioContext fingerprint noise ────────────────────
182
+ // Headless Chrome's AudioContext produces slightly different output.
183
+ // Subtle noise breaks audio-based fingerprinting.
184
+ try {
185
+ var __audioSeed = ((Date.now() & 0x1F) | 1);
186
+ var origGetChannelData = AudioBuffer.prototype.getChannelData;
187
+ AudioBuffer.prototype.getChannelData = __markNative(function getChannelData(channel) {
188
+ var data = origGetChannelData.call(this, channel);
189
+ for (var __i = 0; __i < data.length; __i += 64) {
190
+ data[__i] *= 0.99999;
191
+ }
192
+ return data;
193
+ });
194
+ } catch(_) {}
195
+
125
196
  // ── window outer dimensions ──────────────────────────
126
197
  // outerWidth/Height = 0 in headless — a well-known bot signal.
127
198
  // Mirror innerWidth/Height (set by --window-size flag) so the ratio is sane.
@@ -131,9 +202,15 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
131
202
  } catch(_) {}
132
203
 
133
204
  // ── screen properties ─────────────────────────────────
205
+ // Headless Chrome often reports an 800x600 screen even when the viewport is
206
+ // 1920x1080. Keep screen metrics internally consistent with our launch flags.
134
207
  try {
135
- if (!screen.colorDepth) Object.defineProperty(screen, 'colorDepth', { get: () => 24, configurable: true });
136
- if (!screen.pixelDepth) Object.defineProperty(screen, 'pixelDepth', { get: () => 24, configurable: true });
208
+ Object.defineProperty(screen, 'width', { get: () => 1920, configurable: true });
209
+ Object.defineProperty(screen, 'height', { get: () => 1080, configurable: true });
210
+ Object.defineProperty(screen, 'availWidth', { get: () => 1920, configurable: true });
211
+ Object.defineProperty(screen, 'availHeight', { get: () => 1040, configurable: true });
212
+ Object.defineProperty(screen, 'colorDepth', { get: () => 24, configurable: true });
213
+ Object.defineProperty(screen, 'pixelDepth', { get: () => 24, configurable: true });
137
214
  } catch(_) {}
138
215
 
139
216
  // ── navigator.userAgentData (UA Client Hints) ─────────
@@ -206,29 +283,28 @@ import{spawn as fr,execFileSync as Ve,execSync as pr}from"node:child_process";im
206
283
  };
207
284
  } catch(_) {}
208
285
  })();
209
- `})])}import{basename as lt}from"node:path";function we(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=lt(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}import{existsSync as ye}from"node:fs";import{platform as ut}from"node:os";import{join as b}from"node:path";function x(e){let t=ut()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:b(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:b(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:b(r,"System32","netstat.exe"),taskkill:b(r,"System32","taskkill.exe"),tasklist:b(r,"System32","tasklist.exe"),cmd:b(r,"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=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&ye(i[a]))return i[a];if(t&&a==="netstat"){let l=b(r,"Sysnative","netstat.exe");if(ye(l))return l}return e}import{existsSync as H,mkdirSync as ct,readFileSync as _e,writeFileSync as ft}from"node:fs";import{homedir as pt}from"node:os";import{join as $e}from"node:path";import{tmpdir as Q}from"node:os";function gt(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var c=gt(process.env.GREEDY_SEARCH_PORT,9222),V=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Q().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),A=`${V}/DevToolsActivePort`,re=`${Q().replaceAll("\\","/")}/cdp-pages.json`,w=process.env.GREEDY_SEARCH_MODE_FILE||`${Q().replaceAll("\\","/")}/greedysearch-chrome-mode`,Br=`${Q().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,z=$e(pt(),".dm"),p=$e(z,"greedyconfig"),ee=["perplexity","google","chatgpt"],te="gemini";function mt(){try{if(H(p)){let e=_e(p,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>F[i]),n=t.engines.filter((i)=>!F[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${p}: ${n.join(", ")}
210
- [greedysearch] Available engines: ${Object.keys(F).join(", ")}
211
- `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${p}, falling back to defaults: ${ee.join(", ")}
212
- `)}}}catch{}return ee}function ht(){try{if(!H(z))ct(z,{recursive:!0});if(!H(p))ft(p,JSON.stringify({engines:ee,synthesizer:te},null,2)+`
213
- `,"utf8")}catch{}}ht();var ve=["gemini","chatgpt"];function dt(){try{if(H(p)){let e=_e(p,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(ve.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${p}
214
- [greedysearch] Available synthesizers: ${ve.join(", ")}
215
- [greedysearch] Falling back to default: ${te}
216
- `)}}}catch{}return te}var F={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"},jr=mt();var qr=dt(),Hr=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=V;import{existsSync as Er,mkdirSync as bt,readFileSync as xe,renameSync as wt,unlinkSync as yt,writeFileSync as Ae}from"node:fs";import vt from"node:http";import{platform as Se}from"node:os";import{dirname as _t}from"node:path";var Ce=[9222,9223],$t=/^(0|false|no|off)$/i;function Pt(e){return[...new Set(e.filter(Boolean))]}function Pe(e,t="explicit"){let r=new URL(e),n=r.protocol==="wss:"?"wss:":"ws:",i=r.port?Number.parseInt(r.port,10):n==="wss:"?443:80;return{source:t,wsUrl:`${n}//${r.host}${r.pathname}${r.search}`,host:r.hostname,port:i,path:`${r.pathname}${r.search}`,httpUrl:`http://${r.hostname}:${i}`}}function Ne(e=process.env){return![e.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,e.DM_CUA_REUSE_EXISTING_BROWSER].some((t)=>t!==void 0&&$t.test(String(t)))}function ne(e){let t=Number.parseInt(String(e??""),10);return Number.isInteger(t)&&t>0&&t<65536?t:null}function xt(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=new URL(t.includes("://")?t:`http://${t}`),n=ne(r.port)||(r.protocol==="https:"?443:80);return{host:r.hostname,port:n,source:`env:${t}`}}function At(e){if(!e)return[];return String(e).split(/[,\s]+/).map(ne).filter(Boolean)}function St({env:e=process.env,platformName:t=Se(),procVersionText:r=null}={}){if(t!=="linux")return!1;if(e.WSL_DISTRO_NAME||e.WSL_INTEROP)return!0;let n=r??(()=>{try{return xe("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(n)}function Ct({env:e=process.env,platformName:t=Se(),procVersionText:r=null,resolvConfText:n=null}={}){let i=["localhost","127.0.0.1"];if(St({env:e,platformName:t,procVersionText:r})){let a=(n??(()=>{try{return xe("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(a)i.push(a[1]);i.push("host.docker.internal")}return Pt(i)}function Nt({env:e=process.env,hosts:t=Ct({env:e}),autoPorts:r=Ce,excludePorts:n=[]}={}){let i=[];for(let o of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(e[o])i.push({wsUrl:e[o],source:`env:${o}`});for(let o of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let u=xt(e[o]);if(u)i.push(u)}catch{}for(let o of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let u=ne(e[o]);if(!u)continue;for(let f of t)i.push({host:f,port:u,source:`env:${o}`})}let a=At(e.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let o of a)for(let u of t)i.push({host:u,port:o,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let l=new Set(n.filter(Boolean));if(Ne(e))for(let o of r){if(l.has(o))continue;for(let u of t)i.push({host:u,port:o,source:"auto"})}let s=new Set;return i.filter((o)=>{let u=o.wsUrl||`${o.host}:${o.port}`;if(s.has(u))return!1;return s.add(u),!0})}async function Dt(e,{timeoutMs:t=700}={}){if(e.wsUrl)return Pe(e.wsUrl,e.source);let r=e.host||"localhost",n=e.port;if(!n)return null;let i=await new Promise((a)=>{let l=vt.get({host:r,port:n,path:"/json/version",timeout:t},(s)=>{let o="";s.setEncoding("utf8"),s.on("data",(u)=>o+=u),s.on("end",()=>a(s.statusCode===200?o:null))});l.on("error",()=>a(null)),l.setTimeout(t,()=>{l.destroy(),a(null)})});if(!i)return null;try{let a=JSON.parse(i);if(!a.webSocketDebuggerUrl)return null;let l=Pe(a.webSocketDebuggerUrl,e.source),s=l.path||new URL(a.webSocketDebuggerUrl).pathname;return{...l,host:r,port:n,httpUrl:`http://${r}:${n}`,wsUrl:`ws://${r}:${n}${s}`,path:s}}catch{return null}}async function Wt(e={}){for(let t of Nt(e)){let r=await Dt(t,e);if(r)return r}return null}function Rt(e){if(!e)throw Error("missing CDP endpoint");let t=new URL(e.wsUrl);return`${t.host}
217
- ${t.pathname}${t.search}
218
- `}function kt(e,t){bt(_t(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;Ae(r,Rt(t),"utf8");try{yt(e)}catch{}wt(r,e)}async function De({activePortFile:e,modeFile:t,env:r=process.env,excludePorts:n=[],autoPorts:i=Ce}={}){if(!Ne(r))return null;let a=await Wt({env:r,excludePorts:n,autoPorts:i});if(!a)return null;if(kt(e,a),t)Ae(t,"existing","utf8");return a}import{existsSync as Tt}from"node:fs";import{dirname as Ot,join as S}from"node:path";function Jt(e){let t=new Set;return e.filter((r)=>{if(!r||t.has(r))return!1;return t.add(r),!0})}function Ut({moduleDir:e,entrypoint:t=process.argv[1],env:r=process.env}={}){let n=t?Ot(t):null,i=r.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return Jt([i?S(i,"bin","launch.mjs"):null,e?S(e,"launch.mjs"):null,e?S(e,"..","bin","launch.mjs"):null,e?S(e,"..","..","bin","launch.mjs"):null,n?S(n,"launch.mjs"):null,n?S(n,"..","bin","launch.mjs"):null])}function We({moduleDir:e,entrypoint:t=process.argv[1],env:r=process.env,exists:n=Tt}={}){let i=Ut({moduleDir:e,entrypoint:t,env:r}),a=i.find((l)=>n(l));if(a)return a;throw Error(`GreedySearch launcher not found. Checked candidates:
219
- ${i.map((l)=>`- ${l}`).join(`
220
- `)}`)}import{execFileSync as Mt}from"node:child_process";import{platform as Xt}from"node:os";function Bt(e,t){return Mt(x(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function jt(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function qt(e){return jt(e)}function Ht(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((a)=>a.endsWith(`:${t}`)))continue;let i=r.match(/\bpid=(\d+)\b/);if(i)return Number.parseInt(i[1],10)}return null}function Qt(e,t){for(let r of String(e||"").split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n.length<5||n[0].toUpperCase()!=="TCP")continue;if(!n.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!n[1].endsWith(`:${t}`))continue;let a=Number.parseInt(n.at(-1),10);if(Number.isInteger(a)&&a>0)return a}return null}function ie(e,t,r){try{return e(t,r)}catch{return null}}function Re(e,{platformName:t=Xt(),run:r=Bt}={}){if(t==="win32")return Qt(ie(r,"netstat",["-ano","-p","TCP"]),e);let n=ie(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),i=qt(n);if(i)return i;if(t!=="linux")return null;return Ht(ie(r,"ss",["-ltnp"]),e)}import{execFileSync as ke,execSync as an}from"node:child_process";import{existsSync as y,mkdirSync as Vt,readFileSync as C,unlinkSync as $,writeFileSync as P}from"node:fs";import{platform as Et,tmpdir as Xe}from"node:os";import{existsSync as E,mkdirSync as Yt,readFileSync as Be,writeFileSync as Zt}from"node:fs";import{homedir as It}from"node:os";import{join as je}from"node:path";import{tmpdir as I}from"node:os";import{execFileSync as zt}from"node:child_process";import{platform as er}from"node:os";import{existsSync as Oe}from"node:fs";import{platform as tr}from"node:os";import{join as v}from"node:path";function Kt(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var D=Kt(process.env.GREEDY_SEARCH_PORT,9222),T=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${I().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),pn=`${T}/DevToolsActivePort`,gn=`${I().replaceAll("\\","/")}/cdp-pages.json`,mn=process.env.GREEDY_SEARCH_MODE_FILE||`${I().replaceAll("\\","/")}/greedysearch-chrome-mode`,hn=`${I().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,se=je(It(),".dm"),g=je(se,"greedyconfig"),le=["perplexity","google","chatgpt"],ue="gemini";function Lt(){try{if(E(g)){let e=Be(g,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>ae[i]),n=t.engines.filter((i)=>!ae[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${g}: ${n.join(", ")}
221
- [greedysearch] Available engines: ${Object.keys(ae).join(", ")}
222
- `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${g}, falling back to defaults: ${le.join(", ")}
223
- `)}}}catch{}return le}function Gt(){try{if(!E(se))Yt(se,{recursive:!0});if(!E(g))Zt(g,JSON.stringify({engines:le,synthesizer:ue},null,2)+`
224
- `,"utf8")}catch{}}Gt();var Te=["gemini","chatgpt"];function Ft(){try{if(E(g)){let e=Be(g,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(Te.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${g}
225
- [greedysearch] Available synthesizers: ${Te.join(", ")}
226
- [greedysearch] Falling back to default: ${ue}
227
- `)}}}catch{}return ue}var ae={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"},dn=Lt(),bn=Ft(),wn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=T;function ce(e){let t=tr()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:v(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:v(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:v(r,"System32","netstat.exe"),taskkill:v(r,"System32","taskkill.exe"),tasklist:v(r,"System32","tasklist.exe"),cmd:v(r,"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=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&Oe(i[a]))return i[a];if(t&&a==="netstat"){let l=v(r,"Sysnative","netstat.exe");if(Oe(l))return l}return e}function rr(e,t){return zt(ce(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function nr(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function ir(e){return nr(e)}function ar(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((i)=>i.endsWith(`:${t}`)))continue;let n=r.match(/\bpid=(\d+)\b/);if(n)return Number.parseInt(n[1],10)}return null}function or(e,t){for(let r of String(e||"").split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n.length<5||n[0].toUpperCase()!=="TCP")continue;if(!n.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!n[1].endsWith(`:${t}`))continue;let i=Number.parseInt(n.at(-1),10);if(Number.isInteger(i)&&i>0)return i}return null}function oe(e,t,r){try{return e(t,r)}catch{return null}}function sr(e,{platformName:t=er(),run:r=rr}={}){if(t==="win32")return or(oe(r,"netstat",["-ano","-p","TCP"]),e);let n=oe(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),i=ir(n);if(i)return i;if(t!=="linux")return null;return ar(oe(r,"ss",["-ltnp"]),e)}var J=Xe().replaceAll("\\","/"),Y=`${J}/greedysearch-chrome-metadata.json`,_=`${J}/greedysearch-chrome-launch.lock`,lr=15000,R=`${J}/greedysearch-chrome.pid`,k=`${J}/greedysearch-chrome-mode`,N=`${J}/greedysearch-chrome-last-activity`;function O(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function ur(e){if(!O(e))return null;try{if(Et()==="win32")return ke(ce("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ke(ce("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function fe(e,t,r=D){if(!e)return!1;let n=(l)=>String(l||"").replaceAll("\\","/").toLowerCase(),i=n(e),a=n(t);return i.includes(a)&&i.includes(`--remote-debugging-port=${r}`)&&!i.includes("--type=")}function Je(e,t,r=D){return fe(ur(e),t,r)}function cr(e=D){return sr(e)}function U(){try{if(y(Y)){let e=C(Y,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((r)=>Number.isInteger(r)&&r>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{if(!(y(R)||y(k)||y(N)))return null;let e=y(R)?Number.parseInt(C(R,"utf8").trim(),10)||void 0:void 0,t=y(k)?C(k,"utf8").trim()==="visible"?"visible":"headless":"headless",r=y(N)?Number.parseInt(C(N,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:D,tempDir:T,clientPids:e?[e]:[],sessionMode:t,lastActivity:r,launchedAt:0}}catch{return null}}function Z(e){try{P(Y,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)P(R,String(e.browserPid),"utf8")}catch{}try{P(k,e.sessionMode,"utf8")}catch{}try{P(N,String(e.lastActivity),"utf8")}catch{}}function Ue(){try{$(Y)}catch{}try{$(R)}catch{}try{$(k)}catch{}try{$(N)}catch{}}function qe(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>O(r)||r===process.pid))]};return Z(t),t}function pe(e){let t=Date.now();try{if(e)Z({...e,lastActivity:t});else P(N,String(t),"utf8")}catch{}}var xn=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Me=!1;function He(){if(Me)return;Me=!0;let e=U();if(!e)return;if(e.browserPid){if(!O(e.browserPid)){Ue();return}if(!Je(e.browserPid,e.tempDir,e.debugPort))Ue();else Z({...e,clientPids:e.clientPids.filter((r)=>O(r))})}let t=cr();if(t&&t!==e.browserPid)if(Je(t,T,D))Z({browserPid:t,debugPort:D,tempDir:T,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else return}function Qe(){Vt(Xe(),{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return P(_,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=C(_,"utf8");if(JSON.parse(t).pid===process.pid)$(_)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=C(_,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!O(t.pid)||r>lr){try{$(_)}catch{}try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return P(_,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{$(_)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var hr=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Ze=mr().replaceAll("\\","/"),M=`${Ze}/greedysearch-chrome.pid`,X=`${Ze}/greedysearch-chrome-last-activity`,dr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,br=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function wr(e,t=c){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function Ie(){try{let e=he(),t=e?Ke(e):null,r=wr(t);if(r!==null){try{K(w,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!B(w))return!0;return j(w,"utf8").trim()==="headless"}catch{return!0}}function yr(){try{K(X,String(Date.now()),"utf8")}catch{}try{let e=U();if(e)pe(e)}catch{}}function Ke(e){try{if(Ye()==="win32")return Ve(x("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Ve(x("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function he(){return Re(c)}function Le(){let e=[he()];if(B(M))e.push(Number.parseInt(j(M,"utf8").trim(),10)||null);for(let t of e){if(!t)continue;if(fe(Ke(t),V,c))return t}return null}async function vr(e=1500){let t=Le();if(!t)return!1;try{let n=await new Promise((a,l)=>{let s=me.get(`http://localhost:${c}/json/version`,(o)=>{let u="";o.on("data",(f)=>u+=f),o.on("end",()=>{try{a(JSON.parse(u))}catch{l(Error("bad JSON"))}})});s.on("error",l),s.setTimeout(1000,()=>{s.destroy(),l(Error("timeout"))})}),i=new globalThis.WebSocket(n.webSocketDebuggerUrl);await new Promise((a)=>{i.onopen=()=>{i.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{i.close(),a()},200)},i.onerror=()=>a(),setTimeout(a,1000)})}catch{}let r=Date.now()+e;while(Date.now()<r){let n=he();if(!n)return!0;if(n!==t)return!0;await new Promise((i)=>setTimeout(i,150))}return _r()}function _r(){try{let e=Le();if(!e)return!1;if(Ye()==="win32")pr(`${x("taskkill")} /F /PID ${e}`,{stdio:"ignore"});else process.kill(e,"SIGKILL");return!0}catch{return!1}}async function Ge(){if(!await W(500)){try{m(M)}catch{}try{m(X)}catch{}try{m(w)}catch{}return!1}let t=await vr(1500);try{m(M)}catch{}try{m(X)}catch{}try{m(w)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${c}.
228
- `);return t}var Ee=Ge;async function $r(){let t=Ie()?dr:br;if(t<=0)return!1;if(!B(X))return yr(),!1;try{let r=Number.parseInt(j(X,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Ge()}catch{}return!1}var h=L;async function de(){let t=(await h(["list"])).split(`
229
- `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function Xn(e="about:blank"){let t=await de(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let l=await h(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(l),o=s.slice(0,8);if(await h(["list"]).catch(()=>null),r==="copilot.microsoft.com")await G(o);else G(o).catch(()=>{});return await h(["list"]).catch(()=>null),s}let i=await h(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(i);return await h(["list"]).catch(()=>null),a}async function Bn(e){try{let t=await de();await h(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function Pr(e){try{let t=await de();await h(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function jn(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>Pr(t).catch(()=>{}))),e.length>0)await h(["list"]).catch(()=>null)}function qn(e,t){try{if(!B(re))return null;let n=JSON.parse(j(re,"utf8")).find((i)=>i.url.includes(t[e]));return n?n.targetId:null}catch{return null}}function W(e=3000){return new Promise((t)=>{let r=me.get(`http://localhost:${c}/json/version`,(n)=>{n.resume(),t(n.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function ge(){let e=`${A}.lock`,t=`${A}.tmp`,r=5000,n=1000,i=await new Promise((a)=>{let l=Date.now(),s=()=>{try{let o=JSON.stringify({pid:process.pid,ts:Date.now()});K(e,o,{encoding:"utf8",flag:"wx"}),a(!0)}catch(o){if(o?.code!=="EEXIST"){if(Date.now()-l<1000)setTimeout(s,50);else a(!1);return}try{let u=j(e,"utf8").trim(),f=u.startsWith("{")?JSON.parse(u):{ts:Number(u)},d=Number(f?.ts)||0;if(d>0&&Date.now()-d>5000)try{m(e)}catch{}if(Date.now()-l<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-l<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((u,f)=>{let d=me.get(`http://localhost:${c}/json/version`,(q)=>{let be="";q.on("data",(Fe)=>be+=Fe),q.on("end",()=>u(be))});d.on("error",f),d.setTimeout(3000,()=>{d.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:l}=JSON.parse(a),s=new URL(l),o=`${s.pathname}${s.search}`;if(i){K(t,`localhost:${c}
230
- ${o}`,"utf8");try{m(A)}catch{}gr(t,A)}}catch{}finally{if(i)try{m(e)}catch{}}}async function Hn(){let e=B(M)||!!U(),t=await De({activePortFile:A,modeFile:w,excludePorts:e?[c]:[]});if(t){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${t.httpUrl} (${t.source}).
231
- `);return}He();let r=await $r(),n=r?!1:await W();if(!n&&!r)await new Promise((s)=>setTimeout(s,500)),n=await W();let i=!1;if(n){let s=Ie(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!s)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
232
- `),await Ee(),await new Promise((u)=>setTimeout(u,1000)),i=!0;else if(o&&s)process.stderr.write(`[greedysearch] Headless Chrome detected switching to visible mode...
233
- `),await Ee(),await new Promise((u)=>setTimeout(u,1000)),i=!0}if(i?!1:await W()){await ge();try{let s=U();if(s)pe(s),qe(s)}catch{}return}let l=Qe();if(!l.acquired){let s=Date.now()+15000;while(Date.now()<s)if(await new Promise((o)=>setTimeout(o,250)),await W(1000)){await ge();return}throw Error(`Timed out waiting for another GreedySearch launcher on port ${c}`)}try{if(await W(1000)){await ge();return}process.stderr.write(`GreedySearch Chrome not running on port ${c} auto-launching...
234
- `);let o=[We({moduleDir:hr,entrypoint:process.argv[1]})];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((u,f)=>{fr(we(),o,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(q)=>q===0?u():f(Error("launch.mjs failed")))})}finally{l.release()}}export{yr as touchActivity,ge as refreshPortFile,W as probeGreedyChrome,Xn as openNewTab,Ee as killHeadlessChrome,Ge as killChrome,Ie as isChromeHeadless,qn as getFullTabFromCache,de as getAnyTab,Hn as ensureChrome,wr as detectHeadlessFromChromeCommandLine,jn as closeTabs,Pr as closeTab,$r as checkAndKillIdle,h as cdp,Bn as activateTab};
286
+ `})])}import{existsSync as de}from"node:fs";import{platform as Ke}from"node:os";import{join as w}from"node:path";function C(e){let t=Ke()==="win32",r=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:w(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:w(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:w(r,"System32","netstat.exe"),taskkill:w(r,"System32","taskkill.exe"),tasklist:w(r,"System32","tasklist.exe"),cmd:w(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},n=t?i.win32:i.unix,a=e.toLowerCase();if(n[a]&&de(n[a]))return n[a];if(t&&a==="netstat"){let o=w(r,"Sysnative","netstat.exe");if(de(o))return o}return e}import{execFileSync as et}from"node:child_process";import{platform as tt}from"node:os";function rt(e,t){return et(C(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function nt(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function it(e){return nt(e)}function at(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((a)=>a.endsWith(`:${t}`)))continue;let n=r.match(/\bpid=(\d+)\b/);if(n)return Number.parseInt(n[1],10)}return null}function ot(e,t){for(let r of String(e||"").split(/\r?\n/)){let i=r.trim().split(/\s+/);if(i.length<5||i[0].toUpperCase()!=="TCP")continue;if(!i.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!i[1].endsWith(`:${t}`))continue;let n=Number.parseInt(i.at(-1),10);if(Number.isInteger(n)&&n>0)return n}return null}function E(e,t,r){try{return e(t,r)}catch{return null}}function me(e,{platformName:t=tt(),run:r=rt}={}){if(t==="win32")return ot(E(r,"netstat",["-ano","-p","TCP"]),e);let i=E(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),n=it(i);if(n)return n;if(t!=="linux")return null;return at(E(r,"ss",["-ltnp"]),e)}import{existsSync as O,mkdirSync as st,readFileSync as ye,writeFileSync as lt}from"node:fs";import{homedir as ut}from"node:os";import{join as be}from"node:path";import{tmpdir as ct}from"node:os";function ft(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var pt=ct().replaceAll("\\","/"),g=ft(process.env.GREEDY_SEARCH_PORT),p=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${pt}/greedysearch-chrome-profile`).replaceAll("\\","/"),j=`${p}/DevToolsActivePort`,we=process.env.GREEDY_SEARCH_PID_FILE||`${p}/browser.pid`,te=process.env.CDP_PAGES_CACHE||`${p}/cdp-pages.json`,k=process.env.GREEDY_SEARCH_MODE_FILE||`${p}/browser-mode`,dr=process.env.GREEDY_SEARCH_METADATA_FILE||`${p}/browser-metadata.json`,mr=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${p}/browser-launch.lock`,_e=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${p}/browser-last-activity`,hr=(process.env.CDP_SOCKET_DIR||`${p}/cdp-sockets`).replaceAll("\\","/"),yr=`${p}/visible-recovery.jsonl`,F=be(ut(),".dm"),d=be(F,"greedyconfig"),K=["perplexity","google","chatgpt","gemini"],ee="gemini";function gt(){try{if(O(d)){let e=ye(d,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((n)=>G[n]),i=t.engines.filter((n)=>!G[n]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${d}: ${i.join(", ")}
287
+ [greedysearch] Available engines: ${Object.keys(G).join(", ")}
288
+ `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${d}, falling back to defaults: ${K.join(", ")}
289
+ `)}}}catch{}return K}function dt(){try{if(!O(F))st(F,{recursive:!0});if(!O(d))lt(d,JSON.stringify({engines:K,synthesizer:ee},null,2)+`
290
+ `,"utf8")}catch{}}dt();var he=["gemini","chatgpt"];function mt(){try{if(O(d)){let e=ye(d,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(he.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${d}
291
+ [greedysearch] Available synthesizers: ${he.join(", ")}
292
+ [greedysearch] Falling back to default: ${ee}
293
+ `)}}}catch{}return ee}var G={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"},br=gt();var wr=mt(),_r=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{execFileSync as ve,execSync as xe}from"node:child_process";import{existsSync as J,mkdirSync as ht,readFileSync as S,unlinkSync as P,writeFileSync as $}from"node:fs";import{platform as Se}from"node:os";import{existsSync as H,mkdirSync as yt,readFileSync as De,writeFileSync as bt}from"node:fs";import{homedir as wt}from"node:os";import{join as je}from"node:path";import{tmpdir as _t}from"node:os";import{existsSync as $e}from"node:fs";import{platform as Nt}from"node:os";import{join as _}from"node:path";function vt(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var xt=_t().replaceAll("\\","/"),A=vt(process.env.GREEDY_SEARCH_PORT),c=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${xt}/greedysearch-chrome-profile`).replaceAll("\\","/"),Dr=`${c}/DevToolsActivePort`,Pt=process.env.GREEDY_SEARCH_PID_FILE||`${c}/browser.pid`,jr=process.env.CDP_PAGES_CACHE||`${c}/cdp-pages.json`,$t=process.env.GREEDY_SEARCH_MODE_FILE||`${c}/browser-mode`,At=process.env.GREEDY_SEARCH_METADATA_FILE||`${c}/browser-metadata.json`,Ct=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${c}/browser-launch.lock`,kt=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${c}/browser-last-activity`,Nr=(process.env.CDP_SOCKET_DIR||`${c}/cdp-sockets`).replaceAll("\\","/"),Tr=`${c}/visible-recovery.jsonl`,ne=je(wt(),".dm"),m=je(ne,"greedyconfig"),ie=["perplexity","google","chatgpt","gemini"],ae="gemini";function St(){try{if(H(m)){let e=De(m,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((n)=>re[n]),i=t.engines.filter((n)=>!re[n]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${m}: ${i.join(", ")}
294
+ [greedysearch] Available engines: ${Object.keys(re).join(", ")}
295
+ `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${m}, falling back to defaults: ${ie.join(", ")}
296
+ `)}}}catch{}return ie}function Dt(){try{if(!H(ne))yt(ne,{recursive:!0});if(!H(m))bt(m,JSON.stringify({engines:ie,synthesizer:ae},null,2)+`
297
+ `,"utf8")}catch{}}Dt();var Pe=["gemini","chatgpt"];function jt(){try{if(H(m)){let e=De(m,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(Pe.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${m}
298
+ [greedysearch] Available synthesizers: ${Pe.join(", ")}
299
+ [greedysearch] Falling back to default: ${ae}
300
+ `)}}}catch{}return ae}var re={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"},Mr=St(),Wr=jt(),Or=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=c;function x(e){let t=Nt()==="win32",r=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:_(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:_(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:_(r,"System32","netstat.exe"),taskkill:_(r,"System32","taskkill.exe"),tasklist:_(r,"System32","tasklist.exe"),cmd:_(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},n=t?i.win32:i.unix,a=e.toLowerCase();if(n[a]&&$e(n[a]))return n[a];if(t&&a==="netstat"){let o=_(r,"Sysnative","netstat.exe");if($e(o))return o}return e}var q=At,v=Ct,Tt=15000,X=Pt,U=$t,N=kt;function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Mt(e){if(!T(e))return null;try{if(Se()==="win32")return ve(x("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ve(x("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Wt(e,t,r=A){if(!e)return!1;let i=(o)=>String(o||"").replaceAll("\\","/").toLowerCase(),n=i(e),a=i(t);return n.includes(a)&&n.includes(`--remote-debugging-port=${r}`)&&!n.includes("--type=")}function Ae(e,t,r=A){return Wt(Mt(e),t,r)}function Ot(e=A){try{if(Se()==="win32"){let r=xe(`${x("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),i=new RegExp(String.raw`TCP\s+\S+:${e}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),n=r.match(i);return n?Number.parseInt(n[1],10):null}let t=xe(`${x("lsof")} -i :${e} -t 2>/dev/null || ${x("ss")} -tlnp 2>/dev/null | ${x("grep")} :${e} | ${x("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
301
+ `)[0],10):null}catch{return null}}function M(){try{if(J(q)){let e=S(q,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((r)=>Number.isInteger(r)&&r>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{let e=J(X)?Number.parseInt(S(X,"utf8").trim(),10)||void 0:void 0,t=J(U)?S(U,"utf8").trim()==="visible"?"visible":"headless":"headless",r=J(N)?Number.parseInt(S(N,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:A,tempDir:c,clientPids:e?[e]:[],sessionMode:t,lastActivity:r,launchedAt:0}}catch{return null}}function B(e){try{$(q,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)$(X,String(e.browserPid),"utf8")}catch{}try{$(U,e.sessionMode,"utf8")}catch{}try{$(N,String(e.lastActivity),"utf8")}catch{}}function Ce(){try{P(q)}catch{}try{P(X)}catch{}try{P(U)}catch{}try{P(N)}catch{}}function oe(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>T(r)||r===process.pid))]};return B(t),t}function Z(e){let t=Date.now();try{if(e)B({...e,lastActivity:t});else $(N,String(t),"utf8")}catch{}}var Xr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var ke=!1;function Ne(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(ke)return;ke=!0;let e=M();if(!e)return;if(e.browserPid){if(!T(e.browserPid)){Ce();return}if(!Ae(e.browserPid,e.tempDir,e.debugPort))Ce();else B({...e,clientPids:e.clientPids.filter((r)=>T(r))})}let t=Ot();if(t&&t!==e.browserPid)if(Ae(t,c,A))B({browserPid:t,debugPort:A,tempDir:c,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${t} on port ${A}.
302
+ `)}function Te(){ht(c,{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return $(v,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=S(v,"utf8");if(JSON.parse(t).pid===process.pid)P(v)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=S(v,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!T(t.pid)||r>Tt){try{P(v)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return $(v,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{P(v)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Xt=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Me=we,W=_e,Ut=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Bt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Zt(e,t=g){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function He(){try{let e=L(),t=e?qe(e):null,r=Zt(t);if(r!==null){try{V(k,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!le(k))return!0;return z(k,"utf8").trim()==="headless"}catch{return!0}}function Qt(){try{V(W,String(Date.now()),"utf8")}catch{}try{let e=M();if(e)Z(e)}catch{}}function qe(e){try{if(Je()==="win32")return se(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return se(C("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Vt(e){let t=String(e||"").replaceAll("\\","/"),r=p.replaceAll("\\","/");return t.includes(`--remote-debugging-port=${g}`)&&t.includes(`--user-data-dir=${r}`)&&!t.includes("--type=")}function L(){return me(g)}function R(){let e=L();return e&&Vt(qe(e))?e:null}async function Rt(e=1500){let t=R();if(!t)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
303
+ `),!1;try{let i=await new Promise((a,o)=>{let s=ue.get(`http://localhost:${g}/json/version`,(l)=>{let f="";l.on("data",(u)=>f+=u),l.on("end",()=>{try{a(JSON.parse(f))}catch{o(Error("bad JSON"))}})});s.on("error",o),s.setTimeout(1000,()=>{s.destroy(),o(Error("timeout"))})}),n=new globalThis.WebSocket(i.webSocketDebuggerUrl);await new Promise((a)=>{n.onopen=()=>{if(R()!==t){n.close(),a();return}n.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{n.close(),a()},200)},n.onerror=()=>a(),setTimeout(a,1000)})}catch{}let r=Date.now()+e;while(Date.now()<r){let i=L();if(!i)return!0;if(i!==t)return!1;await new Promise((n)=>setTimeout(n,150))}return zt(t)}function zt(e=null){try{let t=R();if(!t||e&&t!==e)return!1;if(Je()==="win32")se(C("taskkill"),["/F","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Xe(){if(!R()){if(L())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
304
+ `);return!1}if(!await y(500)){try{h(Me)}catch{}try{h(W)}catch{}try{h(k)}catch{}return!1}let t=await Rt(1500);try{h(Me)}catch{}try{h(W)}catch{}try{h(k)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${g}.
305
+ `);return t}var We=Xe;async function Lt(){let t=He()?Ut:Bt;if(t<=0)return!1;if(!le(W))return Qt(),!1;try{let r=Number.parseInt(z(W,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Xe()}catch{}return!1}var b=I;async function ce(){let t=(await b(["list"])).split(`
306
+ `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function Kr(e="about:blank"){let t=await ce(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let o=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(o),l=s.slice(0,8);if(await b(["list"]).catch(()=>null),r==="copilot.microsoft.com")await Y(l);else Y(l).catch(()=>{});return await b(["list"]).catch(()=>null),s}let n=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(n);return await b(["list"]).catch(()=>null),a}async function en(e){try{let t=await ce();await b(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function It(e){try{let t=await ce();await b(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function tn(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>It(t).catch(()=>{}))),e.length>0)await b(["list"]).catch(()=>null)}function rn(e,t){try{if(!le(te))return null;let i=JSON.parse(z(te,"utf8")).find((n)=>n.url.includes(t[e]));return i?i.targetId:null}catch{return null}}function y(e=3000){return new Promise((t)=>{let r=ue.get(`http://localhost:${g}/json/version`,(i)=>{i.resume(),t(i.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function Oe(e=3000,t=200){let r=Date.now()+e;while(Date.now()<r){if(!await y(300))return!0;await new Promise((i)=>setTimeout(i,t))}return!await y(300)}async function Q(){let e=`${j}.lock`,t=`${j}.tmp`,r=5000,i=1000,n=await new Promise((a)=>{let o=Date.now(),s=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});V(e,l,{encoding:"utf8",flag:"wx"}),a(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-o<1000)setTimeout(s,50);else a(!1);return}try{let f=z(e,"utf8").trim(),u=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},D=Number(u?.ts)||0;if(D>0&&Date.now()-D>5000)try{h(e)}catch{}if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((l,f)=>{let u=ue.get(`http://localhost:${g}/json/version`,(D)=>{let fe="";D.on("data",(Ue)=>fe+=Ue),D.on("end",()=>l(fe))});u.on("error",f),u.setTimeout(3000,()=>{u.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:o}=JSON.parse(a),s=new URL(o).pathname;if(n){V(t,`${g}
307
+ ${s}`,"utf8");try{h(j)}catch{}Ht(t,j)}}catch{}finally{if(n)try{h(e)}catch{}}}async function nn(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await y()){await Q();try{let a=M();if(a)Z(a),oe(a)}catch{}return}Ne();let e=await Lt(),t=e?!1:await y();if(!t&&!e)await new Promise((a)=>setTimeout(a,500)),t=await y();let r=!1;if(t){let a=He(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected switching to headless mode...
308
+ `),await We(),await Oe(),r=!0;else if(o&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
309
+ `),await We(),await Oe(),r=!0}if(r?!1:await y()){await Q();try{let a=M();if(a)Z(a),oe(a)}catch{}return}let n=Te();if(!n.acquired){let a=Date.now()+12000,o=!1;while(Date.now()<a){if(o=await y(500),o)break;await new Promise((s)=>setTimeout(s,250))}if(o){await Q();return}}try{if(await y(1000)){await Q();return}process.stderr.write(`GreedySearch Chrome not running on port ${g} — auto-launching...
310
+ `);let o=[qt(Xt,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((s,l)=>{Jt(pe(),o,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(u)=>u===0?s():l(Error("launch.mjs failed")))})}finally{n.release()}}export{Qt as touchActivity,Q as refreshPortFile,y as probeGreedyChrome,Kr as openNewTab,We as killHeadlessChrome,Xe as killChrome,He as isChromeHeadless,rn as getFullTabFromCache,ce as getAnyTab,nn as ensureChrome,Zt as detectHeadlessFromChromeCommandLine,tn as closeTabs,It as closeTab,Lt as checkAndKillIdle,b as cdp,en as activateTab};
@@ -1,8 +1,8 @@
1
- import{existsSync as M,mkdirSync as x,readFileSync as w,writeFileSync as H}from"node:fs";import{homedir as Z}from"node:os";import{join as z}from"node:path";import{tmpdir as Q}from"node:os";function h(K,B=9222){let q=Number.parseInt(String(K??""),10);return Number.isInteger(q)&&q>1024&&q<65535?q:B}var p=h(process.env.GREEDY_SEARCH_PORT,9222),u=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Q().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),C=`${u}/DevToolsActivePort`,f=`${Q().replaceAll("\\","/")}/cdp-pages.json`,T=process.env.GREEDY_SEARCH_MODE_FILE||`${Q().replaceAll("\\","/")}/greedysearch-chrome-mode`,O=`${Q().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,X=z(Z(),".dm"),J=z(X,"greedyconfig"),$=["perplexity","google","chatgpt"],b="gemini";function Y(){try{if(M(J)){let K=w(J,"utf8"),B=JSON.parse(K);if(Array.isArray(B.engines)&&B.engines.length>0&&B.engines.every((q)=>typeof q==="string")){let q=B.engines.filter((V)=>W[V]),j=B.engines.filter((V)=>!W[V]);if(j.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${J}: ${j.join(", ")}
2
- [greedysearch] Available engines: ${Object.keys(W).join(", ")}
3
- `);if(q.length>0)return q;process.stderr.write(`[greedysearch] Warning: no valid engines in ${J}, falling back to defaults: ${$.join(", ")}
4
- `)}}}catch{}return $}function v(){try{if(!M(X))x(X,{recursive:!0});if(!M(J))H(J,JSON.stringify({engines:$,synthesizer:b},null,2)+`
5
- `,"utf8")}catch{}}v();var k=["gemini","chatgpt"];function A(){try{if(M(J)){let K=w(J,"utf8"),B=JSON.parse(K);if(typeof B.synthesizer==="string"){let q=B.synthesizer.toLowerCase();if(k.includes(q))return q;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${B.synthesizer}" in ${J}
1
+ import{existsSync as V,mkdirSync as u,readFileSync as w,writeFileSync as x}from"node:fs";import{homedir as H}from"node:os";import{join as z}from"node:path";import{tmpdir as Z}from"node:os";function h(Q,B=9222){let q=Number.parseInt(String(Q??""),10);return Number.isInteger(q)&&q>1024&&q<65535?q:B}var m=Z().replaceAll("\\","/"),T=h(process.env.GREEDY_SEARCH_PORT),J=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${m}/greedysearch-chrome-profile`).replaceAll("\\","/"),Y=`${J}/DevToolsActivePort`,P=process.env.GREEDY_SEARCH_PID_FILE||`${J}/browser.pid`,t=process.env.CDP_PAGES_CACHE||`${J}/cdp-pages.json`,d=process.env.GREEDY_SEARCH_MODE_FILE||`${J}/browser-mode`,s=process.env.GREEDY_SEARCH_METADATA_FILE||`${J}/browser-metadata.json`,c=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${J}/browser-launch.lock`,l=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${J}/browser-last-activity`,a=(process.env.CDP_SOCKET_DIR||`${J}/cdp-sockets`).replaceAll("\\","/"),O=`${J}/visible-recovery.jsonl`,$=z(H(),".dm"),K=z($,"greedyconfig"),M=["perplexity","google","chatgpt","gemini"],b="gemini";function v(){try{if(V(K)){let Q=w(K,"utf8"),B=JSON.parse(Q);if(Array.isArray(B.engines)&&B.engines.length>0&&B.engines.every((q)=>typeof q==="string")){let q=B.engines.filter((W)=>X[W]),j=B.engines.filter((W)=>!X[W]);if(j.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${K}: ${j.join(", ")}
2
+ [greedysearch] Available engines: ${Object.keys(X).join(", ")}
3
+ `);if(q.length>0)return q;process.stderr.write(`[greedysearch] Warning: no valid engines in ${K}, falling back to defaults: ${M.join(", ")}
4
+ `)}}}catch{}return M}function A(){try{if(!V($))u($,{recursive:!0});if(!V(K))x(K,JSON.stringify({engines:M,synthesizer:b},null,2)+`
5
+ `,"utf8")}catch{}}A();var k=["gemini","chatgpt"];function g(){try{if(V(K)){let Q=w(K,"utf8"),B=JSON.parse(Q);if(typeof B.synthesizer==="string"){let q=B.synthesizer.toLowerCase();if(k.includes(q))return q;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${B.synthesizer}" in ${K}
6
6
  [greedysearch] Available synthesizers: ${k.join(", ")}
7
7
  [greedysearch] Falling back to default: ${b}
8
- `)}}}catch{}return b}var R={perplexity:"perplexity.ai",bing:"copilot.microsoft.com",google:"google.com",gemini:"gemini.google.com",chatgpt:"chatgpt.com","semantic-scholar":"semanticscholar.org",semanticscholar:"semanticscholar.org",s2:"semanticscholar.org",logically:"logically.app"},W={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"},P=Y(),D=P,L=A(),s=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=u;export{h as parseGreedySearchPort,O as VISIBLE_RECOVERY_LOG,L as SYNTHESIZER,k as SUPPORTED_SYNTHESIZERS,s as SOURCE_FETCH_CONCURRENCY,D as RESEARCH_ENGINES,f as PAGES_CACHE,u as GREEDY_PROFILE_DIR,p as GREEDY_PORT,R as ENGINE_DOMAINS,W as ENGINES,b as DEFAULT_SYNTHESIZER,$ as DEFAULT_ENGINES,T as CHROME_MODE_FILE,P as ALL_ENGINES,C as ACTIVE_PORT_FILE};
8
+ `)}}}catch{}return b}var L={perplexity:"perplexity.ai",bing:"copilot.microsoft.com",google:"google.com",gemini:"gemini.google.com",chatgpt:"chatgpt.com","semantic-scholar":"semanticscholar.org",semanticscholar:"semanticscholar.org",s2:"semanticscholar.org",logically:"logically.app"},X={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"},p=v(),r=p,n=g(),N=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=J;export{h as parseGreedySearchPort,O as VISIBLE_RECOVERY_LOG,n as SYNTHESIZER,k as SUPPORTED_SYNTHESIZERS,N as SOURCE_FETCH_CONCURRENCY,r as RESEARCH_ENGINES,t as PAGES_CACHE,J as GREEDY_PROFILE_DIR,T as GREEDY_PORT,P as GREEDY_PID_FILE,s as GREEDY_METADATA_FILE,c as GREEDY_LAUNCH_LOCK_FILE,a as GREEDY_CDP_SOCKET_DIR,l as GREEDY_ACTIVITY_FILE,L as ENGINE_DOMAINS,X as ENGINES,b as DEFAULT_SYNTHESIZER,M as DEFAULT_ENGINES,d as CHROME_MODE_FILE,p as ALL_ENGINES,Y as ACTIVE_PORT_FILE};
@@ -1,9 +1,9 @@
1
- import{spawn as p}from"node:child_process";import{basename as W}from"node:path";function Y(g=process.env,s=process.execPath){let E=g.GREEDY_SEARCH_NODE||g.NODE_BINARY||g.NODE;if(E?.trim())return E.trim();let l=W(s||"").toLowerCase();if(l==="node"||l==="node.exe")return s;return"node"}import{existsSync as i,mkdirSync as Z,readFileSync as L,writeFileSync as e}from"node:fs";import{homedir as J}from"node:os";import{join as z}from"node:path";import{tmpdir as c}from"node:os";function V(g,s=9222){let E=Number.parseInt(String(g??""),10);return Number.isInteger(E)&&E>1024&&E<65535?E:s}var gg=V(process.env.GREEDY_SEARCH_PORT,9222),r=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${c().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),Eg=`${r}/DevToolsActivePort`,sg=`${c().replaceAll("\\","/")}/cdp-pages.json`,lg=process.env.GREEDY_SEARCH_MODE_FILE||`${c().replaceAll("\\","/")}/greedysearch-chrome-mode`,ag=`${c().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,n=z(J(),".dm"),R=z(n,"greedyconfig"),o=["perplexity","google","chatgpt"],H="gemini";function B(){try{if(i(R)){let g=L(R,"utf8"),s=JSON.parse(g);if(Array.isArray(s.engines)&&s.engines.length>0&&s.engines.every((E)=>typeof E==="string")){let E=s.engines.filter((a)=>S[a]),l=s.engines.filter((a)=>!S[a]);if(l.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${R}: ${l.join(", ")}
2
- [greedysearch] Available engines: ${Object.keys(S).join(", ")}
3
- `);if(E.length>0)return E;process.stderr.write(`[greedysearch] Warning: no valid engines in ${R}, falling back to defaults: ${o.join(", ")}
4
- `)}}}catch{}return o}function K(){try{if(!i(n))Z(n,{recursive:!0});if(!i(R))e(R,JSON.stringify({engines:o,synthesizer:H},null,2)+`
5
- `,"utf8")}catch{}}K();var G=["gemini","chatgpt"];function U(){try{if(i(R)){let g=L(R,"utf8"),s=JSON.parse(g);if(typeof s.synthesizer==="string"){let E=s.synthesizer.toLowerCase();if(G.includes(E))return E;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${s.synthesizer}" in ${R}
6
- [greedysearch] Available synthesizers: ${G.join(", ")}
7
- [greedysearch] Falling back to default: ${H}
8
- `)}}}catch{}return H}var S={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"},yg=B();var Rg=U(),_g=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=r;import{existsSync as k}from"node:fs";import{dirname as Q,join as $}from"node:path";import{fileURLToPath as X}from"node:url";function j(g){return X(new URL(".",g)).replace(/^\/([A-Z]:)/,"$1")}function b(g,s=k){let E=new Set;for(let l of g.filter(Boolean)){if(E.has(l))continue;if(E.add(l),s(l))return l}return g.filter(Boolean).at(-1)}function w(g,{moduleDir:s,entrypoint:E=process.argv[1],env:l=process.env,exists:a=k}={}){let N=E?Q(E):null,f=l.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null,O=[s?$(s,"..","..","extractors",g):null,s?$(s,"..","extractors",g):null,f?$(f,"extractors",g):null,N?$(N,"..","extractors",g):null];return b(O,a)}var q=j(import.meta.url);function cg(g,s,E=null,l=!1,a=null,N=null){if(a===null)a=g.includes("logically")?120000:g.includes("chatgpt")?80000:g.includes("gemini")?70000:60000;let f=[...E?["--tab",E]:[],...l?["--short"]:[],...N?["--locale",N]:[]],O=w(g,{moduleDir:q});return new Promise((D,F)=>{let A=p(Y(),[O,"--stdin",...f],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:r}});A.stdin.write(s),A.stdin.end();let I="",T="";A.stdout.on("data",(y)=>I+=y),A.stderr.on("data",(y)=>{if(T+=y,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(y)});let P=setTimeout(()=>{A.kill();let y=(h,C=20)=>String(h??"").split(/\r?\n/).filter(Boolean).slice(-C).join(`
9
- `),_=null;try{let h=JSON.parse(I.trim());if(h._envelope)_=h._envelope}catch{}let m=Error(`${g} timed out after ${a/1000}s`+(_?.lastStage?` (last stage: ${_.lastStage})`:""));m.engineScript=g,m.lastStage=_?.lastStage||null,m.partialErr=y(T),m.partialOut=y(I),F(m)},a);A.on("close",(y)=>{if(clearTimeout(P),y===0)try{D(JSON.parse(I.trim()))}catch{F(Error(`bad JSON from ${g}: ${I.slice(0,100)}`))}else{let _=null;try{let C=JSON.parse(I.trim());if(C._envelope)_=C._envelope}catch{}let m=T.trim()||`extractor exit ${y}`,h=Error(m);if(_)h.envelope=_;F(h)}})})}export{cg as runExtractor,S as ENGINES};
1
+ import{spawn as J}from"node:child_process";import{basename as w}from"node:path";function L(s=process.env,e=process.execPath){let n=s.GREEDY_SEARCH_NODE||s.NODE_BINARY||s.NODE;if(n?.trim())return n.trim();let i=w(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}import{existsSync as C,mkdirSync as v,readFileSync as N,writeFileSync as P}from"node:fs";import{homedir as j}from"node:os";import{join as Y}from"node:path";import{tmpdir as U}from"node:os";function k(s,e=9222){let n=Number.parseInt(String(s??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:e}var x=U().replaceAll("\\","/"),ns=k(process.env.GREEDY_SEARCH_PORT),r=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${x}/greedysearch-chrome-profile`).replaceAll("\\","/"),es=`${r}/DevToolsActivePort`,is=process.env.GREEDY_SEARCH_PID_FILE||`${r}/browser.pid`,rs=process.env.CDP_PAGES_CACHE||`${r}/cdp-pages.json`,Es=process.env.GREEDY_SEARCH_MODE_FILE||`${r}/browser-mode`,as=process.env.GREEDY_SEARCH_METADATA_FILE||`${r}/browser-metadata.json`,os=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${r}/browser-launch.lock`,gs=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${r}/browser-last-activity`,ls=(process.env.CDP_SOCKET_DIR||`${r}/cdp-sockets`).replaceAll("\\","/"),ts=`${r}/visible-recovery.jsonl`,D=Y(j(),".dm"),o=Y(D,"greedyconfig"),h=["perplexity","google","chatgpt","gemini"],p="gemini";function b(){try{if(C(o)){let s=N(o,"utf8"),e=JSON.parse(s);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((E)=>y[E]),i=e.engines.filter((E)=>!y[E]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${o}: ${i.join(", ")}
2
+ [greedysearch] Available engines: ${Object.keys(y).join(", ")}
3
+ `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${o}, falling back to defaults: ${h.join(", ")}
4
+ `)}}}catch{}return h}function z(){try{if(!C(D))v(D,{recursive:!0});if(!C(o))P(o,JSON.stringify({engines:h,synthesizer:p},null,2)+`
5
+ `,"utf8")}catch{}}z();var T=["gemini","chatgpt"];function V(){try{if(C(o)){let s=N(o,"utf8"),e=JSON.parse(s);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(T.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${o}
6
+ [greedysearch] Available synthesizers: ${T.join(", ")}
7
+ [greedysearch] Falling back to default: ${p}
8
+ `)}}}catch{}return p}var y={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"},cs=b();var _s=V(),Rs=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=r;import{existsSync as G}from"node:fs";import{dirname as B,join as S}from"node:path";import{fileURLToPath as K}from"node:url";function F(s){return K(new URL(".",s)).replace(/^\/([A-Z]:)/,"$1")}function Z(s,e=G){let n=new Set;for(let i of s.filter(Boolean)){if(n.has(i))continue;if(n.add(i),e(i))return i}return s.filter(Boolean).at(-1)}function $(s,{moduleDir:e,entrypoint:n=process.argv[1],env:i=process.env,exists:E=G}={}){let R=n?B(n):null,m=i.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return Z([e?S(e,"..","..","extractors",s):null,e?S(e,"..","extractors",s):null,m?S(m,"extractors",s):null,R?S(R,"..","extractors",s):null],E)}var W=F(import.meta.url);function ps(s,e,n=null,i=!1,E=null,R=null){if(E===null)E=s.includes("logically")?120000:s.includes("chatgpt")?80000:s.includes("gemini")?70000:60000;let m=[...n?["--tab",n]:[],...i?["--short"]:[],...R?["--locale",R]:[]];return new Promise((H,f)=>{let O=$(s,{moduleDir:W}),c=J(L(),[O,"--stdin",...m],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:r}});c.stdin.write(e),c.stdin.end();let _="",A="";c.stdout.on("data",(a)=>_+=a),c.stderr.on("data",(a)=>{if(A+=a,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(a)});let u=setTimeout(()=>{c.kill();let a=(t,I=20)=>String(t??"").split(/\r?\n/).filter(Boolean).slice(-I).join(`
9
+ `),g=null;try{let t=JSON.parse(_.trim());if(t._envelope)g=t._envelope}catch{}let l=Error(`${s} timed out after ${E/1000}s`+(g?.lastStage?` (last stage: ${g.lastStage})`:""));l.engineScript=s,l.lastStage=g?.lastStage||null,l.partialErr=a(A),l.partialOut=a(_),f(l)},E);c.on("close",(a)=>{if(clearTimeout(u),a===0)try{H(JSON.parse(_.trim()))}catch{f(Error(`bad JSON from ${s}: ${_.slice(0,100)}`))}else{let g=null;try{let I=JSON.parse(_.trim());if(I._envelope)g=I._envelope}catch{}let l=A.trim()||`extractor exit ${a}`,t=Error(l);if(g)t.envelope=g;f(t)}})})}export{ps as runExtractor,y as ENGINES};