@wrongstack/tools 0.313.0 → 0.316.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 (182) hide show
  1. package/dist/_edit-match.d.ts +3 -2
  2. package/dist/_output-spool.d.ts +4 -3
  3. package/dist/_shell-pick.d.ts +2 -1
  4. package/dist/_spawn-stream.d.ts +2 -1
  5. package/dist/_syntax-check.d.ts +2 -1
  6. package/dist/audit.js +10 -4055
  7. package/dist/bash-kill-guard.d.ts +3 -6
  8. package/dist/bash.js +9 -2308
  9. package/dist/batch-tool-use.js +2 -187
  10. package/dist/browser/index.js +25 -1339
  11. package/dist/browser/network-guard-proxy.d.ts +2 -1
  12. package/dist/builtin.js +69 -33949
  13. package/dist/chunk-22B7GE5T.js +260 -0
  14. package/dist/chunk-2VSZC6QM.js +113 -0
  15. package/dist/chunk-3PVYQFRQ.js +472 -0
  16. package/dist/chunk-42BHI7TN.js +337 -0
  17. package/dist/chunk-4BHUSMNL.js +104 -0
  18. package/dist/chunk-4I4LWFOO.js +431 -0
  19. package/dist/chunk-4UESMQDP.js +122 -0
  20. package/dist/chunk-553IQUMO.js +478 -0
  21. package/dist/chunk-5H4GSJAI.js +223 -0
  22. package/dist/chunk-6RNIFLG4.js +305 -0
  23. package/dist/chunk-7EY5DCRO.js +434 -0
  24. package/dist/chunk-A6BRWIXN.js +317 -0
  25. package/dist/chunk-AHHDWNXC.js +200 -0
  26. package/dist/chunk-BSLVR56S.js +199 -0
  27. package/dist/chunk-BTSFTGIL.js +7 -0
  28. package/dist/chunk-D33S4RQG.js +222 -0
  29. package/dist/chunk-DA4KNE2H.js +4412 -0
  30. package/dist/chunk-DR7JOQTC.js +520 -0
  31. package/dist/chunk-EEOFQDT6.js +898 -0
  32. package/dist/chunk-EJWSCQ6D.js +137 -0
  33. package/dist/chunk-EMRGN4KM.js +170 -0
  34. package/dist/chunk-FQZOHLG3.js +89 -0
  35. package/dist/chunk-GOIZNNOA.js +221 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HYX2TZ7O.js +1272 -0
  38. package/dist/chunk-I64BS3VC.js +15 -0
  39. package/dist/chunk-IVWV2UM6.js +955 -0
  40. package/dist/chunk-IXMNTNW5.js +238 -0
  41. package/dist/chunk-IYK7XGDZ.js +892 -0
  42. package/dist/chunk-J5SKD6LN.js +235 -0
  43. package/dist/chunk-JNNVRHMV.js +2111 -0
  44. package/dist/chunk-JOHXDF3D.js +295 -0
  45. package/dist/chunk-JRJJX3L5.js +424 -0
  46. package/dist/chunk-K3WNSHUF.js +1371 -0
  47. package/dist/chunk-L25CVUVR.js +2830 -0
  48. package/dist/chunk-LIJQMYYX.js +59 -0
  49. package/dist/chunk-LWKUTMD5.js +197 -0
  50. package/dist/chunk-MQX2KXVW.js +54 -0
  51. package/dist/chunk-MZZN7VCD.js +359 -0
  52. package/dist/chunk-NBDZMMG2.js +169 -0
  53. package/dist/chunk-NKJW5GFO.js +366 -0
  54. package/dist/chunk-NKNOBUBU.js +522 -0
  55. package/dist/chunk-O4MBV4AX.js +134 -0
  56. package/dist/chunk-OUBDL3WH.js +3515 -0
  57. package/dist/chunk-PQKK5JH7.js +101 -0
  58. package/dist/chunk-PY2IOS7C.js +1000 -0
  59. package/dist/chunk-Q5JPPCZC.js +12 -0
  60. package/dist/chunk-QBV725YG.js +128 -0
  61. package/dist/chunk-QZQSPUBF.js +315 -0
  62. package/dist/chunk-RGISBZBD.js +231 -0
  63. package/dist/chunk-RJZQWEMS.js +84 -0
  64. package/dist/chunk-RXISBFR5.js +315 -0
  65. package/dist/chunk-S5CCLZL3.js +99 -0
  66. package/dist/chunk-SDLVH5RZ.js +178 -0
  67. package/dist/chunk-T2F4S7U4.js +1723 -0
  68. package/dist/chunk-TEBQ4VPZ.js +163 -0
  69. package/dist/chunk-U4D5S3VQ.js +21 -0
  70. package/dist/chunk-U4VAATKP.js +193 -0
  71. package/dist/chunk-UCYQTZ7F.js +113 -0
  72. package/dist/chunk-UKU2ZX4C.js +203 -0
  73. package/dist/chunk-UNSKG6DC.js +159 -0
  74. package/dist/chunk-V43EQ6VR.js +68 -0
  75. package/dist/chunk-VB3MJGCV.js +610 -0
  76. package/dist/chunk-VFKPWSOX.js +154 -0
  77. package/dist/chunk-VJNHFZ7J.js +190 -0
  78. package/dist/chunk-VXECAJJ7.js +1091 -0
  79. package/dist/chunk-WHIIIREL.js +223 -0
  80. package/dist/chunk-Z6DAKQ3U.js +1 -0
  81. package/dist/chunk-ZJQ4IGXK.js +474 -0
  82. package/dist/chunk-ZLTFLC25.js +385 -0
  83. package/dist/circuit-breaker.js +3 -191
  84. package/dist/codebase-index/ast-invariant-engine.d.ts +5 -4
  85. package/dist/codebase-index/binary-frame.d.ts +0 -2
  86. package/dist/codebase-index/bm25.d.ts +1 -1
  87. package/dist/codebase-index/circuit-breaker.d.ts +2 -1
  88. package/dist/codebase-index/codebase-ast-replace-tool.d.ts +3 -2
  89. package/dist/codebase-index/codebase-impact-analysis-tool.d.ts +4 -3
  90. package/dist/codebase-index/codebase-invariant-check-tool.d.ts +3 -2
  91. package/dist/codebase-index/codebase-repo-map-tool.d.ts +3 -2
  92. package/dist/codebase-index/codebase-skeleton-tool.d.ts +3 -2
  93. package/dist/codebase-index/codebase-targeted-test-tool.d.ts +3 -2
  94. package/dist/codebase-index/content-hash.d.ts +0 -2
  95. package/dist/codebase-index/import-extractor.d.ts +0 -13
  96. package/dist/codebase-index/index-service.d.ts +1 -1
  97. package/dist/codebase-index/index.js +84 -13688
  98. package/dist/codebase-index/languages.d.ts +2 -1
  99. package/dist/codebase-index/module-roots.d.ts +3 -2
  100. package/dist/codebase-index/parser-batch.d.ts +0 -5
  101. package/dist/codebase-index/parser-dispatch.d.ts +2 -1
  102. package/dist/codebase-index/parser-output.d.ts +4 -3
  103. package/dist/codebase-index/parser-worker-pool.d.ts +0 -2
  104. package/dist/codebase-index/parser-worker-script.d.ts +1 -16
  105. package/dist/codebase-index/parser-worker-script.js +8 -3995
  106. package/dist/codebase-index/project-server-client-state.d.ts +2 -2
  107. package/dist/codebase-index/project-server-endpoint.d.ts +0 -15
  108. package/dist/codebase-index/project-server.js +60 -8548
  109. package/dist/codebase-index/tree-sitter/visitor.d.ts +2 -1
  110. package/dist/codebase-index/tree-sitter-parser.d.ts +0 -2
  111. package/dist/codebase-index/ts-parser.d.ts +1 -1
  112. package/dist/codebase-index/vector-search.d.ts +2 -1
  113. package/dist/codebase-index/wal-maintenance.d.ts +3 -2
  114. package/dist/codebase-index/worker.js +20 -8416
  115. package/dist/codebase-index/writer-admin.d.ts +0 -1
  116. package/dist/codebase-index/writer-search.d.ts +0 -9
  117. package/dist/design.js +2 -299
  118. package/dist/diff.js +4 -256
  119. package/dist/document.js +4 -222
  120. package/dist/e2e.js +5 -476
  121. package/dist/edit.js +14 -10200
  122. package/dist/exec.js +16 -3131
  123. package/dist/fetch.js +8 -398
  124. package/dist/format.js +10 -3750
  125. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  126. package/dist/git.js +4 -380
  127. package/dist/glob.js +6 -280
  128. package/dist/go-parser-JXYKJHRC.js +469 -0
  129. package/dist/grep.js +7 -604
  130. package/dist/index.js +318 -35387
  131. package/dist/install.js +10 -4091
  132. package/dist/json-parser-IBHZ4BZC.js +213 -0
  133. package/dist/json.js +4 -665
  134. package/dist/kanban-contract-actions.d.ts +1 -1
  135. package/dist/kanban-detail-actions.d.ts +2 -1
  136. package/dist/kanban-presence.d.ts +2 -1
  137. package/dist/kanban-serializer.d.ts +0 -8
  138. package/dist/kanban-split-task-handler.d.ts +2 -2
  139. package/dist/kanban-tool-types.d.ts +2 -1
  140. package/dist/kanban.js +3 -2096
  141. package/dist/languages/diagnostics.d.ts +2 -1
  142. package/dist/languages/index.js +23 -4664
  143. package/dist/languages/legacy-bridge.d.ts +3 -2
  144. package/dist/languages/types.d.ts +2 -1
  145. package/dist/legacy-bridge-7M6QLUQN.js +18 -0
  146. package/dist/lint.js +10 -3706
  147. package/dist/logs.js +4 -287
  148. package/dist/memory.js +6 -215
  149. package/dist/mode.js +3 -99
  150. package/dist/outdated.js +4 -5170
  151. package/dist/pack.js +65 -33897
  152. package/dist/parser-dispatch-QH4XPGG6.js +14 -0
  153. package/dist/patch.js +13 -9935
  154. package/dist/plan.js +5 -3286
  155. package/dist/process-registry.js +8 -651
  156. package/dist/ps-slash.js +12 -1439
  157. package/dist/pwsh.d.ts +0 -1
  158. package/dist/py-parser-IS4HKYMF.js +16 -0
  159. package/dist/read.js +13 -9816
  160. package/dist/replace.js +15 -10014
  161. package/dist/rs-parser-XHUUO2KZ.js +81 -0
  162. package/dist/scaffold.js +4 -253
  163. package/dist/search.js +5 -585
  164. package/dist/session-kanban-sync.d.ts +0 -6
  165. package/dist/session-kanban.js +30 -972
  166. package/dist/skill.js +2 -215
  167. package/dist/spawn-background.d.ts +1 -1
  168. package/dist/task.js +5 -3410
  169. package/dist/test.js +10 -3773
  170. package/dist/todo.js +4 -2891
  171. package/dist/tool-help.js +3 -123
  172. package/dist/tool-search.js +3 -79
  173. package/dist/tool-tier.js +68 -33984
  174. package/dist/tool-use.js +2 -93
  175. package/dist/tree-sitter-parser-AIERW3YI.js +15 -0
  176. package/dist/tree.js +4 -288
  177. package/dist/ts-parser-RCTYKSVI.js +232 -0
  178. package/dist/typecheck.js +10 -3753
  179. package/dist/win32.js +6 -60
  180. package/dist/write.js +14 -9882
  181. package/dist/yaml-parser-4SAXV3PL.js +157 -0
  182. 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
