dsh-web-discovery 1.0.0 → 1.1.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.
package/lib/index.js CHANGED
@@ -1,22 +1,163 @@
1
1
  // src/shared/types.ts
2
2
  var PLUGIN = "dsh-web-discovery";
3
- var VERSION = "1.0.0";
3
+ var VERSION = "1.1.0";
4
4
 
5
5
  // src/host/tools.ts
6
- import { existsSync } from "node:fs";
6
+ import { existsSync as existsSync2 } from "node:fs";
7
7
  import { join as join3 } from "node:path";
8
8
 
9
9
  // src/host/config.ts
10
- import { readFileSync } from "node:fs";
11
- import { join } from "node:path";
10
+ import { existsSync, readFileSync, statSync } from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import { dirname, join } from "node:path";
13
+
14
+ // src/host/discovery-port.ts
15
+ var DISCOVERY_ENGINES = ["serper", "browser39", "searxng"];
16
+ var MAX_DISCOVERY_MS = 45e3;
17
+ var MAX_BROWSER39_MS = 25e3;
18
+ var DEFAULT_LIMIT = 5;
19
+ var MAX_LIMIT = 50;
20
+ var DiscoveryEngineError = class extends Error {
21
+ constructor(code, message) {
22
+ super(message);
23
+ this.code = code;
24
+ this.name = "DiscoveryEngineError";
25
+ }
26
+ };
27
+
28
+ // src/host/engines/serper.ts
29
+ var DEFAULT_SERPER_ENDPOINT = "https://google.serper.dev/search";
30
+ var DEFAULT_TIMEOUT_MS = 1e4;
31
+ function asString(v) {
32
+ return typeof v === "string" && v.trim() !== "" ? v : void 0;
33
+ }
34
+ function mapSerperOrganic(row) {
35
+ const url = asString(row.link);
36
+ if (!url) return null;
37
+ let isHttp = false;
38
+ try {
39
+ const u = new URL(url);
40
+ isHttp = u.protocol === "http:" || u.protocol === "https:";
41
+ } catch {
42
+ return null;
43
+ }
44
+ if (!isHttp) return null;
45
+ const hit = { url };
46
+ const title = asString(row.title);
47
+ if (title) hit.title = title;
48
+ const snippet = asString(row.snippet);
49
+ if (snippet) hit.snippet = snippet;
50
+ return hit;
51
+ }
52
+ function createSerperEngine(opts) {
53
+ const apiKey = opts.apiKey.trim();
54
+ const endpoint = (opts.endpoint ?? DEFAULT_SERPER_ENDPOINT).replace(/\/+$/, "") || DEFAULT_SERPER_ENDPOINT;
55
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
56
+ const fetchImpl = opts.fetchImpl ?? fetch;
57
+ return {
58
+ kind: "serper",
59
+ async search(query, searchOpts = {}) {
60
+ if (!apiKey) {
61
+ throw new DiscoveryEngineError("serper_auth", "serper API key is not configured");
62
+ }
63
+ const limit = searchOpts.limit ?? DEFAULT_LIMIT;
64
+ const res = await fetchImpl(endpoint, {
65
+ method: "POST",
66
+ signal: AbortSignal.timeout(timeoutMs),
67
+ headers: {
68
+ "X-API-KEY": apiKey,
69
+ "Content-Type": "application/json",
70
+ accept: "application/json"
71
+ },
72
+ body: JSON.stringify({ q: query, num: limit })
73
+ }).catch((error) => {
74
+ throw new DiscoveryEngineError(
75
+ "serper_unreachable",
76
+ `serper unreachable: ${error instanceof Error ? error.message : String(error)}`
77
+ );
78
+ });
79
+ if (res.status === 401 || res.status === 403) {
80
+ throw new DiscoveryEngineError(
81
+ "serper_auth",
82
+ `serper auth failed (HTTP ${res.status})`
83
+ );
84
+ }
85
+ if (!res.ok) {
86
+ throw new DiscoveryEngineError("serper_failed", `serper HTTP ${res.status}`);
87
+ }
88
+ let body;
89
+ try {
90
+ body = await res.json();
91
+ } catch (error) {
92
+ throw new DiscoveryEngineError(
93
+ "serper_failed",
94
+ `serper replied non-JSON: ${error instanceof Error ? error.message : String(error)}`
95
+ );
96
+ }
97
+ const organic = body?.organic;
98
+ if (!Array.isArray(organic)) {
99
+ throw new DiscoveryEngineError("serper_failed", "serper reply has no organic[]");
100
+ }
101
+ const hits = [];
102
+ for (const row of organic) {
103
+ const hit = mapSerperOrganic(row);
104
+ if (hit) hits.push(hit);
105
+ if (hits.length >= limit) break;
106
+ }
107
+ return hits;
108
+ }
109
+ };
110
+ }
111
+
112
+ // src/host/config.ts
12
113
  var CONFIG_DIR = "web-discovery";
13
114
  var CONFIG_FILENAME = "config.json";
14
115
  var DEFAULT_SEARXNG_ENDPOINT = "http://127.0.0.1:8888/searxng";
15
116
  var DEFAULT_BROWSER39_BIN = "browser39";
117
+ var DEFAULT_RECEIPT_CHAR_BUDGET = 6e3;
118
+ var DEFAULT_CATEGORIZER_ENDPOINT = "";
119
+ var DEFAULT_CATEGORIZER_MODEL = "local-categorizer";
120
+ var DEFAULT_CATEGORIZER_API_KEY_ENV = "";
121
+ var DEFAULT_CATEGORIZER_TIMEOUT_MS = 5e3;
16
122
  var DEFAULT_CONFIG = {
123
+ serperApiKey: "",
124
+ serperEndpoint: DEFAULT_SERPER_ENDPOINT,
17
125
  searxngEndpoint: DEFAULT_SEARXNG_ENDPOINT,
18
- browser39Bin: DEFAULT_BROWSER39_BIN
126
+ browser39Bin: DEFAULT_BROWSER39_BIN,
127
+ receiptCharBudget: DEFAULT_RECEIPT_CHAR_BUDGET,
128
+ categorizerEndpoint: DEFAULT_CATEGORIZER_ENDPOINT,
129
+ categorizerModel: DEFAULT_CATEGORIZER_MODEL,
130
+ categorizerApiKeyEnv: DEFAULT_CATEGORIZER_API_KEY_ENV,
131
+ categorizerTimeoutMs: DEFAULT_CATEGORIZER_TIMEOUT_MS,
132
+ aliasWebSearch: false
19
133
  };
