@wrongstack/tools 0.313.0 → 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.
- package/dist/audit.js +10 -4055
- package/dist/bash.js +9 -2308
- package/dist/batch-tool-use.js +2 -187
- package/dist/browser/index.js +25 -1339
- package/dist/builtin.js +69 -33949
- package/dist/chunk-2CTB3UK5.js +197 -0
- package/dist/chunk-2ME7ZWDD.js +1272 -0
- package/dist/chunk-2TFQDEPU.js +113 -0
- package/dist/chunk-2ZCJNKFE.js +315 -0
- package/dist/chunk-3PVYQFRQ.js +472 -0
- package/dist/chunk-3QMQBO5Z.js +89 -0
- package/dist/chunk-42AKKX7O.js +385 -0
- package/dist/chunk-42SKEETB.js +113 -0
- package/dist/chunk-4BHUSMNL.js +104 -0
- package/dist/chunk-4I4LWFOO.js +431 -0
- package/dist/chunk-553IQUMO.js +478 -0
- package/dist/chunk-55KF77OK.js +1944 -0
- package/dist/chunk-6HLZK37X.js +359 -0
- package/dist/chunk-6RNIFLG4.js +305 -0
- package/dist/chunk-A6BRWIXN.js +317 -0
- package/dist/chunk-AHHDWNXC.js +200 -0
- package/dist/chunk-B2CIOKWP.js +899 -0
- package/dist/chunk-BTSFTGIL.js +7 -0
- package/dist/chunk-D33S4RQG.js +222 -0
- package/dist/chunk-DIJKHSUO.js +134 -0
- package/dist/chunk-DPL47QGS.js +3515 -0
- package/dist/chunk-EMRGN4KM.js +170 -0
- package/dist/chunk-FGOABE4Z.js +955 -0
- package/dist/chunk-FW65TP4G.js +520 -0
- package/dist/chunk-GOIZNNOA.js +221 -0
- package/dist/chunk-H5MJUAA6.js +295 -0
- package/dist/chunk-H5OHH6F4.js +223 -0
- package/dist/chunk-HC5RM4WY.js +199 -0
- package/dist/chunk-HEQFMLZ7.js +190 -0
- package/dist/chunk-HFXSNKCV.js +196 -0
- package/dist/chunk-HXSBQ2SE.js +1723 -0
- package/dist/chunk-ILESNGNM.js +163 -0
- package/dist/chunk-INF5CGAO.js +137 -0
- package/dist/chunk-IWDFZ6XR.js +337 -0
- package/dist/chunk-IXMNTNW5.js +238 -0
- package/dist/chunk-J4SRJKBW.js +428 -0
- package/dist/chunk-J5SKD6LN.js +235 -0
- package/dist/chunk-JRJJX3L5.js +424 -0
- package/dist/chunk-KXNDHMUB.js +366 -0
- package/dist/chunk-LIJQMYYX.js +59 -0
- package/dist/chunk-MAN26PZ5.js +260 -0
- package/dist/chunk-MKRQMLZA.js +474 -0
- package/dist/chunk-NBDZMMG2.js +169 -0
- package/dist/chunk-NHA6BEIH.js +101 -0
- package/dist/chunk-OA6YJIWL.js +4412 -0
- package/dist/chunk-OZC255IC.js +2830 -0
- package/dist/chunk-PUR6WU2B.js +154 -0
- package/dist/chunk-Q5JPPCZC.js +12 -0
- package/dist/chunk-QBV725YG.js +128 -0
- package/dist/chunk-QHVW4AAM.js +892 -0
- package/dist/chunk-QNJ7AQ4B.js +1000 -0
- package/dist/chunk-RGISBZBD.js +231 -0
- package/dist/chunk-RJZQWEMS.js +84 -0
- package/dist/chunk-RP2ZA47V.js +15 -0
- package/dist/chunk-RXISBFR5.js +315 -0
- package/dist/chunk-S5CCLZL3.js +99 -0
- package/dist/chunk-TVTCSBJF.js +122 -0
- package/dist/chunk-U4D5S3VQ.js +21 -0
- package/dist/chunk-U4VAATKP.js +193 -0
- package/dist/chunk-UKU2ZX4C.js +203 -0
- package/dist/chunk-UNSKG6DC.js +159 -0
- package/dist/chunk-URFKEIHM.js +1091 -0
- package/dist/chunk-UTV7YAW7.js +178 -0
- package/dist/chunk-V43EQ6VR.js +68 -0
- package/dist/chunk-VB3MJGCV.js +610 -0
- package/dist/chunk-WHIIIREL.js +223 -0
- package/dist/chunk-XMIFYKUT.js +1371 -0
- package/dist/chunk-YF2RSV34.js +54 -0
- package/dist/chunk-Z6DAKQ3U.js +1 -0
- package/dist/chunk-ZIGAZFWE.js +522 -0
- package/dist/circuit-breaker.js +3 -191
- package/dist/codebase-index/index.js +84 -13688
- package/dist/codebase-index/parser-worker-script.js +8 -3995
- package/dist/codebase-index/project-server.js +60 -8548
- package/dist/codebase-index/worker.js +20 -8416
- package/dist/design.js +2 -299
- package/dist/diff.js +4 -256
- package/dist/document.js +4 -222
- package/dist/e2e.js +5 -476
- package/dist/edit.js +14 -10200
- package/dist/exec.js +16 -3131
- package/dist/fetch.js +8 -398
- package/dist/format.js +10 -3750
- package/dist/generic-parser-VUXDIAOZ.js +13 -0
- package/dist/git.js +4 -380
- package/dist/glob.js +6 -280
- package/dist/go-parser-6CA77WZ4.js +469 -0
- package/dist/grep.js +7 -604
- package/dist/index.js +318 -35387
- package/dist/install.js +10 -4091
- package/dist/json-parser-7YMDJSBJ.js +213 -0
- package/dist/json.js +4 -665
- package/dist/kanban.js +3 -2096
- package/dist/languages/index.js +23 -4664
- package/dist/legacy-bridge-7UKZT46G.js +18 -0
- package/dist/lint.js +10 -3706
- package/dist/logs.js +4 -287
- package/dist/memory.js +6 -215
- package/dist/mode.js +3 -99
- package/dist/outdated.js +4 -5170
- package/dist/pack.js +65 -33897
- package/dist/parser-dispatch-VPOFDO2U.js +14 -0
- package/dist/patch.js +13 -9935
- package/dist/plan.js +5 -3286
- package/dist/process-registry.js +8 -651
- package/dist/ps-slash.js +12 -1439
- package/dist/py-parser-GPM5VYRG.js +16 -0
- package/dist/read.js +13 -9816
- package/dist/replace.js +15 -10014
- package/dist/rs-parser-WVQ4KYCX.js +81 -0
- package/dist/scaffold.js +4 -253
- package/dist/search.js +5 -585
- package/dist/session-kanban.js +30 -972
- package/dist/skill.js +2 -215
- package/dist/task.js +5 -3410
- package/dist/test.js +10 -3773
- package/dist/todo.js +4 -2891
- package/dist/tool-help.js +3 -123
- package/dist/tool-search.js +3 -79
- package/dist/tool-tier.js +68 -33984
- package/dist/tool-use.js +2 -93
- package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
- package/dist/tree.js +4 -288
- package/dist/ts-parser-YH4ZMWMH.js +232 -0
- package/dist/typecheck.js +10 -3753
- package/dist/win32.js +6 -60
- package/dist/write.js +14 -9882
- package/dist/yaml-parser-GFAOKV53.js +157 -0
- package/package.json +5 -5
package/dist/search.js
CHANGED
|
@@ -1,588 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import * as dns from "node:dns/promises";
|
|
7
|
-
import * as net from "node:net";
|
|
8
|
-
import { isPrivateIPv4, isPrivateIPv6 } from "@wrongstack/core/utils";
|
|
9
|
-
import { FetchError, ToolValidationError } from "@wrongstack/core/types";
|
|
10
|
-
import { Agent, fetch as undiciFetch } from "undici";
|
|
11
|
-
var nativeGlobalFetch = globalThis.fetch;
|
|
12
|
-
var ALLOW_PRIVATE = process.env["WRONGSTACK_FETCH_ALLOW_PRIVATE"] === "1";
|
|
13
|
-
if (ALLOW_PRIVATE && !process.env["CI"]) {
|
|
14
|
-
console.warn(
|
|
15
|
-
"[WrongStack] WARNING: WRONGSTACK_FETCH_ALLOW_PRIVATE=1 is active \u2014\n fetch tool can now access private IPs (10.x, 192.168.x, 169.254.x),\n cloud metadata endpoints, and plaintext HTTP. Use only on isolated networks."
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
function guardedLookup(hostname, options, callback) {
|
|
19
|
-
dns.lookup(hostname, { all: true }).then((records) => {
|
|
20
|
-
const family = options?.family;
|
|
21
|
-
const byFamily = family === 4 || family === 6 ? records.filter((r) => r.family === family) : records;
|
|
22
|
-
const list = byFamily.length > 0 ? byFamily : records;
|
|
23
|
-
if (!ALLOW_PRIVATE) {
|
|
24
|
-
for (const r of list) {
|
|
25
|
-
const bad = r.family === 4 ? isPrivateIPv4(r.address) : isPrivateIPv6(r.address);
|
|
26
|
-
if (bad) {
|
|
27
|
-
callback(
|
|
28
|
-
Object.assign(new Error(`fetch: resolved to private address ${r.address}`), {
|
|
29
|
-
code: "EAI_FAIL"
|
|
30
|
-
})
|
|
31
|
-
);
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
if (options?.all) {
|
|
37
|
-
callback(
|
|
38
|
-
null,
|
|
39
|
-
list.map((r) => ({ address: r.address, family: r.family }))
|
|
40
|
-
);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
const first = list.at(0);
|
|
44
|
-
if (!first) {
|
|
45
|
-
callback(
|
|
46
|
-
Object.assign(new Error(`fetch: no address for ${hostname}`), { code: "ENOTFOUND" })
|
|
47
|
-
);
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
callback(null, first.address, first.family);
|
|
51
|
-
}).catch((err) => callback(err));
|
|
52
|
-
}
|
|
53
|
-
var pinnedAgent;
|
|
54
|
-
function getPinnedDispatcher() {
|
|
55
|
-
if (!pinnedAgent) {
|
|
56
|
-
pinnedAgent = new Agent({ allowH2: false, connect: { lookup: guardedLookup } });
|
|
57
|
-
}
|
|
58
|
-
return pinnedAgent;
|
|
59
|
-
}
|
|
60
|
-
function dispatcherFetch() {
|
|
61
|
-
return globalThis.fetch === nativeGlobalFetch ? undiciFetch : globalThis.fetch;
|
|
62
|
-
}
|
|
63
|
-
var _beforeExitRegistered = false;
|
|
64
|
-
if (!_beforeExitRegistered) {
|
|
65
|
-
_beforeExitRegistered = true;
|
|
66
|
-
process.on("beforeExit", () => {
|
|
67
|
-
pinnedAgent?.destroy();
|
|
68
|
-
pinnedAgent = void 0;
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
async function guardedFetch(url, maxRedirects, signal, headers = {
|
|
72
|
-
"user-agent": "WrongStack/1.0 (+https://wrongstack.com)",
|
|
73
|
-
accept: "text/html,application/json;q=0.9,text/plain;q=0.8,*/*;q=0.1"
|
|
74
|
-
}) {
|
|
75
|
-
let redirectCount = 0;
|
|
76
|
-
let currentUrl = url;
|
|
77
|
-
for (; ; ) {
|
|
78
|
-
const parsed = new URL(currentUrl);
|
|
79
|
-
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
80
|
-
throw new ToolValidationError({
|
|
81
|
-
message: `fetch: redirect to unsupported protocol "${parsed.protocol}"`,
|
|
82
|
-
field: "url"
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
if (parsed.protocol === "http:" && !ALLOW_PRIVATE) {
|
|
86
|
-
throw new ToolValidationError({
|
|
87
|
-
message: "fetch: redirect to http:// blocked (HTTPS required by default)",
|
|
88
|
-
field: "url"
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
await assertNotPrivate(parsed.hostname);
|
|
92
|
-
const init = {
|
|
93
|
-
redirect: "manual",
|
|
94
|
-
signal,
|
|
95
|
-
headers,
|
|
96
|
-
dispatcher: getPinnedDispatcher()
|
|
97
|
-
};
|
|
98
|
-
const res = await dispatcherFetch()(currentUrl, init);
|
|
99
|
-
if (res.status < 300 || res.status > 399) {
|
|
100
|
-
return res;
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
await res.body?.cancel();
|
|
104
|
-
} catch {
|
|
105
|
-
}
|
|
106
|
-
redirectCount++;
|
|
107
|
-
if (redirectCount > maxRedirects) {
|
|
108
|
-
throw new FetchError({
|
|
109
|
-
message: `fetch: exceeded ${maxRedirects} redirects`,
|
|
110
|
-
status: res.status,
|
|
111
|
-
context: { url: currentUrl, maxRedirects, redirectCount }
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
const location = res.headers.get("location");
|
|
115
|
-
if (!location) {
|
|
116
|
-
throw new FetchError({
|
|
117
|
-
message: "fetch: redirect status with no location header",
|
|
118
|
-
status: res.status,
|
|
119
|
-
context: { url: currentUrl, redirectCount }
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
currentUrl = new URL(location, currentUrl).toString();
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
async function assertNotPrivate(hostname) {
|
|
126
|
-
if (ALLOW_PRIVATE) return;
|
|
127
|
-
const host = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
|
|
128
|
-
if (host === "localhost" || host.endsWith(".localhost")) {
|
|
129
|
-
throw new ToolValidationError({
|
|
130
|
-
message: "fetch: blocked localhost target",
|
|
131
|
-
field: "url"
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
const ipVersion = net.isIP(host);
|
|
135
|
-
if (ipVersion === 4) {
|
|
136
|
-
if (isPrivateIPv4(host)) {
|
|
137
|
-
throw new ToolValidationError({
|
|
138
|
-
message: `fetch: blocked private/loopback address "${host}"`,
|
|
139
|
-
field: "url"
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
} else if (ipVersion === 6) {
|
|
143
|
-
if (isPrivateIPv6(host)) {
|
|
144
|
-
throw new ToolValidationError({
|
|
145
|
-
message: `fetch: blocked private/loopback address "${host}"`,
|
|
146
|
-
field: "url"
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
} else {
|
|
150
|
-
try {
|
|
151
|
-
const records = await dns.lookup(host, { all: true });
|
|
152
|
-
for (const r of records) {
|
|
153
|
-
const bad = r.family === 4 ? isPrivateIPv4(r.address) : isPrivateIPv6(r.address);
|
|
154
|
-
if (bad) {
|
|
155
|
-
throw new ToolValidationError({
|
|
156
|
-
message: `fetch: resolved to private address ${r.address}`,
|
|
157
|
-
field: "url"
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
} catch (err) {
|
|
162
|
-
if (err instanceof ToolValidationError) throw err;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
// src/search.ts
|
|
168
|
-
import { toErrorMessage } from "@wrongstack/core/utils";
|
|
169
|
-
var DEFAULT_NUM = 10;
|
|
170
|
-
var MAX_RESULTS = 50;
|
|
171
|
-
var MAX_SNIPPET_CHARS = 300;
|
|
172
|
-
var TIMEOUT_MS = 15e3;
|
|
173
|
-
var CACHE_TTL_MS = 3e5;
|
|
174
|
-
var CACHE_MAX_ENTRIES = 200;
|
|
175
|
-
var cache = /* @__PURE__ */ new Map();
|
|
176
|
-
var searchTool = {
|
|
177
|
-
name: "search",
|
|
178
|
-
category: "Search",
|
|
179
|
-
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.",
|
|
180
|
-
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.",
|
|
181
|
-
permission: "auto",
|
|
182
|
-
mutating: false,
|
|
183
|
-
capabilities: ["net.outbound"],
|
|
184
|
-
icon: "search",
|
|
185
|
-
timeoutMs: TIMEOUT_MS,
|
|
186
|
-
inputSchema: {
|
|
187
|
-
type: "object",
|
|
188
|
-
properties: {
|
|
189
|
-
query: { type: "string", description: "Search query" },
|
|
190
|
-
num_results: {
|
|
191
|
-
type: "integer",
|
|
192
|
-
description: "Number of results (1-50, default 10)",
|
|
193
|
-
minimum: 1,
|
|
194
|
-
maximum: MAX_RESULTS
|
|
195
|
-
},
|
|
196
|
-
source: {
|
|
197
|
-
type: "string",
|
|
198
|
-
enum: ["duckduckgo", "google", "bing"],
|
|
199
|
-
description: "Search engine to use (default: duckduckgo)"
|
|
200
|
-
},
|
|
201
|
-
skip_cache: {
|
|
202
|
-
type: "boolean",
|
|
203
|
-
description: "Skip the in-memory cache and force a fresh search (default: false)"
|
|
204
|
-
}
|
|
205
|
-
},
|
|
206
|
-
required: ["query"]
|
|
207
|
-
},
|
|
208
|
-
async execute(input, ctx, opts) {
|
|
209
|
-
let final;
|
|
210
|
-
const executeStream = searchTool.executeStream;
|
|
211
|
-
if (!executeStream) throw new Error("searchTool: stream execution unavailable");
|
|
212
|
-
for await (const ev of executeStream(input, ctx, opts)) {
|
|
213
|
-
if (ev.type === "final") final = ev.output;
|
|
214
|
-
}
|
|
215
|
-
if (!final) throw new Error("search: stream ended without final event");
|
|
216
|
-
return final;
|
|
217
|
-
},
|
|
218
|
-
async *executeStream(input, _ctx, opts) {
|
|
219
|
-
if (!input?.query || input.query.trim() === "") {
|
|
220
|
-
throw new ToolValidationError2({
|
|
221
|
-
message: "search: query is required and must be a non-empty string",
|
|
222
|
-
field: "query"
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
const num = Math.max(1, Math.min(input.num_results ?? DEFAULT_NUM, MAX_RESULTS));
|
|
226
|
-
const source = input.source ?? "duckduckgo";
|
|
227
|
-
const skipCache = input.skip_cache ?? false;
|
|
228
|
-
const cacheKey = `${source}:${input.query}`;
|
|
229
|
-
if (!skipCache) {
|
|
230
|
-
const entry = cache.get(cacheKey);
|
|
231
|
-
if (entry && Date.now() - entry.timestamp < CACHE_TTL_MS) {
|
|
232
|
-
const results = entry.results.map((r) => ({
|
|
233
|
-
title: r.title,
|
|
234
|
-
url: r.url,
|
|
235
|
-
snippet: r.snippet
|
|
236
|
-
}));
|
|
237
|
-
yield {
|
|
238
|
-
type: "log",
|
|
239
|
-
text: `Cache hit for "${input.query}" (${source})`,
|
|
240
|
-
data: { source, query: input.query, cached: true }
|
|
241
|
-
};
|
|
242
|
-
yield {
|
|
243
|
-
type: "partial_output",
|
|
244
|
-
text: `${results.length} cached results from ${entry.source}`,
|
|
245
|
-
data: { count: results.length, cached: true, source: entry.source }
|
|
246
|
-
};
|
|
247
|
-
yield {
|
|
248
|
-
type: "final",
|
|
249
|
-
output: {
|
|
250
|
-
query: input.query,
|
|
251
|
-
results: results.slice(0, num),
|
|
252
|
-
source: entry.source,
|
|
253
|
-
truncated: results.length > num,
|
|
254
|
-
cached: true
|
|
255
|
-
}
|
|
256
|
-
};
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
yield {
|
|
261
|
-
type: "log",
|
|
262
|
-
text: `Querying ${source} for "${input.query}"\u2026`,
|
|
263
|
-
data: { source, query: input.query, cached: false }
|
|
264
|
-
};
|
|
265
|
-
let engine;
|
|
266
|
-
let effectiveSource = source;
|
|
267
|
-
switch (source) {
|
|
268
|
-
case "duckduckgo":
|
|
269
|
-
engine = await duckduckgoSearch(input.query, opts.signal);
|
|
270
|
-
break;
|
|
271
|
-
case "google":
|
|
272
|
-
engine = await googleSearch(input.query, opts.signal);
|
|
273
|
-
break;
|
|
274
|
-
case "bing":
|
|
275
|
-
engine = await bingSearch(input.query, opts.signal);
|
|
276
|
-
break;
|
|
277
|
-
default:
|
|
278
|
-
throw new ToolValidationError2({
|
|
279
|
-
message: `search: unknown source "${source}"`,
|
|
280
|
-
field: "source"
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
let ranked = rankSearchResults(engine.results, input.query);
|
|
284
|
-
let engineError = engine.error;
|
|
285
|
-
if (source !== "duckduckgo" && shouldFallbackToDuckDuckGo(ranked, input.query)) {
|
|
286
|
-
yield {
|
|
287
|
-
type: "log",
|
|
288
|
-
text: `${source} returned no relevant static results; falling back to duckduckgo`,
|
|
289
|
-
data: { source, fallback: "duckduckgo", query: input.query }
|
|
290
|
-
};
|
|
291
|
-
const fallback = await duckduckgoSearch(input.query, opts.signal);
|
|
292
|
-
ranked = rankSearchResults(fallback.results, input.query);
|
|
293
|
-
engineError = fallback.error;
|
|
294
|
-
effectiveSource = "duckduckgo";
|
|
295
|
-
}
|
|
296
|
-
const finalResults = ranked.slice(0, num);
|
|
297
|
-
if (!engineError) {
|
|
298
|
-
cache.set(cacheKey, { results: ranked, source: effectiveSource, timestamp: Date.now() });
|
|
299
|
-
pruneCacheEntries();
|
|
300
|
-
}
|
|
301
|
-
yield {
|
|
302
|
-
type: "partial_output",
|
|
303
|
-
text: engineError ? `search failed: ${engineError}` : `${finalResults.length} results from ${effectiveSource}`,
|
|
304
|
-
data: { count: finalResults.length, cached: false, source: effectiveSource }
|
|
305
|
-
};
|
|
306
|
-
yield {
|
|
307
|
-
type: "final",
|
|
308
|
-
output: {
|
|
309
|
-
query: input.query,
|
|
310
|
-
results: finalResults.map((r) => ({
|
|
311
|
-
title: r.title,
|
|
312
|
-
url: r.url,
|
|
313
|
-
snippet: r.snippet
|
|
314
|
-
})),
|
|
315
|
-
source: effectiveSource,
|
|
316
|
-
truncated: ranked.length > num,
|
|
317
|
-
cached: false,
|
|
318
|
-
...engineError ? { error: engineError } : {}
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
};
|
|
323
|
-
function pruneCacheEntries() {
|
|
324
|
-
const cutoff = Date.now() - CACHE_TTL_MS * 2;
|
|
325
|
-
for (const [key, entry] of cache.entries()) {
|
|
326
|
-
if (entry.timestamp < cutoff) cache.delete(key);
|
|
327
|
-
}
|
|
328
|
-
while (cache.size > CACHE_MAX_ENTRIES) {
|
|
329
|
-
const oldestKey = cache.keys().next().value;
|
|
330
|
-
if (oldestKey === void 0) break;
|
|
331
|
-
cache.delete(oldestKey);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
function __clearSearchCache() {
|
|
335
|
-
cache.clear();
|
|
336
|
-
}
|
|
337
|
-
function rankSearchResults(results, query) {
|
|
338
|
-
const seenUrls = /* @__PURE__ */ new Set();
|
|
339
|
-
const deduped = [];
|
|
340
|
-
for (const r of results) {
|
|
341
|
-
const noQuery = r.url.split("?")[0] ?? r.url;
|
|
342
|
-
const normalized = noQuery.split("#")[0] ?? r.url;
|
|
343
|
-
if (!seenUrls.has(normalized) && r.url.startsWith("http")) {
|
|
344
|
-
seenUrls.add(normalized);
|
|
345
|
-
deduped.push(r);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
return scoreResults(deduped, query);
|
|
349
|
-
}
|
|
350
|
-
function scoreResults(results, query) {
|
|
351
|
-
const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
|
|
352
|
-
return results.map((r) => {
|
|
353
|
-
const titleLower = r.title.toLowerCase();
|
|
354
|
-
const snippetLower = r.snippet.toLowerCase();
|
|
355
|
-
let score = r.score;
|
|
356
|
-
for (const term of terms) {
|
|
357
|
-
if (titleLower.includes(term)) score += 2;
|
|
358
|
-
if (snippetLower.includes(term)) score += 1;
|
|
359
|
-
}
|
|
360
|
-
return { ...r, score };
|
|
361
|
-
}).sort((a, b) => b.score - a.score);
|
|
362
|
-
}
|
|
363
|
-
function shouldFallbackToDuckDuckGo(results, query) {
|
|
364
|
-
if (results.length === 0) return true;
|
|
365
|
-
const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3);
|
|
366
|
-
if (terms.length === 0) return false;
|
|
367
|
-
return !results.some((r) => {
|
|
368
|
-
const haystack = `${r.title} ${r.url} ${r.snippet}`.toLowerCase();
|
|
369
|
-
return terms.some((term) => haystack.includes(term));
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
async function duckduckgoSearch(query, signal) {
|
|
373
|
-
const encoded = encodeURIComponent(query);
|
|
374
|
-
const url = `https://lite.duckduckgo.com/lite/?q=${encoded}&kd=-1&kl=wt-wt`;
|
|
375
|
-
try {
|
|
376
|
-
const response = await fetchWithTimeout(url, signal, TIMEOUT_MS);
|
|
377
|
-
const html = await response.text();
|
|
378
|
-
return { results: parseDuckDuckGo(html, MAX_RESULTS) };
|
|
379
|
-
} catch (err) {
|
|
380
|
-
console.log(
|
|
381
|
-
JSON.stringify({ level: "debug", event: "search_failed", query, error: toErrorMessage(err) })
|
|
382
|
-
);
|
|
383
|
-
return { results: [], error: `duckduckgo unreachable: ${toErrorMessage(err)}` };
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
function takeFrom(iter, max) {
|
|
387
|
-
const out = [];
|
|
388
|
-
for (const item of iter) {
|
|
389
|
-
if (out.length >= max) break;
|
|
390
|
-
out.push(item);
|
|
391
|
-
}
|
|
392
|
-
return out;
|
|
393
|
-
}
|
|
394
|
-
function parseDuckDuckGo(html, num) {
|
|
395
|
-
const results = [];
|
|
396
|
-
const linkRegex = /<a\b([^>]*\bclass=(["'])[^"']*\bresult-link\b[^"']*\2[^>]*)>([\s\S]*?)<\/a>/gi;
|
|
397
|
-
const snippetRegex = /<([a-z0-9]+)\b([^>]*\bclass=(["'])[^"']*\bresult-snippet\b[^"']*\3[^>]*)>([\s\S]*?)<\/\1>/gi;
|
|
398
|
-
const linkMatches = takeFrom(
|
|
399
|
-
[...html.matchAll(linkRegex)].map((m) => {
|
|
400
|
-
const attrs = expectDefined(m[1]);
|
|
401
|
-
const href = getHtmlAttr(attrs, "href");
|
|
402
|
-
const title = stripTags(expectDefined(m[3]));
|
|
403
|
-
return href && title ? { url: normalizeDuckDuckGoUrl(href), title } : void 0;
|
|
404
|
-
}).filter((m) => m !== void 0),
|
|
405
|
-
num
|
|
406
|
-
);
|
|
407
|
-
const snippetMatches = takeFrom(
|
|
408
|
-
[...html.matchAll(snippetRegex)].filter((m) => m[4]).map((m) => stripTags(expectDefined(m[4]))),
|
|
409
|
-
num
|
|
410
|
-
);
|
|
411
|
-
for (let i = 0; i < linkMatches.length && i < num; i++) {
|
|
412
|
-
const entry = linkMatches[i];
|
|
413
|
-
if (entry) {
|
|
414
|
-
results.push({
|
|
415
|
-
title: entry.title ?? "",
|
|
416
|
-
url: entry.url ?? "",
|
|
417
|
-
snippet: capSnippet(snippetMatches[i] ?? ""),
|
|
418
|
-
score: 1
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
return results;
|
|
423
|
-
}
|
|
424
|
-
function escapeRegex(s) {
|
|
425
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
426
|
-
}
|
|
427
|
-
function getHtmlAttr(attrs, name) {
|
|
428
|
-
const escaped = escapeRegex(name);
|
|
429
|
-
const quoted = new RegExp(`\\b${escaped}\\s*=\\s*(["'])(.*?)\\1`, "i").exec(attrs);
|
|
430
|
-
if (quoted?.[2]) return decodeHtmlEntities(quoted[2]);
|
|
431
|
-
const unquoted = new RegExp(`\\b${escaped}\\s*=\\s*([^\\s>]+)`, "i").exec(attrs);
|
|
432
|
-
return unquoted?.[1] ? decodeHtmlEntities(unquoted[1]) : void 0;
|
|
433
|
-
}
|
|
434
|
-
function normalizeDuckDuckGoUrl(raw) {
|
|
435
|
-
if (raw.startsWith("//")) return `https:${raw}`;
|
|
436
|
-
if (!raw.startsWith("/")) return raw;
|
|
437
|
-
if (!raw.startsWith("/l/")) return raw;
|
|
438
|
-
try {
|
|
439
|
-
const url = new URL(raw, "https://duckduckgo.com");
|
|
440
|
-
const uddg = url.searchParams.get("uddg");
|
|
441
|
-
return uddg?.startsWith("http") ? uddg : url.toString();
|
|
442
|
-
} catch {
|
|
443
|
-
return raw;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
async function googleSearch(query, signal) {
|
|
447
|
-
const encoded = encodeURIComponent(query);
|
|
448
|
-
const url = `https://www.google.com/search?q=${encoded}&hl=en`;
|
|
449
|
-
try {
|
|
450
|
-
const html = await fetchWithTimeout(url, signal, TIMEOUT_MS).then((r) => r.text());
|
|
451
|
-
return { results: parseGoogleResults(html, MAX_RESULTS) };
|
|
452
|
-
} catch (err) {
|
|
453
|
-
return { results: [], error: `google unreachable: ${toErrorMessage(err)}` };
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
function parseGoogleResults(html, num) {
|
|
457
|
-
const results = [];
|
|
458
|
-
const titleRegex = /<h3[^>]*class="[^"]*DKV84"[^>]*>([^<]+)<\/h3>/gi;
|
|
459
|
-
const urlRegex = /<cite[^>]*>([^<]+)<\/cite>/gi;
|
|
460
|
-
const snippetRegex = /<span[^>]*class="[^"]*aXCZ0b[^>]*>([^<]+)<\/span>/gi;
|
|
461
|
-
const titles = takeFrom(
|
|
462
|
-
[...html.matchAll(titleRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1]))),
|
|
463
|
-
num
|
|
464
|
-
);
|
|
465
|
-
const urls = takeFrom(
|
|
466
|
-
[...html.matchAll(urlRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1])).replace(/^\*(https?:\/\/[^\s]+).*$/, "$1")).filter((u) => u.startsWith("http")),
|
|
467
|
-
num
|
|
468
|
-
);
|
|
469
|
-
const snippets = takeFrom(
|
|
470
|
-
[...html.matchAll(snippetRegex)].filter((m) => m[1]).map((m) => stripTags(expectDefined(m[1]))),
|
|
471
|
-
num
|
|
472
|
-
);
|
|
473
|
-
for (let i = 0; i < Math.min(titles.length, num); i++) {
|
|
474
|
-
results.push({
|
|
475
|
-
title: titles[i] ?? "",
|
|
476
|
-
url: urls[i] ?? "",
|
|
477
|
-
snippet: capSnippet(snippets[i] ?? ""),
|
|
478
|
-
score: 1
|
|
479
|
-
});
|
|
480
|
-
}
|
|
481
|
-
return results;
|
|
482
|
-
}
|
|
483
|
-
async function bingSearch(query, signal) {
|
|
484
|
-
const encoded = encodeURIComponent(query);
|
|
485
|
-
const url = `https://www.bing.com/search?q=${encoded}`;
|
|
486
|
-
try {
|
|
487
|
-
const html = await fetchWithTimeout(url, signal, TIMEOUT_MS).then((r) => r.text());
|
|
488
|
-
return { results: parseBingResults(html, MAX_RESULTS) };
|
|
489
|
-
} catch (err) {
|
|
490
|
-
return { results: [], error: `bing unreachable: ${toErrorMessage(err)}` };
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
function parseBingResults(html, num) {
|
|
494
|
-
const results = [];
|
|
495
|
-
const blocks = [
|
|
496
|
-
...html.matchAll(
|
|
497
|
-
/<li\b[^>]*class=(["'])[^"']*\bb_algo\b[^"']*\1[^>]*>([\s\S]*?)(?=<li\b[^>]*class=(["'])[^"']*\bb_algo\b[^"']*\3|<\/ol>)/gi
|
|
498
|
-
)
|
|
499
|
-
].map((m) => expectDefined(m[2]));
|
|
500
|
-
const candidates = blocks.length > 0 ? blocks : [html];
|
|
501
|
-
const entries = takeFrom(
|
|
502
|
-
candidates.flatMap((block) => {
|
|
503
|
-
const titleMatch = /<h2[^>]*>\s*<a\b([^>]*)>([\s\S]*?)<\/a>\s*<\/h2>/i.exec(block);
|
|
504
|
-
if (!titleMatch) return [];
|
|
505
|
-
const href = getHtmlAttr(expectDefined(titleMatch[1]), "href");
|
|
506
|
-
const title = stripTags(expectDefined(titleMatch[2]));
|
|
507
|
-
if (!href || !title) return [];
|
|
508
|
-
const snippetMatch = /<p\b[^>]*class=(["'])[^"']*\b(?:b_paractl|b_lineclamp\d*)\b[^"']*\1[^>]*>([\s\S]*?)<\/p>/i.exec(
|
|
509
|
-
block
|
|
510
|
-
) ?? /<p\b[^>]*>([\s\S]*?)<\/p>/i.exec(block);
|
|
511
|
-
const snippet = snippetMatch ? capSnippet(stripTags(expectDefined(snippetMatch.at(-1)))) : "";
|
|
512
|
-
return [{ url: normalizeBingUrl(href), title, snippet, score: 1 }];
|
|
513
|
-
}),
|
|
514
|
-
num
|
|
515
|
-
);
|
|
516
|
-
for (let i = 0; i < entries.length; i++) {
|
|
517
|
-
const entry = entries[i];
|
|
518
|
-
if (entry) {
|
|
519
|
-
results.push({
|
|
520
|
-
title: entry.title ?? "",
|
|
521
|
-
url: entry.url ?? "",
|
|
522
|
-
snippet: entry.snippet ?? "",
|
|
523
|
-
score: 1
|
|
524
|
-
});
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
return results;
|
|
528
|
-
}
|
|
529
|
-
function normalizeBingUrl(raw) {
|
|
530
|
-
try {
|
|
531
|
-
const url = new URL(raw);
|
|
532
|
-
if (url.hostname.endsWith("bing.com") && url.pathname.startsWith("/ck/")) {
|
|
533
|
-
const encoded = url.searchParams.get("u");
|
|
534
|
-
const decoded = decodeBingTarget(encoded);
|
|
535
|
-
if (decoded?.startsWith("http")) return decoded;
|
|
536
|
-
}
|
|
537
|
-
} catch {
|
|
538
|
-
}
|
|
539
|
-
return raw;
|
|
540
|
-
}
|
|
541
|
-
function decodeBingTarget(encoded) {
|
|
542
|
-
if (!encoded) return void 0;
|
|
543
|
-
const payload = encoded.startsWith("a1") ? encoded.slice(2) : encoded;
|
|
544
|
-
try {
|
|
545
|
-
const padded = payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(payload.length / 4) * 4, "=");
|
|
546
|
-
return Buffer.from(padded, "base64").toString("utf8");
|
|
547
|
-
} catch {
|
|
548
|
-
return void 0;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
async function fetchWithTimeout(url, signal, timeoutMs) {
|
|
552
|
-
const controller = new AbortController();
|
|
553
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
554
|
-
const fetchSignal = anySignal(signal, controller.signal);
|
|
555
|
-
try {
|
|
556
|
-
const res = await guardedFetch(url, 5, fetchSignal, {
|
|
557
|
-
"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"
|
|
558
|
-
});
|
|
559
|
-
clearTimeout(timer);
|
|
560
|
-
return res;
|
|
561
|
-
} catch (e) {
|
|
562
|
-
clearTimeout(timer);
|
|
563
|
-
if (e instanceof FetchError2) {
|
|
564
|
-
throw e;
|
|
565
|
-
}
|
|
566
|
-
throw new FetchError2({
|
|
567
|
-
message: `search: failed to fetch ${url}`,
|
|
568
|
-
status: 0,
|
|
569
|
-
context: { url },
|
|
570
|
-
cause: e
|
|
571
|
-
});
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
function anySignal(...signals) {
|
|
575
|
-
return AbortSignal.any(signals);
|
|
576
|
-
}
|
|
577
|
-
function stripTags(html) {
|
|
578
|
-
return decodeHtmlEntities(html.replace(/<[^>]+>/g, "")).trim();
|
|
579
|
-
}
|
|
580
|
-
function capSnippet(snippet) {
|
|
581
|
-
return snippet.length > MAX_SNIPPET_CHARS ? `${snippet.slice(0, MAX_SNIPPET_CHARS - 1)}\u2026` : snippet;
|
|
582
|
-
}
|
|
583
|
-
function decodeHtmlEntities(text) {
|
|
584
|
-
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
|
|
585
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
__clearSearchCache,
|
|
3
|
+
searchTool
|
|
4
|
+
} from "./chunk-4I4LWFOO.js";
|
|
5
|
+
import "./chunk-NBDZMMG2.js";
|
|
586
6
|
export {
|
|
587
7
|
__clearSearchCache,
|
|
588
8
|
searchTool
|