@@ -0,0 +1,122 @@
1
+ import {
2
+ resolveIndexDir
3
+ } from "./chunk-DA4KNE2H.js";
4
+
5
+ // src/codebase-index/binary-frame.ts
6
+ import { decode, encode } from "@msgpack/msgpack";
7
+ var BINARY_FRAME_MAGIC = 87;
8
+ var MAX_BINARY_FRAME_BYTES = 256 * 1024 * 1024;
9
+ var MAX_INBOUND_BINARY_FRAME_BYTES = 64 * 1024 * 1024;
10
+ function isBinaryFrame(firstByte) {
11
+ return firstByte === BINARY_FRAME_MAGIC;
12
+ }
13
+ function encodeBinaryFrame(message) {
14
+ const payload = encode(normalizeUndefined(message));
15
+ const header = Buffer.allocUnsafe(5);
16
+ header[0] = BINARY_FRAME_MAGIC;
17
+ header.writeUInt32BE(payload.length, 1);
18
+ return Buffer.concat([header, payload], 5 + payload.length);
19
+ }
20
+ function normalizeUndefined(value) {
21
+ if (value instanceof Date) {
22
+ const time = value.getTime();
23
+ return Number.isNaN(time) ? null : value.toISOString();
24
+ }
25
+ if (value instanceof Map) return normalizeUndefined(Object.fromEntries(value));
26
+ if (value instanceof Set) return normalizeUndefined([...value]);
27
+ if (value instanceof Error) {
28
+ return normalizeUndefined({ name: value.name, message: value.message, stack: value.stack });
29
+ }
30
+ if (value instanceof RegExp) return String(value);
31
+ if (value instanceof URL) return value.toJSON();
32
+ if (Buffer.isBuffer(value)) return { type: "Buffer", data: [...value] };
33
+ if (Array.isArray(value)) return value.map((entry) => normalizeUndefined(entry));
34
+ if (!isPlainObject(value)) return value;
35
+ const out = {};
36
+ for (const [key, entry] of Object.entries(value)) {
37
+ if (entry === void 0) continue;
38
+ out[key] = normalizeUndefined(entry);
39
+ }
40
+ return out;
41
+ }
42
+ function isPlainObject(value) {
43
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
44
+ const proto = Object.getPrototypeOf(value);
45
+ return proto === Object.prototype || proto === null;
46
+ }
47
+ function decodeBinaryFrame(payload) {
48
+ return decode(payload);
49
+ }
50
+ function encodeJsonFrame(message) {
51
+ return `${JSON.stringify(normalizeUndefined(message))}
52
+ `;
53
+ }
54
+
55
+ // src/codebase-index/project-server-endpoint.ts
56
+ import { createHash } from "node:crypto";
57
+ import * as fs from "node:fs";
58
+ import * as os from "node:os";
59
+ import * as path from "node:path";
60
+ import { fileURLToPath } from "node:url";
61
+ var PROJECT_INDEX_SERVER_PROTOCOL_VERSION = 1;
62
+ var PROJECT_INDEX_SERVER_METADATA_FILE = "server.json";
63
+ var PROJECT_INDEX_SERVER_SOCKET_DIR = `wsci-v${PROJECT_INDEX_SERVER_PROTOCOL_VERSION}`;
64
+ var buildIdCache;
65
+ function projectIndexServerBuildId(entrypoint) {
66
+ const href = entrypoint instanceof URL ? entrypoint.href : entrypoint;
67
+ const cleanHref = href.split(/[?#]/, 1)[0] ?? href;
68
+ const file = cleanHref.startsWith("file:") ? fileURLToPath(cleanHref) : path.resolve(cleanHref);
69
+ try {
70
+ const stat = fs.statSync(file);
71
+ if (buildIdCache?.file === file && buildIdCache.mtimeMs === stat.mtimeMs && buildIdCache.size === stat.size) {
72
+ return buildIdCache.buildId;
73
+ }
74
+ const buildId = createHash("sha256").update(fs.readFileSync(file)).digest("hex").slice(0, 24);
75
+ buildIdCache = { file, mtimeMs: stat.mtimeMs, size: stat.size, buildId };
76
+ return buildId;
77
+ } catch {
78
+ return `unreadable:${path.basename(file)}`;
79
+ }
80
+ }
81
+ function normalizeLocalPath(value) {
82
+ const resolved = path.resolve(value);
83
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
84
+ }
85
+ function projectIndexServerKey(projectRoot, indexDir) {
86
+ const resolvedIndexDir = normalizeLocalPath(resolveIndexDir(projectRoot, indexDir));
87
+ return createHash("sha256").update(resolvedIndexDir).digest("hex").slice(0, 24);
88
+ }
89
+ function projectIndexServerEndpoint(projectRoot, indexDir) {
90
+ const key = projectIndexServerKey(projectRoot, indexDir);
91
+ if (process.platform === "win32") {
92
+ return `\\\\.\\pipe\\wrongstack-codebase-index-v${PROJECT_INDEX_SERVER_PROTOCOL_VERSION}-${key}`;
93
+ }
94
+ return path.join(os.tmpdir(), PROJECT_INDEX_SERVER_SOCKET_DIR, `${key}.sock`);
95
+ }
96
+ function projectIndexServerMetadataPath(projectRoot, indexDir) {
97
+ return path.join(
98
+ path.resolve(resolveIndexDir(projectRoot, indexDir)),
99
+ PROJECT_INDEX_SERVER_METADATA_FILE
100
+ );
101
+ }
102
+
103
+ // src/codebase-index/project-server-protocol.ts
104
+ var PROJECT_INDEX_SERVER_MAX_FRAME_CHARS = 64 * 1024 * 1024;
105
+ function encodeProjectServerMessage(message) {
106
+ return encodeJsonFrame(message);
107
+ }
108
+
109
+ export {
110
+ MAX_BINARY_FRAME_BYTES,
111
+ MAX_INBOUND_BINARY_FRAME_BYTES,
112
+ isBinaryFrame,
113
+ encodeBinaryFrame,
114
+ decodeBinaryFrame,
115
+ PROJECT_INDEX_SERVER_PROTOCOL_VERSION,
116
+ projectIndexServerBuildId,
117
+ projectIndexServerEndpoint,
118
+ projectIndexServerMetadataPath,
119
+ PROJECT_INDEX_SERVER_MAX_FRAME_CHARS,
120
+ encodeProjectServerMessage
121
+ };
122
+ //# sourceMappingURL=chunk-4UESMQDP.js.map