min-agent 0.2.0 → 0.3.0

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 (81) hide show
  1. package/README.md +146 -18
  2. package/dist/agent.js +293 -408
  3. package/dist/assistant-stream.js +11 -7
  4. package/dist/cli.js +403 -140
  5. package/dist/clipboard.js +59 -23
  6. package/dist/code-mode.js +3 -3
  7. package/dist/compaction.js +182 -81
  8. package/dist/config.js +186 -35
  9. package/dist/confirm.js +55 -6
  10. package/dist/context-window.js +67 -54
  11. package/dist/doom-loop.js +19 -12
  12. package/dist/http.js +119 -0
  13. package/dist/instructions.js +51 -33
  14. package/dist/logger.js +66 -0
  15. package/dist/markdown.js +3 -44
  16. package/dist/mcp.js +547 -100
  17. package/dist/memory.js +48 -6
  18. package/dist/output.js +36 -27
  19. package/dist/paste-handler.js +3 -3
  20. package/dist/plugins.js +33 -6
  21. package/dist/pricing.js +119 -0
  22. package/dist/provider.js +17 -15
  23. package/dist/serve.js +658 -369
  24. package/dist/sessions.js +151 -13
  25. package/dist/skills.js +466 -76
  26. package/dist/synthetic.js +7 -0
  27. package/dist/title-gen.js +2 -1
  28. package/dist/tool-display.js +173 -0
  29. package/dist/tool-output.js +54 -45
  30. package/dist/tools/apply_patch.js +191 -0
  31. package/dist/tools/backend.js +61 -0
  32. package/dist/tools/bash.js +147 -70
  33. package/dist/tools/code_search.js +6 -5
  34. package/dist/tools/edit.js +23 -7
  35. package/dist/tools/explore.js +80 -12
  36. package/dist/tools/glob.js +3 -3
  37. package/dist/tools/grep.js +146 -14
  38. package/dist/tools/index.js +7 -7
  39. package/dist/tools/question.js +4 -22
  40. package/dist/tools/read.js +71 -11
  41. package/dist/tools/task.js +33 -20
  42. package/dist/tools/todo.js +83 -73
  43. package/dist/tools/web_fetch.js +150 -46
  44. package/dist/tools/web_search.js +706 -28
  45. package/dist/tools/write.js +13 -7
  46. package/dist/tui/App.js +40 -6
  47. package/dist/tui/ConfirmBar.js +24 -3
  48. package/dist/tui/InputBar.js +390 -45
  49. package/dist/tui/MessageList.js +533 -20
  50. package/dist/tui/ModelPicker.js +108 -0
  51. package/dist/tui/QuestionBar.js +104 -0
  52. package/dist/tui/StatusBar.js +19 -11
  53. package/dist/tui/agent-runner.js +103 -0
  54. package/dist/tui/caret-pos.js +134 -0
  55. package/dist/tui/caret.js +69 -0
  56. package/dist/tui/diff-view.js +61 -0
  57. package/dist/tui/drag-state.js +44 -0
  58. package/dist/tui/index.js +153 -24
  59. package/dist/tui/input-history.js +44 -0
  60. package/dist/tui/layout.js +17 -0
  61. package/dist/tui/mouse.js +46 -0
  62. package/dist/tui/selection.js +134 -0
  63. package/dist/tui/slash-commands.js +90 -0
  64. package/dist/tui/slash-handler.js +370 -0
  65. package/dist/tui/text-width.js +91 -0
  66. package/dist/tui/theme.js +12 -0
  67. package/dist/tui/undo-stack.js +14 -0
  68. package/dist/tui/use-sgr-mouse.js +27 -0
  69. package/dist/tui-chat.js +111 -331
  70. package/dist/updater.js +57 -0
  71. package/docs/API.md +160 -14
  72. package/docs/superpowers/plans/2026-08-16-batch1-tui-improvements.md +1510 -0
  73. package/docs/superpowers/plans/2026-08-16-batch2-cli-tools-api.md +2105 -0
  74. package/docs/superpowers/plans/2026-08-16-batch3-config-engineering.md +1595 -0
  75. package/docs/superpowers/plans/2026-08-16-input-caret.md +782 -0
  76. package/docs/superpowers/specs/2026-08-16-batch1-tui-improvements-design.md +183 -0
  77. package/docs/superpowers/specs/2026-08-16-batch2-cli-tools-api-design.md +220 -0
  78. package/docs/superpowers/specs/2026-08-16-batch3-config-engineering-design.md +196 -0
  79. package/docs/superpowers/specs/2026-08-16-input-caret-design.md +63 -0
  80. package/docs/superpowers/specs/2026-08-17-mouse-selection-design.md +116 -0
  81. package/package.json +7 -8
@@ -1,40 +1,718 @@
1
1
  import { tool, jsonSchema } from "ai";
2
2
  import { truncateToolOutput } from "../tool-output.js";
