@wrongstack/tools 0.310.1 → 0.313.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/_shell-pick.d.ts +5 -10
  2. package/dist/audit.js +10 -4055
  3. package/dist/bash.js +9 -2332
  4. package/dist/batch-tool-use.js +2 -187
  5. package/dist/browser/index.js +25 -1339
  6. package/dist/builtin.js +69 -33985
  7. package/dist/chunk-2CTB3UK5.js +197 -0
  8. package/dist/chunk-2ME7ZWDD.js +1272 -0
  9. package/dist/chunk-2TFQDEPU.js +113 -0
  10. package/dist/chunk-2ZCJNKFE.js +315 -0
  11. package/dist/chunk-3PVYQFRQ.js +472 -0
  12. package/dist/chunk-3QMQBO5Z.js +89 -0
  13. package/dist/chunk-42AKKX7O.js +385 -0
  14. package/dist/chunk-42SKEETB.js +113 -0
  15. package/dist/chunk-4BHUSMNL.js +104 -0
  16. package/dist/chunk-4I4LWFOO.js +431 -0
  17. package/dist/chunk-553IQUMO.js +478 -0
  18. package/dist/chunk-55KF77OK.js +1944 -0
  19. package/dist/chunk-6HLZK37X.js +359 -0
  20. package/dist/chunk-6RNIFLG4.js +305 -0
  21. package/dist/chunk-A6BRWIXN.js +317 -0
  22. package/dist/chunk-AHHDWNXC.js +200 -0
  23. package/dist/chunk-B2CIOKWP.js +899 -0
  24. package/dist/chunk-BTSFTGIL.js +7 -0
  25. package/dist/chunk-D33S4RQG.js +222 -0
  26. package/dist/chunk-DIJKHSUO.js +134 -0
  27. package/dist/chunk-DPL47QGS.js +3515 -0
  28. package/dist/chunk-EMRGN4KM.js +170 -0
  29. package/dist/chunk-FGOABE4Z.js +955 -0
  30. package/dist/chunk-FW65TP4G.js +520 -0
  31. package/dist/chunk-GOIZNNOA.js +221 -0
  32. package/dist/chunk-H5MJUAA6.js +295 -0
  33. package/dist/chunk-H5OHH6F4.js +223 -0
  34. package/dist/chunk-HC5RM4WY.js +199 -0
  35. package/dist/chunk-HEQFMLZ7.js +190 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HXSBQ2SE.js +1723 -0
  38. package/dist/chunk-ILESNGNM.js +163 -0
  39. package/dist/chunk-INF5CGAO.js +137 -0
  40. package/dist/chunk-IWDFZ6XR.js +337 -0
  41. package/dist/chunk-IXMNTNW5.js +238 -0
  42. package/dist/chunk-J4SRJKBW.js +428 -0
  43. package/dist/chunk-J5SKD6LN.js +235 -0
  44. package/dist/chunk-JRJJX3L5.js +424 -0
  45. package/dist/chunk-KXNDHMUB.js +366 -0
  46. package/dist/chunk-LIJQMYYX.js +59 -0
  47. package/dist/chunk-MAN26PZ5.js +260 -0
  48. package/dist/chunk-MKRQMLZA.js +474 -0
  49. package/dist/chunk-NBDZMMG2.js +169 -0
  50. package/dist/chunk-NHA6BEIH.js +101 -0
  51. package/dist/chunk-OA6YJIWL.js +4412 -0
  52. package/dist/chunk-OZC255IC.js +2830 -0
  53. package/dist/chunk-PUR6WU2B.js +154 -0
  54. package/dist/chunk-Q5JPPCZC.js +12 -0
  55. package/dist/chunk-QBV725YG.js +128 -0
  56. package/dist/chunk-QHVW4AAM.js +892 -0
  57. package/dist/chunk-QNJ7AQ4B.js +1000 -0
  58. package/dist/chunk-RGISBZBD.js +231 -0
  59. package/dist/chunk-RJZQWEMS.js +84 -0
  60. package/dist/chunk-RP2ZA47V.js +15 -0
  61. package/dist/chunk-RXISBFR5.js +315 -0
  62. package/dist/chunk-S5CCLZL3.js +99 -0
  63. package/dist/chunk-TVTCSBJF.js +122 -0
  64. package/dist/chunk-U4D5S3VQ.js +21 -0
  65. package/dist/chunk-U4VAATKP.js +193 -0
  66. package/dist/chunk-UKU2ZX4C.js +203 -0
  67. package/dist/chunk-UNSKG6DC.js +159 -0
  68. package/dist/chunk-URFKEIHM.js +1091 -0
  69. package/dist/chunk-UTV7YAW7.js +178 -0
  70. package/dist/chunk-V43EQ6VR.js +68 -0
  71. package/dist/chunk-VB3MJGCV.js +610 -0
  72. package/dist/chunk-WHIIIREL.js +223 -0
  73. package/dist/chunk-XMIFYKUT.js +1371 -0
  74. package/dist/chunk-YF2RSV34.js +54 -0
  75. package/dist/chunk-Z6DAKQ3U.js +1 -0
  76. package/dist/chunk-ZIGAZFWE.js +522 -0
  77. package/dist/circuit-breaker.js +3 -191
  78. package/dist/codebase-index/index.js +84 -13688
  79. package/dist/codebase-index/parser-worker-script.js +8 -3995
  80. package/dist/codebase-index/project-server.js +60 -8548
  81. package/dist/codebase-index/worker.js +20 -8416
  82. package/dist/design.js +2 -299
  83. package/dist/diff.js +4 -256
  84. package/dist/document.js +4 -222
  85. package/dist/e2e.js +5 -476
  86. package/dist/edit.js +14 -10200
  87. package/dist/exec.js +16 -3131
  88. package/dist/fetch.js +8 -398
  89. package/dist/format.js +10 -3750
  90. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  91. package/dist/git.js +4 -380
  92. package/dist/glob.js +6 -280
  93. package/dist/go-parser-6CA77WZ4.js +469 -0
  94. package/dist/grep.js +7 -604
  95. package/dist/index.js +318 -35423
  96. package/dist/install.js +10 -4091
  97. package/dist/json-parser-7YMDJSBJ.js +213 -0
  98. package/dist/json.js +4 -665
  99. package/dist/kanban.js +3 -2096
  100. package/dist/languages/index.js +23 -4664
  101. package/dist/legacy-bridge-7UKZT46G.js +18 -0
  102. package/dist/lint.js +10 -3706
  103. package/dist/logs.js +4 -287
  104. package/dist/memory.js +6 -215
  105. package/dist/mode.js +3 -99
  106. package/dist/outdated.js +4 -5170
  107. package/dist/pack.js +65 -33933
  108. package/dist/parser-dispatch-VPOFDO2U.js +14 -0
  109. package/dist/patch.js +13 -9935
  110. package/dist/plan.js +5 -3286
  111. package/dist/process-registry.js +8 -651
  112. package/dist/ps-slash.js +12 -1439
  113. package/dist/py-parser-GPM5VYRG.js +16 -0
  114. package/dist/read.js +13 -9816
  115. package/dist/replace.js +15 -10014
  116. package/dist/rs-parser-WVQ4KYCX.js +81 -0
  117. package/dist/scaffold.js +4 -253
  118. package/dist/search.js +5 -585
  119. package/dist/session-kanban.js +30 -972
  120. package/dist/skill.js +2 -215
  121. package/dist/task.js +5 -3410
  122. package/dist/test.js +10 -3773
  123. package/dist/todo.js +4 -2891
  124. package/dist/tool-help.js +3 -123
  125. package/dist/tool-search.js +3 -79
  126. package/dist/tool-tier.js +68 -34020
  127. package/dist/tool-use.js +2 -93
  128. package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
  129. package/dist/tree.js +4 -288
  130. package/dist/ts-parser-YH4ZMWMH.js +232 -0
  131. package/dist/typecheck.js +10 -3753
  132. package/dist/win32.js +6 -60
  133. package/dist/write.js +14 -9882
  134. package/dist/yaml-parser-GFAOKV53.js +157 -0
  135. package/package.json +5 -5
