@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,406 @@
1
+ /**
2
+ * DeepSeek tools API 的共用调用层(搜索与抓取**共用**一份,避免两套重试/错误语义)。
3
+ *
4
+ * 设计口径(§2.5 / §5.3 / §6.1 / §6.3):
5
+ * - 缺 key ⇒ 本地判 `provider_auth_failed`,**一个字节都不发出去**;
6
+ * - 只有 408 / 429 / 5xx / 网络层可重试,且**最多 2 次重试**(3 attempts);
7
+ * - 400/401/402/403/404/413 **一次都不重试**(余额不足还连打 3 次是最贵的错误);
8
+ * - `Retry-After` ≤5s 照做,>5s 直接放弃(让模型等 60s 不如直接告诉它 `retry_after_s`);
9
+ * - 整体一个 deadline(含所有重试与 body 读取),半开连接也受同一个 signal 约束;
10
+ * - key 只在 `Authorization: Bearer` 头里,**永不进 URL**;上游文本进 message 前双擦除。
11
+ */
12
+
13
+ import type { WebToolsConfig } from './config';
14
+ import {
15
+ type KeyKind,
16
+ missingKeyMessage,
17
+ readKey,
18
+ redactKey,
19
+ sanitizeUpstreamText,
20
+ } from './secrets';
21
+ import { WebFetchError, type WebToolErrorCode } from './types';
22
+
23
+ /** 端点路径(⚠️ owner 口径:仓里没有第二处来源;实现以真实响应为准) */
24
+ export const DEEPSEEK_SEARCH_PATH = '/v1/tools/search';
25
+ export const DEEPSEEK_FETCH_PATH = '/v1/tools/fetch';
26
+
27
+ export interface DeepSeekDeps {
28
+ fetch?: typeof fetch;
29
+ now?: () => number;
30
+ sleep?: (ms: number) => Promise<void>;
31
+ env?: Record<string, string | undefined>;
32
+ }
33
+
34
+ export interface DeepSeekCallOptions {
35
+ config: WebToolsConfig;
36
+ /** 这次调用该看哪个环境变量(search / fetch 可分开账户) */
37
+ keyKind: KeyKind;
38
+ /**
39
+ * 显式指定环境变量名(搜索侧按 provider 的 `keyEnv` 解析好后传进来)。
40
+ * 不给 ⇒ 走 `config` 的 `search_key_env`/`fetch_key_env`/`key_env` 口径。
41
+ */
42
+ keyEnvName?: string;
43
+ path: string;
44
+ /**
45
+ * 绝对地址覆盖(缺省 = `config.baseUrl` + path)。
46
+ *
47
+ * Tavily / Serper 这类**固定 host** 的后端用绝对地址:它们的域名不该被
48
+ * `base_url` 配置串到(那是 DeepSeek tools API 的旋钮)。
49
+ */
50
+ endpoint?: string;
51
+ /**
52
+ * 鉴权头(缺省 = `authorization: Bearer <key>`)。
53
+ *
54
+ * Serper 只认 `X-API-KEY`,这时由它的 `ProviderHttp` 提供本函数;
55
+ * **重试/退避/错误映射/擦除仍然只有这一份实现**,不因为头不同而分叉。
56
+ */
57
+ authHeaders?: (key: string) => Record<string, string>;
58
+ /**
59
+ * 查询串鉴权(`auth.style: query`):key 作为 URL 参数。
60
+ * 只给声明式自定义后端用;同样是共用这一份重试/映射实现。
61
+ */
62
+ authQuery?: (key: string) => Record<string, string>;
63
+ method?: 'POST' | 'GET';
64
+ query?: Record<string, string>;
65
+ /** 额外请求头(声明式后端的 `request.headers`;`authorization` 等鉴权头不许从这里覆盖) */
66
+ headers?: Record<string, string>;
67
+ body: unknown;
68
+ signal?: AbortSignal;
69
+ deps?: DeepSeekDeps;
70
+ /** 退避毫秒(由 `CostController.backoffMs` 提供,带抖动) */
71
+ backoff: (attempt: number, retryAfterMs?: number) => number;
72
+ /** 400 的补充提示(搜索与抓取的错法不同) */
73
+ badRequestHint?: string;
74
+ }
75
+
76
+ export interface DeepSeekCallResult {
77
+ json: unknown;
78
+ status: number;
79
+ attempts: number;
80
+ /** 最后一次尝试的上游耗时(毫秒) */
81
+ upstreamMs: number;
82
+ /** 整次调用(含重试)耗时(毫秒) */
83
+ latencyMs: number;
84
+ }
85
+
86
+ const defaultSleep = (ms: number): Promise<void> =>
87
+ new Promise((resolve) => {
88
+ setTimeout(resolve, Math.max(0, ms));
89
+ });
90
+
91
+ /** `Retry-After` 可能是秒数,也可能是 HTTP 日期;解析成毫秒 */
92
+ export function parseRetryAfterMs(raw: string | null, now: number): number | undefined {
93
+ if (raw === null || raw.trim() === '') return undefined;
94
+ const seconds = Number(raw.trim());
95
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
96
+ const at = Date.parse(raw);
97
+ if (!Number.isFinite(at)) return undefined;
98
+ return Math.max(0, at - now);
99
+ }
100
+
101
+ function endpointFor(baseUrl: string, path: string): string {
102
+ return `${baseUrl.replace(/\/+$/, '')}${path.startsWith('/') ? path : `/${path}`}`;
103
+ }
104
+
105
+ /** 追加查询参数(值一律 `encodeURIComponent`;只给声明式后端的 query / query 鉴权用) */
106
+ function appendQuery(endpoint: string, params: Record<string, string>): string {
107
+ const search = new URLSearchParams(params).toString();
108
+ if (search === '') return endpoint;
109
+ const separator = endpoint.includes('?') ? '&' : '?';
110
+ return `${endpoint}${separator}${search}`;
111
+ }
112
+
113
+ /** 上游错误体里的原因(JSON 或纯文本),只用于拼 message,且必先擦除 */
114
+ function upstreamReason(text: string): string {
115
+ const flat = text.trim();
116
+ if (flat === '') return '(空响应体)';
117
+ try {
118
+ const parsed = JSON.parse(flat) as unknown;
119
+ const reason = pickString(parsed, [['error', 'message'], ['message'], ['detail'], ['error']]);
120
+ if (reason !== undefined) return reason;
121
+ } catch {
122
+ // 不是 JSON:原样截断
123
+ }
124
+ return flat;
125
+ }
126
+
127
+ /** 按路径取第一个非空字符串(`error.message` 这类嵌套也走这里) */
128
+ export function pickString(
129
+ value: unknown,
130
+ paths: readonly (readonly string[])[],
131
+ ): string | undefined {
132
+ for (const path of paths) {
133
+ let cursor: unknown = value;
134
+ for (const segment of path) {
135
+ if (cursor === null || typeof cursor !== 'object') {
136
+ cursor = undefined;
137
+ break;
138
+ }
139
+ cursor = (cursor as Record<string, unknown>)[segment];
140
+ }
141
+ if (typeof cursor === 'string' && cursor.trim() !== '') return cursor.trim();
142
+ }
143
+ return undefined;
144
+ }
145
+
146
+ interface StatusMapping {
147
+ code: WebToolErrorCode;
148
+ message: string;
149
+ retryable: boolean;
150
+ retryAfterMs?: number;
151
+ }
152
+
153
+ /** HTTP 状态码 → 码 / 文案 / 能否重试(设计 §2.5(c) 的逐条表) */
154
+ function mapHttpStatus(
155
+ status: number,
156
+ bodyText: string,
157
+ keyValue: string,
158
+ retryAfterHeader: string | null,
159
+ now: number,
160
+ attempt: number,
161
+ badRequestHint: string,
162
+ ): StatusMapping {
163
+ const reason = sanitizeUpstreamText(
164
+ upstreamReason(bodyText === '' ? '' : redactKey(bodyText, keyValue)),
165
+ keyValue,
166
+ );
167
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader, now);
168
+
169
+ if (status === 400) {
170
+ return {
171
+ code: 'provider_bad_request',
172
+ message: `请求被服务端判为非法:${reason};${badRequestHint}`,
173
+ retryable: false,
174
+ };
175
+ }
176
+ if (status === 401) {
177
+ return {
178
+ code: 'provider_auth_failed',
179
+ message: '鉴权失败:key 无效或已撤销(检查环境变量名配置,不放 key 本身)',
180
+ retryable: false,
181
+ };
182
+ }
183
+ if (status === 402) {
184
+ return {
185
+ code: 'provider_quota_exhausted',
186
+ message: '账户余额不足,服务端拒绝(需充值)。本次不降级到其它后端',
187
+ retryable: false,
188
+ };
189
+ }
190
+ if (status === 403) {
191
+ return {
192
+ code: 'provider_auth_failed',
193
+ message: '无权访问该接口(key 权限或账户状态问题)',
194
+ retryable: false,
195
+ };
196
+ }
197
+ if (status === 404) {
198
+ return {
199
+ code: 'endpoint_not_found',
200
+ message: '接口路径不存在:检查 base_url/版本号配置',
201
+ retryable: false,
202
+ };
203
+ }
204
+ if (status >= 300 && status < 400) {
205
+ // 本客户端不跟随重定向(`redirect: 'manual'`):只可能是 base_url 配错(例如少了 /v1)
206
+ return {
207
+ code: 'endpoint_not_found',
208
+ message: `上游返回重定向 ${status}:本客户端不跟随重定向,检查 base_url 配置`,
209
+ retryable: false,
210
+ };
211
+ }
212
+ if (status === 408) {
213
+ return { code: 'timeout', message: '服务端抓取/检索超时', retryable: true };
214
+ }
215
+ if (status === 413) {
216
+ return {
217
+ code: 'too_large',
218
+ message: '请求体过大:缩短 query 或降低 count',
219
+ retryable: false,
220
+ };
221
+ }
222
+ if (status === 429) {
223
+ // >5s 直接放弃:让模型等一分钟不如把等待时间告诉它
224
+ if (retryAfterMs !== undefined && retryAfterMs > 5_000) {
225
+ return {
226
+ code: 'provider_rate_limited',
227
+ message: `限流:服务端要求 ${Math.round(retryAfterMs / 1000)}s 后重试(超过 5s,本次不再退避)`,
228
+ retryable: false,
229
+ retryAfterMs,
230
+ };
231
+ }
232
+ return {
233
+ code: 'provider_rate_limited',
234
+ message: `限流:${retryAfterMs !== undefined ? `${Math.round(retryAfterMs / 1000)}s 后` : '稍后'}重试(已自动退避 ${attempt} 次)`,
235
+ retryable: true,
236
+ retryAfterMs,
237
+ };
238
+ }
239
+ if (status === 500 || status === 502 || status === 503 || status === 504) {
240
+ return {
241
+ code: 'provider_unavailable',
242
+ message: `${status === 504 ? '网关超时' : '服务端错误'}(已重试 ${attempt} 次)`,
243
+ retryable: true,
244
+ };
245
+ }
246
+ if (status >= 500) {
247
+ return {
248
+ code: 'provider_unavailable',
249
+ message: `服务端错误 ${status}(已重试 ${attempt} 次)`,
250
+ retryable: true,
251
+ };
252
+ }
253
+ return {
254
+ code: 'provider_bad_request',
255
+ message: `客户端错误 ${status}:${reason}`,
256
+ retryable: false,
257
+ };
258
+ }
259
+
260
+ interface NetworkMapping {
261
+ code: WebToolErrorCode;
262
+ message: string;
263
+ retryable: boolean;
264
+ }
265
+
266
+ function mapNetworkError(error: unknown, timedOut: boolean, canceled: boolean): NetworkMapping {
267
+ const name = (error as { name?: string } | null)?.name ?? '';
268
+ const message = error instanceof Error ? error.message : String(error);
269
+ if (canceled) {
270
+ return {
271
+ code: 'connect_failed',
272
+ message: '调用被取消(本次没有完成计费调用)',
273
+ retryable: false,
274
+ };
275
+ }
276
+ if (timedOut || name === 'AbortError' || name === 'TimeoutError') {
277
+ return { code: 'timeout', message: '上游调用超时(整体 deadline 到点)', retryable: true };
278
+ }
279
+ if (/ENOTFOUND|EAI_AGAIN|getaddrinfo|DNS/i.test(message)) {
280
+ return { code: 'dns_failed', message: `DNS 解析失败:${message}`, retryable: true };
281
+ }
282
+ if (/certificate|tls|ssl|self-signed/i.test(message)) {
283
+ return { code: 'tls_error', message: `TLS 握手失败:${message}`, retryable: true };
284
+ }
285
+ return { code: 'connect_failed', message: `连接失败:${message}`, retryable: true };
286
+ }
287
+
288
+ /**
289
+ * 调一次 tools API(含重试)。成功返回解析后的 JSON;失败抛 `WebFetchError`。
290
+ *
291
+ * 非预期异常(例如注入的 fetch 抛了奇怪的东西)一律映射成 `connect_failed`,
292
+ * 由上层按「网络层失败」处理——不把内部栈暴露给模型。
293
+ */
294
+ export async function callDeepSeekTool(options: DeepSeekCallOptions): Promise<DeepSeekCallResult> {
295
+ const config = options.config;
296
+ const deps = options.deps ?? {};
297
+ const doFetch = deps.fetch ?? fetch;
298
+ const now = deps.now ?? (() => Date.now());
299
+ const sleep = deps.sleep ?? defaultSleep;
300
+
301
+ const key = readKey(config, options.keyKind, deps.env ?? process.env, options.keyEnvName);
302
+ if (!key.present) {
303
+ // 缺 key:本地判,不发请求,不静默降级
304
+ throw new WebFetchError('provider_auth_failed', missingKeyMessage(key.envName));
305
+ }
306
+
307
+ const endpoint =
308
+ options.endpoint !== undefined && options.endpoint !== ''
309
+ ? options.endpoint
310
+ : endpointFor(config.baseUrl, options.path);
311
+ // 缺省是 Bearer:只因为 deepseek 是第一个后端,不代表其他家的鉴权风格
312
+ const authHeaders =
313
+ options.authHeaders ?? ((value: string) => ({ authorization: `Bearer ${value}` }));
314
+ const method = options.method ?? 'POST';
315
+ const queryParams: Record<string, string> = {
316
+ ...(options.query ?? {}),
317
+ ...(options.authQuery?.(key.value) ?? {}),
318
+ };
319
+ const target =
320
+ Object.keys(queryParams).length === 0 ? endpoint : appendQuery(endpoint, queryParams);
321
+ const startedAt = now();
322
+ const controller = new AbortController();
323
+ let timedOut = false;
324
+ const timer = setTimeout(() => {
325
+ timedOut = true;
326
+ controller.abort();
327
+ }, config.apiTimeoutMs);
328
+ const onOuterAbort = (): void => controller.abort();
329
+ options.signal?.addEventListener('abort', onOuterAbort, { once: true });
330
+
331
+ const maxAttempts = Math.max(0, config.retryMax) + 1;
332
+ let lastError: WebFetchError | undefined;
333
+ const badRequestHint = options.badRequestHint ?? '检查 query 里的特殊字符与 site/lang/after 格式';
334
+
335
+ try {
336
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
337
+ const attemptStarted = now();
338
+ let mapping: StatusMapping | NetworkMapping;
339
+ let retryAfterMs: number | undefined;
340
+ try {
341
+ const response = await doFetch(target, {
342
+ method,
343
+ redirect: 'manual',
344
+ headers: {
345
+ ...authHeaders(key.value),
346
+ ...(options.headers ?? {}),
347
+ ...(method === 'GET' ? {} : { 'content-type': 'application/json' }),
348
+ accept: 'application/json',
349
+ 'user-agent': config.userAgent,
350
+ },
351
+ ...(method === 'GET' ? {} : { body: JSON.stringify(options.body) }),
352
+ signal: controller.signal,
353
+ });
354
+ // body 读完之前不许清 timer:header 到了、body 挂住是最常见的「超时没生效」
355
+ const text = await response.text();
356
+ const upstreamMs = now() - attemptStarted;
357
+ if (response.ok) {
358
+ let json: unknown;
359
+ try {
360
+ json = text.trim() === '' ? {} : JSON.parse(text);
361
+ } catch {
362
+ throw new WebFetchError(
363
+ 'provider_bad_request',
364
+ '上游返回的不是 JSON(响应形状变了,检查版本号/路径配置)',
365
+ );
366
+ }
367
+ return {
368
+ json,
369
+ status: response.status,
370
+ attempts: attempt + 1,
371
+ upstreamMs,
372
+ latencyMs: now() - startedAt,
373
+ };
374
+ }
375
+ const mapped = mapHttpStatus(
376
+ response.status,
377
+ text,
378
+ key.value,
379
+ response.headers.get('retry-after'),
380
+ now(),
381
+ attempt,
382
+ badRequestHint,
383
+ );
384
+ mapping = mapped;
385
+ retryAfterMs = mapped.retryAfterMs;
386
+ } catch (error) {
387
+ if (error instanceof WebFetchError) throw error;
388
+ mapping = mapNetworkError(error, timedOut, options.signal?.aborted === true);
389
+ }
390
+
391
+ const failure = new WebFetchError(mapping.code, mapping.message);
392
+ if (!mapping.retryable || attempt === maxAttempts - 1) throw failure;
393
+ const waitMs = options.backoff(attempt, retryAfterMs);
394
+ if (now() - startedAt + waitMs >= config.apiTimeoutMs) {
395
+ // 再等就超总 deadline:把最后一次失败如实抛出去,不假装还在重试
396
+ throw failure;
397
+ }
398
+ lastError = failure;
399
+ await sleep(waitMs);
400
+ }
401
+ throw lastError ?? new WebFetchError('timeout', '上游调用超时(整体 deadline 到点)');
402
+ } finally {
403
+ clearTimeout(timer);
404
+ options.signal?.removeEventListener('abort', onOuterAbort);
405
+ }
406
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * `deepseek` 抓取后端:把 URL 交给服务端抓取,拿回 Markdown。
3
+ *
4
+ * 这一节最容易被做假的地方(设计 §2.4 / §9.1):**不许用空值冒充能力**。
5
+ * - `status` 只能固定 200 且 `status_source: "api"`(它不代表目标站点状态);
6
+ * - `redirects: []` 必须配 `redirects_known: false`;
7
+ * - `links: []` 必须配 `links_source: "none"`;
8
+ * - `bytes` 是正文的 UTF-8 字节 ⇒ `bytes_source: "extracted-text"`;
9
+ * - `robots` 只能是 `unknown`(服务端是否遵守 robots 不可知,绝不写 respected)。
10
+ *
11
+ * 安全含义(§6.3):
12
+ * - 我们只做**语法校验**(scheme / port / userinfo / 长度),不做 DNS/IP 判定
13
+ * (请求目标是 api.deepseek.com,「这域名解析到内网」没有意义);
14
+ * - 内网不可达是**特性**,文案不许写成「我们拦住了内网」;
15
+ * - 新增风险 = **数据外发** ⇒ `deepseek_fetch_block_query_string` 缺省开。
16
+ */
17
+
18
+ import type { WebToolsConfig } from './config';
19
+ import {
20
+ callDeepSeekTool,
21
+ DEEPSEEK_FETCH_PATH,
22
+ type DeepSeekDeps,
23
+ pickString,
24
+ } from './deepseek-client';
25
+ import type { FetchBackend, FetchRequest } from './fetch/provider';
26
+ import { checkUrl } from './ssrf';
27
+ import { WebFetchError, type WebFetchResult } from './types';
28
+
29
+ const MAX_URL_CHARS = 2_048;
30
+
31
+ function hostMatches(host: string, entries: readonly string[]): boolean {
32
+ return entries.some((entry) => {
33
+ const cleaned = entry.startsWith('.') ? entry.slice(1) : entry;
34
+ return cleaned !== '' && (host === cleaned || host.endsWith(`.${cleaned}`));
35
+ });
36
+ }
37
+
38
+ /**
39
+ * 本地校验(**不发请求**):
40
+ * 1. 语法(scheme / 端口 / userinfo / 长度)——保证契约一致与快速失败;
41
+ * 2. 私网/环回**字面量**直接拒(明确报错,而不是把垃圾交给服务端);
42
+ * 3. query string 策略(缺省拦,白名单显式放行)。
43
+ */
44
+ export function validateDeepSeekFetchUrl(rawUrl: string, config: WebToolsConfig): URL {
45
+ const input = rawUrl.trim();
46
+ if (input === '') throw new WebFetchError('invalid_input', 'url 不能为空');
47
+ if (input.length > MAX_URL_CHARS) {
48
+ throw new WebFetchError('invalid_input', `url 过长(${input.length} > ${MAX_URL_CHARS} 字符)`);
49
+ }
50
+
51
+ let checked: ReturnType<typeof checkUrl>;
52
+ try {
53
+ checked = checkUrl(input, {
54
+ allowPrivateNetworks: false,
55
+ domainAllowlist: config.domainAllowlist,
56
+ domainDenylist: config.domainDenylist,
57
+ });
58
+ } catch (error) {
59
+ if (error instanceof WebFetchError && error.code === 'blocked_url') {
60
+ throw new WebFetchError(
61
+ 'blocked_url',
62
+ `${error.message};另外注意:deepseek 后端在服务端抓取,内网/环回/本机地址对它不可达(这是后端特性,不是我们拦住了内网);内网或离线调试请用 backend=local`,
63
+ { url: input },
64
+ );
65
+ }
66
+ throw error;
67
+ }
68
+
69
+ const url = checked.url;
70
+ if (config.deepseekFetchBlockQueryString && url.search !== '') {
71
+ if (!hostMatches(checked.host, config.deepseekFetchAllowQueryStringHosts)) {
72
+ throw new WebFetchError(
73
+ 'blocked_by_policy',
74
+ `这是 deepseek 后端的默认策略:带 query string 的 URL 不交给第三方抓取(里面常带一次性 token / 会话 id / 邮箱)。` +
75
+ '两种放行方式:把主机加进 deepseek_fetch_allow_query_string_hosts,或改用 backend=local',
76
+ { url: url.href },
77
+ );
78
+ }
79
+ }
80
+ return url;
81
+ }
82
+
83
+ function byteLength(text: string): number {
84
+ return new TextEncoder().encode(text).byteLength;
85
+ }
86
+
87
+ /** 上游响应里取 Markdown 正文(形状未核 ⇒ 多路径防御,取不到就是 `extract_empty`) */
88
+ function extractMarkdown(payload: unknown): string | undefined {
89
+ return pickString(payload, [
90
+ ['content'],
91
+ ['markdown'],
92
+ ['text'],
93
+ ['body'],
94
+ ['data', 'content'],
95
+ ['data', 'markdown'],
96
+ ['data', 'text'],
97
+ ['result', 'content'],
98
+ ['result', 'markdown'],
99
+ ]);
100
+ }
101
+
102
+ export const deepseekFetchBackend: FetchBackend = {
103
+ id: 'deepseek',
104
+ billed: true,
105
+ requiresKey: true,
106
+
107
+ validate(request: FetchRequest): void {
108
+ validateDeepSeekFetchUrl(request.url, request.config);
109
+ },
110
+
111
+ async fetch(request: FetchRequest): Promise<WebFetchResult> {
112
+ const config = request.config;
113
+ const url = validateDeepSeekFetchUrl(request.url, config);
114
+ const apiDeps: DeepSeekDeps = {
115
+ ...(request.deps.fetch !== undefined ? { fetch: request.deps.fetch } : {}),
116
+ ...(request.deps.now !== undefined ? { now: request.deps.now } : {}),
117
+ ...(request.api ?? {}),
118
+ };
119
+
120
+ const response = await callDeepSeekTool({
121
+ config,
122
+ keyKind: 'fetch',
123
+ path: DEEPSEEK_FETCH_PATH,
124
+ body: { url: url.href },
125
+ backoff: request.backoff,
126
+ deps: apiDeps,
127
+ badRequestHint: '检查 URL 是否可公开访问(内网/环回地址服务端不可达)',
128
+ ...(request.signal !== undefined ? { signal: request.signal } : {}),
129
+ });
130
+
131
+ const markdown = extractMarkdown(response.json);
132
+ if (markdown === undefined || markdown.trim() === '') {
133
+ // 没拿到正文 ⇒ 不计费;不许返回 ok:true + 空正文冒充成功
134
+ throw new WebFetchError(
135
+ 'extract_empty',
136
+ '服务端没有返回正文(本次不计费,也不降级到 local 后端)',
137
+ { url: url.href },
138
+ );
139
+ }
140
+
141
+ const title =
142
+ pickString(response.json, [['title'], ['data', 'title'], ['result', 'title']]) ?? '';
143
+ const now = request.deps.now ?? (() => Date.now());
144
+
145
+ return {
146
+ ok: true,
147
+ // 服务端跳链不可见 ⇒ `url` 只是我们请求的那个
148
+ url: url.href,
149
+ requested_url: request.url,
150
+ status: 200,
151
+ status_source: 'api',
152
+ content_type: 'text/markdown; charset=utf-8',
153
+ format: 'markdown',
154
+ bytes: byteLength(markdown),
155
+ bytes_source: 'extracted-text',
156
+ fetched_at: new Date(now()).toISOString(),
157
+ title,
158
+ text: markdown,
159
+ truncated: false,
160
+ links: [],
161
+ links_source: 'none',
162
+ redirects: [],
163
+ redirects_known: false,
164
+ robots: 'unknown',
165
+ backend: 'deepseek',
166
+ };
167
+ },
168
+ };