3
- const SEARXNG_BASE = "https://searxng.xc.lonae.com";
3
+ import { readBodyLimited } from "../http.js";
4
+ import { loadConfig } from "../config.js";
5
+ import { configHint, describeFetchError, resolveBackendBase } from "./backend.js";
6
+ /** Built-in Serper key; override via config or the env var below. */
7
+ const DEFAULT_SERPER_API_KEY = "7913c19ae7a80320771b843ddffa152c9162c9f2";
8
+ const SERPER_KEY_ENV = "MIN_AGENT_SERPER_API_KEY";
9
+ const SERPER_API = "https://google.serper.dev/search";
10
+ /** SearXNG is used when explicitly configured (webSearchURL / MIN_AGENT_SEARXNG_URL). */
11
+ export const SEARXNG_BACKEND = {
12
+ envName: "MIN_AGENT_SEARXNG_URL",
13
+ configKey: "webSearchURL",
14
+ fallback: "https://searxng.xc.lonae.com",
15
+ };
16
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
17
+ const SERPER_TIMEOUT_MS = 35000;
18
+ const SEARCH_TIMEOUT_MS = 20000;
19
+ const DEFAULT_MAX_RESULTS = 10;
20
+ const MAX_RESULTS_LIMIT = 30;
21
+ const SNIPPET_MAX_CHARS = 300;
22
+ const DEFAULT_FALLBACK_ENGINES = "google,bing";
23
+ /** SearXNG's built-in category names. */
24
+ const VALID_CATEGORIES = new Set([
25
+ "general",
26
+ "images",
27
+ "videos",
28
+ "news",
29
+ "map",
30
+ "music",
31
+ "it",
32
+ "science",
33
+ "files",
34
+ "social media",
35
+ ]);
36
+ /** Common near-misses models produce, mapped onto real category names. */
37
+ const CATEGORY_ALIASES = {
38
+ web: "general",
39
+ text: "general",
40
+ default: "general",
41
+ image: "images",
42
+ picture: "images",
43
+ pictures: "images",
44
+ photo: "images",
45
+ photos: "images",
46
+ video: "videos",
47
+ movie: "videos",
48
+ movies: "videos",
49
+ maps: "map",
50
+ social: "social media",
51
+ socialmedia: "social media",
52
+ social_media: "social media",
53
+ "social-media": "social media",
54
+ tech: "it",
55
+ technology: "it",
56
+ code: "it",
57
+ programming: "it",
58
+ file: "files",
59
+ torrent: "files",
60
+ torrents: "files",
61
+ paper: "science",
62
+ papers: "science",
63
+ academic: "science",
64
+ scholar: "science",
65
+ };
66
+ const VALID_TIME_RANGES = new Set(["day", "week", "month", "year"]);
67
+ /** Google's tbs time filter for each supported time_range value. */
68
+ const TBS_BY_RANGE = {
69
+ day: "qdr:d",
70
+ week: "qdr:w",
71
+ month: "qdr:m",
72
+ year: "qdr:y",
73
+ };
74
+ /** ISO 639-1/2 with an optional region subtag, or SearXNG's "all". */
75
+ const LANGUAGE_RE = /^(all|[a-z]{2,3}([-_][a-zA-Z]{2,4})?)$/;
76
+ const EXACT_TRACKING_PARAMS = new Set([
77
+ "ref",
78
+ "ref_src",
79
+ "referrer",
80
+ "fbclid",
81
+ "gclid",
82
+ "msclkid",
83
+ "igshid",
84
+ "mc_cid",
85
+ "mc_eid",
86
+ "spm",
87
+ "source",
88
+ ]);
89
+ const emptyResponse = () => ({
90
+ results: [],
91
+ answers: [],
92
+ suggestions: [],
93
+ corrections: [],
94
+ infoboxes: [],
95
+ unresponsive_engines: [],
96
+ });
97
+ function isString(v) {
98
+ return typeof v === "string";
99
+ }
100
+ function asResult(r) {
101
+ if (typeof r !== "object" || r === null)
102
+ return null;
103
+ const o = r;
104
+ if (!isString(o.url))
105
+ return null;
106
+ return {
107
+ title: isString(o.title) ? o.title : "",
108
+ url: o.url,
109
+ content: isString(o.content) ? o.content : "",
110
+ engine: isString(o.engine) ? o.engine : "",
111
+ score: typeof o.score === "number" ? o.score : 0,
112
+ publishedDate: isString(o.publishedDate) ? o.publishedDate : "",
113
+ imgSrc: isString(o.img_src) ? o.img_src : isString(o.thumbnail) ? o.thumbnail : "",
114
+ };
115
+ }
116
+ function parseResponse(data) {
117
+ if (typeof data !== "object" || data === null)
118
+ return emptyResponse();
119
+ const o = data;
120
+ const results = (Array.isArray(o.results) ? o.results : [])
121
+ .map(asResult)
122
+ .filter((r) => r !== null);
123
+ // Some engines return answers as objects ({ answer, url }) rather than plain strings.
124
+ const answers = (Array.isArray(o.answers) ? o.answers : [])
125
+ .map((a) => {
126
+ if (isString(a))
127
+ return a;
128
+ if (typeof a === "object" && a !== null) {
129
+ const rec = a;
130
+ if (isString(rec.answer))
131
+ return rec.answer;
132
+ if (isString(rec.content))
133
+ return rec.content;
134
+ }
135
+ return "";
136
+ })
137
+ .filter((a) => a !== "");
138
+ const suggestions = Array.isArray(o.suggestions) ? o.suggestions.filter(isString) : [];
139
+ const corrections = Array.isArray(o.corrections) ? o.corrections.filter(isString) : [];
140
+ const infoboxes = (Array.isArray(o.infoboxes) ? o.infoboxes : [])
141
+ .map((b) => {
142
+ if (typeof b !== "object" || b === null)
143
+ return null;
144
+ const box = b;
145
+ return {
146
+ infobox: isString(box.infobox) ? box.infobox : "",
147
+ content: isString(box.content) ? box.content : "",
148
+ };
149
+ })
150
+ .filter((b) => b !== null && (b.infobox !== "" || b.content !== ""));
151
+ const unresponsive = (Array.isArray(o.unresponsive_engines) ? o.unresponsive_engines : [])
152
+ .map((e) => {
153
+ if (!Array.isArray(e) || !isString(e[0]))
154
+ return null;
155
+ return [e[0], isString(e[1]) ? e[1] : ""];
156
+ })
157
+ .filter((e) => e !== null);
158
+ return { results, answers, suggestions, corrections, infoboxes, unresponsive_engines: unresponsive };
159
+ }
160
+ /** SearXNG reports parameter problems as {"error": "..."} — sometimes with HTTP 200. */
161
+ function backendErrorMessage(data) {
162
+ if (typeof data !== "object" || data === null)
163
+ return "";
164
+ const o = data;
165
+ for (const key of ["error", "detail", "message"]) {
166
+ const v = o[key];
167
+ if (isString(v) && v.trim())
168
+ return collapse(v);
169
+ if (typeof v === "object" && v !== null) {
170
+ const nested = v.message;
171
+ if (isString(nested) && nested.trim())
172
+ return collapse(nested);
173
+ }
174
+ }
175
+ return "";
176
+ }
177
+ function serperKey() {
178
+ const env = process.env[SERPER_KEY_ENV];
179
+ if (env && env.trim())
180
+ return env.trim();
181
+ const configured = loadConfig().serperApiKey;
182
+ if (configured && configured.trim())
183
+ return configured.trim();
184
+ return DEFAULT_SERPER_API_KEY;
185
+ }
186
+ /** True when the built-in shared key is in use (no env var, no config key). */
187
+ function usingBuiltInSerperKey() {
188
+ const env = process.env[SERPER_KEY_ENV];
189
+ if (env && env.trim())
190
+ return false;
191
+ const configured = loadConfig().serperApiKey;
192
+ return !(configured && configured.trim());
193
+ }
194
+ function serperHint() {
195
+ return `Override the built-in key via "serperApiKey" in ~/.min-agent/config.json or the ${SERPER_KEY_ENV} env var.`;
196
+ }
197
+ function asSerperResult(r) {
198
+ if (typeof r !== "object" || r === null)
199
+ return null;
200
+ const o = r;
201
+ if (!isString(o.link) || o.link.trim() === "")
202
+ return null;
203
+ return {
204
+ title: isString(o.title) ? o.title : "",
205
+ url: o.link,
206
+ content: isString(o.snippet) ? o.snippet : "",
207
+ engine: hostOf(o.link),
208
+ score: 0,
209
+ publishedDate: isString(o.date) ? o.date : "",
210
+ imgSrc: "",
211
+ };
212
+ }
213
+ function emptySerper() {
214
+ return { ...emptyResponse(), questions: [] };
215
+ }
216
+ function stringList(v, key) {
217
+ return (Array.isArray(v) ? v : [])
218
+ .map((item) => {
219
+ if (typeof item === "object" && item !== null) {
220
+ const rec = item;
221
+ if (isString(rec[key]))
222
+ return rec[key];
223
+ }
224
+ return "";
225
+ })
226
+ .filter((s) => s.trim() !== "");
227
+ }
228
+ function parseSerper(data) {
229
+ if (typeof data !== "object" || data === null)
230
+ return emptySerper();
231
+ const o = data;
232
+ const results = (Array.isArray(o.organic) ? o.organic : [])
233
+ .map(asSerperResult)
234
+ .filter((r) => r !== null);
235
+ const answers = [];
236
+ const ab = o.answerBox;
237
+ if (typeof ab === "object" && ab !== null) {
238
+ const rec = ab;
239
+ for (const key of ["answer", "snippet", "title"]) {
240
+ if (isString(rec[key]) && rec[key].trim()) {
241
+ answers.push(collapse(rec[key]));
242
+ break;
243
+ }
244
+ }
245
+ }
246
+ const suggestions = stringList(o.relatedSearches, "query");
247
+ const questions = stringList(o.peopleAlsoAsk, "question");
248
+ const infoboxes = [];
249
+ const kg = o.knowledgeGraph;
250
+ if (typeof kg === "object" && kg !== null) {
251
+ const rec = kg;
252
+ const title = isString(rec.title) ? rec.title : "";
253
+ const description = isString(rec.description) ? rec.description : "";
254
+ if (title || description)
255
+ infoboxes.push({ infobox: title, content: description });
256
+ }
257
+ return { results, answers, suggestions, corrections: [], infoboxes, unresponsive_engines: [], questions };
258
+ }
259
+ /** Serper reports problems as {"message": "...", "statusCode": N}. */
260
+ function serperErrorMessage(data) {
261
+ return backendErrorMessage(data);
262
+ }
263
+ async function serperSearch(payload) {
264
+ let response;
265
+ try {
266
+ response = await fetch(SERPER_API, {
267
+ method: "POST",
268
+ headers: {
269
+ "X-API-KEY": serperKey(),
270
+ "Content-Type": "application/json",
271
+ Accept: "application/json",
272
+ },
273
+ body: JSON.stringify(payload),
274
+ signal: AbortSignal.timeout(SERPER_TIMEOUT_MS),
275
+ });
276
+ }
277
+ catch (err) {
278
+ return { kind: "network", message: describeFetchError(err) };
279
+ }
280
+ let text;
281
+ let bodyTooLarge;
282
+ try {
283
+ const body = await readBodyLimited(response, MAX_BODY_BYTES);
284
+ text = body.text;
285
+ bodyTooLarge = body.truncated;
286
+ }
287
+ catch (err) {
288
+ return { kind: "network", message: describeFetchError(err) };
289
+ }
290
+ let parsed;
291
+ let parseFailed = false;
292
+ try {
293
+ parsed = JSON.parse(text);
294
+ }
295
+ catch {
296
+ parseFailed = true;
297
+ }
298
+ const backendMessage = parseFailed ? "" : serperErrorMessage(parsed);
299
+ if (!response.ok)
300
+ return { kind: "http", status: response.status, backendMessage };
301
+ if (parseFailed) {
302
+ return { kind: "invalid-json", bodyTooLarge, sample: clamp(collapse(text), 100) };
303
+ }
304
+ if (bodyTooLarge)
305
+ return { kind: "invalid-json", bodyTooLarge: true, sample: "" };
306
+ if (backendMessage)
307
+ return { kind: "http", status: response.status, backendMessage };
308
+ return { kind: "ok", data: parseSerper(parsed) };
309
+ }
310
+ function renderSerperFailure(o) {
311
+ const hint = serperHint();
312
+ switch (o.kind) {
313
+ case "network":
314
+ return `Search error: could not reach the Serper search API (${o.message}). This is not a problem with the query.`;
315
+ case "invalid-json":
316
+ if (o.bodyTooLarge) {
317
+ return `Search error: the search API response exceeded ${MAX_BODY_BYTES / 1024 / 1024} MB and could not be parsed. Narrow the query or request fewer results.`;
318
+ }
319
+ return `Search error: the search API returned a non-JSON response${o.sample ? ` (starts with: ${o.sample})` : ""}.`;
320
+ case "http": {
321
+ const detail = o.backendMessage ? ` Backend message: ${o.backendMessage}.` : "";
322
+ if (o.status === 429) {
323
+ return `Search error: the search API is rate-limiting (HTTP 429).${detail} Wait a few seconds before retrying.`;
324
+ }
325
+ if (o.status === 401 || o.status === 403) {
326
+ if (usingBuiltInSerperKey()) {
327
+ return `Search error: the built-in shared Serper key was rejected (HTTP ${o.status}).${detail} The shared key's quota is likely exhausted. Set your own key via "${SERPER_KEY_ENV}" or "serperApiKey" in ~/.min-agent/config.json, or configure your own SearXNG instance via "webSearchURL".`;
328
+ }
329
+ return `Search error: the search API rejected the API key (HTTP ${o.status}).${detail} ${hint}`;
330
+ }
331
+ if (o.status === 400 || o.status === 422) {
332
+ return `Search error: the search API rejected these parameters (HTTP ${o.status}).${detail} Fix the arguments and retry; retrying with the same values will fail again.`;
333
+ }
334
+ if (o.status >= 500) {
335
+ return `Search error: the search API failed with HTTP ${o.status}.${detail} It may be temporarily overloaded — retry once.`;
336
+ }
337
+ return `Search error: HTTP ${o.status} from the search API.${detail}`;
338
+ }
339
+ }
340
+ }
341
+ function buildSerperPayload(input, notes, maxResults) {
342
+ const payload = { q: input.query, num: maxResults };
343
+ const lang = (input.language ?? "").trim().toLowerCase();
344
+ if (lang) {
345
+ if (LANGUAGE_RE.test(lang) && lang !== "all") {
346
+ payload.hl = lang.replace("_", "-");
347
+ }
348
+ else {
349
+ notes.push(`ignored invalid language "${input.language}"; use a code like "zh", "en" or "zh-CN"`);
350
+ }
351
+ }
352
+ const range = (input.time_range ?? "").trim().toLowerCase();
353
+ if (range) {
354
+ if (VALID_TIME_RANGES.has(range))
355
+ payload.tbs = TBS_BY_RANGE[range];
356
+ else
357
+ notes.push(`ignored invalid time_range "${range}"; valid values: day, week, month, year`);
358
+ }
359
+ return payload;
360
+ }
361
+ function searxngConfigured() {
362
+ const env = process.env[SEARXNG_BACKEND.envName];
363
+ if (env && env.trim())
364
+ return true;
365
+ const configured = loadConfig().webSearchURL;
366
+ return !!(configured && configured.trim());
367
+ }
368
+ // --- SearXNG (legacy, only when explicitly configured) ---
369
+ function collapse(s) {
370
+ return s.replace(/\s+/g, " ").trim();
371
+ }
372
+ function clamp(s, max) {
373
+ const chars = Array.from(s);
374
+ if (chars.length <= max)
375
+ return s;
376
+ return chars.slice(0, max - 1).join("") + "…";
377
+ }
378
+ function hostOf(url) {
379
+ try {
380
+ return new URL(url).hostname.replace(/^www\./, "");
381
+ }
382
+ catch {
383
+ return url;
384
+ }
385
+ }
386
+ /** Normalize a published date to YYYY-MM-DD; pass unparseable values through. */
387
+ function formatPublished(raw) {
388
+ if (!raw)
389
+ return "";
390
+ const ms = Date.parse(raw);
391
+ if (Number.isNaN(ms))
392
+ return collapse(raw);
393
+ return new Date(ms).toISOString().slice(0, 10);
394
+ }
395
+ /**
396
+ * Identity key for deduplication: scheme, "www.", trailing slash, fragment and
397
+ * tracking parameters all describe the same page.
398
+ */
399
+ export function dedupeKey(raw) {
400
+ try {
401
+ const u = new URL(raw);
402
+ const host = u.hostname.toLowerCase().replace(/^www\./, "");
403
+ const path = u.pathname.replace(/\/+$/, "");
404
+ const params = [...u.searchParams].filter(([k]) => !k.toLowerCase().startsWith("utm_") && !EXACT_TRACKING_PARAMS.has(k.toLowerCase()));
405
+ params.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
406
+ const query = params.map(([k, v]) => `${k}=${v}`).join("&");
407
+ return `${host}${path}${query ? `?${query}` : ""}`;
408
+ }
409
+ catch {
410
+ return raw.trim().toLowerCase();
411
+ }
412
+ }
413
+ function dedupeByUrl(results) {
414
+ const seen = new Set();
415
+ return results.filter((r) => {
416
+ const key = dedupeKey(r.url);
417
+ if (seen.has(key))
418
+ return false;
419
+ seen.add(key);
420
+ return true;
421
+ });
422
+ }
423
+ /**
424
+ * One block per result:
425
+ * 1. Title
426
+ * https://url
427
+ * [2026-08-18 · google]
428
+ * snippet on a single line
429
+ * Snippets are whitespace-collapsed and clamped so the indented block
430
+ * structure survives multi-line engine output.
431
+ */
432
+ function formatResults(results, withImages) {
433
+ return results
434
+ .map((r, i) => {
435
+ const lines = [`${i + 1}. ${collapse(r.title) || hostOf(r.url)}`, ` ${r.url}`];
436
+ const meta = [];
437
+ const date = formatPublished(r.publishedDate);
438
+ if (date)
439
+ meta.push(date);
440
+ if (r.engine)
441
+ meta.push(r.engine);
442
+ if (meta.length > 0)
443
+ lines.push(` [${meta.join(" · ")}]`);
444
+ const snippet = clamp(collapse(r.content), SNIPPET_MAX_CHARS);
445
+ if (snippet)
446
+ lines.push(` ${snippet}`);
447
+ // Image results usually carry an empty title/content; the asset URL is
448
+ // the only useful payload, so surface it for image searches.
449
+ if (withImages && r.imgSrc)
450
+ lines.push(` image: ${r.imgSrc}`);
451
+ return lines.join("\n");
452
+ })
453
+ .join("\n\n");
454
+ }
455
+ /**
456
+ * SearXNG reports the instance-wide unresponsive list regardless of which
457
+ * engines a request used, so narrow it to the requested set when there is one
458
+ * and say so otherwise.
459
+ */
460
+ function unresponsiveHint(engines, requested) {
461
+ let relevant = engines;
462
+ if (requested && requested.length > 0) {
463
+ const wanted = new Set(requested.map((e) => e.toLowerCase()));
464
+ relevant = engines.filter(([name]) => wanted.has(name.toLowerCase()));
465
+ }
466
+ if (relevant.length === 0)
467
+ return "";
468
+ const detail = relevant.map(([name, reason]) => (reason ? `${name} (${reason})` : name)).join(", ");
469
+ const scope = requested
470
+ ? "The requested engines are unavailable"
471
+ : "The backend reports these engines as unavailable (instance-wide list, may include engines this query did not use)";
472
+ return `${scope}: ${detail}. Try a different query, or pass "engines" explicitly (e.g. "google,bing").`;
473
+ }
474
+ async function searchOnce(base, params) {
475
+ let response;
476
+ try {
477
+ response = await fetch(`${base}/search?${params}`, {
478
+ headers: { Accept: "application/json" },
479
+ signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
480
+ });
481
+ }
482
+ catch (err) {
483
+ return { kind: "network", message: describeFetchError(err) };
484
+ }
485
+ let text;
486
+ let bodyTooLarge;
487
+ try {
488
+ const body = await readBodyLimited(response, MAX_BODY_BYTES);
489
+ text = body.text;
490
+ bodyTooLarge = body.truncated;
491
+ }
492
+ catch (err) {
493
+ return { kind: "network", message: describeFetchError(err) };
494
+ }
495
+ let parsed;
496
+ let parseFailed = false;
497
+ try {
498
+ parsed = JSON.parse(text);
499
+ }
500
+ catch {
501
+ parseFailed = true;
502
+ }
503
+ // Error bodies are valid JSON even on a 4xx, so parse before branching on the
504
+ // status; that way the backend's own message reaches the caller.
505
+ const backendMessage = parseFailed ? "" : backendErrorMessage(parsed);
506
+ if (!response.ok)
507
+ return { kind: "http", status: response.status, backendMessage };
508
+ if (parseFailed) {
509
+ return { kind: "invalid-json", bodyTooLarge, sample: clamp(collapse(text), 100) };
510
+ }
511
+ // A truncated body that still parsed would be missing results silently.
512
+ if (bodyTooLarge)
513
+ return { kind: "invalid-json", bodyTooLarge: true, sample: "" };
514
+ if (backendMessage)
515
+ return { kind: "http", status: response.status, backendMessage };
516
+ return { kind: "ok", data: parseResponse(parsed) };
517
+ }
518
+ function renderFailure(o) {
519
+ const hint = configHint(SEARXNG_BACKEND);
520
+ switch (o.kind) {
521
+ case "network":
522
+ return `Search error: could not reach the search backend (${o.message}). The instance may be down or the network may be unavailable — this is not a problem with the query. ${hint}`;
523
+ case "invalid-json":
524
+ if (o.bodyTooLarge) {
525
+ return `Search error: the search backend response exceeded ${MAX_BODY_BYTES / 1024 / 1024} MB and could not be parsed. Narrow the query or request fewer engines.`;
526
+ }
527
+ return `Search error: the search backend returned a non-JSON response${o.sample ? ` (starts with: ${o.sample})` : ""}. The instance most likely has the JSON output format disabled. ${hint}`;
528
+ case "http": {
529
+ const detail = o.backendMessage ? ` Backend message: ${o.backendMessage}.` : "";
530
+ if (o.status === 429) {
531
+ return `Search error: the search backend is rate-limiting (HTTP 429).${detail} Wait a few seconds before retrying, or use a different instance. ${hint}`;
532
+ }
533
+ if (o.status === 401 || o.status === 403) {
534
+ return `Search error: the search backend rejected the request (HTTP ${o.status}).${detail} The instance likely requires authentication or has the JSON output format disabled. ${hint}`;
535
+ }
536
+ if (o.status === 400 || o.status === 422) {
537
+ return `Search error: the search backend rejected these parameters (HTTP ${o.status}).${detail} Fix the arguments and retry; retrying with the same values will fail again.`;
538
+ }
539
+ if (o.status >= 500) {
540
+ return `Search error: the search backend failed with HTTP ${o.status}.${detail} It may be temporarily overloaded — retry once, then try a different instance. ${hint}`;
541
+ }
542
+ return `Search error: HTTP ${o.status} from the search backend.${detail} ${hint}`;
543
+ }
544
+ }
545
+ }
546
+ function fallbackEngines() {
547
+ const env = process.env.MIN_AGENT_SEARXNG_FALLBACK_ENGINES;
548
+ if (env !== undefined)
549
+ return env.trim();
550
+ const configured = loadConfig().webSearchFallbackEngines;
551
+ if (configured !== undefined)
552
+ return configured.trim();
553
+ return DEFAULT_FALLBACK_ENGINES;
554
+ }
555
+ /** Validate/normalize the model-supplied arguments, collecting notes for anything ignored. */
556
+ function buildParams(input, notes) {
557
+ const params = new URLSearchParams({ q: input.query, format: "json", categories: "general" });
558
+ const lang = (input.language ?? "").trim();
559
+ if (lang) {
560
+ if (LANGUAGE_RE.test(lang))
561
+ params.set("language", lang.replace("_", "-"));
562
+ else
563
+ notes.push(`ignored invalid language "${lang}"; use a code like "zh", "en" or "zh-CN"`);
564
+ }
565
+ const range = (input.time_range ?? "").trim().toLowerCase();
566
+ if (range) {
567
+ if (VALID_TIME_RANGES.has(range))
568
+ params.set("time_range", range);
569
+ else
570
+ notes.push(`ignored invalid time_range "${range}"; valid values: day, week, month, year`);
571
+ }
572
+ return { params, requested: null, wantsImages: false };
573
+ }
574
+ function resolveMaxResults(raw, notes) {
575
+ if (raw === undefined)
576
+ return DEFAULT_MAX_RESULTS;
577
+ const n = Math.floor(Number(raw));
578
+ if (!Number.isFinite(n) || n < 1) {
579
+ notes.push(`ignored invalid max_results "${raw}"; using ${DEFAULT_MAX_RESULTS}`);
580
+ return DEFAULT_MAX_RESULTS;
581
+ }
582
+ if (n > MAX_RESULTS_LIMIT) {
583
+ notes.push(`max_results capped at ${MAX_RESULTS_LIMIT}`);
584
+ return MAX_RESULTS_LIMIT;
585
+ }
586
+ return n;
587
+ }
588
+ async function runSearxng(input, query, notes) {
589
+ const resolved = resolveBackendBase(SEARXNG_BACKEND, loadConfig().webSearchURL);
590
+ if (!resolved.ok)
591
+ return `Search error: ${resolved.error}. ${configHint(SEARXNG_BACKEND)}`;
592
+ const maxResults = resolveMaxResults(input.max_results, notes);
593
+ const { params, requested } = buildParams({ ...input, query }, notes);
594
+ let outcome = await searchOnce(resolved.base, params);
595
+ // The default engine set on a given instance can be entirely blocked
596
+ // (CAPTCHA / rate limits), which looks identical to "no such page exists".
597
+ // A single retry against known-good engines distinguishes the two. The
598
+ // unresponsive list is instance-wide and therefore not a reliable trigger.
599
+ let usedFallback = null;
600
+ if (outcome.kind === "ok" && outcome.data.results.length === 0 && !requested) {
601
+ const fallback = fallbackEngines();
602
+ if (fallback) {
603
+ const retryParams = new URLSearchParams(params);
604
+ retryParams.set("engines", fallback);
605
+ const retry = await searchOnce(resolved.base, retryParams);
606
+ if (retry.kind === "ok" && retry.data.results.length > 0) {
607
+ outcome = retry;
608
+ usedFallback = fallback;
609
+ }
610
+ else if (retry.kind !== "ok") {
611
+ notes.push(`the fallback engines (${fallback}) also failed: ${renderFailure(retry).replace(/^Search error: /, "")}`);
612
+ }
613
+ }
614
+ }
615
+ if (outcome.kind !== "ok")
616
+ return renderFailure(outcome);
617
+ const data = outcome.data;
618
+ const results = dedupeByUrl(data.results).slice(0, maxResults);
619
+ const noteBlock = notes.map((n) => `Note: ${n}`).join("\n");
620
+ if (results.length === 0) {
621
+ const parts = [`No search results found for "${query}".`];
622
+ if (noteBlock)
623
+ parts.push(noteBlock);
624
+ const hint = unresponsiveHint(data.unresponsive_engines, usedFallback ? usedFallback.split(",") : requested);
625
+ if (hint)
626
+ parts.push(hint);
627
+ if (data.corrections.length > 0)
628
+ parts.push(`Did you mean: ${data.corrections.join(", ")}`);
629
+ if (data.suggestions.length > 0)
630
+ parts.push(`Related queries: ${data.suggestions.slice(0, 8).join(", ")}`);
631
+ if (!hint && data.corrections.length === 0 && data.suggestions.length === 0) {
632
+ parts.push("Try a different query or a broader wording.");
633
+ }
634
+ return parts.join("\n\n");
635
+ }
636
+ // Direct answers and infoboxes carry the highest information density, so
637
+ // they precede the result list.
638
+ const sections = [];
639
+ if (noteBlock)
640
+ sections.push(noteBlock);
641
+ for (const a of data.answers)
642
+ sections.push(`Answer: ${collapse(a)}`);
643
+ for (const b of data.infoboxes) {
644
+ sections.push(`Infobox${b.infobox ? ` (${collapse(b.infobox)})` : ""}: ${clamp(collapse(b.content), 600)}`);
645
+ }
646
+ sections.push(`Found ${results.length} result${results.length === 1 ? "" : "s"} for "${query}"${usedFallback ? ` via fallback engines ${usedFallback}` : ""}:`);
647
+ sections.push(formatResults(results, false));
648
+ if (data.corrections.length > 0)
649
+ sections.push(`Did you mean: ${data.corrections.join(", ")}`);
650
+ if (data.suggestions.length > 0)
651
+ sections.push(`Related queries: ${data.suggestions.slice(0, 8).join(", ")}`);
652
+ return truncateToolOutput(sections.join("\n\n"), { direction: "head" }).content;
653
+ }
654
+ async function runSerper(input, query, notes) {
655
+ const maxResults = resolveMaxResults(input.max_results, notes);
656
+ const payload = buildSerperPayload(input, notes, maxResults);
657
+ const outcome = await serperSearch(payload);
658
+ if (outcome.kind !== "ok")
659
+ return renderSerperFailure(outcome);
660
+ const data = outcome.data;
661
+ const results = dedupeByUrl(data.results).slice(0, maxResults);
662
+ const noteBlock = notes.map((n) => `Note: ${n}`).join("\n");
663
+ if (results.length === 0) {
664
+ const parts = [`No search results found for "${query}".`];
665
+ if (noteBlock)
666
+ parts.push(noteBlock);
667
+ if (data.questions.length > 0)
668
+ parts.push(`Related questions: ${data.questions.slice(0, 5).join(" · ")}`);
669
+ if (data.suggestions.length > 0)
670
+ parts.push(`Related searches: ${data.suggestions.slice(0, 8).join(" · ")}`);
671
+ if (data.questions.length === 0 && data.suggestions.length === 0) {
672
+ parts.push("Try a different query or a broader wording.");
673
+ }
674
+ return parts.join("\n\n");
675
+ }
676
+ const sections = [];
677
+ if (noteBlock)
678
+ sections.push(noteBlock);
679
+ for (const a of data.answers)
680
+ sections.push(`Answer: ${collapse(a)}`);
681
+ for (const b of data.infoboxes) {
682
+ sections.push(`Infobox${b.infobox ? ` (${collapse(b.infobox)})` : ""}: ${clamp(collapse(b.content), 600)}`);
683
+ }
684
+ sections.push(`Found ${results.length} result${results.length === 1 ? "" : "s"} for "${query}":`);
685
+ sections.push(formatResults(results, false));
686
+ if (data.questions.length > 0)
687
+ sections.push(`Related questions: ${data.questions.slice(0, 5).join(" · ")}`);
688
+ if (data.suggestions.length > 0)
689
+ sections.push(`Related searches: ${data.suggestions.slice(0, 8).join(" · ")}`);
690
+ return truncateToolOutput(sections.join("\n\n"), { direction: "head" }).content;
691
+ }
4
692
  export const webSearchTool = tool({
5
- description: "Search the web for information. Returns search results with titles, URLs, and snippets. Use this when you need current information, news, documentation, or answers that require up-to-date knowledge.",
693
+ description: `Search the web via Google. Returns ranked results with title, URL, source and a snippet. Use this for current information, news, documentation, or anything needing up-to-date knowledge. Today's date: ${new Date().toISOString().slice(0, 10)}. When the user asks about the latest or newest state of something, use the current year in the query or set time_range (day, week, month, year) — do not append an older year from your training knowledge.`,
6
694
  inputSchema: jsonSchema({
7
695
  type: "object",
8
696
  properties: {
9
697
  query: { type: "string", description: "The search query" },
10
- categories: { type: "string", description: "Search categories: general, news, images, science, it (default: general)" },
698
+ language: { type: "string", description: "Search language code, e.g. zh, en, zh-CN (default: en)" },
699
+ time_range: { type: "string", description: "Time range filter: day, week, month, year" },
700
+ max_results: {
701
+ type: "number",
702
+ description: `Maximum number of results to return (default ${DEFAULT_MAX_RESULTS}, max ${MAX_RESULTS_LIMIT})`,
703
+ },
11
704
  },
12
705
  required: ["query"],
13
706
  }),
14
- execute: async ({ query, categories }) => {
15
- try {
16
- const params = new URLSearchParams({
17
- q: query,
18
- format: "json",
19
- categories: categories ?? "general",
20
- });
21
- const response = await fetch(`${SEARXNG_BASE}/search?${params}`, {
22
- headers: { "Accept": "application/json" },
23
- signal: AbortSignal.timeout(15000),
24
- });
25
- if (!response.ok)
26
- return `Search error: HTTP ${response.status}`;
27
- const data = await response.json();
28
- const results = (data.results ?? []).slice(0, 10);
29
- if (results.length === 0)
30
- return "No search results found. Try a different query.";
31
- const text = results
32
- .map((r, i) => `${i + 1}. ${r.title}\n ${r.url}\n ${r.content ?? ""}`)
33
- .join("\n\n");
34
- return truncateToolOutput(text, { direction: "head" }).content;
35
- }
36
- catch (err) {
37
- return `Search error: ${err.message}`;
38
- }
707
+ execute: async (input) => {
708
+ const query = (input.query ?? "").trim();
709
+ if (!query)
710
+ return 'Search error: "query" must be a non-empty string.';
711
+ const notes = [];
712
+ // SearXNG is only used when the user explicitly configures an instance;
713
+ // otherwise the built-in Serper key powers the default backend.
714
+ if (searxngConfigured())
715
+ return runSearxng(input, query, notes);
716
+ return runSerper(input, query, notes);
39
717
  },
40
718
  });