@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
package/dist/search.js CHANGED
@@ -1,588 +1,8 @@
1
- // src/search.ts
2
- import { FetchError as FetchError2, ToolValidationError as ToolValidationError2 } from "@wrongstack/core/types";
3
- import { expectDefined } from "@wrongstack/core/utils";
4
-
5
- // src/_fetch-guard.ts
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(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/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
@@ -1,6 +1,5 @@
1
1
  import type { Context, TodoItem } from '@wrongstack/core/agent';
2
2
  import { type PlanFile, type TaskFile } from '@wrongstack/core/storage';
3
- import type { TaskStatus } from '@wrongstack/core/types';
4
3
  import { type KanbanBoard, type KanbanTask } from '@wrongstack/kanban';
5
4
  export interface SessionKanbanSourceUpdate {
6
5
  source: 'todo' | 'task' | 'plan' | null;
@@ -8,15 +7,10 @@ export interface SessionKanbanSourceUpdate {
8
7
  tasks?: TaskFile | undefined;
9
8
  plan?: PlanFile | undefined;
10
9
  }
11
- export declare function sourceStatus(task: KanbanTask): TaskStatus;
12
10
  export declare function todoStatus(task: KanbanTask): TodoItem['status'];
13
- export declare function sessionTodoFromTask(task: KanbanTask, board?: KanbanBoard): TodoItem;
14
- export declare function managedTodoFromTask(task: KanbanTask, board: KanbanBoard): TodoItem;
15
11
  export declare function blockingTitles(board: KanbanBoard, task: KanbanTask): string[];
16
12
  export declare function orderTasksForTodos(board: KanbanBoard, tasks: readonly KanbanTask[]): KanbanTask[];
17
- export declare function sameTodos(left: readonly TodoItem[], right: readonly TodoItem[]): boolean;
18
13
  export declare function broadcastTodoUpdate(context: Context, todos: readonly TodoItem[]): void;
19
- export declare function notifyTodoUpdate(context: Context, todos: readonly TodoItem[]): void;
20
14
  export declare function todosNeedingSessionMirror(todos: readonly TodoItem[], activeBoardId: string | undefined): readonly TodoItem[];
21
15
  export declare function applySessionKanbanBoardToTodos(context: Context, board: KanbanBoard, options: {
22
16
  sessionIdFromTags: (tags: readonly string[] | undefined) => string | null;