@vessel-agent/web-tools 0.0.0-stage → 2.3.0-beta.2

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.
@@ -0,0 +1,595 @@
1
+ /**
2
+ * 声明式「自定义搜索后端」:用**一段配置**描述一家同类 API,不再为每家写适配器。
3
+ *
4
+ * ## 能力边界(刻意很小,超出就退回专用适配器)
5
+ *
6
+ * 只支持「URL 固定 + 一种鉴权 + 请求体/查询串里的人字形占位符 + 点号路径取结果字段」。
7
+ * **不做表达式语言**:出现 `if` / `map` / `filter` / 数组遍历 / 分页翻页 / 二次请求,
8
+ * 就说明这家不适配声明式,写专用 `SearchProvider` 并说明原因。
9
+ *
10
+ * ## 五条硬约束
11
+ *
12
+ * 1. **占位符只能是字面替换**:`{{query}} {{count}} {{need_content}} {{freshness}}
13
+ * {{site}} {{lang}} {{after}} {{before}}`,没有函数、没有条件。
14
+ * 2. **SSRF**:`url` 来自配置(人可信),但**必须 https**;`http` 只允许 loopback/私网
15
+ * (本地 SearxNG 是合法用途)。**工具入参永远不影响 host**(url 里出现 `{{` 直接拒)。
16
+ * 3. **映射失败要响**:`results_path` 取不到 / 不是数组 / `field_map.url` 全空
17
+ * ⇒ `provider_schema_mismatch`,**绝不返回 0 条当成「没搜到」**。
18
+ * 4. **闸只有一份**:这是普通 `SearchProvider`,走 `runWebSearch`
19
+ * ⇒ 预算 / 配额 / 缓存键(`custom:<id>` + 版本)/ 熔断 / 指标行 / `sk-` 擦除全部复用。
20
+ * 5. **可见性同等**:注册进同一张表,`--tools` 的可用性预检一视同仁。
21
+ *
22
+ * ## 过滤条件的诚实处理
23
+ *
24
+ * 配置里有 `{{site}}` 才支持 `site`,有 `{{lang}}` 才支持 `lang`,有
25
+ * `{{after}}`/`{{before}}`/`{{freshness}}` 才支持日期。**用户给了但映射不了 ⇒
26
+ * `provider_bad_request` 说清楚**,不静默丢掉过滤(丢过滤比报错更坏:结果看着像过滤过)。
27
+ */
28
+
29
+ import { hashKey } from '../cache';
30
+ import { createJsonHttp, type ProviderHttp } from '../provider-http';
31
+ import { isBlockedIpv4Tuple, parseIpv4 } from '../ssrf';
32
+ import { WebFetchError } from '../types';
33
+ import {
34
+ asRecord,
35
+ type ProviderHttpOptions,
36
+ type ProviderHttpResponse,
37
+ type RawSearchEntry,
38
+ type SearchHit,
39
+ type SearchProvider,
40
+ type SearchQuery,
41
+ } from './provider';
42
+
43
+ /** 注册 id 前缀:`custom:bocha`、`custom:searx` */
44
+ export const CUSTOM_PRESET_PREFIX = 'custom:';
45
+
46
+ /** 占位符(**只有这些**;不做表达式语言) */
47
+ export const CUSTOM_PLACEHOLDERS = [
48
+ 'query',
49
+ 'count',
50
+ 'need_content',
51
+ 'freshness',
52
+ 'site',
53
+ 'lang',
54
+ 'after',
55
+ 'before',
56
+ ] as const;
57
+
58
+ export type CustomPlaceholder = (typeof CUSTOM_PLACEHOLDERS)[number];
59
+
60
+ /** `field_map`:只映射 `SearchHit` **真有**的字段(没有 destination 的一律不收,免得成哑配置) */
61
+ export interface CustomFieldMap {
62
+ title?: string;
63
+ url: string;
64
+ summary?: string;
65
+ content?: string;
66
+ date?: string;
67
+ }
68
+
69
+ export interface CustomSearchSpec {
70
+ /** 短名 ⇒ 注册为 `custom:<id>` */
71
+ id: string;
72
+ request: {
73
+ url: string;
74
+ method: 'POST' | 'GET';
75
+ /** query 放 body 还是放 URL 查询串 */
76
+ queryIn: 'body' | 'query';
77
+ body: Record<string, unknown>;
78
+ headers: Record<string, string>;
79
+ };
80
+ auth: {
81
+ style: 'bearer' | 'header' | 'query';
82
+ /** `header`/`query` 用:头名或参数名 */
83
+ headerName?: string;
84
+ keyEnv: string;
85
+ };
86
+ response: {
87
+ /** 点号路径,例如 `data.webPages.value` */
88
+ resultsPath: string;
89
+ fieldMap: CustomFieldMap;
90
+ };
91
+ limits: {
92
+ /** 上游条数上限 */
93
+ maxCount?: number;
94
+ /** 声明「这套配置必须用到的占位符」;缺了就是配置错误(不是运行期才发现) */
95
+ requires: CustomPlaceholder[];
96
+ };
97
+ }
98
+
99
+ // ---------------------------------------------------------------- 配置解析
100
+
101
+ /** 递归把 camelCase 键转成 snake_case(配置层会把 `plugins[].config` 整棵树转成 camel) */
102
+ function deepSnakeKeys(value: unknown): unknown {
103
+ if (Array.isArray(value)) return value.map((item) => deepSnakeKeys(item));
104
+ if (value === null || typeof value !== 'object') return value;
105
+ const out: Record<string, unknown> = {};
106
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
107
+ const snake = key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
108
+ out[snake] = deepSnakeKeys(item);
109
+ }
110
+ return out;
111
+ }
112
+
113
+ function requireString(value: unknown, where: string): string {
114
+ if (typeof value !== 'string' || value.trim() === '') {
115
+ throw new Error(`web-tools: ${where} 必须是非空字符串`);
116
+ }
117
+ return value.trim();
118
+ }
119
+
120
+ function readStringMap(value: unknown, where: string): Record<string, string> {
121
+ if (value === undefined) return {};
122
+ const record = asRecord(deepSnakeKeys(value));
123
+ const out: Record<string, string> = {};
124
+ for (const [key, item] of Object.entries(record)) {
125
+ if (typeof item !== 'string') throw new Error(`web-tools: ${where}.${key} 必须是字符串`);
126
+ out[key] = item;
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /** `https`;`http` 只允许 loopback/私网(本地 SearxNG 等),**url 里不许有占位符** */
132
+ export function assertCustomUrl(raw: string, where: string): string {
133
+ if (raw.includes('{{')) {
134
+ throw new Error(
135
+ `web-tools: ${where}.url 不允许占位符 —— host 只能来自配置,工具入参永远不能影响 host`,
136
+ );
137
+ }
138
+ let parsed: URL;
139
+ try {
140
+ parsed = new URL(raw);
141
+ } catch {
142
+ throw new Error(`web-tools: ${where}.url 不是合法 URL`);
143
+ }
144
+ if (parsed.protocol === 'https:') return parsed.href;
145
+ if (parsed.protocol !== 'http:') {
146
+ throw new Error(`web-tools: ${where}.url 只支持 http(s),收到 ${parsed.protocol}`);
147
+ }
148
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
149
+ const loopback =
150
+ host === 'localhost' ||
151
+ host.endsWith('.localhost') ||
152
+ host === '::1' ||
153
+ host === '0.0.0.0' ||
154
+ host.endsWith('.local') ||
155
+ host.endsWith('.internal') ||
156
+ // 不带点的裸主机名 = 内网机器(Docker/K8s service、searx 之类)
157
+ !host.includes('.');
158
+ const ipv4 = parseIpv4(host);
159
+ const privateV4 = ipv4 !== null && isBlockedIpv4Tuple(ipv4);
160
+ if (loopback || privateV4) return parsed.href;
161
+ throw new Error(
162
+ `web-tools: ${where}.url 用 http 只允许 loopback/私网(例:http://127.0.0.1:8080/search),收到 ${host};公网请用 https`,
163
+ );
164
+ }
165
+
166
+ const CUSTOM_ID = /^[a-z0-9][a-z0-9_-]{0,31}$/;
167
+
168
+ /** 解析并校验一段自定义后端配置(**配置错就在这里抛**,不留到运行期) */
169
+ export function parseCustomSearchSpec(raw: unknown, where: string): CustomSearchSpec {
170
+ const spec = asRecord(deepSnakeKeys(raw));
171
+
172
+ const id = requireString(spec.id, `${where}.id`);
173
+ if (!CUSTOM_ID.test(id)) {
174
+ throw new Error(`web-tools: ${where}.id 只允许小写字母/数字/-/_(≤32 字符),收到 ${id}`);
175
+ }
176
+ if (
177
+ id === 'deepseek' ||
178
+ id === 'tavily' ||
179
+ id === 'serper' ||
180
+ id === 'custom' ||
181
+ id === 'bocha'
182
+ ) {
183
+ throw new Error(
184
+ `web-tools: ${where}.id=${id} 与内置后端重名(bocha 是内置预设,用 search_provider: bocha 选中它),换个名字`,
185
+ );
186
+ }
187
+
188
+ const request = asRecord(spec.request);
189
+ const url = assertCustomUrl(
190
+ requireString(request.url, `${where}.request.url`),
191
+ `${where}.request`,
192
+ );
193
+ const methodRaw = requireString(
194
+ request.method ?? 'POST',
195
+ `${where}.request.method`,
196
+ ).toUpperCase();
197
+ if (methodRaw !== 'POST' && methodRaw !== 'GET') {
198
+ throw new Error(`web-tools: ${where}.request.method 只支持 POST | GET`);
199
+ }
200
+ const queryInRaw = requireString(request.query_in ?? 'body', `${where}.request.query_in`);
201
+ if (queryInRaw !== 'body' && queryInRaw !== 'query') {
202
+ throw new Error(`web-tools: ${where}.request.query_in 只支持 body | query`);
203
+ }
204
+ if (methodRaw === 'GET' && queryInRaw === 'body') {
205
+ throw new Error(`web-tools: ${where}.request: GET 必须配 query_in: query(GET 没有 body)`);
206
+ }
207
+
208
+ const auth = asRecord(spec.auth);
209
+ const styleRaw = requireString(auth.style ?? 'bearer', `${where}.auth.style`);
210
+ if (styleRaw !== 'bearer' && styleRaw !== 'header' && styleRaw !== 'query') {
211
+ throw new Error(`web-tools: ${where}.auth.style 只支持 bearer | header | query`);
212
+ }
213
+ const headerName =
214
+ styleRaw === 'bearer'
215
+ ? undefined
216
+ : requireString(auth.header_name, `${where}.auth.header_name`);
217
+ const keyEnv = requireString(auth.key_env, `${where}.auth.key_env`);
218
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(keyEnv)) {
219
+ throw new Error(`web-tools: ${where}.auth.key_env 必须是环境变量名(只存名字,不存值)`);
220
+ }
221
+
222
+ const response = asRecord(spec.response);
223
+ const resultsPath = requireString(response.results_path, `${where}.response.results_path`);
224
+ const rawFieldMap = asRecord(response.field_map);
225
+ const allowedFields = ['title', 'url', 'summary', 'content', 'date'];
226
+ for (const key of Object.keys(rawFieldMap)) {
227
+ if (!allowedFields.includes(key)) {
228
+ throw new Error(
229
+ `web-tools: ${where}.response.field_map.${key} 无处安放:SearchHit 只有 ${allowedFields.join(' / ')}` +
230
+ `(site/icon 之类要么没有 destination,要么会变成「拿域名冒充权威度」,不收)`,
231
+ );
232
+ }
233
+ }
234
+ const fieldMap: CustomFieldMap = {
235
+ url: requireString(rawFieldMap.url, `${where}.response.field_map.url`),
236
+ ...(typeof rawFieldMap.title === 'string' ? { title: rawFieldMap.title } : {}),
237
+ ...(typeof rawFieldMap.summary === 'string' ? { summary: rawFieldMap.summary } : {}),
238
+ ...(typeof rawFieldMap.content === 'string' ? { content: rawFieldMap.content } : {}),
239
+ ...(typeof rawFieldMap.date === 'string' ? { date: rawFieldMap.date } : {}),
240
+ };
241
+
242
+ const limits = asRecord(spec.limits);
243
+ const rawMax = limits.max_count;
244
+ const maxCount =
245
+ rawMax === undefined
246
+ ? undefined
247
+ : typeof rawMax === 'number' && rawMax > 0
248
+ ? Math.floor(rawMax)
249
+ : undefined;
250
+ if (rawMax !== undefined && maxCount === undefined) {
251
+ throw new Error(`web-tools: ${where}.limits.max_count 必须是正整数`);
252
+ }
253
+ const requiresRaw = limits.requires ?? [];
254
+ if (!Array.isArray(requiresRaw))
255
+ throw new Error(`web-tools: ${where}.limits.requires 必须是数组`);
256
+ const requires: CustomPlaceholder[] = [];
257
+ for (const item of requiresRaw) {
258
+ if (typeof item !== 'string' || !CUSTOM_PLACEHOLDERS.includes(item as CustomPlaceholder)) {
259
+ throw new Error(
260
+ `web-tools: ${where}.limits.requires 只接受 ${CUSTOM_PLACEHOLDERS.join(' / ')},收到 ${String(item)}`,
261
+ );
262
+ }
263
+ requires.push(item as CustomPlaceholder);
264
+ }
265
+
266
+ const body = asRecord(deepSnakeKeys(request.body ?? {}));
267
+ const headers = readStringMap(request.headers, `${where}.request.headers`);
268
+
269
+ // requires 是「这套配置必须用到这些占位符」:声明了却没写 = 配置错,不留到运行期
270
+ const used = collectPlaceholders({ body, headers });
271
+ for (const name of requires) {
272
+ if (!used.has(name)) {
273
+ throw new Error(
274
+ `web-tools: ${where}.limits.requires 声明了 ${name},但 request.body/headers 里没有 {{${name}}} 占位符`,
275
+ );
276
+ }
277
+ }
278
+
279
+ return {
280
+ id,
281
+ request: { url, method: methodRaw, queryIn: queryInRaw, body, headers },
282
+ auth: { style: styleRaw, ...(headerName !== undefined ? { headerName } : {}), keyEnv },
283
+ response: { resultsPath, fieldMap },
284
+ limits: { ...(maxCount !== undefined ? { maxCount } : {}), requires },
285
+ };
286
+ }
287
+
288
+ // ---------------------------------------------------------------- 占位符
289
+
290
+ function collectPlaceholders(spec: {
291
+ body: unknown;
292
+ headers: Record<string, string>;
293
+ }): Set<CustomPlaceholder> {
294
+ const used = new Set<CustomPlaceholder>();
295
+ const scan = (value: unknown): void => {
296
+ if (typeof value === 'string') {
297
+ for (const match of value.matchAll(/\{\{([a-z_]+)\}\}/g)) {
298
+ const name = match[1] ?? '';
299
+ if (CUSTOM_PLACEHOLDERS.includes(name as CustomPlaceholder))
300
+ used.add(name as CustomPlaceholder);
301
+ }
302
+ return;
303
+ }
304
+ if (Array.isArray(value)) {
305
+ for (const item of value) scan(item);
306
+ return;
307
+ }
308
+ if (value !== null && typeof value === 'object') {
309
+ for (const item of Object.values(value as Record<string, unknown>)) scan(item);
310
+ }
311
+ };
312
+ scan(spec.body);
313
+ scan(spec.headers);
314
+ return used;
315
+ }
316
+
317
+ /** `{{freshness}}` = `after..before`(两端都给);都不给 = `noLimit`;只给一端 = 不可用 */
318
+ export function freshnessValue(query: SearchQuery): string | undefined {
319
+ const iso = (value: string | undefined): string | undefined =>
320
+ value !== undefined && /^\d{4}-\d{2}-\d{2}$/.test(value) ? value : undefined;
321
+ const after = iso(query.after);
322
+ const before = iso(query.before);
323
+ if (after !== undefined && before !== undefined) return `${after}..${before}`;
324
+ if (query.after === undefined && query.before === undefined) return 'noLimit';
325
+ return undefined;
326
+ }
327
+
328
+ type PlaceholderContext = Partial<Record<CustomPlaceholder, string | number | boolean>>;
329
+
330
+ function contextFor(query: SearchQuery): PlaceholderContext {
331
+ const freshness = freshnessValue(query);
332
+ return {
333
+ query: query.query,
334
+ count: query.count,
335
+ need_content: query.needContent,
336
+ ...(freshness !== undefined ? { freshness } : {}),
337
+ ...(query.site !== undefined ? { site: query.site } : {}),
338
+ ...(query.lang !== undefined ? { lang: query.lang } : {}),
339
+ ...(query.after !== undefined ? { after: query.after } : {}),
340
+ ...(query.before !== undefined ? { before: query.before } : {}),
341
+ };
342
+ }
343
+
344
+ const WHOLE_PLACEHOLDER = /^\{\{([a-z_]+)\}\}$/;
345
+
346
+ /**
347
+ * 替换占位符(**只做字面替换**):
348
+ * - 整个值就是一个占位符 ⇒ 保留原始类型(`"{{count}}"` → 数字,`"{{need_content}}"` → 布尔);
349
+ * - 占位符嵌在字符串里 ⇒ 拼字符串,缺值就整个键丢掉;
350
+ * - 缺值的键**整条不出现**(不写 `null`,也不写空串——那会让上游以为我们传了东西)。
351
+ */
352
+ function substitute(value: unknown, context: PlaceholderContext): unknown {
353
+ if (typeof value === 'string') {
354
+ const whole = WHOLE_PLACEHOLDER.exec(value);
355
+ if (whole !== null) return context[whole[1] as CustomPlaceholder];
356
+ let missing = false;
357
+ const replaced = value.replace(/\{\{([a-z_]+)\}\}/g, (_match, name: string) => {
358
+ const resolved = context[name as CustomPlaceholder];
359
+ if (resolved === undefined) {
360
+ missing = true;
361
+ return '';
362
+ }
363
+ return String(resolved);
364
+ });
365
+ return missing ? undefined : replaced;
366
+ }
367
+ if (Array.isArray(value)) {
368
+ const items = value
369
+ .map((item) => substitute(item, context))
370
+ .filter((item) => item !== undefined);
371
+ return items;
372
+ }
373
+ if (value !== null && typeof value === 'object') {
374
+ const out: Record<string, unknown> = {};
375
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
376
+ const resolved = substitute(item, context);
377
+ if (resolved !== undefined) out[key] = resolved;
378
+ }
379
+ return out;
380
+ }
381
+ return value;
382
+ }
383
+
384
+ // ---------------------------------------------------------------- 结果解析
385
+
386
+ /** 点号路径取值(`data.webPages.value`;支持数组下标 `items.0.title`) */
387
+ export function resolvePath(root: unknown, path: string): unknown {
388
+ let current: unknown = root;
389
+ for (const segment of path.split('.')) {
390
+ if (segment === '') continue;
391
+ if (Array.isArray(current)) {
392
+ const index = Number(segment);
393
+ if (!Number.isInteger(index)) return undefined;
394
+ current = current[index];
395
+ continue;
396
+ }
397
+ const record = asRecord(current);
398
+ if (!(segment in record)) return undefined;
399
+ current = record[segment];
400
+ }
401
+ return current;
402
+ }
403
+
404
+ // ---------------------------------------------------------------- provider 工厂
405
+
406
+ /** 这套配置的版本(进缓存键):改任何一个字段 ⇒ 旧缓存自动失效 */
407
+ function specVersion(spec: CustomSearchSpec): string {
408
+ return `1.${hashKey([spec]).slice(0, 8)}`;
409
+ }
410
+
411
+ /** 把一段声明式配置变成普通 `SearchProvider`(闸/缓存/指标全部复用共用层) */
412
+ export function createCustomProvider(
413
+ spec: CustomSearchSpec,
414
+ options: { id?: string } = {},
415
+ ): SearchProvider {
416
+ const providerId = options.id ?? `${CUSTOM_PRESET_PREFIX}${spec.id}`;
417
+ const used = collectPlaceholders({ body: spec.request.body, headers: spec.request.headers });
418
+ const supportsDates = used.has('after') || used.has('before') || used.has('freshness');
419
+ return {
420
+ // 内置预设用短名(`bocha`,用户不必记新名字);用户自定义一律 `custom:<id>`
421
+ id: providerId,
422
+ version: specVersion(spec),
423
+ billed: true,
424
+ requiresKey: true,
425
+ keyEnv: spec.auth.keyEnv,
426
+ ...(spec.limits.maxCount !== undefined ? { maxCount: spec.limits.maxCount } : {}),
427
+
428
+ // 声明式后端不替上游「翻译语法」:查询串原样,过滤条件走 body/headers
429
+ renderQuery: (query: SearchQuery): string => query.query,
430
+
431
+ /**
432
+ * 哪些过滤**这套配置表达不了**(用户给了才算):共用的渲染层会把它写进
433
+ * 信封的 `filters_ignored:`。省略仍然发生(映射规则不变),但不再静默。
434
+ */
435
+ unsupportedFilters(query: SearchQuery): string[] {
436
+ const ignored: string[] = [];
437
+ if (query.site !== undefined && !used.has('site')) ignored.push('site');
438
+ if (query.lang !== undefined && !used.has('lang')) ignored.push('lang');
439
+ if (query.after !== undefined || query.before !== undefined) {
440
+ if (!supportsDates) ignored.push('after/before');
441
+ else if (contextFor(query).freshness === undefined) ignored.push('after/before 单边');
442
+ }
443
+ return ignored;
444
+ },
445
+
446
+ createHttp(options: ProviderHttpOptions): ProviderHttp {
447
+ const headers =
448
+ spec.auth.style === 'bearer'
449
+ ? (key: string) => ({ authorization: `Bearer ${key}` })
450
+ : spec.auth.style === 'header'
451
+ ? (key: string) => ({ [spec.auth.headerName ?? 'x-api-key']: key })
452
+ : undefined;
453
+ return createJsonHttp({
454
+ config: options.config,
455
+ keyKind: 'search',
456
+ keyEnvName: options.keyEnvName,
457
+ endpoint: spec.request.url,
458
+ ...(headers !== undefined ? { authHeaders: headers } : {}),
459
+ ...(spec.auth.style === 'query'
460
+ ? { authQuery: (key: string) => ({ [spec.auth.headerName ?? 'key']: key }) }
461
+ : {}),
462
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
463
+ ...(options.deps !== undefined ? { deps: options.deps } : {}),
464
+ backoff: options.backoff,
465
+ });
466
+ },
467
+
468
+ async call(
469
+ http: ProviderHttp,
470
+ query: SearchQuery,
471
+ renderedQuery: string,
472
+ ): Promise<ProviderHttpResponse> {
473
+ // 过滤条件:**能表达就表达;表达不了照常返回,但如实报告**(信封 `filters_ignored:`)。
474
+ // 纯省略 = 静默变宽(用户以为过滤了、其实全网);硬报错 = 太脆(模型得多一轮才知道)。
475
+ // 所以选「照常返回 + 显式披露」;底层仍然是「占位符解析为空 ⇒ 整条键省略」,
476
+ // 不需要表达式语言——披露是渲染层的一行事实,不是映射逻辑。
477
+ const context = contextFor({ ...query, query: renderedQuery });
478
+
479
+ const resolvedBody = substitute(spec.request.body, context);
480
+ const resolvedHeaders = substitute(spec.request.headers, context);
481
+ const asQuery = spec.request.queryIn === 'query';
482
+
483
+ return http.postJson({
484
+ path: '',
485
+ method: spec.request.method,
486
+ body: asQuery ? undefined : resolvedBody,
487
+ ...(asQuery ? { query: stringifyParams(resolvedBody) } : {}),
488
+ hint: '检查 query 是否为空、占位符的值是否合法;声明式后端的报错来自上游',
489
+ ...(Object.keys(resolvedHeaders as Record<string, string>).length > 0
490
+ ? { headers: resolvedHeaders as Record<string, string> }
491
+ : {}),
492
+ });
493
+ },
494
+
495
+ parseEntries(payload: unknown): RawSearchEntry[] {
496
+ const entries = resolvePath(payload, spec.response.resultsPath);
497
+ if (!Array.isArray(entries)) {
498
+ // 这里**绝不能**返回 []:0 条 = 「上游说没有」,形状不对 = 「配置和上游不一致」
499
+ throw new WebFetchError(
500
+ 'provider_schema_mismatch',
501
+ `自定义后端 ${CUSTOM_PRESET_PREFIX}${spec.id} 的 results_path=${spec.response.resultsPath} 取不到数组` +
502
+ `(实际类型:${entries === undefined ? 'undefined(路径不存在)' : typeof entries});` +
503
+ '检查 response.results_path 或上游是否改了响应形状',
504
+ );
505
+ }
506
+ return entries.map((item) => asRecord(item));
507
+ },
508
+
509
+ normalize(entry: RawSearchEntry): SearchHit | null {
510
+ const map = spec.response.fieldMap;
511
+ const rawUrl = pickString(entry, map.url);
512
+ if (rawUrl === undefined) return null;
513
+ let parsed: URL;
514
+ try {
515
+ parsed = new URL(rawUrl);
516
+ } catch {
517
+ return null;
518
+ }
519
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
520
+ const summary = map.summary !== undefined ? pickString(entry, map.summary) : undefined;
521
+ const content = map.content !== undefined ? pickString(entry, map.content) : undefined;
522
+ const date = map.date !== undefined ? pickString(entry, map.date) : undefined;
523
+ const title = map.title !== undefined ? pickString(entry, map.title) : undefined;
524
+ return {
525
+ title: title ?? '',
526
+ url: parsed.href,
527
+ summary: summary ?? '',
528
+ ...(content !== undefined && content !== summary ? { content } : {}),
529
+ ...(date !== undefined ? { date } : {}),
530
+ };
531
+ },
532
+ };
533
+ }
534
+
535
+ /** GET/查询串模式:值一律转字符串(`URLSearchParams` 只认字符串) */
536
+ function stringifyParams(value: unknown): Record<string, string> {
537
+ const out: Record<string, string> = {};
538
+ for (const [key, item] of Object.entries(asRecord(value))) {
539
+ if (item === undefined || item === null) continue;
540
+ out[key] = typeof item === 'string' ? item : JSON.stringify(item);
541
+ }
542
+ return out;
543
+ }
544
+
545
+ // ---------------------------------------------------------------- 内置预设
546
+
547
+ /**
548
+ * Bocha 的内置预设(`search_provider: custom:bocha` 即可用,零配置)。
549
+ *
550
+ * 字段对应:`name`→title、`url`→url、`snippet`→summary、`summary`(`summary: true` 才回)
551
+ * →content、`datePublished`→date;`siteName`/`siteIcon`/`image` **无处安放就不映射**
552
+ * (`field_map` 里干脆没有它们——写进来会变成哑配置)。
553
+ */
554
+ export const BOCHA_PRESET: CustomSearchSpec = {
555
+ id: 'bocha',
556
+ request: {
557
+ url: 'https://api.bocha.cn/v1/web-search',
558
+ method: 'POST',
559
+ queryIn: 'body',
560
+ body: {
561
+ query: '{{query}}',
562
+ summary: '{{need_content}}',
563
+ freshness: '{{freshness}}',
564
+ count: '{{count}}',
565
+ },
566
+ headers: {},
567
+ },
568
+ auth: { style: 'bearer', keyEnv: 'BOCHAAI_SEARCH_API_KEY' },
569
+ response: {
570
+ resultsPath: 'data.webPages.value',
571
+ fieldMap: {
572
+ title: 'name',
573
+ url: 'url',
574
+ summary: 'snippet',
575
+ content: 'summary',
576
+ date: 'datePublished',
577
+ },
578
+ },
579
+ limits: { maxCount: 50, requires: ['freshness'] },
580
+ };
581
+
582
+ /** `field_map` 的取值:点号路径 + 只认非空字符串(数字/布尔不硬转,免得编数据) */
583
+ function pickString(entry: RawSearchEntry, path: string): string | undefined {
584
+ const value = resolvePath(entry, path);
585
+ if (typeof value === 'string' && value.trim() !== '') return value.trim();
586
+ return undefined;
587
+ }
588
+
589
+ /** 注册一组自定义后端(同 id 后注册者胜:用户配置覆盖内置预设) */
590
+ export function registerCustomSearchProviders(
591
+ specs: readonly CustomSearchSpec[],
592
+ register: (provider: SearchProvider) => void,
593
+ ): void {
594
+ for (const spec of specs) register(createCustomProvider(spec));
595
+ }