@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,725 @@
1
+ /**
2
+ * `web_search` 的共用层(0.56 P0)。
3
+ *
4
+ * 一次调用的顺序(**拒绝要快、且不花钱**,设计 §5.5):
5
+ * 参数校验 → 缺 key → 缓存 → 熔断 → 每 run 配额 → 日上限 → 限流 → 发请求 → 归一 → 预算 → 定界渲染
6
+ * 前五步任何一步拒绝都**不产生网络往返**;缓存命中不算计费调用,所以放在配额之前
7
+ * (否则「今天到顶」会把已有的缓存也给挡掉,白白多花一次钱)。
8
+ *
9
+ * 「只数会被计费的调用」:search 只有**结果非空**才计费 ⇒ 空结果是
10
+ * `ok: true` + `results: 0`(不是 error,模型不会为同一 query 重试三次)。
11
+ *
12
+ * ⚠️ 出口预算的唯一口径是 token(`estimateTokens`),不是条数:见 `planSearchBudget`。
13
+ */
14
+
15
+ import { estimateTokens } from '../budget';
16
+ import { hashKey, type TtlLruCache } from '../cache';
17
+ import type { WebToolsConfig } from '../config';
18
+ import type { DeepSeekDeps } from '../deepseek-client';
19
+ import { type CostController, type CostSnapshot, type CostTicket, emitMetric } from '../limits';
20
+ import { createDeepSeekHttp } from '../provider-http';
21
+ import {
22
+ renderSearchFailure,
23
+ renderSearchResult,
24
+ type SearchRenderHit,
25
+ searchEnvelopeTokens,
26
+ truncateWithLabel,
27
+ } from '../render';
28
+ import { missingKeyMessage, readKey } from '../secrets';
29
+ import { WebFetchError, type WebToolErrorCode } from '../types';
30
+ import {
31
+ DEFAULT_SEARCH_PROVIDER_ID,
32
+ getSearchProvider,
33
+ listSearchProviderEntries,
34
+ listSearchProviders,
35
+ type ProviderHttp,
36
+ type ProviderHttpOptions,
37
+ type SearchHit,
38
+ type SearchProvider,
39
+ type SearchQuery,
40
+ } from './provider';
41
+
42
+ /** 缺省返回条数(schema 默认值同此) */
43
+ export const DEFAULT_SEARCH_COUNT = 5;
44
+ /** 每条摘要的保底预算:低于它就减条数,而不是把摘要压成一行(设计 §4.2) */
45
+ export const MIN_SUMMARY_CHARS = 300;
46
+
47
+ export interface SearchDeps {
48
+ deepseek?: DeepSeekDeps;
49
+ /** 注入时钟(真机脚本用;缺省 Date.now) */
50
+ now?: () => number;
51
+ }
52
+
53
+ /** 缓存里存的是**归一后的条目**,不是渲染后的字符串(否则 detail 一变就串味) */
54
+ export interface SearchCacheEntry {
55
+ providerId: string;
56
+ providerVersion: string;
57
+ hits: SearchHit[];
58
+ /** 上游真实返回条数(可能大于渲染条数) */
59
+ upstreamCount: number;
60
+ fetchedAt: string;
61
+ }
62
+
63
+ export interface WebSearchRun {
64
+ config: WebToolsConfig;
65
+ cost: CostController;
66
+ cache: TtlLruCache<SearchCacheEntry>;
67
+ deps: SearchDeps;
68
+ /** 每 run 配额的键(run_id 优先,退到 session_id) */
69
+ runKey: string;
70
+ signal?: AbortSignal;
71
+ }
72
+
73
+ // ---------------------------------------------------------------- 参数校验
74
+
75
+ /** 行首/空白后的 `site:` / `-site:` / `lang:` / `after:` / `before:` 一律拒(设计 §2.1) */
76
+ const QUERY_SYNTAX_PATTERN = /(^|\s)-?(site|lang|after|before):/i;
77
+ const SITE_PATTERN = /^[a-z0-9.-]+$/;
78
+ const LANG_PATTERN = /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/;
79
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
80
+
81
+ const KNOWN_SEARCH_KEYS = new Set([
82
+ 'query',
83
+ 'count',
84
+ 'need_content',
85
+ 'detail',
86
+ 'site',
87
+ 'lang',
88
+ 'after',
89
+ 'before',
90
+ ]);
91
+
92
+ function invalid(message: string): never {
93
+ throw new WebFetchError('invalid_input', message);
94
+ }
95
+
96
+ /** trim + 内部连续空白折叠为 1 个空格;**不改大小写、不做全半角变换** */
97
+ function normalizeQueryText(raw: string): string {
98
+ return raw.trim().replace(/\s+/g, ' ');
99
+ }
100
+
101
+ function isRealDate(value: string): boolean {
102
+ if (!DATE_PATTERN.test(value)) return false;
103
+ const year = Number(value.slice(0, 4));
104
+ const month = Number(value.slice(5, 7));
105
+ const day = Number(value.slice(8, 10));
106
+ if (year < 1970 || year > 2100) return false;
107
+ const date = new Date(Date.UTC(year, month - 1, day));
108
+ return (
109
+ date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
110
+ );
111
+ }
112
+
113
+ /** 校验工具参数 → 归一后的 `SearchQuery`;非法一律 `invalid_input`(不「帮你修」) */
114
+ export function parseSearchArgs(args: unknown, config: WebToolsConfig): SearchQuery {
115
+ const record =
116
+ args !== null && typeof args === 'object' && !Array.isArray(args)
117
+ ? (args as Record<string, unknown>)
118
+ : {};
119
+
120
+ for (const key of Object.keys(record)) {
121
+ if (!KNOWN_SEARCH_KEYS.has(key)) invalid(`不认识的参数:${key}`);
122
+ }
123
+
124
+ const rawQuery = record.query;
125
+ if (typeof rawQuery !== 'string') invalid('query 必须是字符串');
126
+ const trimmed = rawQuery.trim();
127
+ if (trimmed === '') invalid('query 不能为空');
128
+ if (trimmed.length > 128) {
129
+ // 不截断:截断会静默改语义
130
+ invalid(`query 过长(${trimmed.length} > 128 字符);请缩短后重试,本工具不截断 query`);
131
+ }
132
+ if (QUERY_SYNTAX_PATTERN.test(trimmed)) {
133
+ invalid(
134
+ 'query 里不要写搜索语法:请用 site/lang/after/before 参数(query 里只留关键词与原样短语)',
135
+ );
136
+ }
137
+ const query = normalizeQueryText(trimmed);
138
+
139
+ let count = DEFAULT_SEARCH_COUNT;
140
+ if (record.count !== undefined && record.count !== null) {
141
+ if (typeof record.count !== 'number' || !Number.isInteger(record.count)) {
142
+ invalid('count 必须是整数');
143
+ }
144
+ count = Math.min(Math.max(record.count, 1), Math.min(50, config.searchCountMax));
145
+ }
146
+
147
+ let needContent = false;
148
+ if (record.need_content !== undefined && record.need_content !== null) {
149
+ if (typeof record.need_content !== 'boolean') invalid('need_content 必须是布尔值');
150
+ needContent = record.need_content;
151
+ }
152
+
153
+ let detail = config.searchDetailDefault;
154
+ if (record.detail !== undefined && record.detail !== null) {
155
+ const value = typeof record.detail === 'string' ? record.detail.trim().toLowerCase() : '';
156
+ if (value !== 'brief' && value !== 'full') invalid('detail 只支持 brief | full');
157
+ detail = value;
158
+ }
159
+
160
+ const optionalString = (key: string): string | undefined => {
161
+ const value = record[key];
162
+ if (value === undefined || value === null) return undefined;
163
+ if (typeof value !== 'string') invalid(`${key} 必须是字符串`);
164
+ const text = value.trim();
165
+ return text === '' ? undefined : text;
166
+ };
167
+
168
+ const site = optionalString('site');
169
+ if (site !== undefined) {
170
+ if (site.length > 255) invalid('site 过长(>255 字符)');
171
+ if (!SITE_PATTERN.test(site)) {
172
+ invalid('site 必须是主机名形态(小写字母/数字/点/连字符,无 scheme、无路径、无空格)');
173
+ }
174
+ }
175
+
176
+ const lang = optionalString('lang');
177
+ if (lang !== undefined) {
178
+ if (lang.length > 16) invalid('lang 过长(>16 字符)');
179
+ if (!LANG_PATTERN.test(lang)) invalid('lang 形态是 xx 或 xx-YY(例如 zh / en / pt-BR)');
180
+ }
181
+
182
+ const after = optionalString('after');
183
+ if (after !== undefined && !isRealDate(after)) invalid('after 必须是真实日期 YYYY-MM-DD');
184
+ const before = optionalString('before');
185
+ if (before !== undefined && !isRealDate(before)) invalid('before 必须是真实日期 YYYY-MM-DD');
186
+ if (after !== undefined && before !== undefined && after > before) {
187
+ invalid('after 晚于 before(时间窗为空)');
188
+ }
189
+
190
+ return {
191
+ query,
192
+ count,
193
+ needContent,
194
+ detail,
195
+ ...(site !== undefined ? { site } : {}),
196
+ ...(lang !== undefined ? { lang } : {}),
197
+ ...(after !== undefined ? { after } : {}),
198
+ ...(before !== undefined ? { before } : {}),
199
+ };
200
+ }
201
+
202
+ // ---------------------------------------------------------------- 预算分配
203
+
204
+ export interface SearchBudget {
205
+ budgetTokens: number;
206
+ /** 信封成本(头 + 定界 + hint)实测 token */
207
+ envelopeTokens: number;
208
+ /** 每条摘要字符上限 */
209
+ perItemChars: number;
210
+ /** 实际渲染条数(可能被预算收缩) */
211
+ renderedCount: number;
212
+ /** 每条正文上限(`need_content=false` 时 0) */
213
+ contentChars: number;
214
+ }
215
+
216
+ /**
217
+ * token 预算 → 条级字符预算(设计 §4.2 的算法)。
218
+ *
219
+ * 算术自证(全 CJK + 摘要满额的最坏情况,`E ≈ 300`):
220
+ * - `count=5, brief`:`per_item = min(800, floor(3700/5)) = 740` ⇒ 5×740×0.5 + 300 = **2,150 tok**
221
+ * - `count=10, brief`:`per_item = 370` ⇒ 10×370×0.5 + 300 = **2,150 tok**(死按 800 字 = 4,300 ❌)
222
+ * - `count=12, brief`:`per_item` 触 300 下限 ⇒ 12×300×0.5 + 300 = **2,100 tok**(边界)
223
+ * - `count=50, brief`:装不下 ⇒ `rendered = floor(3700 / 150) = 24` ⇒ 24×150 + 300 = **3,900 tok**
224
+ * (死按 50 条 = 7,500 ❌),头条写明「只渲染 24 条」
225
+ */
226
+ export function planSearchBudget(
227
+ query: SearchQuery,
228
+ config: WebToolsConfig,
229
+ envelopeTokens: number,
230
+ ): SearchBudget {
231
+ const budgetTokens =
232
+ query.detail === 'full' ? config.searchBudgetFullTokens : config.searchBudgetBriefTokens;
233
+ const available = Math.max(0, budgetTokens - envelopeTokens);
234
+ const count = Math.max(1, query.count);
235
+ const rawPerItem = Math.floor(available / count);
236
+ const perItemChars = Math.min(
237
+ Math.max(rawPerItem, MIN_SUMMARY_CHARS),
238
+ config.searchSummaryMaxChars,
239
+ );
240
+ const contentChars = query.needContent ? Math.min(config.searchContentMaxChars, perItemChars) : 0;
241
+ // 最坏情况:全 CJK(0.5 token/字符)+ 摘要满额(+ 正文满额)
242
+ const itemTokens = (perItemChars + contentChars) * 0.5;
243
+ let renderedCount = count;
244
+ if (rawPerItem < MIN_SUMMARY_CHARS || itemTokens * count > available) {
245
+ renderedCount = Math.max(1, Math.min(count, Math.floor(available / Math.max(1, itemTokens))));
246
+ }
247
+ return { budgetTokens, envelopeTokens, perItemChars, renderedCount, contentChars };
248
+ }
249
+
250
+ /** 把归一后的条目按预算渲染(摘要/正文各自截断,带业务标记) */
251
+ export function renderHits(hits: readonly SearchHit[], budget: SearchBudget): SearchRenderHit[] {
252
+ const out: SearchRenderHit[] = [];
253
+ for (const hit of hits.slice(0, budget.renderedCount)) {
254
+ const summary = truncateWithLabel(hit.summary, budget.perItemChars, '摘要');
255
+ const rendered: SearchRenderHit = {
256
+ title: hit.title,
257
+ url: hit.url,
258
+ summary: summary.text,
259
+ ...(hit.date !== undefined ? { date: hit.date } : {}),
260
+ ...(hit.authority !== undefined ? { authority: hit.authority } : {}),
261
+ };
262
+ if (budget.contentChars > 0 && hit.content !== undefined) {
263
+ rendered.content = truncateWithLabel(
264
+ hit.content,
265
+ budget.contentChars,
266
+ '正文',
267
+ ',用 web_fetch 取全文',
268
+ ).text;
269
+ }
270
+ out.push(rendered);
271
+ }
272
+ return out;
273
+ }
274
+
275
+ // ---------------------------------------------------------------- 选后端
276
+
277
+ type EnvLike = Record<string, string | undefined>;
278
+
279
+ /**
280
+ * 这次调用读哪个环境变量名:**配置 `search_key_env` > provider 的 `keyEnv` > `key_env`**。
281
+ *
282
+ * 为什么不直接用 `provider.keyEnv`:用户的 key 可能挂在别的变量名下(CI、多账户),
283
+ * 显式配置必须能盖过 provider 的缺省值——这是「配置优先」在 key 上的同一条规则。
284
+ */
285
+ function keyEnvNameFor(config: WebToolsConfig, provider: SearchProvider): string {
286
+ if (config.searchKeyEnv !== '') return config.searchKeyEnv;
287
+ if (provider.keyEnv !== undefined && provider.keyEnv !== '') return provider.keyEnv;
288
+ return config.keyEnv;
289
+ }
290
+
291
+ function providerHasKey(config: WebToolsConfig, provider: SearchProvider, env: EnvLike): boolean {
292
+ if (!provider.requiresKey) return true;
293
+ return readKey(config, 'search', env, keyEnvNameFor(config, provider)).present;
294
+ }
295
+
296
+ /**
297
+ * 选后端(**纯本地**,不发请求):
298
+ * ① 配置 `search_provider` 显式指定 ⇒ 只用它(未注册 ⇒ `provider_unavailable`);
299
+ * ② `auto`(缺省)⇒ 按**注册顺序**取第一个 key 在位的;
300
+ * ③ 一个 key 都没有 ⇒ `provider_auth_failed`,并把每家要哪个环境变量列出来
301
+ * (不猜、不降级、不发请求)。
302
+ */
303
+ function selectSearchProvider(config: WebToolsConfig, env: EnvLike): SearchProvider {
304
+ if (config.searchProvider !== 'auto') {
305
+ const explicit = getSearchProvider(config.searchProvider);
306
+ if (explicit === undefined) {
307
+ throw new WebFetchError(
308
+ 'provider_unavailable',
309
+ `配置 search_provider=${config.searchProvider} 没有对应的搜索后端;已注册:${listSearchProviders().join(' | ')}`,
310
+ );
311
+ }
312
+ return explicit;
313
+ }
314
+
315
+ const candidates = listSearchProviderEntries();
316
+ if (candidates.length === 0) {
317
+ throw new WebFetchError(
318
+ 'provider_unavailable',
319
+ `没有注册任何搜索后端(连 ${DEFAULT_SEARCH_PROVIDER_ID} 都没有)`,
320
+ );
321
+ }
322
+ for (const candidate of candidates) {
323
+ if (providerHasKey(config, candidate, env)) return candidate;
324
+ }
325
+
326
+ const order = candidates.map((provider) => provider.id).join(' → ');
327
+ const needs = candidates
328
+ .map((provider) => `${provider.id} → ${keyEnvNameFor(config, provider)}`)
329
+ .join('、');
330
+ throw new WebFetchError(
331
+ 'provider_auth_failed',
332
+ `没有可用的搜索后端:按注册顺序(${order})都没有可用的 key。设置其一即可:${needs};` +
333
+ '或用配置 search_provider 指定某一家(本次没有发出任何请求)',
334
+ );
335
+ }
336
+
337
+ /** 每个后端「要哪把 key、现在在不在」——**只有变量名,没有值**,供诊断与工具装配判定 */
338
+ export interface SearchKeyRequirement {
339
+ providerId: string;
340
+ keyEnv: string;
341
+ present: boolean;
342
+ }
343
+
344
+ export interface SearchAvailability {
345
+ /** 现在这个配置下,至少有一个搜索后端能解析到 key */
346
+ available: boolean;
347
+ /** 将会选中的后端(`auto` 时是第一个 key 在位的;不可用时为 undefined) */
348
+ providerId?: string;
349
+ /** 不可用的原因(**不含 key 值**,只含变量名)——写进 debug 行,别让它静默 */
350
+ reason?: string;
351
+ /** 全部在册后端的 key 需求(顺序 = 注册顺序),诊断用 */
352
+ requirements: SearchKeyRequirement[];
353
+ }
354
+
355
+ /**
356
+ * 可用性预检(**纯本地**,不发请求、不读 key 值):
357
+ * 工具装配时用它决定「要不要注册 `web_search`」。
358
+ *
359
+ * 与 `selectSearchProvider` 的区别:那个在调用时抛错(`provider_auth_failed`),
360
+ * 这个在装配时回答「有没有任何一个能用」——同一个判定函数,两种用途,
361
+ * 避免出现「--tools 说有、调用说没有」的两套口径。
362
+ */
363
+ export function searchAvailability(
364
+ config: WebToolsConfig,
365
+ env: EnvLike = process.env,
366
+ ): SearchAvailability {
367
+ const entries = listSearchProviderEntries();
368
+ const requirements: SearchKeyRequirement[] = entries.map((provider) => ({
369
+ providerId: provider.id,
370
+ keyEnv: keyEnvNameFor(config, provider),
371
+ present: provider.requiresKey ? providerHasKey(config, provider, env) : true,
372
+ }));
373
+
374
+ if (config.searchProvider !== 'auto') {
375
+ const explicit = getSearchProvider(config.searchProvider);
376
+ if (explicit === undefined) {
377
+ return {
378
+ available: false,
379
+ reason: `search_provider=${config.searchProvider} 没有对应的后端;在册:${listSearchProviders().join(' | ')}`,
380
+ requirements,
381
+ };
382
+ }
383
+ const requirement = requirements.find((item) => item.providerId === explicit.id);
384
+ if (explicit.requiresKey && requirement !== undefined && !requirement.present) {
385
+ return {
386
+ available: false,
387
+ reason: `search_provider=${explicit.id} 的 key 未设置(${requirement.keyEnv})`,
388
+ requirements,
389
+ };
390
+ }
391
+ return { available: true, providerId: explicit.id, requirements };
392
+ }
393
+
394
+ for (const provider of entries) {
395
+ const requirement = requirements.find((item) => item.providerId === provider.id);
396
+ if (!provider.requiresKey || requirement?.present === true) {
397
+ return { available: true, providerId: provider.id, requirements };
398
+ }
399
+ }
400
+
401
+ return {
402
+ available: false,
403
+ reason: `按注册顺序(${entries.map((provider) => provider.id).join(' → ')})都没有可用的 key:${requirements
404
+ .map((item) => `${item.providerId} → ${item.keyEnv}`)
405
+ .join('、')}`,
406
+ requirements,
407
+ };
408
+ }
409
+
410
+ // ---------------------------------------------------------------- 主流程
411
+
412
+ /** 本地拒绝(未发请求):只释放半开探针,不计也不罚 */
413
+ function isLocalRejection(code: WebToolErrorCode): boolean {
414
+ return code === 'max_uses_exceeded' || code === 'circuit_open' || code === 'invalid_input';
415
+ }
416
+
417
+ /** 4xx 客户端错:不动熔断(是我们的请求不合法,不是服务挂了) */
418
+ function isClientError(code: WebToolErrorCode): boolean {
419
+ return (
420
+ code === 'provider_auth_failed' ||
421
+ code === 'provider_bad_request' ||
422
+ code === 'provider_quota_exhausted' ||
423
+ code === 'endpoint_not_found' ||
424
+ code === 'too_large'
425
+ );
426
+ }
427
+
428
+ function toWebFetchError(error: unknown): WebFetchError {
429
+ if (error instanceof WebFetchError) return error;
430
+ const message = error instanceof Error ? error.message : String(error);
431
+ return new WebFetchError('connect_failed', `搜索失败:${message}`);
432
+ }
433
+
434
+ function sha8(text: string): string {
435
+ return hashKey([text]).slice(0, 8);
436
+ }
437
+
438
+ interface RenderOutcome {
439
+ text: string;
440
+ tokens: number;
441
+ results: number;
442
+ }
443
+
444
+ function renderEntry(
445
+ entry: SearchCacheEntry,
446
+ query: SearchQuery,
447
+ config: WebToolsConfig,
448
+ options: { cached: boolean; cachedAgeMs?: number; filtersIgnored?: string[] },
449
+ ): RenderOutcome {
450
+ // 上游一条都没有 ⇒ 0(这样头条是 `results: 0`,而不是「只渲染 0 条,预算限制」)
451
+ //
452
+ // 否则如实报**上游条数**:只有 `rendered < 上游` 才是预算收缩。写成
453
+ // `max(count, upstream)` 会把「这家上游只给了 2 条」谎报成「我们压掉了预算」
454
+ // ——Tavily/Serper 对小众 query 经常少给,deepseek 也可能。
455
+ const requestedCount = entry.upstreamCount;
456
+ const baseOptions = {
457
+ providerId: entry.providerId,
458
+ query: query.query,
459
+ requestedCount,
460
+ detail: query.detail,
461
+ budgetTokens:
462
+ query.detail === 'full' ? config.searchBudgetFullTokens : config.searchBudgetBriefTokens,
463
+ perItemChars: 0,
464
+ cached: options.cached,
465
+ ...(options.cachedAgeMs !== undefined ? { cachedAgeMs: options.cachedAgeMs } : {}),
466
+ ...(options.filtersIgnored !== undefined && options.filtersIgnored.length > 0
467
+ ? { filtersIgnored: options.filtersIgnored }
468
+ : {}),
469
+ fetchedAt: entry.fetchedAt,
470
+ };
471
+ // 信封成本实测(头 + 定界 + hint),再分配条级预算
472
+ const envelopeTokens = searchEnvelopeTokens({ ...baseOptions, hits: [] });
473
+ const budget = planSearchBudget(query, config, envelopeTokens);
474
+
475
+ const build = (hits: SearchRenderHit[]): string =>
476
+ renderSearchResult({
477
+ ...baseOptions,
478
+ hits,
479
+ requestedCount,
480
+ perItemChars: budget.perItemChars,
481
+ });
482
+
483
+ let rendered = renderHits(entry.hits, budget);
484
+ let text = build(rendered);
485
+ let tokens = estimateTokens(text);
486
+ // 兜底(不依赖上面算术一定对):超预算就从尾部丢条,直到进入预算
487
+ while (tokens > budget.budgetTokens && rendered.length > 0) {
488
+ rendered = rendered.slice(0, -1);
489
+ text = build(rendered);
490
+ tokens = estimateTokens(text);
491
+ }
492
+ return { text, tokens, results: rendered.length };
493
+ }
494
+
495
+ interface SearchMetricInput {
496
+ provider: SearchProvider;
497
+ query: SearchQuery;
498
+ cached: boolean;
499
+ cachedAgeMs?: number;
500
+ results: number;
501
+ outTokens: number;
502
+ latencyMs: number;
503
+ upstreamMs?: number;
504
+ attempts?: number;
505
+ snapshot: CostSnapshot;
506
+ }
507
+
508
+ function emitSearchMetric(input: SearchMetricInput): void {
509
+ emitMetric({
510
+ tool: 'web_search',
511
+ backend: input.provider.id,
512
+ provider_id: input.provider.id,
513
+ query_chars: input.query.query.length,
514
+ query_sha8: sha8(input.query.query),
515
+ count: input.query.count,
516
+ detail: input.query.detail,
517
+ need_content: input.query.needContent,
518
+ cached: input.cached,
519
+ ...(input.cachedAgeMs !== undefined
520
+ ? { cached_age_s: Math.round(input.cachedAgeMs / 1000) }
521
+ : {}),
522
+ results: input.results,
523
+ out_tokens_est: input.outTokens,
524
+ latency_ms: input.latencyMs,
525
+ ...(input.upstreamMs !== undefined ? { upstream_ms: input.upstreamMs } : {}),
526
+ ...(input.attempts !== undefined ? { attempts: input.attempts } : {}),
527
+ breaker_state: input.snapshot.breaker,
528
+ quota_used: input.snapshot.dailyUsed,
529
+ });
530
+ }
531
+
532
+ /** 一次 `web_search` 调用:返回给模型看的文本(成功与失败都不抛) */
533
+ export async function runWebSearch(args: unknown, run: WebSearchRun): Promise<string> {
534
+ const startedAt = Date.now();
535
+ const config = run.config;
536
+ const clock = run.deps.now ?? (() => Date.now());
537
+ let ticket: CostTicket | undefined;
538
+ let query: SearchQuery | undefined;
539
+ let provider: SearchProvider | undefined;
540
+ let attempts: number | undefined;
541
+ let upstreamMs: number | undefined;
542
+
543
+ try {
544
+ // ① 参数
545
+ query = parseSearchArgs(args, config);
546
+ // ② 选后端 + 缺 key:都在本地判,不发请求,不静默降级
547
+ // (选中谁进指标行 `provider_id`,也进结果信封 `backend:`——用户能看见用了哪家)
548
+ const env = run.deps.deepseek?.env ?? process.env;
549
+ const selected: SearchProvider = selectSearchProvider(config, env);
550
+ provider = selected;
551
+ const keyEnvName = keyEnvNameFor(config, selected);
552
+ // 这家表达不了的过滤条件(纯本地判定):信封里如实报 `filters_ignored:`,
553
+ // 因为底层是「占位符为空 ⇒ 键省略」——沉默地变宽比多一行字危险得多。
554
+ const filtersIgnored = selected.unsupportedFilters?.(query) ?? [];
555
+ if (selected.requiresKey) {
556
+ const key = readKey(config, 'search', env, keyEnvName);
557
+ if (!key.present) {
558
+ throw new WebFetchError('provider_auth_failed', missingKeyMessage(key.envName));
559
+ }
560
+ }
561
+
562
+ // 缓存键字段清单(顺序固定;漏一个 = 静默给错内容 + 继续计费):
563
+ // provider_id + provider_version + normalized_query + count + need_content
564
+ // + detail + site + lang + after + before
565
+ const cacheKey = hashKey([
566
+ selected.id,
567
+ selected.version,
568
+ query.query,
569
+ query.count,
570
+ query.needContent,
571
+ query.detail,
572
+ query.site ?? '',
573
+ query.lang ?? '',
574
+ query.after ?? '',
575
+ query.before ?? '',
576
+ ]);
577
+ const cached = run.cache.get(cacheKey);
578
+ if (cached !== undefined) {
579
+ const rendered = renderEntry(cached.value, query, config, {
580
+ cached: true,
581
+ cachedAgeMs: cached.ageMs,
582
+ filtersIgnored,
583
+ });
584
+ emitSearchMetric({
585
+ provider: selected,
586
+ query,
587
+ cached: true,
588
+ cachedAgeMs: cached.ageMs,
589
+ results: rendered.results,
590
+ outTokens: rendered.tokens,
591
+ latencyMs: Date.now() - startedAt,
592
+ snapshot: run.cost.snapshot('search', run.runKey),
593
+ });
594
+ return rendered.text;
595
+ }
596
+
597
+ // ③④⑤ 熔断 / 每 run 配额 / 日上限(前五步拒绝都不产生网络往返)
598
+ if (selected.billed) ticket = await run.cost.acquire('search', run.runKey);
599
+ if (selected.billed) {
600
+ try {
601
+ await run.cost.throttle('search');
602
+ } catch (error) {
603
+ // 本地排队超时不是上游失败:不算进熔断(settle 幂等,外层再 settle 会被忽略)
604
+ ticket?.skipped();
605
+ throw error;
606
+ }
607
+ }
608
+
609
+ // ⑥ 发请求(重试 / 退避 / 错误映射在 ProviderHttp 里)
610
+ // 传输层:provider 自带 `createHttp`(鉴权风格不同,例如 Serper 的 X-API-KEY)就用它;
611
+ // 没带 ⇒ 回落 deepseek 的 Bearer 实现(第一个实现,不代表其他家也长这样)。
612
+ const backoff = (attempt: number, retryAfterMs?: number): number =>
613
+ run.cost.backoffMs(attempt, retryAfterMs);
614
+ const httpOptions: ProviderHttpOptions = {
615
+ config,
616
+ keyEnvName,
617
+ ...(run.signal !== undefined ? { signal: run.signal } : {}),
618
+ ...(run.deps.deepseek !== undefined ? { deps: run.deps.deepseek } : {}),
619
+ backoff,
620
+ };
621
+ const http: ProviderHttp =
622
+ selected.createHttp !== undefined
623
+ ? selected.createHttp(httpOptions)
624
+ : createDeepSeekHttp({
625
+ config,
626
+ keyKind: 'search',
627
+ ...(run.signal !== undefined ? { signal: run.signal } : {}),
628
+ ...(run.deps.deepseek !== undefined ? { deps: run.deps.deepseek } : {}),
629
+ backoff,
630
+ });
631
+ const renderedQuery = selected.renderQuery(query);
632
+ // 上游条数上限(Tavily 只认 ≤20):夹在 `call` 之前,body 与上游口径一致;
633
+ // 缓存键/预算仍按模型请求的 count,信封报上游真实条数。
634
+ const upstreamQuery: SearchQuery =
635
+ selected.maxCount !== undefined && query.count > selected.maxCount
636
+ ? { ...query, count: selected.maxCount }
637
+ : query;
638
+ const callStart = Date.now();
639
+ const response = await selected.call(http, upstreamQuery, renderedQuery);
640
+ upstreamMs = Date.now() - callStart;
641
+ attempts = response.attempts;
642
+
643
+ // ⑦ 归一(缓存存条目,渲染每次现做)
644
+ const entries = selected.parseEntries(response.json);
645
+ const hits = entries
646
+ .map((entry) => selected.normalize(entry))
647
+ .filter((hit): hit is SearchHit => hit !== null);
648
+ const entry: SearchCacheEntry = {
649
+ providerId: selected.id,
650
+ providerVersion: selected.version,
651
+ hits,
652
+ upstreamCount: entries.length,
653
+ fetchedAt: new Date(clock()).toISOString(),
654
+ };
655
+ run.cache.set(cacheKey, entry);
656
+
657
+ if (hits.length === 0) {
658
+ // 空结果**不计费**、也不是 error
659
+ ticket?.empty();
660
+ const rendered = renderEntry(entry, query, config, { cached: false, filtersIgnored });
661
+ emitSearchMetric({
662
+ provider: selected,
663
+ query,
664
+ cached: false,
665
+ results: 0,
666
+ outTokens: rendered.tokens,
667
+ latencyMs: Date.now() - startedAt,
668
+ ...(upstreamMs !== undefined ? { upstreamMs } : {}),
669
+ ...(attempts !== undefined ? { attempts } : {}),
670
+ snapshot: run.cost.snapshot('search', run.runKey),
671
+ });
672
+ return rendered.text;
673
+ }
674
+
675
+ // ⑧ 计费(结果非空)⑨ 预算 + 定界渲染
676
+ ticket?.billed();
677
+ const rendered = renderEntry(entry, query, config, { cached: false, filtersIgnored });
678
+ emitSearchMetric({
679
+ provider: selected,
680
+ query,
681
+ cached: false,
682
+ results: rendered.results,
683
+ outTokens: rendered.tokens,
684
+ latencyMs: Date.now() - startedAt,
685
+ ...(upstreamMs !== undefined ? { upstreamMs } : {}),
686
+ ...(attempts !== undefined ? { attempts } : {}),
687
+ snapshot: run.cost.snapshot('search', run.runKey),
688
+ });
689
+ return rendered.text;
690
+ } catch (error) {
691
+ const failure = toWebFetchError(error);
692
+ if (isLocalRejection(failure.code)) ticket?.skipped();
693
+ else if (isClientError(failure.code)) ticket?.clientError();
694
+ else ticket?.failure();
695
+
696
+ const snapshot = run.cost.snapshot('search', run.runKey);
697
+ // 失败也要写清试的是哪家:选了后端但没到发请求就失败时,用配置口径兜底
698
+ const backendId = provider?.id ?? config.searchProvider;
699
+ emitMetric({
700
+ tool: 'web_search',
701
+ backend: backendId,
702
+ ...(query !== undefined
703
+ ? {
704
+ provider_id: backendId,
705
+ query_chars: query.query.length,
706
+ query_sha8: sha8(query.query),
707
+ count: query.count,
708
+ detail: query.detail,
709
+ need_content: query.needContent,
710
+ }
711
+ : {}),
712
+ latency_ms: Date.now() - startedAt,
713
+ ...(upstreamMs !== undefined ? { upstream_ms: upstreamMs } : {}),
714
+ ...(attempts !== undefined ? { attempts } : {}),
715
+ code: failure.code,
716
+ breaker_state: snapshot.breaker,
717
+ quota_used: snapshot.dailyUsed,
718
+ });
719
+ const daily =
720
+ failure.code === 'max_uses_exceeded' || failure.code === 'circuit_open'
721
+ ? { dailyUsed: snapshot.dailyUsed, dailyLimit: snapshot.dailyLimit }
722
+ : {};
723
+ return renderSearchFailure({ code: failure.code, message: failure.message, ...daily });
724
+ }
725
+ }