134
+ function resolveBrowser39Bin(configured) {
135
+ const trimmed = configured.trim();
136
+ if (trimmed === "") return null;
137
+ if (trimmed !== DEFAULT_BROWSER39_BIN) {
138
+ return { cmd: trimmed, prefixArgs: [] };
139
+ }
140
+ try {
141
+ const require2 = createRequire(import.meta.url);
142
+ const pkgJson = require2.resolve("@aquintanar/browser39/package.json");
143
+ const binJs = join(dirname(pkgJson), "bin.js");
144
+ if (existsSync(binJs)) {
145
+ return { cmd: process.execPath, prefixArgs: [binJs] };
146
+ }
147
+ } catch {
148
+ }
149
+ for (const dir of (process.env.PATH ?? "").split(":")) {
150
+ if (dir === "") continue;
151
+ const candidate = join(dir, "browser39");
152
+ try {
153
+ if (statSync(candidate).mode & 73) {
154
+ return { cmd: candidate, prefixArgs: [] };
155
+ }
156
+ } catch {
157
+ }
158
+ }
159
+ return { cmd: "browser39", prefixArgs: [] };
160
+ }
20
161
  var DiscoveryConfigError = class extends Error {
21
162
  constructor(code, message) {
22
163
  super(message);
@@ -25,12 +166,26 @@ var DiscoveryConfigError = class extends Error {
25
166
  }
26
167
  };
27
168
  var FIELDS = [
169
+ { key: "serperApiKey", kind: "string" },
170
+ { key: "serperEndpoint", kind: "string" },
28
171
  { key: "searxngEndpoint", kind: "string" },
29
- { key: "browser39Bin", kind: "string" }
172
+ { key: "browser39Bin", kind: "string" },
173
+ { key: "categorizerEndpoint", kind: "string" },
174
+ { key: "categorizerModel", kind: "string" },
175
+ { key: "categorizerApiKeyEnv", kind: "string" },
176
+ { key: "receiptCharBudget", kind: "number" },
177
+ { key: "categorizerTimeoutMs", kind: "number" },
178
+ { key: "aliasWebSearch", kind: "boolean" }
30
179
  ];
31
180
  function configPath(cwd) {
32
181
  return join(cwd, ".dsh", CONFIG_DIR, CONFIG_FILENAME);
33
182
  }
183
+ function clampReceiptBudget(n) {
184
+ return Math.min(1e5, Math.max(500, Math.round(n)));
185
+ }
186
+ function clampTimeoutMs(n) {
187
+ return Math.min(6e4, Math.max(500, Math.round(n)));
188
+ }
34
189
  function readDiscoveryConfig(cwd, env = process.env) {
35
190
  let file = {};
36
191
  const path = configPath(cwd);
@@ -54,44 +209,335 @@ function readDiscoveryConfig(cwd, env = process.env) {
54
209
  }
55
210
  const config = { ...DEFAULT_CONFIG };
56
211
  for (const spec of FIELDS) {
57
- if (spec.key in file) {
58
- const value = file[spec.key];
212
+ if (!(spec.key in file)) continue;
213
+ const value = file[spec.key];
214
+ if (spec.kind === "string") {
59
215
  if (typeof value !== "string") {
60
- throw new DiscoveryConfigError(
61
- "config_corrupt",
62
- `${path}: ${spec.key} must be a string`
63
- );
216
+ throw new DiscoveryConfigError("config_corrupt", `${path}: ${spec.key} must be a string`);
64
217
  }
218
+ ;
65
219
  config[spec.key] = value;
220
+ } else if (spec.kind === "boolean") {
221
+ if (typeof value !== "boolean") {
222
+ throw new DiscoveryConfigError("config_corrupt", `${path}: ${spec.key} must be a boolean`);
223
+ }
224
+ config.aliasWebSearch = value;
225
+ } else {
226
+ if (typeof value !== "number" || !Number.isFinite(value)) {
227
+ throw new DiscoveryConfigError("config_corrupt", `${path}: ${spec.key} must be a finite number`);
228
+ }
229
+ if (spec.key === "categorizerTimeoutMs") config.categorizerTimeoutMs = clampTimeoutMs(value);
230
+ else config.receiptCharBudget = clampReceiptBudget(value);
66
231
  }
67
232
  }
233
+ const serperEndpoint = env.SERPER_ENDPOINT;
234
+ if (serperEndpoint !== void 0) config.serperEndpoint = serperEndpoint;
68
235
  const endpoint = env.SEARXNG_ENDPOINT;
69
236
  if (endpoint !== void 0) config.searxngEndpoint = endpoint;
70
237
  const bin = env.BROWSER39_BIN;
71
238
  if (bin !== void 0) config.browser39Bin = bin;
239
+ const budgetEnv = env.RECEIPT_CHAR_BUDGET;
240
+ if (budgetEnv !== void 0 && budgetEnv.trim() !== "") {
241
+ const n = Number(budgetEnv);
242
+ if (!Number.isFinite(n)) {
243
+ throw new DiscoveryConfigError("config_corrupt", `RECEIPT_CHAR_BUDGET must be a finite number (got ${JSON.stringify(budgetEnv)})`);
244
+ }
245
+ config.receiptCharBudget = clampReceiptBudget(n);
246
+ }
247
+ if (env.CATEGORIZER_ENDPOINT !== void 0) config.categorizerEndpoint = env.CATEGORIZER_ENDPOINT;
248
+ if (env.CATEGORIZER_MODEL !== void 0) config.categorizerModel = env.CATEGORIZER_MODEL;
249
+ if (env.CATEGORIZER_API_KEY_ENV !== void 0) config.categorizerApiKeyEnv = env.CATEGORIZER_API_KEY_ENV;
250
+ if (env.CATEGORIZER_TIMEOUT_MS !== void 0 && env.CATEGORIZER_TIMEOUT_MS.trim() !== "") {
251
+ const n = Number(env.CATEGORIZER_TIMEOUT_MS);
252
+ if (!Number.isFinite(n)) {
253
+ throw new DiscoveryConfigError("config_corrupt", `CATEGORIZER_TIMEOUT_MS must be a finite number`);
254
+ }
255
+ config.categorizerTimeoutMs = clampTimeoutMs(n);
256
+ }
257
+ if (env.ALIAS_WEB_SEARCH !== void 0) {
258
+ const v = env.ALIAS_WEB_SEARCH.trim().toLowerCase();
259
+ config.aliasWebSearch = v === "1" || v === "true" || v === "yes" || v === "on";
260
+ }
72
261
  return config;
73
262
  }
74
- function enginesForConfig(config) {
263
+ function resolveSerperApiKey(config, env = process.env) {
264
+ const fromEnv = (env.SERPER_API_KEY ?? "").trim();
265
+ if (fromEnv) return fromEnv;
266
+ return config.serperApiKey.trim();
267
+ }
268
+ function llmConfigFrom(config) {
269
+ if (!config.categorizerEndpoint.trim()) return null;
270
+ return {
271
+ endpoint: config.categorizerEndpoint.trim(),
272
+ model: config.categorizerModel.trim() || DEFAULT_CATEGORIZER_MODEL,
273
+ apiKeyEnv: config.categorizerApiKeyEnv.trim(),
274
+ timeoutMs: config.categorizerTimeoutMs
275
+ };
276
+ }
277
+ function enginesForConfig(config, env = process.env) {
75
278
  return {
279
+ serper: resolveSerperApiKey(config, env) !== "",
76
280
  searxng: config.searxngEndpoint.trim() !== "",
77
281
  browser39: config.browser39Bin.trim() !== ""
78
282
  };
79
283
  }
80
284
 
81
- // src/host/engines/browser39.ts
82
- import { execFile } from "node:child_process";
285
+ // src/host/categorizer.ts
286
+ var LOGIN_RE = /login|signin|sign-in|auth|sso|paywall|subscribe|cookie/i;
287
+ var DOCS_HOST_RE = /^(docs|developer|dev|api|learn)\.|\.github\.io$/i;
288
+ var DOCS_PATH_RE = /\/docs?\/|\/reference\/|\/api\//i;
289
+ var FORUM_RE = /stackoverflow\.com|stackexchange\.com|reddit\.com|discourse\.|forum\./i;
290
+ var COMMERCIAL_RE = /\/pricing|\/cart|\/shop|amazon\.|ebay\./i;
291
+ var JUNK_RE = /pinterest\.|facebook\.com\/|twitter\.com\/|x\.com\//i;
292
+ function hostOf(url) {
293
+ try {
294
+ return new URL(url).hostname.toLowerCase();
295
+ } catch {
296
+ return "";
297
+ }
298
+ }
299
+ function queryTokens(query) {
300
+ return query.toLowerCase().split(/[^a-z0-9]+/i).filter((t) => t.length >= 3);
301
+ }
302
+ function labelFor(host, url, flags) {
303
+ if (flags.includes("denylisted")) return "junk";
304
+ if (JUNK_RE.test(host) || JUNK_RE.test(url)) return "junk";
305
+ if (FORUM_RE.test(host)) return "forum";
306
+ if (COMMERCIAL_RE.test(url) || COMMERCIAL_RE.test(host)) return "commercial";
307
+ if (flags.includes("docs_cue") || host.endsWith(".org") || host === "github.com") return "primary";
308
+ if (host.endsWith(".edu") || host.endsWith(".gov")) return "reference";
309
+ return "reference";
310
+ }
311
+ var LABEL_RANK = {
312
+ primary: 0,
313
+ reference: 1,
314
+ forum: 2,
315
+ commercial: 3,
316
+ junk: 4
317
+ };
318
+ function createHeuristicCategorizer() {
319
+ return {
320
+ categorize(query, hits, opts = {}) {
321
+ const denylist = (opts.denylist ?? []).map((s) => s.toLowerCase());
322
+ const priors = (opts.priors ?? []).map((s) => s.toLowerCase());
323
+ const tokens = queryTokens(query);
324
+ const seenHosts = /* @__PURE__ */ new Set();
325
+ let dropped = 0;
326
+ const kept = [];
327
+ for (const hit of hits) {
328
+ const host = hostOf(hit.url);
329
+ const flags = [];
330
+ if (denylist.some((d) => host.includes(d) || hit.url.toLowerCase().includes(d))) {
331
+ dropped++;
332
+ continue;
333
+ }
334
+ if (seenHosts.has(host)) flags.push("dup_host");
335
+ else seenHosts.add(host);
336
+ if (LOGIN_RE.test(hit.url) || LOGIN_RE.test(hit.title ?? "")) flags.push("login_cue");
337
+ if (DOCS_HOST_RE.test(host) || DOCS_PATH_RE.test(hit.url)) flags.push("docs_cue");
338
+ const blob = `${hit.title ?? ""} ${hit.snippet ?? ""}`.toLowerCase();
339
+ if (tokens.length > 0 && tokens.every((t) => !blob.includes(t) && !hit.url.toLowerCase().includes(t))) {
340
+ flags.push("token_miss");
341
+ }
342
+ const label = labelFor(host, hit.url, flags);
343
+ kept.push({
344
+ i: 0,
345
+ url: hit.url,
346
+ host,
347
+ ...hit.title ? { title: hit.title } : {},
348
+ ...hit.snippet ? { snippet: hit.snippet } : {},
349
+ flags,
350
+ label
351
+ });
352
+ }
353
+ kept.sort((a, b) => {
354
+ const fa = a.flags.length;
355
+ const fb = b.flags.length;
356
+ const pa = priors.some((p) => a.host.includes(p)) ? 0 : 1;
357
+ const pb = priors.some((p) => b.host.includes(p)) ? 0 : 1;
358
+ if (pa !== pb) return pa - pb;
359
+ if (LABEL_RANK[a.label] !== LABEL_RANK[b.label]) return LABEL_RANK[a.label] - LABEL_RANK[b.label];
360
+ if (fa !== fb) return fa - fb;
361
+ return 0;
362
+ });
363
+ return {
364
+ rows: kept.map((r, i) => ({ ...r, i: i + 1 })),
365
+ dropped,
366
+ categorizer: "heuristic"
367
+ };
368
+ }
369
+ };
370
+ }
371
+ var RECEIPT_CHAR_BUDGET = DEFAULT_RECEIPT_CHAR_BUDGET;
372
+ function fitReceiptChars(rows, budget = RECEIPT_CHAR_BUDGET) {
373
+ const out = [];
374
+ let used = 0;
375
+ for (const row of rows) {
376
+ const title = row.title?.slice(0, 120);
377
+ const snippet = row.snippet?.slice(0, 180);
378
+ const cost = (row.url?.length ?? 0) + (title?.length ?? 0) + (snippet?.length ?? 0) + 32;
379
+ if (used + cost > budget && out.length > 0) break;
380
+ out.push({
381
+ ...row,
382
+ ...title !== void 0 ? { title } : {},
383
+ ...snippet !== void 0 ? { snippet } : {}
384
+ });
385
+ used += cost;
386
+ }
387
+ return out;
388
+ }
83
389
 
84
- // src/host/discovery-port.ts
85
- var DISCOVERY_ENGINES = ["searxng", "browser39"];
86
- var DiscoveryEngineError = class extends Error {
390
+ // src/host/llm-categorizer.ts
391
+ var LABELS = /* @__PURE__ */ new Set(["primary", "reference", "forum", "commercial", "junk"]);
392
+ function isLocalEndpoint(endpoint) {
393
+ try {
394
+ const u = new URL(endpoint);
395
+ return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1";
396
+ } catch {
397
+ return false;
398
+ }
399
+ }
400
+ function modeForEndpoint(endpoint) {
401
+ return isLocalEndpoint(endpoint) ? "llm-local" : "llm-remote";
402
+ }
403
+ async function categorizeWithOptionalLlm(query, hits, llm, fetchImpl = fetch) {
404
+ const base = createHeuristicCategorizer().categorize(query, hits);
405
+ if (!llm || !llm.endpoint.trim()) {
406
+ return { ...base, categorizer: "heuristic" };
407
+ }
408
+ const apiKey = llm.apiKeyEnv ? process.env[llm.apiKeyEnv] ?? "" : "";
409
+ const url = llm.endpoint.replace(/\/$/, "") + "/chat/completions";
410
+ const payload = {
411
+ model: llm.model,
412
+ temperature: 0,
413
+ response_format: { type: "json_object" },
414
+ messages: [
415
+ {
416
+ role: "system",
417
+ content: 'Classify search hits. Reply JSON only: {"rows":[{"i":number,"label":"primary"|"reference"|"forum"|"commercial"|"junk"}]}. Use 1-based i matching input. Never invent URLs. Never fetch.'
418
+ },
419
+ {
420
+ role: "user",
421
+ content: JSON.stringify({
422
+ query,
423
+ rows: base.rows.slice(0, 8).map((r) => ({
424
+ i: r.i,
425
+ url: r.url,
426
+ host: r.host,
427
+ title: r.title ?? "",
428
+ snippet: r.snippet ?? ""
429
+ }))
430
+ })
431
+ }
432
+ ]
433
+ };
434
+ try {
435
+ const ctrl = new AbortController();
436
+ const timer = setTimeout(() => ctrl.abort(), Math.max(500, llm.timeoutMs));
437
+ const headers = { "content-type": "application/json" };
438
+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;
439
+ const res = await fetchImpl(url, {
440
+ method: "POST",
441
+ headers,
442
+ body: JSON.stringify(payload),
443
+ signal: ctrl.signal
444
+ });
445
+ clearTimeout(timer);
446
+ if (!res.ok) {
447
+ return { ...base, categorizer: "heuristic (llm unavailable)" };
448
+ }
449
+ const body = await res.json();
450
+ const text = body.choices?.[0]?.message?.content ?? "";
451
+ const parsed = JSON.parse(text);
452
+ if (!Array.isArray(parsed.rows)) {
453
+ return { ...base, categorizer: "heuristic (llm unavailable)" };
454
+ }
455
+ const byI = /* @__PURE__ */ new Map();
456
+ for (const row of parsed.rows) {
457
+ const i = typeof row.i === "number" ? row.i : Number(row.i);
458
+ const label = typeof row.label === "string" ? row.label : "";
459
+ if (Number.isFinite(i) && LABELS.has(label)) {
460
+ byI.set(i, label);
461
+ }
462
+ }
463
+ if (byI.size === 0) {
464
+ return { ...base, categorizer: "heuristic (llm unavailable)" };
465
+ }
466
+ const rows = base.rows.map((r) => ({
467
+ ...r,
468
+ label: byI.get(r.i) ?? r.label
469
+ }));
470
+ return {
471
+ rows,
472
+ dropped: base.dropped,
473
+ categorizer: modeForEndpoint(llm.endpoint)
474
+ };
475
+ } catch {
476
+ return { ...base, categorizer: "heuristic (llm unavailable)" };
477
+ }
478
+ }
479
+
480
+ // src/host/discovery-store.ts
481
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
482
+ import { dirname as dirname2, join as join2 } from "node:path";
483
+ var DISCOVERY_FILENAME = "discovery.json";
484
+ var DiscoveryStoreError = class extends Error {
87
485
  constructor(code, message) {
88
486
  super(message);
89
487
  this.code = code;
90
- this.name = "DiscoveryEngineError";
488
+ this.name = "DiscoveryStoreError";
91
489
  }
92
490
  };
491
+ function discoveryPath(missionDir) {
492
+ return join2(missionDir, DISCOVERY_FILENAME);
493
+ }
494
+ function readDiscoveryFile(missionDir) {
495
+ const path = discoveryPath(missionDir);
496
+ let raw;
497
+ try {
498
+ raw = readFileSync2(path, "utf8");
499
+ } catch (error) {
500
+ if (error.code === "ENOENT") return null;
501
+ throw new DiscoveryStoreError("discovery_unwritable", `cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
502
+ }
503
+ try {
504
+ const parsed = JSON.parse(raw);
505
+ if (parsed === null || typeof parsed !== "object" || !Array.isArray(parsed.urls) || typeof parsed.updated_at !== "string") {
506
+ throw new Error("bad shape");
507
+ }
508
+ return parsed;
509
+ } catch (error) {
510
+ throw new DiscoveryStoreError("discovery_corrupt", `${path} is not valid discovery.json: ${error instanceof Error ? error.message : String(error)}`);
511
+ }
512
+ }
513
+ function recordDiscovery(missionDir, hits, via) {
514
+ const at = via.at ?? (/* @__PURE__ */ new Date()).toISOString();
515
+ if (typeof at !== "string" || at.length === 0) {
516
+ throw new DiscoveryStoreError("bad_provenance", `via.at must be an ISO timestamp string (got ${String(via.at)})`);
517
+ }
518
+ const file = readDiscoveryFile(missionDir) ?? { updated_at: at, urls: [] };
519
+ const seen = new Set(file.urls.map((u) => u.url.toLowerCase()));
520
+ for (const hit of hits) {
521
+ const key = hit.url.toLowerCase();
522
+ if (seen.has(key)) continue;
523
+ seen.add(key);
524
+ file.urls.push({ ...hit, via: { ...via, at } });
525
+ }
526
+ file.updated_at = at;
527
+ const path = discoveryPath(missionDir);
528
+ const tmp = `${path}.tmp-${process.pid}`;
529
+ mkdirSync(dirname2(path), { recursive: true });
530
+ try {
531
+ writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
532
+ renameSync(tmp, path);
533
+ } catch (error) {
534
+ throw new DiscoveryStoreError("discovery_unwritable", `cannot write ${path}: ${error instanceof Error ? error.message : String(error)}`);
535
+ }
536
+ return file;
537
+ }
93
538
 
94
539
  // src/host/engines/browser39.ts
540
+ import { execFile } from "node:child_process";
95
541
  function defaultRunner(timeoutMs) {
96
542
  return (bin, args) => new Promise((resolve) => {
97
543
  execFile(
@@ -114,8 +560,7 @@ function defaultRunner(timeoutMs) {
114
560
  );
115
561
  });
116
562
  }
117
- var DEFAULT_TIMEOUT_MS = 3e4;
118
- var DEFAULT_LIMIT = 10;
563
+ var DEFAULT_TIMEOUT_MS2 = 25e3;
119
564
  var SERP_CHROME_HOST = "duckduckgo.com";
120
565
  function unwrapSerpHref(href) {
121
566
  let u;
@@ -159,15 +604,16 @@ function mapSerpPage(page, limit) {
159
604
  return hits;
160
605
  }
161
606
  function createBrowser39Engine(opts) {
162
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
607
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
163
608
  const runner = opts.runner ?? defaultRunner(timeoutMs);
609
+ const prefix = opts.binPrefixArgs ?? [];
164
610
  return {
165
611
  kind: "browser39",
166
612
  async search(query, searchOpts = {}) {
167
613
  const limit = searchOpts.limit ?? DEFAULT_LIMIT;
168
614
  let result;
169
615
  try {
170
- result = await runner(opts.bin, ["search", query, "--output", "json", "--no-persist"]);
616
+ result = await runner(opts.bin, [...prefix, "search", query, "--output", "json", "--no-persist"]);
171
617
  } catch (error) {
172
618
  throw new DiscoveryEngineError(
173
619
  "browser39_missing",
@@ -207,13 +653,12 @@ function createBrowser39Engine(opts) {
207
653
  }
208
654
 
209
655
  // src/host/engines/searxng.ts
210
- var DEFAULT_TIMEOUT_MS2 = 1e4;
211
- var DEFAULT_LIMIT2 = 10;
212
- function asString(v) {
656
+ var DEFAULT_TIMEOUT_MS3 = 1e4;
657
+ function asString2(v) {
213
658
  return typeof v === "string" && v.trim() !== "" ? v : void 0;
214
659
  }
215
660
  function mapSearxngRow(row) {
216
- const url = asString(row.url);
661
+ const url = asString2(row.url);
217
662
  if (!url) return null;
218
663
  let isHttp = false;
219
664
  try {
@@ -224,15 +669,15 @@ function mapSearxngRow(row) {
224
669
  }
225
670
  if (!isHttp) return null;
226
671
  const hit = { url };
227
- const title = asString(row.title);
672
+ const title = asString2(row.title);
228
673
  if (title) hit.title = title;
229
- const snippet = asString(row.content);
674
+ const snippet = asString2(row.content);
230
675
  if (snippet) hit.snippet = snippet;
231
676
  return hit;
232
677
  }
233
678
  function createSearxngEngine(opts) {
234
679
  const endpoint = opts.endpoint.replace(/\/+$/, "");
235
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
680
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
236
681
  const fetchImpl = opts.fetchImpl ?? fetch;
237
682
  return {
238
683
  kind: "searxng",
@@ -240,7 +685,7 @@ function createSearxngEngine(opts) {
240
685
  if (!endpoint) {
241
686
  throw new DiscoveryEngineError("searxng_unreachable", "searxng endpoint is not configured");
242
687
  }
243
- const limit = searchOpts.limit ?? DEFAULT_LIMIT2;
688
+ const limit = searchOpts.limit ?? DEFAULT_LIMIT;
244
689
  const qs = new URLSearchParams({ q: query, format: "json" });
245
690
  const res = await fetchImpl(`${endpoint}/search?${qs.toString()}`, {
246
691
  signal: AbortSignal.timeout(timeoutMs),
@@ -278,105 +723,96 @@ function createSearxngEngine(opts) {
278
723
  };
279
724
  }
280
725
 
281
- // src/host/discovery-store.ts
282
- import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
283
- import { dirname, join as join2 } from "node:path";
284
- var DISCOVERY_FILENAME = "discovery.json";
285
- var DiscoveryStoreError = class extends Error {
286
- constructor(code, message) {
287
- super(message);
288
- this.code = code;
289
- this.name = "DiscoveryStoreError";
290
- }
291
- };
292
- function discoveryPath(missionDir) {
293
- return join2(missionDir, DISCOVERY_FILENAME);
294
- }
295
- function readDiscoveryFile(missionDir) {
296
- const path = discoveryPath(missionDir);
297
- let raw;
298
- try {
299
- raw = readFileSync2(path, "utf8");
300
- } catch (error) {
301
- if (error.code === "ENOENT") return null;
302
- throw new DiscoveryStoreError("discovery_unwritable", `cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
303
- }
304
- try {
305
- const parsed = JSON.parse(raw);
306
- if (parsed === null || typeof parsed !== "object" || !Array.isArray(parsed.urls) || typeof parsed.updated_at !== "string") {
307
- throw new Error("bad shape");
308
- }
309
- return parsed;
310
- } catch (error) {
311
- throw new DiscoveryStoreError("discovery_corrupt", `${path} is not valid discovery.json: ${error instanceof Error ? error.message : String(error)}`);
312
- }
313
- }
314
- function recordDiscovery(missionDir, hits, via) {
315
- const at = via.at ?? (/* @__PURE__ */ new Date()).toISOString();
316
- if (typeof at !== "string" || at.length === 0) {
317
- throw new DiscoveryStoreError("bad_provenance", `via.at must be an ISO timestamp string (got ${String(via.at)})`);
318
- }
319
- const file = readDiscoveryFile(missionDir) ?? { updated_at: at, urls: [] };
320
- const seen = new Set(file.urls.map((u) => u.url.toLowerCase()));
321
- for (const hit of hits) {
322
- const key = hit.url.toLowerCase();
323
- if (seen.has(key)) continue;
324
- seen.add(key);
325
- file.urls.push({ ...hit, via: { ...via, at } });
326
- }
327
- file.updated_at = at;
328
- const path = discoveryPath(missionDir);
329
- const tmp = `${path}.tmp-${process.pid}`;
330
- mkdirSync(dirname(path), { recursive: true });
331
- try {
332
- writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
333
- renameSync(tmp, path);
334
- } catch (error) {
335
- throw new DiscoveryStoreError("discovery_unwritable", `cannot write ${path}: ${error instanceof Error ? error.message : String(error)}`);
336
- }
337
- return file;
338
- }
339
-
340
726
  // src/host/discovery-tool.ts
727
+ function clampLimit(limit) {
728
+ if (typeof limit !== "number" || !Number.isFinite(limit)) return DEFAULT_LIMIT;
729
+ return Math.min(MAX_LIMIT, Math.max(1, Math.round(limit)));
730
+ }
731
+ var FALL_THROUGH_CODES = /* @__PURE__ */ new Set([
732
+ "serper_unreachable",
733
+ "serper_auth",
734
+ "serper_failed",
735
+ "searxng_unreachable",
736
+ "browser39_missing",
737
+ "browser39_blocked",
738
+ "budget_exhausted"
739
+ ]);
341
740
  function engineReason(kind, error) {
342
741
  switch (error.code) {
742
+ case "serper_unreachable":
743
+ case "serper_auth":
744
+ case "serper_failed":
745
+ return `serper: ${error.message}`;
343
746
  case "searxng_unreachable":
344
747
  return "searxng not running at the configured endpoint";
345
748
  case "browser39_missing":
346
749
  return "browser39 search binary not found";
347
750
  case "browser39_blocked":
348
751
  return "browser39 blocked by the search engine (bot challenge / rate limit)";
752
+ case "budget_exhausted":
753
+ return "discovery wall-clock budget exhausted";
349
754
  default:
350
755
  return `${kind} engine error (${error.code})`;
351
756
  }
352
757
  }
758
+ function absentReason(kind) {
759
+ switch (kind) {
760
+ case "serper":
761
+ return "serper key not set";
762
+ case "searxng":
763
+ return "searxng endpoint not configured";
764
+ case "browser39":
765
+ return "browser39 search not configured";
766
+ }
767
+ }
353
768
  async function runDiscoverySearch(deps, rawQuery, opts = {}) {
354
769
  const query = rawQuery.trim();
355
770
  if (!query) {
356
771
  return { ok: false, error: "query_required: pass a non-empty search query" };
357
772
  }
358
- const limit = opts.limit ?? 10;
773
+ const limit = clampLimit(opts.limit);
774
+ const now = deps.nowMs ?? (() => Date.now());
775
+ const started = now();
776
+ const maxTotal = deps.maxDiscoveryMs ?? MAX_DISCOVERY_MS;
777
+ const maxB39 = deps.maxBrowser39Ms ?? MAX_BROWSER39_MS;
359
778
  const candidates = opts.engine ? [opts.engine] : DISCOVERY_ENGINES.filter((k) => deps.engines[k] !== void 0);
360
779
  if (candidates.length === 0) {
361
780
  return {
362
781
  ok: false,
363
- error: "no_engine: no discovery engines configured (searxng endpoint not configured; browser39 search not configured) \u2014 missing discovery is a supported state; supply URLs directly (fixtures or manual)"
782
+ error: "no_engine: no discovery engines configured (serper key not set; searxng endpoint not configured; browser39 search not configured) \u2014 missing discovery is a supported state; supply URLs directly (fixtures or manual)"
364
783
  };
365
784
  }
366
785
  const failures = [];
367
786
  for (const kind of candidates) {
787
+ const elapsed = now() - started;
788
+ if (elapsed >= maxTotal) {
789
+ return {
790
+ ok: false,
791
+ error: `budget_exhausted: discovery exceeded ${maxTotal}ms across engines (${failures.join("; ") || "no engine answered in time"})`
792
+ };
793
+ }
368
794
  const engine = deps.engines[kind];
369
795
  if (!engine) {
370
- failures.push(
371
- kind === "searxng" ? "searxng endpoint not configured" : "browser39 search not configured"
372
- );
796
+ failures.push(absentReason(kind));
797
+ continue;
798
+ }
799
+ if (kind === "browser39" && elapsed >= maxB39) {
800
+ failures.push(`browser39 skipped (already ${elapsed}ms \u2265 ${maxB39}ms soft cap)`);
373
801
  continue;
374
802
  }
375
803
  try {
376
804
  const urls = await engine.search(query, { limit });
377
- return { ok: true, query, engine: engine.kind, count: urls.length, urls };
805
+ const result = {
806
+ ok: true,
807
+ query,
808
+ engine: engine.kind,
809
+ count: urls.length,
810
+ urls
811
+ };
812
+ if (failures.length > 0) result.notes = [...failures];
813
+ return result;
378
814
  } catch (error) {
379
- if (error instanceof DiscoveryEngineError && (error.code === "searxng_unreachable" || error.code === "browser39_missing" || error.code === "browser39_blocked")) {
815
+ if (error instanceof DiscoveryEngineError && FALL_THROUGH_CODES.has(error.code)) {
380
816
  failures.push(engineReason(engine.kind, error));
381
817
  continue;
382
818
  }
@@ -392,6 +828,44 @@ async function runDiscoverySearch(deps, rawQuery, opts = {}) {
392
828
  const reason = candidates.length === 1 && opts.engine ? `${opts.engine}: ${failures[0] ?? "unavailable"}` : failures.join("; ");
393
829
  return { ok: false, error: `no_engine: ${reason} \u2014 missing discovery is a supported state; supply URLs directly (fixtures or manual)` };
394
830
  }
831
+ function enginesFromConfig(config, opts = {}) {
832
+ const env = opts.env ?? process.env;
833
+ const presence = enginesForConfig(config, env);
834
+ const engines = {};
835
+ if (presence.serper) {
836
+ const apiKey = resolveSerperApiKey(config, env);
837
+ engines.serper = createSerperEngine({
838
+ apiKey,
839
+ endpoint: config.serperEndpoint,
840
+ ...opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}
841
+ });
842
+ }
843
+ if (presence.searxng) {
844
+ engines.searxng = createSearxngEngine({
845
+ endpoint: config.searxngEndpoint,
846
+ ...opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}
847
+ });
848
+ }
849
+ if (presence.browser39) {
850
+ const inv = resolveBrowser39Bin(config.browser39Bin);
851
+ if (inv) engines.browser39 = createBrowser39Engine({ bin: inv.cmd, binPrefixArgs: inv.prefixArgs });
852
+ }
853
+ return engines;
854
+ }
855
+ function createDiscoveryPort(cwd) {
856
+ const config = readDiscoveryConfig(cwd);
857
+ const engines = enginesFromConfig(config);
858
+ return {
859
+ async search(query, opts) {
860
+ const result = await runDiscoverySearch({ engines }, query, opts);
861
+ if (!result.ok) {
862
+ const code = result.error.startsWith("no_engine:") ? "no_engine" : result.error.startsWith("budget_exhausted:") ? "budget_exhausted" : "browser39_failed";
863
+ throw new DiscoveryEngineError(code, result.error);
864
+ }
865
+ return result.urls;
866
+ }
867
+ };
868
+ }
395
869
 
396
870
  // src/host/tools.ts
397
871
  var MISSION_STORE_DIR = join3(".dsh", "web-missions");
@@ -408,17 +882,16 @@ var CWD_PARAM = {
408
882
  };
409
883
  function buildEngines(cwd) {
410
884
  const config = readDiscoveryConfig(cwd);
411
- const presence = enginesForConfig(config);
412
- const engines = {};
413
- if (presence.searxng) engines.searxng = createSearxngEngine({ endpoint: config.searxngEndpoint });
414
- if (presence.browser39) engines.browser39 = createBrowser39Engine({ bin: config.browser39Bin });
415
- return engines;
885
+ return { engines: enginesFromConfig(config), config };
886
+ }
887
+ function renderJson(_args, value) {
888
+ return [{ type: "text", text: JSON.stringify(value) }];
416
889
  }
417
890
  function registerDiscoveryTools(ctx) {
418
891
  const disposers = [];
419
892
  const unregisterSearch = ctx.tools.register({
420
893
  name: "discovery_search",
421
- description: "Discover candidate URLs from a local search engine (SearXNG or the browser39 search CLI) \u2014 the mission core only sees URLs in / URLs out. Engines are optional: when none is available the result is no_engine (a supported state \u2014 supply URLs directly instead). Results are candidates: they pass the mission allowlist gate when fetched. With mission_id, hits are recorded into that mission\u2019s discovery.json (surfaced by mission_status; not ledger rows until fetched).",
894
+ description: "Discover candidate URLs (Serper.dev when keyed, else browser39 / SearXNG) \u2014 the mission core only sees URLs in / URLs out. Engines are optional: when none is available the result is no_engine (a supported state \u2014 supply URLs directly instead). Results are candidates: they pass the mission allowlist gate when fetched. With mission_id, hits are recorded into that mission\u2019s discovery.json (surfaced by mission_status; not ledger rows until fetched).",
422
895
  parameters: {
423
896
  type: "object",
424
897
  additionalProperties: false,
@@ -428,9 +901,9 @@ function registerDiscoveryTools(ctx) {
428
901
  engine: {
429
902
  type: "string",
430
903
  enum: [...DISCOVERY_ENGINES],
431
- description: "Pin one engine; omit to auto-select (searxng first, then browser39)."
904
+ description: "Pin one engine; omit to auto-select (serper \u2192 browser39 \u2192 searxng)."
432
905
  },
433
- limit: { type: "number", description: "Max results (default 10, clamped to 1..50)." },
906
+ limit: { type: "number", description: `Max results (default ${DEFAULT_LIMIT}, clamped to 1..${MAX_LIMIT}).` },
434
907
  mission_id: {
435
908
  type: "string",
436
909
  description: "Mission id to record hits into (its discovery.json). Omit to search without recording."
@@ -443,72 +916,123 @@ function registerDiscoveryTools(ctx) {
443
916
  type: "object",
444
917
  additionalProperties: true,
445
918
  properties: {
919
+ v: { type: "number" },
446
920
  ok: { type: "boolean" },
447
921
  error: { type: "string" },
448
922
  query: { type: "string" },
449
923
  engine: { type: "string" },
450
924
  count: { type: "number" },
925
+ dropped: { type: "number" },
926
+ categorizer: { type: "string" },
451
927
  urls: {
452
928
  type: "array",
453
929
  items: {
454
930
  type: "object",
455
931
  additionalProperties: true,
456
932
  properties: {
933
+ i: { type: "number" },
457
934
  url: { type: "string" },
935
+ host: { type: "string" },
458
936
  title: { type: "string" },
459
- snippet: { type: "string" }
937
+ snippet: { type: "string" },
938
+ flags: { type: "array", items: { type: "string" } },
939
+ label: { type: "string" }
460
940
  }
461
941
  }
462
942
  },
463
- recorded: { type: "string" }
943
+ recorded: { type: "string" },
944
+ notes: { type: "array", items: { type: "string" } }
464
945
  }
465
- }
946
+ },
947
+ render: renderJson
466
948
  },
467
949
  execute: async (args, exec) => {
468
950
  let cwd;
469
951
  try {
470
952
  cwd = resolveCwd(args, exec);
471
953
  } catch (error) {
472
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
954
+ return { v: 1, ok: false, error: error instanceof Error ? error.message : String(error) };
473
955
  }
474
- const limit = typeof args.limit === "number" && Number.isFinite(args.limit) ? Math.min(50, Math.max(1, Math.round(args.limit))) : 10;
956
+ const limit = clampLimit(args.limit);
475
957
  let result;
958
+ let config;
476
959
  try {
477
- const engines = buildEngines(cwd);
478
- result = await runDiscoverySearch({ engines }, args.query ?? "", {
960
+ const built = buildEngines(cwd);
961
+ config = built.config;
962
+ result = await runDiscoverySearch({ engines: built.engines }, args.query ?? "", {
479
963
  engine: args.engine,
480
964
  limit
481
965
  });
482
966
  } catch (error) {
483
- return { ok: false, error: `internal_error: ${error instanceof Error ? error.message : String(error)}` };
967
+ return {
968
+ v: 1,
969
+ ok: false,
970
+ error: `internal_error: ${error instanceof Error ? error.message : String(error)}`
971
+ };
972
+ }
973
+ if (!result.ok) {
974
+ return { v: 1, ok: false, error: result.error };
484
975
  }
485
- if (!result.ok) return result;
976
+ const categorized = await categorizeWithOptionalLlm(
977
+ result.query,
978
+ result.urls,
979
+ llmConfigFrom(config)
980
+ );
981
+ const fitted = fitReceiptChars(categorized.rows, config.receiptCharBudget);
982
+ const urls = fitted.map(({ i, url, host, title, snippet, flags, label }) => ({
983
+ i,
984
+ url,
985
+ host,
986
+ ...title ? { title } : {},
987
+ ...snippet ? { snippet } : {},
988
+ flags,
989
+ label
990
+ }));
991
+ const bridgeHits = urls.map(({ url, title, snippet }) => ({
992
+ url,
993
+ ...title ? { title } : {},
994
+ ...snippet ? { snippet } : {}
995
+ }));
486
996
  if (!args.mission_id || !args.mission_id.trim()) {
487
- return { ok: true, query: result.query, engine: result.engine, count: result.count, urls: result.urls };
997
+ return {
998
+ v: 1,
999
+ ok: true,
1000
+ query: result.query,
1001
+ engine: result.engine,
1002
+ count: urls.length,
1003
+ dropped: categorized.dropped,
1004
+ categorizer: categorized.categorizer,
1005
+ urls,
1006
+ ...result.notes && result.notes.length > 0 ? { notes: result.notes } : {}
1007
+ };
488
1008
  }
489
1009
  const missionDir = join3(cwd, MISSION_STORE_DIR, args.mission_id.trim());
490
- if (!existsSync(missionDir)) {
491
- return { ok: false, error: `unknown_mission: no such mission: ${args.mission_id.trim()}` };
1010
+ if (!existsSync2(missionDir)) {
1011
+ return { v: 1, ok: false, error: `unknown_mission: no such mission: ${args.mission_id.trim()}` };
492
1012
  }
493
1013
  try {
494
- recordDiscovery(missionDir, result.urls, {
1014
+ recordDiscovery(missionDir, bridgeHits, {
495
1015
  query: result.query,
496
1016
  engine: result.engine,
497
1017
  at: (/* @__PURE__ */ new Date()).toISOString()
498
1018
  });
499
1019
  } catch (error) {
500
1020
  if (error instanceof DiscoveryStoreError) {
501
- return { ok: false, error: `${error.code}: ${error.message}` };
1021
+ return { v: 1, ok: false, error: `${error.code}: ${error.message}` };
502
1022
  }
503
- return { ok: false, error: `record_failed: ${error instanceof Error ? error.message : String(error)}` };
1023
+ return { v: 1, ok: false, error: `record_failed: ${error instanceof Error ? error.message : String(error)}` };
504
1024
  }
505
1025
  return {
1026
+ v: 1,
506
1027
  ok: true,
507
1028
  query: result.query,
508
1029
  engine: result.engine,
509
- count: result.count,
510
- urls: result.urls,
511
- recorded: join3(args.mission_id.trim(), "discovery.json")
1030
+ count: urls.length,
1031
+ dropped: categorized.dropped,
1032
+ categorizer: categorized.categorizer,
1033
+ urls,
1034
+ recorded: join3(args.mission_id.trim(), "discovery.json"),
1035
+ ...result.notes && result.notes.length > 0 ? { notes: result.notes } : {}
512
1036
  };
513
1037
  }
514
1038
  });
@@ -518,25 +1042,135 @@ function registerDiscoveryTools(ctx) {
518
1042
  };
519
1043
  }
520
1044
 
1045
+ // src/host/web-search-alias.ts
1046
+ function renderJson2(_args, value) {
1047
+ return [{ type: "text", text: JSON.stringify(value) }];
1048
+ }
1049
+ function buildEngines2(cwd) {
1050
+ const config = readDiscoveryConfig(cwd);
1051
+ return { engines: enginesFromConfig(config), config };
1052
+ }
1053
+ function registerWebSearchAlias(ctx) {
1054
+ return ctx.tools.register({
1055
+ name: "web_search",
1056
+ description: "Local web search (dsh-web-discovery alias). Pass queries (1-4 strings); v0 runs the first query via discovery engines (serper / browser39 / SearXNG). Returns sources[{url,title?,snippet?}]. Untrusted external data.",
1057
+ parameters: {
1058
+ type: "object",
1059
+ additionalProperties: false,
1060
+ required: ["queries"],
1061
+ properties: {
1062
+ queries: {
1063
+ type: "array",
1064
+ items: { type: "string" },
1065
+ description: "1-4 search queries; v0 uses queries[0] only."
1066
+ },
1067
+ cwd: { type: "string", description: "Project cwd (defaults to session cwd)." }
1068
+ }
1069
+ },
1070
+ output: {
1071
+ schema: {
1072
+ type: "object",
1073
+ additionalProperties: true,
1074
+ properties: {
1075
+ content: { type: "string" },
1076
+ sources: {
1077
+ type: "array",
1078
+ items: {
1079
+ type: "object",
1080
+ additionalProperties: true,
1081
+ properties: {
1082
+ url: { type: "string" },
1083
+ title: { type: "string" },
1084
+ snippet: { type: "string" }
1085
+ }
1086
+ }
1087
+ },
1088
+ truncated: { type: "boolean" }
1089
+ }
1090
+ },
1091
+ render: renderJson2
1092
+ },
1093
+ execute: async (args, exec) => {
1094
+ const queries = (args.queries ?? []).map((q) => String(q).trim()).filter(Boolean);
1095
+ if (queries.length === 0) {
1096
+ return { sources: [], truncated: false, content: "queries must contain at least one query" };
1097
+ }
1098
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() || exec.agent?.session?.header?.cwd || "";
1099
+ if (!cwd) {
1100
+ return { sources: [], truncated: false, content: "cwd required" };
1101
+ }
1102
+ try {
1103
+ const { engines, config } = buildEngines2(cwd);
1104
+ const result = await runDiscoverySearch({ engines }, queries[0], { limit: clampLimit(void 0) });
1105
+ if (!result.ok) {
1106
+ return { sources: [], truncated: false, content: result.error };
1107
+ }
1108
+ const categorized = await categorizeWithOptionalLlm(result.query, result.urls, llmConfigFrom(config));
1109
+ const fitted = fitReceiptChars(categorized.rows, config.receiptCharBudget);
1110
+ const sources = fitted.map((r) => ({
1111
+ url: r.url,
1112
+ ...r.title ? { title: r.title } : {},
1113
+ ...r.snippet ? { snippet: r.snippet } : {}
1114
+ }));
1115
+ const truncated = queries.length > 1 || categorized.rows.length > fitted.length;
1116
+ const noteBit = result.notes && result.notes.length > 0 ? ` Notes: ${result.notes.join("; ")}.` : "";
1117
+ const content = queries.length > 1 ? `Used queries[0] only (${queries.length} supplied). Engine=${result.engine}; categorizer=${categorized.categorizer}.${noteBit}` : `Engine=${result.engine}; categorizer=${categorized.categorizer}.${noteBit}`;
1118
+ return { content, sources, truncated };
1119
+ } catch (error) {
1120
+ return {
1121
+ sources: [],
1122
+ truncated: false,
1123
+ content: `search_failed: ${error instanceof Error ? error.message : String(error)}`
1124
+ };
1125
+ }
1126
+ }
1127
+ });
1128
+ }
1129
+
521
1130
  // src/host/index.ts
522
1131
  var name = PLUGIN;
523
1132
  var inject = ["tools"];
524
1133
  function errorMessage(error) {
525
1134
  return error instanceof Error ? error.message : String(error);
526
1135
  }
527
- function apply(ctx) {
1136
+ function toolAlreadyRegistered(ctx, toolName) {
528
1137
  try {
529
- const disposeTools = registerDiscoveryTools(ctx);
530
- ctx.effect(() => disposeTools, "web-discovery: tools");
531
- } catch (error) {
532
- ctx.logger?.(PLUGIN).warn("tool registration failed (continuing without it): %s", errorMessage(error));
1138
+ const tools = ctx.tools;
1139
+ return typeof tools?.get === "function" && !!tools.get(toolName);
1140
+ } catch {
1141
+ return false;
1142
+ }
1143
+ }
1144
+ function aliasWebSearchEnabled() {
1145
+ const v = (process.env.ALIAS_WEB_SEARCH ?? "").trim().toLowerCase();
1146
+ return v === "1" || v === "true" || v === "yes" || v === "on";
1147
+ }
1148
+ function apply(ctx) {
1149
+ if (!toolAlreadyRegistered(ctx, "discovery_search")) {
1150
+ try {
1151
+ const disposeTools = registerDiscoveryTools(ctx);
1152
+ ctx.effect(() => disposeTools, "web-discovery: tools");
1153
+ } catch (error) {
1154
+ ctx.logger?.(PLUGIN).warn("tool registration failed (continuing without it): %s", errorMessage(error));
1155
+ }
1156
+ }
1157
+ if (aliasWebSearchEnabled() && !toolAlreadyRegistered(ctx, "web_search")) {
1158
+ try {
1159
+ const disposeAlias = registerWebSearchAlias(ctx);
1160
+ ctx.effect(() => disposeAlias, "web-discovery: web_search alias");
1161
+ } catch (error) {
1162
+ ctx.logger?.(PLUGIN).warn("web_search alias registration failed: %s", errorMessage(error));
1163
+ }
533
1164
  }
534
1165
  }
535
1166
  export {
536
1167
  PLUGIN,
537
1168
  VERSION,
538
1169
  apply,
1170
+ createDiscoveryPort,
539
1171
  inject,
540
- name
1172
+ name,
1173
+ registerDiscoveryTools,
1174
+ registerWebSearchAlias
541
1175
  };
542
1176
  //# sourceMappingURL=index.js.map