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

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/src/limits.ts ADDED
@@ -0,0 +1,388 @@
1
+ /**
2
+ * 三道成本闸 + 限流 + 熔断(设计 §5.4 / §5.5)。
3
+ *
4
+ * **为什么必须有**:按次计费 + 模型自我纠错会反复搜同一个问题。一次 run 打 200 次搜索 = 1 元,
5
+ * 而且没人会注意。每 run 配额是「看得见」的那道,**每进程日上限**是「没人看也不会失控」的那道。
6
+ *
7
+ * 检查顺序(失败要快、且不花钱):
8
+ * `参数校验` → `缺 key` → `熔断打开?` → `每 run 配额` → `日上限` → 发请求。
9
+ * `acquire()` 只负责后三步;前两步在工具层(参数、`secrets.readKey`),
10
+ * 五步之中任何一步拒绝都**不产生网络往返**。
11
+ *
12
+ * 计数口径:**只数「会被计费的调用」**(search 且结果非空、fetch 且拿到正文)。
13
+ * 失败不计费 ⇒ 不计入日上限;持续的失败由熔断挡——否则「失败把日配额烧光」会让工具
14
+ * 在坏天气里彻底不可用。
15
+ */
16
+
17
+ import {
18
+ MAX_BILLED_CALLS_PER_DAY,
19
+ MAX_DEEPSEEK_FETCH_PER_RUN,
20
+ MAX_SEARCH_PER_RUN,
21
+ type WebToolsConfig,
22
+ } from './config';
23
+ import { WebFetchError } from './types';
24
+
25
+ /** 一个 run 里最多 15 次搜索(常量与本文件所有理由见 config.ts 的同名导出) */
26
+ export { MAX_BILLED_CALLS_PER_DAY, MAX_DEEPSEEK_FETCH_PER_RUN, MAX_SEARCH_PER_RUN };
27
+ /** 连续 5 次失败(不含 4xx 客户端错)⇒ 打开 60s:够区分偶发抖动与真挂了 */
28
+ export const BREAKER_FAILURES = 5;
29
+ export const BREAKER_OPEN_MS = 60_000;
30
+ /** 重试:最多 2 次重试(3 attempts),400ms 起指数 ×2 + ±30% 抖动 */
31
+ export const RETRY_MAX = 2;
32
+ export const RETRY_BASE_MS = 400;
33
+ /** 自建限流(远低于服务端 100/25 QPS):被 429 比慢 200ms 贵 */
34
+ export const SEARCH_QPS = 5;
35
+ export const FETCH_QPS = 3;
36
+ export const FETCH_HOST_MIN_INTERVAL_MS = 500;
37
+ /** 排队最多等 2s,超时即 `provider_rate_limited`(有界等待,不建无界队列) */
38
+ export const QUEUE_MAX_WAIT_MS = 2_000;
39
+
40
+ export type CostKind = 'search' | 'deepseek_fetch';
41
+
42
+ /**
43
+ * 一次计费调用的结局:
44
+ * - `billed`:会被计费(search 有结果 / fetch 拿到正文)⇒ 累加 run 与日计数;
45
+ * - `empty`:成功但不计费(空结果)⇒ 不算配额,只重置熔断;
46
+ * - `client_error`:上游 4xx(我们的错)⇒ 不动熔断、不计数;
47
+ * - `failure`:5xx / 网络 / 超时 ⇒ 熔断计数;
48
+ * - `skipped`:本地拒绝(未发请求)⇒ 只释放半开探针。
49
+ */
50
+ export type CostOutcome = 'billed' | 'empty' | 'client_error' | 'failure' | 'skipped';
51
+
52
+ export type BreakerState = 'closed' | 'open' | 'half_open';
53
+
54
+ export interface CostDeps {
55
+ now?: () => number;
56
+ sleep?: (ms: number) => Promise<void>;
57
+ random?: () => number;
58
+ }
59
+
60
+ export interface CostSnapshot {
61
+ runUsed: number;
62
+ runLimit: number;
63
+ dailyUsed: number;
64
+ dailyLimit: number;
65
+ breaker: BreakerState;
66
+ }
67
+
68
+ /** 一次 `acquire()` 的凭据:结局必须结算一次(幂等) */
69
+ export interface CostTicket {
70
+ billed(): void;
71
+ empty(): void;
72
+ clientError(): void;
73
+ failure(): void;
74
+ skipped(): void;
75
+ snapshot(): CostSnapshot;
76
+ }
77
+
78
+ interface BreakerRecord {
79
+ failures: number;
80
+ openedAt: number;
81
+ probing: boolean;
82
+ }
83
+
84
+ const defaultSleep = (ms: number): Promise<void> =>
85
+ new Promise((resolve) => {
86
+ setTimeout(resolve, Math.max(0, ms));
87
+ });
88
+
89
+ function stableInt(value: number, fallback: number): number {
90
+ return Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
91
+ }
92
+
93
+ export class CostController {
94
+ private readonly config: WebToolsConfig;
95
+ private readonly now: () => number;
96
+ private readonly sleep: (ms: number) => Promise<void>;
97
+ private readonly random: () => number;
98
+ private readonly billedByRun = new Map<CostKind, Map<string, number>>();
99
+ private readonly breakers = new Map<CostKind, BreakerRecord>();
100
+ private readonly windows = new Map<CostKind, number[]>();
101
+ /** host → 最近一次开始时间;与下面那条 tail 链分开,避免链被旧对象覆盖 */
102
+ private readonly hostLast = new Map<string, number>();
103
+ private readonly hostTails = new Map<string, Promise<void>>();
104
+ private dayKey = '';
105
+ private dailyUsed = 0;
106
+
107
+ constructor(config: WebToolsConfig, deps: CostDeps = {}) {
108
+ this.config = config;
109
+ this.now = deps.now ?? (() => Date.now());
110
+ this.sleep = deps.sleep ?? defaultSleep;
111
+ this.random = deps.random ?? Math.random;
112
+ }
113
+
114
+ // ---------------------------------------------------------------- 三道闸
115
+
116
+ async acquire(kind: CostKind, runKey: string): Promise<CostTicket> {
117
+ const limit = this.runLimit(kind);
118
+ // ① 熔断:打开期间**不发请求**
119
+ const breaker = this.breakerOf(kind);
120
+ if (breaker.openedAt > 0) {
121
+ const elapsed = this.now() - breaker.openedAt;
122
+ if (elapsed < this.config.breakerOpenMs) {
123
+ throw new WebFetchError(
124
+ 'circuit_open',
125
+ `熔断打开:连续 ${breaker.failures} 次失败,${Math.ceil((this.config.breakerOpenMs - elapsed) / 1000)}s 后恢复(本次没有发出任何请求)`,
126
+ );
127
+ }
128
+ if (breaker.probing) {
129
+ throw new WebFetchError(
130
+ 'circuit_open',
131
+ '熔断半开:已有一个探针在途(本次没有发出任何请求)',
132
+ );
133
+ }
134
+ breaker.probing = true;
135
+ }
136
+
137
+ // ② 每 run 配额
138
+ const used = this.runUsed(kind, runKey);
139
+ if (used >= limit) {
140
+ throw new WebFetchError(
141
+ 'max_uses_exceeded',
142
+ `本次 run 的 ${kindLabel(kind)} 配额已用尽(${used}/${limit});继续要更多请开新 run(本次没有发出任何请求)`,
143
+ );
144
+ }
145
+
146
+ // ③ 每进程日上限
147
+ this.rollDay();
148
+ const dailyLimit = this.config.maxBilledCallsPerDay;
149
+ if (this.dailyUsed >= dailyLimit) {
150
+ const error = new WebFetchError(
151
+ 'max_uses_exceeded',
152
+ `今日计费调用已达上限(daily_used ${this.dailyUsed}/${dailyLimit}),本进程内不再发计费请求(本次没有发出任何请求)`,
153
+ );
154
+ throw error;
155
+ }
156
+
157
+ let settled = false;
158
+ const settle = (outcome: CostOutcome): void => {
159
+ if (settled) return;
160
+ settled = true;
161
+ this.applyOutcome(kind, runKey, outcome, breaker);
162
+ };
163
+
164
+ return {
165
+ billed: () => settle('billed'),
166
+ empty: () => settle('empty'),
167
+ clientError: () => settle('client_error'),
168
+ failure: () => settle('failure'),
169
+ skipped: () => settle('skipped'),
170
+ snapshot: () => this.snapshot(kind, runKey),
171
+ };
172
+ }
173
+
174
+ snapshot(kind: CostKind, runKey: string): CostSnapshot {
175
+ this.rollDay();
176
+ return {
177
+ runUsed: this.runUsed(kind, runKey),
178
+ runLimit: this.runLimit(kind),
179
+ dailyUsed: this.dailyUsed,
180
+ dailyLimit: this.config.maxBilledCallsPerDay,
181
+ breaker: this.breakerState(kind),
182
+ };
183
+ }
184
+
185
+ /** 日计数与 run 计数器(日志/输出用;不含 key、不含 query 明文) */
186
+ dailyCount(): number {
187
+ this.rollDay();
188
+ return this.dailyUsed;
189
+ }
190
+
191
+ private applyOutcome(
192
+ kind: CostKind,
193
+ runKey: string,
194
+ outcome: CostOutcome,
195
+ breaker: BreakerRecord,
196
+ ): void {
197
+ switch (outcome) {
198
+ case 'billed': {
199
+ const map = this.billedByRun.get(kind) ?? new Map<string, number>();
200
+ map.set(runKey, (map.get(runKey) ?? 0) + 1);
201
+ // run 结束没有清理钩子 ⇒ 自己封顶:超了就丢最早的那个 run 键
202
+ while (map.size > 512) {
203
+ const oldest = map.keys().next();
204
+ if (oldest.done === true) break;
205
+ map.delete(oldest.value);
206
+ }
207
+ this.billedByRun.set(kind, map);
208
+ this.rollDay();
209
+ this.dailyUsed += 1;
210
+ this.resetBreaker(breaker);
211
+ return;
212
+ }
213
+ case 'empty':
214
+ this.resetBreaker(breaker);
215
+ return;
216
+ case 'failure': {
217
+ breaker.failures += 1;
218
+ breaker.probing = false;
219
+ if (breaker.failures >= this.config.breakerFailures) {
220
+ breaker.openedAt = this.now();
221
+ }
222
+ return;
223
+ }
224
+ case 'client_error':
225
+ breaker.probing = false;
226
+ return;
227
+ case 'skipped':
228
+ breaker.probing = false;
229
+ return;
230
+ default:
231
+ return;
232
+ }
233
+ }
234
+
235
+ private resetBreaker(breaker: BreakerRecord): void {
236
+ breaker.failures = 0;
237
+ breaker.openedAt = 0;
238
+ breaker.probing = false;
239
+ }
240
+
241
+ private breakerOf(kind: CostKind): BreakerRecord {
242
+ const existing = this.breakers.get(kind);
243
+ if (existing) return existing;
244
+ const created: BreakerRecord = { failures: 0, openedAt: 0, probing: false };
245
+ this.breakers.set(kind, created);
246
+ return created;
247
+ }
248
+
249
+ private breakerState(kind: CostKind): BreakerState {
250
+ const breaker = this.breakerOf(kind);
251
+ if (breaker.openedAt === 0) return 'closed';
252
+ return this.now() - breaker.openedAt < this.config.breakerOpenMs ? 'open' : 'half_open';
253
+ }
254
+
255
+ private runLimit(kind: CostKind): number {
256
+ const configured =
257
+ kind === 'search' ? this.config.maxUsesSearchPerRun : this.config.maxUsesFetchPerRun;
258
+ const fallback = kind === 'search' ? MAX_SEARCH_PER_RUN : MAX_DEEPSEEK_FETCH_PER_RUN;
259
+ return stableInt(configured, fallback);
260
+ }
261
+
262
+ private runUsed(kind: CostKind, runKey: string): number {
263
+ return this.billedByRun.get(kind)?.get(runKey) ?? 0;
264
+ }
265
+
266
+ /** 日计数按**本地时区自然日**翻转(只在翻转或进程重启时归零) */
267
+ private rollDay(): void {
268
+ const today = new Date(this.now()).toDateString();
269
+ if (today !== this.dayKey) {
270
+ this.dayKey = today;
271
+ this.dailyUsed = 0;
272
+ }
273
+ }
274
+
275
+ // ---------------------------------------------------------------- 限流
276
+
277
+ /** 1s 滑动窗口令牌桶;有界等待 ≤2s,超时即 `provider_rate_limited`(未发请求) */
278
+ async throttle(kind: CostKind): Promise<void> {
279
+ const qps = kind === 'search' ? this.config.searchQps : this.config.fetchQps;
280
+ const limit = stableInt(qps, kind === 'search' ? SEARCH_QPS : FETCH_QPS);
281
+ const startedAt = this.now();
282
+ for (;;) {
283
+ const now = this.now();
284
+ const window = (this.windows.get(kind) ?? []).filter((at) => now - at < 1_000);
285
+ if (window.length < limit) {
286
+ window.push(now);
287
+ this.windows.set(kind, window);
288
+ return;
289
+ }
290
+ const oldest = window[0] ?? now;
291
+ const waitMs = Math.max(1, 1_000 - (now - oldest));
292
+ if (now - startedAt + waitMs > QUEUE_MAX_WAIT_MS) {
293
+ this.windows.set(kind, window);
294
+ throw new WebFetchError(
295
+ 'provider_rate_limited',
296
+ `本地限流排队超过 ${QUEUE_MAX_WAIT_MS / 1000}s(${kindLabel(kind)} ${limit} QPS),本次没有发出请求`,
297
+ );
298
+ }
299
+ this.windows.set(kind, window);
300
+ await this.sleep(waitMs);
301
+ }
302
+ }
303
+
304
+ /** 同一 host 串行 + 最小间隔(服务端有域名级限制,数值未知 ⇒ 保守自建) */
305
+ async throttleHost(host: string): Promise<void> {
306
+ const key = host.toLowerCase();
307
+ const previous = this.hostTails.get(key) ?? Promise.resolve();
308
+ let release: () => void = () => undefined;
309
+ const gate = new Promise<void>((resolve) => {
310
+ release = resolve;
311
+ });
312
+ // 链上排队:下一个调用者等这个 gate,避免「等着等着又并发出去」
313
+ this.hostTails.set(
314
+ key,
315
+ previous.then(() => gate),
316
+ );
317
+ await previous;
318
+ try {
319
+ const last = this.hostLast.get(key) ?? 0;
320
+ const wait = this.config.fetchHostMinIntervalMs - (this.now() - last);
321
+ if (wait > 0) await this.sleep(Math.min(wait, QUEUE_MAX_WAIT_MS));
322
+ this.hostLast.set(key, this.now());
323
+ } finally {
324
+ release();
325
+ }
326
+ }
327
+
328
+ // ---------------------------------------------------------------- 重试退避
329
+
330
+ /** 指数退避 + ±30% 抖动(必须有抖动:否则并发调用同步重试把限流变雪崩) */
331
+ backoffMs(attempt: number, retryAfterMs?: number): number {
332
+ if (retryAfterMs !== undefined && retryAfterMs > 0) {
333
+ return Math.min(retryAfterMs, this.config.retryBaseMs * 4);
334
+ }
335
+ const base = this.config.retryBaseMs * 2 ** Math.max(0, attempt);
336
+ const jitter = 0.7 + this.random() * 0.6;
337
+ return Math.min(Math.round(base * jitter), 2_000);
338
+ }
339
+ }
340
+
341
+ function kindLabel(kind: CostKind): string {
342
+ return kind === 'search' ? '搜索' : 'deepseek 抓取';
343
+ }
344
+
345
+ // ---------------------------------------------------------------- 指标行
346
+
347
+ /** 只记白名单字段:**永不**记 query 明文 / 完整 URL 的 query string / 任何 header / key */
348
+ export interface MetricFields {
349
+ tool: string;
350
+ backend?: string;
351
+ provider_id?: string;
352
+ query_chars?: number;
353
+ query_sha8?: string;
354
+ count?: number;
355
+ detail?: string;
356
+ need_content?: boolean;
357
+ cached?: boolean;
358
+ cached_age_s?: number;
359
+ results?: number;
360
+ out_tokens_est?: number;
361
+ latency_ms?: number;
362
+ upstream_ms?: number;
363
+ attempts?: number;
364
+ status_class?: string;
365
+ code?: string;
366
+ breaker_state?: string;
367
+ quota_used?: number;
368
+ key_env?: string;
369
+ key_present?: boolean;
370
+ host?: string;
371
+ url_sha8?: string;
372
+ }
373
+
374
+ export type MetricSink = (line: string) => void;
375
+
376
+ /** 插件没有 logger ⇒ 一行 JSON 到 stderr,前缀 `[web-tools]`(设计 §7) */
377
+ export function emitMetric(fields: MetricFields, sink: MetricSink = defaultSink): void {
378
+ const payload = { ts: new Date().toISOString(), ...fields };
379
+ try {
380
+ sink(`[web-tools] ${JSON.stringify(payload)}`);
381
+ } catch {
382
+ // 指标永远不许把主流程带崩
383
+ }
384
+ }
385
+
386
+ function defaultSink(line: string): void {
387
+ process.stderr.write(`${line}\n`);
388
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `ProviderHttp` 的两个实现:
3
+ * 1. `createDeepSeekHttp` —— DeepSeek tools API(Bearer + `config.base_url`,历史第一个);
4
+ * 2. `createJsonHttp` —— 通用 JSON 传输(固定 host + 自定义鉴权头,Tavily / Serper 用)。
5
+ *
6
+ * 两者共用 `deepseek-client.ts` 里**同一套**重试/退避/错误映射/擦除:把「这家怎么鉴权」
7
+ * 与「重试几次、429 怎么退避、错误码怎么映射」彻底隔开。
8
+ * 以后接一家 auth 风格又不同的后端:在插件包里再写一个 `ProviderHttp` 即可,
9
+ * 工具层与预算/缓存/闸一行都不用动。
10
+ */
11
+
12
+ import type { WebToolsConfig } from './config';
13
+ import { callDeepSeekTool, type DeepSeekDeps } from './deepseek-client';
14
+ import type { ProviderHttp } from './search/provider';
15
+ import type { KeyKind } from './secrets';
16
+
17
+ export type { ProviderHttp };
18
+
19
+ export interface DeepSeekHttpOptions {
20
+ config: WebToolsConfig;
21
+ keyKind: KeyKind;
22
+ signal?: AbortSignal;
23
+ deps?: DeepSeekDeps;
24
+ /** 退避毫秒(带抖动);由 CostController 提供 */
25
+ backoff: (attempt: number, retryAfterMs?: number) => number;
26
+ }
27
+
28
+ export function createDeepSeekHttp(options: DeepSeekHttpOptions): ProviderHttp {
29
+ return {
30
+ async postJson(request) {
31
+ const result = await callDeepSeekTool({
32
+ config: options.config,
33
+ keyKind: options.keyKind,
34
+ path: request.path,
35
+ body: request.body,
36
+ signal: options.signal,
37
+ deps: options.deps,
38
+ backoff: options.backoff,
39
+ badRequestHint: request.hint,
40
+ });
41
+ return {
42
+ json: result.json,
43
+ status: result.status,
44
+ attempts: result.attempts,
45
+ upstreamMs: result.upstreamMs,
46
+ };
47
+ },
48
+ };
49
+ }
50
+
51
+ /**
52
+ * 通用 JSON 传输层:**同一套**重试/退避/错误码映射/整体 deadline/`sk-` 擦除,
53
+ * 只换「host」与「鉴权头」两件东西(Tavily = 固定 host + Bearer,Serper = 固定 host + `X-API-KEY`)。
54
+ *
55
+ * 为什么不是各写一份 `ProviderHttp`:重试策略、429/402/413 的语义、`Retry-After` ≤5s 的
56
+ * 取舍、错误体擦除,这些一旦分叉就会出现「同一家后端两套闸」——本单的硬要求正是反过来的。
57
+ */
58
+ export interface JsonHttpOptions {
59
+ config: WebToolsConfig;
60
+ keyKind: KeyKind;
61
+ /** 已解析好的 key 环境变量名(只存名字) */
62
+ keyEnvName: string;
63
+ /** 绝对地址(固定 host 的后端用它,绕开 `config.baseUrl`) */
64
+ endpoint: string;
65
+ /** 鉴权头构造(值只在这一处出现,不进 URL/日志) */
66
+ authHeaders?: (key: string) => Record<string, string>;
67
+ /** 查询串鉴权(`auth.style: query`):key 进 URL 参数 */
68
+ authQuery?: (key: string) => Record<string, string>;
69
+ signal?: AbortSignal;
70
+ deps?: DeepSeekDeps;
71
+ backoff: (attempt: number, retryAfterMs?: number) => number;
72
+ }
73
+
74
+ export function createJsonHttp(options: JsonHttpOptions): ProviderHttp {
75
+ return {
76
+ async postJson(request) {
77
+ const result = await callDeepSeekTool({
78
+ config: options.config,
79
+ keyKind: options.keyKind,
80
+ keyEnvName: options.keyEnvName,
81
+ endpoint: options.endpoint,
82
+ ...(options.authHeaders !== undefined ? { authHeaders: options.authHeaders } : {}),
83
+ ...(options.authQuery !== undefined ? { authQuery: options.authQuery } : {}),
84
+ path: request.path,
85
+ body: request.body,
86
+ ...(request.method !== undefined ? { method: request.method } : {}),
87
+ ...(request.query !== undefined ? { query: request.query } : {}),
88
+ ...(request.headers !== undefined ? { headers: request.headers } : {}),
89
+ ...(request.hint !== undefined ? { badRequestHint: request.hint } : {}),
90
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
91
+ ...(options.deps !== undefined ? { deps: options.deps } : {}),
92
+ backoff: options.backoff,
93
+ });
94
+ return {
95
+ json: result.json,
96
+ status: result.status,
97
+ attempts: result.attempts,
98
+ upstreamMs: result.upstreamMs,
99
+ };
100
+ },
101
+ };
102
+ }