@@ -0,0 +1,431 @@
1
+ import {
2
+ guardedFetch
3
+ } from "./chunk-NBDZMMG2.js";
4
+
5
+ // src/search.ts
6
+ import { FetchError, ToolValidationError } from "@wrongstack/core/types";
7
+ import { expectDefined } from "@wrongstack/core/utils";
8
+ import { toErrorMessage } from "@wrongstack/core/utils";
9
+ var DEFAULT_NUM = 10;
10
+ var MAX_RESULTS = 50;
11
+ var MAX_SNIPPET_CHARS = 300;
12
+ var TIMEOUT_MS = 15e3;
13
+ var CACHE_TTL_MS = 3e5;
14
+ var CACHE_MAX_ENTRIES = 200;
15
+ var cache = /* @__PURE__ */ new Map();
16
+ var searchTool = {
17
+ name: "search",
18
+ category: "Search",
19
+ description: "Perform a web search and return results with title, URL, and snippet. Use this when you need up-to-date external information that is not in the local codebase. Results are cached (5 min TTL) and deduplicated by URL. google and bing are best-effort HTML scrapes that fall back to duckduckgo when they return nothing usable.",
20
+ usageHint: "Good for: API documentation, error messages, library usage examples, current best practices.\n\n- Prefer specific queries over very broad ones.\n- Results go through the guarded fetch system (same protections as the `fetch` tool).\n- Supports duckduckgo (default), google, and bing sources.\n- Set `skip_cache: true` to force a fresh search.\n- This is often better than the model trying to recall outdated knowledge.",
21
+ permission: "auto",
22
+ mutating: false,
23
+ capabilities: ["net.outbound"],
24
+ icon: "search",
25
+ timeoutMs: TIMEOUT_MS,
26
+ inputSchema: {
27
+ type: "object",
28
+ properties: {
29
+ query: { type: "string", description: "Search query" },
30
+ num_results: {
31
+ type: "integer",
32
+ description: "Number of results (1-50, default 10)",
33
+ minimum: 1,
34
+ maximum: MAX_RESULTS
35
+ },
36
+ source: {
37
+ type: "string",
38
+ enum: ["duckduckgo", "google", "bing"],
39
+ description: "Search engine to use (default: duckduckgo)"
40
+ },
41
+ skip_cache: {
42
+ type: "boolean",
43
+ description: "Skip the in-memory cache and force a fresh search (default: false)"
44
+ }
45
+ },
46
+ required: ["query"]
47
+ },
48
+ async execute(input, ctx, opts) {
49
+ let final;
50
+ const executeStream = searchTool.executeStream;
51
+ if (!executeStream) throw new Error("searchTool: stream execution unavailable");
52
+ for await (const ev of executeStream(input, ctx, opts)) {
53
+ if (ev.type === "final") final = ev.output;
54
+ }
55
+ if (!final) throw new Error("search: stream ended without final event");
56
+ return final;
57
+ },
58
+ async *executeStream(input, _ctx, opts) {
59
+ if (!input?.query || input.query.trim() === "") {
60
+ throw new ToolValidationError({
61
+ message: "search: query is required and must be a non-empty string",
62
+ field: "query"
63
+ });
64
+ }
65
+ const num = Math.max(1, Math.min(input.num_results ?? DEFAULT_NUM, MAX_RESULTS));
66
+ const source = input.source ?? "duckduckgo";
67
+ const skipCache = input.skip_cache ?? false;
68
+ const cacheKey = `${source}:${input.query}`;
69
+ if (!skipCache) {
70
+ const entry = cache.get(cacheKey);
71
+ if (entry && Date.now() - entry.timestamp < CACHE_TTL_MS) {
72
+ const results = entry.results.map((r) => ({
73
+ title: r.title,
74
+ url: r.url,
75
+ snippet: r.snippet
76
+ }));
77
+ yield {
78
+ type: "log",
79
+ text: `Cache hit for "${input.query}" (${source})`,
80
+ data: { source, query: input.query, cached: true }
81
+ };
82
+ yield {
83
+ type: "partial_output",
84
+ text: `${results.length} cached results from ${entry.source}`,
85
+ data: { count: results.length, cached: true, source: entry.source }
86
+ };
87
+ yield {
88
+ type: "final",
89
+ output: {
90
+ query: input.query,
91
+ results: results.slice(0, num),
92
+ source: entry.source,
93
+ truncated: results.length > num,
94
+ cached: true
95
+ }
96
+ };
97
+ return;
98
+ }
99
+ }
100
+ yield {
101
+ type: "log",
102
+ text: `Querying ${source} for "${input.query}"\u2026`,
103
+ data: { source, query: input.query, cached: false }
104
+ };
105
+ let engine;
106
+ let effectiveSource = source;
107
+ switch (source) {
108
+ case "duckduckgo":
109
+ engine = await duckduckgoSearch(input.query, opts.signal);
110
+ break;
111
+ case "google":
112
+ engine = await googleSearch(input.query, opts.signal);
113
+ break;
114
+ case "bing":
115
+ engine = await bingSearch(input.query, opts.signal);
116
+ break;
117
+ default:
118
+ throw new ToolValidationError({
119
+ message: `search: unknown source "${source}"`,
120
+ field: "source"
121
+ });
122
+ }
123
+ let ranked = rankSearchResults(engine.results, input.query);
124
+ let engineError = engine.error;
125
+ if (source !== "duckduckgo" && shouldFallbackToDuckDuckGo(ranked, input.query)) {
126
+ yield {
127
+ type: "log",
128
+ text: `${source} returned no relevant static results; falling back to duckduckgo`,
129
+ data: { source, fallback: "duckduckgo", query: input.query }
130
+ };
131
+ const fallback = await duckduckgoSearch(input.query, opts.signal);
132
+ ranked = rankSearchResults(fallback.results, input.query);
133
+ engineError = fallback.error;
134
+ effectiveSource = "duckduckgo";
135
+ }
136
+ const finalResults = ranked.slice(0, num);
137
+ if (!engineError) {
138
+ cache.set(cacheKey, { results: ranked, source: effectiveSource, timestamp: Date.now() });
139
+ pruneCacheEntries();
140
+ }
141
+ yield {
142
+ type: "partial_output",
143
+ text: engineError ? `search failed: ${engineError}` : `${finalResults.length} results from ${effectiveSource}`,
144
+ data: { count: finalResults.length, cached: false, source: effectiveSource }
145
+ };
146
+ yield {
147
+ type: "final",
148
+ output: {
149
+ query: input.query,
150
+ results: finalResults.map((r) => ({
151
+ title: r.title,
152
+ url: r.url,
153
+ snippet: r.snippet
154
+ })),
155
+ source: effectiveSource,
156
+ truncated: ranked.length > num,
157
+ cached: false,
158
+ ...engineError ? { error: engineError } : {}
159
+ }
160
+ };
161
+ }
162
+ };
163
+ function pruneCacheEntries() {
164
+ const cutoff = Date.now() - CACHE_TTL_MS * 2;
165
+ for (const [key, entry] of cache.entries()) {
166
+ if (entry.timestamp < cutoff) cache.delete(key);
167
+ }
168
+ while (cache.size > CACHE_MAX_ENTRIES) {
169
+ const oldestKey = cache.keys().next().value;
170
+ if (oldestKey === void 0) break;
171
+ cache.delete(oldestKey);
172
+ }
173
+ }
174
+ function __clearSearchCache() {
175
+ cache.clear();
176
+ }
177
+ function rankSearchResults(results, query) {
178
+ const seenUrls = /* @__PURE__ */ new Set();
179
+ const deduped = [];
180
+ for (const r of results) {
181
+ const noQuery = r.url.split("?")[0] ?? r.url;
182
+ const normalized = noQuery.split("#")[0] ?? r.url;
183
+ if (!seenUrls.has(normalized) && r.url.startsWith("http")) {
184
+ seenUrls.add(normalized);
185
+ deduped.push(r);
186
+ }
187
+ }
188
+ return scoreResults(deduped, query);
189
+ }
190
+ function scoreResults(results, query) {
191
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
192
+ return results.map((r) => {
193
+ const titleLower = r.title.toLowerCase();
194
+ const snippetLower = r.snippet.toLowerCase();
195
+ let score = r.score;
196
+ for (const term of terms) {
197
+ if (titleLower.includes(term)) score += 2;
198
+ if (snippetLower.includes(term)) score += 1;
199
+ }
200
+ return { ...r, score };
201
+ }).sort((a, b) => b.score - a.score);
202
+ }
203
+ function shouldFallbackToDuckDuckGo(results, query) {
204
+ if (results.length === 0) return true;
205
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3);
206
+ if (terms.length === 0) return false;
207
+ return !results.some((r) => {
208
+ const haystack = `${r.title} ${r.url} ${r.snippet}`.toLowerCase();
209
+ return terms.some((term) => haystack.includes(term));
210
+ });
211
+ }
212
+ async function duckduckgoSearch(query, signal) {
213
+ const encoded = encodeURIComponent(query);
214
+ const url = `https://lite.duckduckgo.com/lite/?q=${encoded}&kd=-1&kl=wt-wt`;
215
+ try {
216
+ const response = await fetchWithTimeout(url, signal, TIMEOUT_MS);
217
+ const html = await response.text();
218
+ return { results: parseDuckDuckGo(html, MAX_RESULTS) };
219
+ } catch (err) {
220
+ console.log(
221
+ JSON.stringify({ level: "debug", event: "search_failed", query, error: toErrorMessage(err) })
222
+ );
223
+ return { results: [], error: `duckduckgo unreachable: ${toErrorMessage(err)}` };
224
+ }
225
+ }
226
+ function takeFrom(iter, max) {
227
+ const out = [];
228
+ for (const item of iter) {
229
+ if (out.length >= max) break;
230
+ out.push(item);
231
+ }
232
+ return out;
233
+ }
234
+ function parseDuckDuckGo(html, num) {
235
+ const results = [];
236
+ const linkRegex = /<a\b([^>]*\bclass=(["'])[^"']*\bresult-link\b[^"']*\2[^>]*)>([\s\S]*?)<\/a>/gi;
237
+ const snippetRegex = /<([a-z0-9]+)\b([^>]*\bclass=(["'])[^"']*\bresult-snippet\b[^"']*\3[^>]*)>([\s\S]*?)<\/\1>/gi;
238
+ const linkMatches = takeFrom(
239
+ [...html.matchAll(linkRegex)].map((m) => {
240
+ const attrs = expectDefined(m[1]);
241
+ const href = getHtmlAttr(attrs, "href");
242
+ const title = stripTags(expectDefined(m[3]));
243
+ return href && title ? { url: normalizeDuckDuckGoUrl(href), title } : void 0;
244
+ }).filter((m) => m !== void 0),
245
+ num
246
+ );
247
+ const snippetMatches = takeFrom(
248
+ [...html.matchAll(snippetRegex)].filter((m) => m[4]).map((m) => stripTags(expectDefined(m[4]))),
249
+ num
250
+ );
251
+ for (let i = 0; i < linkMatches.length && i < num; i++) {
252
+ const entry = linkMatches[i];
253
+ if (entry) {
254
+ results.push({
255
+ title: entry.title ?? "",
256
+ url: entry.url ?? "",
257
+ snippet: capSnippet(snippetMatches[i] ?? ""),
258
+ score: 1
259
+ });
260
+ }
261
+ }
262
+ return results;
263
+ }
264
+ function escapeRegex(s) {
265
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
266
+ }
267
+ function getHtmlAttr(attrs, name) {
268
+ const escaped = escapeRegex(name);
269
+ const quoted = new RegExp(`\\b${escaped}\\s*=\\s*(["'])(.*?)\\1`, "i").exec(attrs);
270
+ if (quoted?.[2]) return decodeHtmlEntities(quoted[2]);
271
+ const unquoted = new RegExp(`\\b${escaped}\\s*=\\s*([^\\s>]+)`, "i").exec(attrs);
272
+ return unquoted?.[1] ? decodeHtmlEntities(unquoted[1]) : void 0;
273
+ }
274
+ function normalizeDuckDuckGoUrl(raw) {
275
+ if (raw.startsWith("//")) return `https:${raw}`;
276
+ if (!raw.startsWith("/")) return raw;
277
+ if (!raw.startsWith("/l/")) return raw;
278
+ try {
279
+ const url = new URL(raw, "https://duckduckgo.com");
280
+ const uddg = url.searchParams.get("uddg");
281
+ return uddg?.startsWith("http") ? uddg : url.toString();
282
+ } catch {
283
+ return raw;
284
+ }
285
+ }
286
+ async function googleSearch(query, signal) {
287
+ const encoded = encodeURIComponent(query);
288
+ const url = `https://www.google.com/search?q=${encoded}&hl=en`;
289
+ try {
290
+ const html = await fetchWithTimeout(url, signal, TIMEOUT_MS).then((r) => r.text());
291
+ return { results: parseGoogleResults(html, MAX_RESULTS) };
292
+ } catch (err) {
293
+ return { results: [], error: `google unreachable: ${toErrorMessage(err)}` };
294
+ }
295
+ }
296
+ function parseGoogleResults(html, num) {
297
+ const results = [];
298
+ const titleRegex = /<h3[^>]*class="[^"]*DKV84"[^>]*>([^<]+)<\/h3>/gi;
299
+ const urlRegex = /<cite[^>]*>([^<]+)<\/cite>/gi;
300
+ const snippetRegex = /<span[^>]*class="[^"]*aXCZ0b[^>]*>([^<]+)<\/span>/gi;
301
+ const titles = takeFrom(
302
+ [...html.matchAll(titleRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1]))),
303
+ num
304
+ );
305
+ const urls = takeFrom(
306
+ [...html.matchAll(urlRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1])).replace(/^\*(https?:\/\/[^\s]+).*$/, "$1")).filter((u) => u.startsWith("http")),
307
+ num
308
+ );
309
+ const snippets = takeFrom(
310
+ [...html.matchAll(snippetRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1]))),
311
+ num
312
+ );
313
+ for (let i = 0; i < Math.min(titles.length, num); i++) {
314
+ results.push({
315
+ title: titles[i] ?? "",
316
+ url: urls[i] ?? "",
317
+ snippet: capSnippet(snippets[i] ?? ""),
318
+ score: 1
319
+ });
320
+ }
321
+ return results;
322
+ }
323
+ async function bingSearch(query, signal) {
324
+ const encoded = encodeURIComponent(query);
325
+ const url = `https://www.bing.com/search?q=${encoded}`;
326
+ try {
327
+ const html = await fetchWithTimeout(url, signal, TIMEOUT_MS).then((r) => r.text());
328
+ return { results: parseBingResults(html, MAX_RESULTS) };
329
+ } catch (err) {
330
+ return { results: [], error: `bing unreachable: ${toErrorMessage(err)}` };
331
+ }
332
+ }
333
+ function parseBingResults(html, num) {
334
+ const results = [];
335
+ const blocks = [
336
+ ...html.matchAll(
337
+ /<li\b[^>]*class=(["'])[^"']*\bb_algo\b[^"']*\1[^>]*>([\s\S]*?)(?=<li\b[^>]*class=(["'])[^"']*\bb_algo\b[^"']*\3|<\/ol>)/gi
338
+ )
339
+ ].map((m) => expectDefined(m[2]));
340
+ const candidates = blocks.length > 0 ? blocks : [html];
341
+ const entries = takeFrom(
342
+ candidates.flatMap((block) => {
343
+ const titleMatch = /<h2[^>]*>\s*<a\b([^>]*)>([\s\S]*?)<\/a>\s*<\/h2>/i.exec(block);
344
+ if (!titleMatch) return [];
345
+ const href = getHtmlAttr(expectDefined(titleMatch[1]), "href");
346
+ const title = stripTags(expectDefined(titleMatch[2]));
347
+ if (!href || !title) return [];
348
+ const snippetMatch = /<p\b[^>]*class=(["'])[^"']*\b(?:b_paractl|b_lineclamp\d*)\b[^"']*\1[^>]*>([\s\S]*?)<\/p>/i.exec(
349
+ block
350
+ ) ?? /<p\b[^>]*>([\s\S]*?)<\/p>/i.exec(block);
351
+ const snippet = snippetMatch ? capSnippet(stripTags(expectDefined(snippetMatch.at(-1)))) : "";
352
+ return [{ url: normalizeBingUrl(href), title, snippet, score: 1 }];
353
+ }),
354
+ num
355
+ );
356
+ for (let i = 0; i < entries.length; i++) {
357
+ const entry = entries[i];
358
+ if (entry) {
359
+ results.push({
360
+ title: entry.title ?? "",
361
+ url: entry.url ?? "",
362
+ snippet: entry.snippet ?? "",
363
+ score: 1
364
+ });
365
+ }
366
+ }
367
+ return results;
368
+ }
369
+ function normalizeBingUrl(raw) {
370
+ try {
371
+ const url = new URL(raw);
372
+ if (url.hostname.endsWith("bing.com") && url.pathname.startsWith("/ck/")) {
373
+ const encoded = url.searchParams.get("u");
374
+ const decoded = decodeBingTarget(encoded);
375
+ if (decoded?.startsWith("http")) return decoded;
376
+ }
377
+ } catch {
378
+ }
379
+ return raw;
380
+ }
381
+ function decodeBingTarget(encoded) {
382
+ if (!encoded) return void 0;
383
+ const payload = encoded.startsWith("a1") ? encoded.slice(2) : encoded;
384
+ try {
385
+ const padded = payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(payload.length / 4) * 4, "=");
386
+ return Buffer.from(padded, "base64").toString("utf8");
387
+ } catch {
388
+ return void 0;
389
+ }
390
+ }
391
+ async function fetchWithTimeout(url, signal, timeoutMs) {
392
+ const controller = new AbortController();
393
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
394
+ const fetchSignal = anySignal(signal, controller.signal);
395
+ try {
396
+ const res = await guardedFetch(url, 5, fetchSignal, {
397
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
398
+ });
399
+ clearTimeout(timer);
400
+ return res;
401
+ } catch (e) {
402
+ clearTimeout(timer);
403
+ if (e instanceof FetchError) {
404
+ throw e;
405
+ }
406
+ throw new FetchError({
407
+ message: `search: failed to fetch ${url}`,
408
+ status: 0,
409
+ context: { url },
410
+ cause: e
411
+ });
412
+ }
413
+ }
414
+ function anySignal(...signals) {
415
+ return AbortSignal.any(signals);
416
+ }
417
+ function stripTags(html) {
418
+ return decodeHtmlEntities(html.replace(/<[^>]+>/g, "")).trim();
419
+ }
420
+ function capSnippet(snippet) {
421
+ return snippet.length > MAX_SNIPPET_CHARS ? `${snippet.slice(0, MAX_SNIPPET_CHARS - 1)}\u2026` : snippet;
422
+ }
423
+ function decodeHtmlEntities(text) {
424
+ return text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
425
+ }
426
+
427
+ export {
428
+ searchTool,
429
+ __clearSearchCache
430
+ };
431
+ //# sourceMappingURL=chunk-4I4LWFOO.js.map