@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/extract.ts ADDED
@@ -0,0 +1,373 @@
1
+ /**
2
+ * 正文抽取(M1,无第三方依赖)。
3
+ *
4
+ * 两步:
5
+ * 1. `HTMLRewriter`(Bun 内建)做净化:删掉 script/style/nav/footer/form 控件,
6
+ * 以及**隐藏元素**(`hidden`、`aria-hidden="true"`、`display:none`/`visibility:hidden`/`opacity:0`)——
7
+ * 隐藏文本是提示注入最常见的藏匿点,必须在抽取阶段就丢掉。
8
+ * 2. 自己的小扫描器把净化后的 HTML 拍平成纯文本:块级标签变成换行(保留段落与标题),
9
+ * 顺便收 `<a href>`(后续在 http.ts 里再按同源过滤、去重、限量)。
10
+ *
11
+ * 质量目标不是 Readability 级别,只要求「不丢正文、不留垃圾、不留隐藏文本」。
12
+ */
13
+
14
+ export interface ExtractOptions {
15
+ /** 收集链接的上限(同源过滤在调用方做) */
16
+ maxLinks: number;
17
+ }
18
+
19
+ export interface ExtractOutput {
20
+ text: string;
21
+ title: string;
22
+ links: string[];
23
+ }
24
+
25
+ /** 这些元素整体丢掉:无正文价值,且常被用来塞提示注入。 */
26
+ const NOISE_SELECTOR =
27
+ 'script, style, noscript, template, svg, canvas, iframe, object, embed, ' +
28
+ 'nav, footer, form, button, input, select, textarea';
29
+
30
+ /** HTML 的 void 元素:没有闭合标签,扫描时不能拿它们去加减 skip 深度。 */
31
+ const VOID_TAGS = new Set([
32
+ 'area',
33
+ 'base',
34
+ 'br',
35
+ 'col',
36
+ 'embed',
37
+ 'hr',
38
+ 'img',
39
+ 'input',
40
+ 'link',
41
+ 'meta',
42
+ 'param',
43
+ 'source',
44
+ 'track',
45
+ 'wbr',
46
+ ]);
47
+
48
+ /** 扫描器里整体跳过文本的标签(净化后基本不会出现,作为兜底)。 */
49
+ const SKIP_TEXT_TAGS = new Set([
50
+ 'head',
51
+ 'script',
52
+ 'style',
53
+ 'noscript',
54
+ 'template',
55
+ 'svg',
56
+ 'canvas',
57
+ 'iframe',
58
+ 'object',
59
+ 'embed',
60
+ 'nav',
61
+ 'footer',
62
+ 'form',
63
+ 'button',
64
+ 'input',
65
+ 'select',
66
+ 'textarea',
67
+ ]);
68
+
69
+ /** 块级标签:前后补换行,保证段落/标题之间不会粘成一行。 */
70
+ const BLOCK_TAGS = new Set([
71
+ 'p',
72
+ 'div',
73
+ 'br',
74
+ 'hr',
75
+ 'li',
76
+ 'ul',
77
+ 'ol',
78
+ 'dl',
79
+ 'dt',
80
+ 'dd',
81
+ 'tr',
82
+ 'table',
83
+ 'thead',
84
+ 'tbody',
85
+ 'h1',
86
+ 'h2',
87
+ 'h3',
88
+ 'h4',
89
+ 'h5',
90
+ 'h6',
91
+ 'section',
92
+ 'article',
93
+ 'header',
94
+ 'main',
95
+ 'aside',
96
+ 'blockquote',
97
+ 'pre',
98
+ 'figure',
99
+ 'figcaption',
100
+ 'address',
101
+ 'details',
102
+ 'summary',
103
+ ]);
104
+
105
+ const NAMED_ENTITIES: Record<string, string> = {
106
+ amp: '&',
107
+ lt: '<',
108
+ gt: '>',
109
+ quot: '"',
110
+ apos: "'",
111
+ nbsp: ' ',
112
+ mdash: '—',
113
+ ndash: '–',
114
+ hellip: '…',
115
+ laquo: '«',
116
+ raquo: '»',
117
+ copy: '©',
118
+ reg: '®',
119
+ trade: '™',
120
+ rsquo: '’',
121
+ lsquo: '‘',
122
+ ldquo: '“',
123
+ rdquo: '”',
124
+ middot: '·',
125
+ bull: '•',
126
+ times: '×',
127
+ divide: '÷',
128
+ deg: '°',
129
+ euro: '€',
130
+ pound: '£',
131
+ yen: '¥',
132
+ sect: '§',
133
+ para: '¶',
134
+ frac12: '½',
135
+ frac14: '¼',
136
+ frac34: '¾',
137
+ sup2: '²',
138
+ sup3: '³',
139
+ micro: 'µ',
140
+ larr: '←',
141
+ rarr: '→',
142
+ uarr: '↑',
143
+ darr: '↓',
144
+ };
145
+
146
+ export function decodeEntities(input: string): string {
147
+ if (!input.includes('&')) return input;
148
+ return input.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, body: string) => {
149
+ if (body.startsWith('#')) {
150
+ const hex = body[1] === 'x' || body[1] === 'X';
151
+ const code = Number.parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10);
152
+ if (!Number.isFinite(code) || code <= 0 || code > 0x10ffff) return match;
153
+ try {
154
+ return String.fromCodePoint(code);
155
+ } catch {
156
+ return match;
157
+ }
158
+ }
159
+ return NAMED_ENTITIES[body.toLowerCase()] ?? match;
160
+ });
161
+ }
162
+
163
+ interface RewriterElementLike {
164
+ getAttribute(name: string): string | null;
165
+ hasAttribute(name: string): boolean;
166
+ remove(): void;
167
+ }
168
+
169
+ /** 只描述本模块用到的那部分 HTMLRewriter API,避免绑死某个版本的运行时类型声明。 */
170
+ interface RewriterLike {
171
+ on(selector: string, handlers: { element(element: RewriterElementLike): void }): RewriterLike;
172
+ transform(input: Response): { text(): Promise<string> };
173
+ }
174
+
175
+ /** 隐藏元素的判定:属性 + 内联样式的常见写法。 */
176
+ export function isHiddenElement(element: RewriterElementLike): boolean {
177
+ if (element.hasAttribute('hidden')) return true;
178
+ const ariaHidden = (element.getAttribute('aria-hidden') ?? '').trim().toLowerCase();
179
+ if (ariaHidden === 'true') return true;
180
+
181
+ const style = (element.getAttribute('style') ?? '').toLowerCase();
182
+ if (style === '') return false;
183
+ const compact = style.replace(/\s+/g, '');
184
+ if (compact.includes('display:none')) return true;
185
+ if (compact.includes('visibility:hidden')) return true;
186
+ // opacity: 0 / 0.0 / 0.00 —— 不要用 includes('opacity:0'),会把 opacity:0.5 也误杀
187
+ if (/(^|[;])opacity:0(\.0+)?(;|$)/.test(compact)) return true;
188
+ return false;
189
+ }
190
+
191
+ /**
192
+ * 用 HTMLRewriter 净化。HTMLRewriter 不可用(非 Bun 运行时)时退化成原文,
193
+ * 由扫描器按标签兜底跳过噪声——只是失去隐藏元素识别,不会崩。
194
+ */
195
+ async function sanitizeWithRewriter(html: string): Promise<string> {
196
+ const rewriterCtor = (globalThis as { HTMLRewriter?: new () => RewriterLike }).HTMLRewriter;
197
+ if (typeof rewriterCtor !== 'function') return html;
198
+
199
+ const rewriter = new rewriterCtor()
200
+ .on(NOISE_SELECTOR, {
201
+ element(element) {
202
+ element.remove();
203
+ },
204
+ })
205
+ .on('*', {
206
+ element(element) {
207
+ if (isHiddenElement(element)) element.remove();
208
+ },
209
+ });
210
+
211
+ return rewriter.transform(new Response(html)).text();
212
+ }
213
+
214
+ function findTagEnd(html: string, from: number): number {
215
+ let quote: string | null = null;
216
+ for (let index = from + 1; index < html.length; index += 1) {
217
+ const char = html[index];
218
+ if (quote !== null) {
219
+ if (char === quote) quote = null;
220
+ continue;
221
+ }
222
+ if (char === '"' || char === "'") {
223
+ quote = char;
224
+ continue;
225
+ }
226
+ if (char === '>') return index;
227
+ }
228
+ return -1;
229
+ }
230
+
231
+ function parseAttributes(raw: string): Map<string, string> {
232
+ const attributes = new Map<string, string>();
233
+ const pattern = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*(?:=\s*("[^"]*"|'[^']*'|[^\s"'>]+))?/g;
234
+ let match = pattern.exec(raw);
235
+ while (match !== null) {
236
+ const name = (match[1] ?? '').toLowerCase();
237
+ let value = match[2] ?? '';
238
+ if (
239
+ (value.startsWith('"') && value.endsWith('"')) ||
240
+ (value.startsWith("'") && value.endsWith("'"))
241
+ ) {
242
+ value = value.slice(1, -1);
243
+ }
244
+ if (name !== '') attributes.set(name, decodeEntities(value));
245
+ match = pattern.exec(raw);
246
+ }
247
+ return attributes;
248
+ }
249
+
250
+ function normalizeText(raw: string): string {
251
+ const lines = raw
252
+ // 去掉零宽字符与 bidi 覆写符:它们能让「肉眼看到的文本」与模型读到的文本不一致
253
+ .replace(/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, '')
254
+ .replace(/\r\n?/g, '\n')
255
+ .split('\n')
256
+ .map((line) => line.replace(/[ \t\u00a0]+/g, ' ').trim());
257
+ return lines
258
+ .join('\n')
259
+ .replace(/\n{3,}/g, '\n\n')
260
+ .trim();
261
+ }
262
+
263
+ /** 把净化后的 HTML 拍平成纯文本 + 链接 + 标题。 */
264
+ export function flattenHtml(html: string, base: URL, options: ExtractOptions): ExtractOutput {
265
+ const links: string[] = [];
266
+ const body: string[] = [];
267
+ const titleParts: string[] = [];
268
+
269
+ let index = 0;
270
+ let skipDepth = 0;
271
+ let inTitle = false;
272
+
273
+ const pushText = (chunk: string): void => {
274
+ if (chunk === '') return;
275
+ if (inTitle) {
276
+ titleParts.push(chunk);
277
+ return;
278
+ }
279
+ if (skipDepth > 0) return;
280
+ body.push(decodeEntities(chunk));
281
+ };
282
+
283
+ while (index < html.length) {
284
+ const lt = html.indexOf('<', index);
285
+ if (lt === -1) {
286
+ pushText(html.slice(index));
287
+ break;
288
+ }
289
+ pushText(html.slice(index, lt));
290
+
291
+ if (html.startsWith('<!--', lt)) {
292
+ const end = html.indexOf('-->', lt + 4);
293
+ if (end === -1) break;
294
+ index = end + 3;
295
+ continue;
296
+ }
297
+
298
+ const gt = findTagEnd(html, lt);
299
+ if (gt === -1) break;
300
+ const rawTag = html.slice(lt + 1, gt);
301
+ index = gt + 1;
302
+
303
+ if (rawTag.startsWith('!') || rawTag.startsWith('?')) continue;
304
+
305
+ const closing = rawTag.startsWith('/');
306
+ const withoutSlash = closing ? rawTag.slice(1) : rawTag;
307
+ const nameMatch = /^[a-zA-Z][a-zA-Z0-9:-]*/.exec(withoutSlash);
308
+ if (!nameMatch) continue;
309
+ const name = (nameMatch[0] ?? '').toLowerCase();
310
+ const selfClosing = /\/\s*$/.test(rawTag);
311
+
312
+ if (name === 'title') {
313
+ inTitle = !closing;
314
+ continue;
315
+ }
316
+
317
+ if (SKIP_TEXT_TAGS.has(name)) {
318
+ if (!VOID_TAGS.has(name) && !selfClosing) {
319
+ skipDepth = closing ? Math.max(0, skipDepth - 1) : skipDepth + 1;
320
+ }
321
+ continue;
322
+ }
323
+
324
+ if (closing) {
325
+ if (BLOCK_TAGS.has(name) && skipDepth === 0) body.push('\n\n');
326
+ continue;
327
+ }
328
+
329
+ const attributes = parseAttributes(withoutSlash.slice(name.length));
330
+
331
+ if (name === 'a' && links.length < options.maxLinks) {
332
+ const href = attributes.get('href');
333
+ if (href !== undefined && href !== '' && !href.startsWith('#')) {
334
+ try {
335
+ const resolved = new URL(href, base);
336
+ if (resolved.protocol === 'http:' || resolved.protocol === 'https:')
337
+ links.push(resolved.href);
338
+ } catch {
339
+ // 解析不了的 href 直接忽略
340
+ }
341
+ }
342
+ }
343
+
344
+ if (name === 'img' && skipDepth === 0) {
345
+ const alt = (attributes.get('alt') ?? '').trim();
346
+ if (alt !== '') body.push(`\n[图片: ${alt}]\n`);
347
+ }
348
+
349
+ if (BLOCK_TAGS.has(name) && skipDepth === 0) {
350
+ body.push(name === 'li' ? '\n- ' : '\n\n');
351
+ if (selfClosing) body.push('\n');
352
+ }
353
+ }
354
+
355
+ // 标题放在最前面:既是正文的一部分,也让模型一眼知道页面主题
356
+ // 标题也限量:某些站点标题能堆几千字符,不该白吃 budget
357
+ const title = normalizeText(titleParts.join(' ')).replace(/\n+/g, ' ').slice(0, 200);
358
+ const text = normalizeText(body.join(''));
359
+ return {
360
+ text: title === '' ? text : `${title}\n\n${text}`,
361
+ title,
362
+ links,
363
+ };
364
+ }
365
+
366
+ export async function extractDocument(
367
+ html: string,
368
+ base: URL,
369
+ options: ExtractOptions,
370
+ ): Promise<ExtractOutput> {
371
+ const sanitized = await sanitizeWithRewriter(html);
372
+ return flattenHtml(sanitized, base, options);
373
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `local` 抓取后端(缺省):本进程直接连目标,走 `http.ts` 的全套 SSRF / robots / 抽取。
3
+ *
4
+ * 免费、离线可用、内网可调试(显式开 `allow_private_networks`)、每一跳都在我们眼里。
5
+ * 它不计费 ⇒ 不进三道成本闸,也不改任何现有行为(设计 §10 第 1 条)。
6
+ */
7
+
8
+ import { withMaxChars } from '../config';
9
+ import { fetchPage, type WebFetchDeps } from '../http';
10
+ import { checkUrl } from '../ssrf';
11
+ import type { WebFetchResult } from '../types';
12
+ import type { FetchBackend, FetchRequest } from './provider';
13
+
14
+ export const localFetchBackend: FetchBackend = {
15
+ id: 'local',
16
+ billed: false,
17
+ requiresKey: false,
18
+
19
+ validate(request: FetchRequest): void {
20
+ // 静态校验(不发 DNS、不发请求):连 URL 都不合法就不用往下走了
21
+ checkUrl(request.url, {
22
+ allowPrivateNetworks: request.config.allowPrivateNetworks,
23
+ domainAllowlist: request.config.domainAllowlist,
24
+ domainDenylist: request.config.domainDenylist,
25
+ });
26
+ },
27
+
28
+ async fetch(request: FetchRequest): Promise<WebFetchResult> {
29
+ const deps: WebFetchDeps = request.deps;
30
+ return fetchPage(request.url, {
31
+ config: withMaxChars(request.config, request.maxChars),
32
+ deps,
33
+ ...(request.signal !== undefined ? { signal: request.signal } : {}),
34
+ });
35
+ },
36
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 抓取后端的**接口 + 注册点**(宪法第十三条:后端能力做成插件包内的扩展点)。
3
+ *
4
+ * 加一个抓取后端(例如以后接某家 reader 服务)只需在插件包里
5
+ * `registerFetchBackend(...)`,**不动 `web_fetch` 的输入/输出契约**:
6
+ * 预算、缓存、限流、熔断、错误渲染都在工具层,后端只负责「把 URL 变成结果」。
7
+ */
8
+
9
+ import type { WebToolsConfig } from '../config';
10
+ import type { DeepSeekDeps } from '../deepseek-client';
11
+ import type { WebFetchDeps } from '../http';
12
+ import type { FetchBackendId, WebFetchResult } from '../types';
13
+
14
+ export interface FetchRequest {
15
+ /** 工具参数里的原始 URL(trim 过) */
16
+ url: string;
17
+ config: WebToolsConfig;
18
+ /** 生效的字符预算(配置 + 工具参数 clamp 之后) */
19
+ maxChars: number;
20
+ deps: WebFetchDeps;
21
+ /** 上游调用注入点(deepseek 后端用;缺省回落到 `deps.fetch`/`deps.now`) */
22
+ api?: DeepSeekDeps;
23
+ /** 退避毫秒(带抖动);由 CostController 提供,只有计费后端用得上 */
24
+ backoff: (attempt: number, retryAfterMs?: number) => number;
25
+ signal?: AbortSignal;
26
+ }
27
+
28
+ export interface FetchBackend {
29
+ readonly id: FetchBackendId;
30
+ /** 是否计费(决定是否走三道成本闸与 QPS/host 限流;`local` = false) */
31
+ readonly billed: boolean;
32
+ /** 是否需要 key(true ⇒ 缺 key 时本地拒,不发请求) */
33
+ readonly requiresKey: boolean;
34
+ /**
35
+ * 本地校验(**不发请求**):URL 语法 / 端口 / userinfo / 私网字面量 / query string 策略。
36
+ * 抛 `WebFetchError`。注意它跑在成本闸**之前**(参数校验是五步闸的第一步)。
37
+ */
38
+ validate(request: FetchRequest): void;
39
+ /** 真正的抓取;成功返回统一结果,失败抛 `WebFetchError` */
40
+ fetch(request: FetchRequest): Promise<WebFetchResult>;
41
+ }
42
+
43
+ const backends = new Map<FetchBackendId, FetchBackend>();
44
+
45
+ /** 注册(或覆盖)一个抓取后端。幂等。 */
46
+ export function registerFetchBackend(backend: FetchBackend): void {
47
+ backends.set(backend.id, backend);
48
+ }
49
+
50
+ export function getFetchBackend(id: FetchBackendId): FetchBackend | undefined {
51
+ return backends.get(id);
52
+ }
53
+
54
+ export function listFetchBackends(): FetchBackendId[] {
55
+ return [...backends.keys()].sort();
56
+ }