pi-auto-web-search 0.1.1

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/tools.ts ADDED
@@ -0,0 +1,928 @@
1
+ import { statSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import type { ExtensionCommandContext, Theme, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
+ import type { JsonValue } from "@earendil-works/pi-ai";
5
+ import { Text } from "@earendil-works/pi-tui";
6
+ import { Type, type Static } from "typebox";
7
+ import { callableInstance, ConfigStore, type LoadedConfig, type ResolveConfigOptions } from "./config.ts";
8
+ import {
9
+ CloudflareOAuth,
10
+ DEFAULT_CONFIG_PATH,
11
+ readOAuthToken,
12
+ type OAuthToken,
13
+ } from "./cloudflare-oauth.ts";
14
+ import { HttpClient, ProviderError, type ProviderAttempt } from "./http.ts";
15
+ import { formatInstanceQuotaSummary, UsageStore } from "./key-quota.ts";
16
+ import { SearchService, type ExtractResponse, type MapResponse, type SearchResponse } from "./search-service.ts";
17
+ import { openSearchPanel, runCloudflareLogin, runCloudflareLogout } from "./settings-ui.ts";
18
+ import type { MapLink, SearchResult } from "./adapters/types.ts";
19
+
20
+ /** 单条摘要在工具输出里的上限,避免把长正文全部塞回模型上下文。 */
21
+ const SNIPPET_CHARS = 400;
22
+
23
+ /** contents 为 markdown 时单条结果的正文上限。 */
24
+ const CONTENT_CHARS = 2_000;
25
+
26
+ /** 抓取正文上限;超出部分截断并在结果里标注。 */
27
+ const FETCH_CHARS = 12_000;
28
+
29
+ /** 工具支持的搜索与抓取结果格式。 */
30
+ const FETCH_FORMATS = ["markdown", "text", "html", "json", "links"] as const;
31
+
32
+ type FetchFormat = (typeof FETCH_FORMATS)[number];
33
+
34
+ /** 配置文件路径:默认 ~/.pi/agent/search.json,PI_SEARCH_CONFIG 供测试与临时配置覆盖。 */
35
+ export function resolveConfigPath(env: NodeJS.ProcessEnv = process.env): string {
36
+ return env.PI_SEARCH_CONFIG ?? DEFAULT_CONFIG_PATH;
37
+ }
38
+
39
+ export interface SearchRuntimeOptions {
40
+ configPath: string;
41
+ /** Cloudflare OAuth 令牌文件路径,默认与配置文件同目录下的 search-oauth.json。 */
42
+ tokenPath?: string;
43
+ /** 按密钥调用次数记录文件路径,默认与配置文件同目录下的 search-usage.json。 */
44
+ usagePath?: string;
45
+ env?: NodeJS.ProcessEnv;
46
+ clock?: () => number;
47
+ /** 仅供测试注入 OAuth 端点与 fetch 实现。 */
48
+ oauthFetch?: typeof globalThis.fetch;
49
+ oauthAccountsUrl?: string;
50
+ oauthRevokeUrl?: string;
51
+ }
52
+
53
+ /** 搜索与抓取工具的运行期状态:配置未变时复用同一个 HttpClient,冷却与并发闸门才能跨调用生效。 */
54
+ export class SearchRuntime {
55
+ readonly configPath: string;
56
+ readonly tokenPath: string;
57
+ readonly usagePath: string;
58
+ readonly store: ConfigStore;
59
+ readonly usage: UsageStore;
60
+ readonly env: NodeJS.ProcessEnv;
61
+ private readonly clock?: () => number;
62
+ private readonly oauthFetch?: typeof globalThis.fetch;
63
+ private readonly oauthAccountsUrl?: string;
64
+ private readonly oauthRevokeUrl?: string;
65
+ private loaded?: { signature: string; config: LoadedConfig; service: SearchService };
66
+ private oauthCache?: { key: string; client: CloudflareOAuth };
67
+ private readonly failures = new Map<string, string>();
68
+
69
+ constructor(options: SearchRuntimeOptions) {
70
+ this.configPath = options.configPath;
71
+ this.tokenPath = options.tokenPath ?? join(dirname(options.configPath), "search-oauth.json");
72
+ this.usagePath = options.usagePath ?? join(dirname(options.configPath), "search-usage.json");
73
+ this.store = new ConfigStore(options.configPath);
74
+ this.clock = options.clock;
75
+ this.usage = new UsageStore({ filePath: this.usagePath, clock: this.clock });
76
+ this.env = options.env ?? process.env;
77
+ this.oauthFetch = options.oauthFetch;
78
+ this.oauthAccountsUrl = options.oauthAccountsUrl;
79
+ this.oauthRevokeUrl = options.oauthRevokeUrl;
80
+ }
81
+
82
+ /** 当前本地保存的 Cloudflare OAuth 令牌。 */
83
+ oauthToken(): OAuthToken | undefined {
84
+ return readOAuthToken(this.tokenPath);
85
+ }
86
+
87
+ /** 供配置解析使用的 OAuth 摘要,让无静态 key 的 cloudflare sdk 实例在登录后立即就绪。 */
88
+ resolveOptions(): ResolveConfigOptions {
89
+ const token = this.oauthToken();
90
+ return token ? { cloudflareOAuthToken: { accountId: token.account_id || undefined } } : {};
91
+ }
92
+
93
+ /** 复用同一个 CloudflareOAuth 实例,保留 beginLogin → completeLogin 之间的内存 state。 */
94
+ cloudflareOAuth(config?: LoadedConfig): CloudflareOAuth {
95
+ const oauthConfig = (config ?? this.store.load(this.env, this.resolveOptions())).cloudflareOAuth;
96
+ const key = JSON.stringify(oauthConfig);
97
+ if (this.oauthCache?.key !== key) {
98
+ this.oauthCache = {
99
+ key,
100
+ client: new CloudflareOAuth({
101
+ config: oauthConfig,
102
+ configPath: this.configPath,
103
+ tokenPath: this.tokenPath,
104
+ env: this.env,
105
+ fetch: this.oauthFetch,
106
+ accountsUrl: this.oauthAccountsUrl,
107
+ revokeUrl: this.oauthRevokeUrl,
108
+ }),
109
+ };
110
+ }
111
+ return this.oauthCache.client;
112
+ }
113
+
114
+ /** 读取配置并返回服务;配置或 OAuth 令牌文件改动后重建,解析失败时直接抛出配置错误。 */
115
+ snapshot(): { config: LoadedConfig; service: SearchService } {
116
+ const signature = this.signature();
117
+ if (this.loaded?.signature !== signature) {
118
+ const config = this.store.load(this.env, this.resolveOptions());
119
+ const cloudflareOAuth = this.cloudflareOAuth(config);
120
+ const service = new SearchService(
121
+ config,
122
+ new HttpClient(config, {
123
+ env: this.env,
124
+ cloudflareOAuth,
125
+ usage: this.usage,
126
+ clock: this.clock,
127
+ }),
128
+ );
129
+ this.loaded = { signature, config, service };
130
+ }
131
+ return this.loaded;
132
+ }
133
+
134
+ /** 配置或 OAuth 状态写入后丢弃缓存,让下一次 snapshot 重新解析。 */
135
+ reload(): void {
136
+ this.loaded = undefined;
137
+ }
138
+
139
+ /** 记下失败实例的原因,面板据此显示「上次错误」。 */
140
+ recordFailure(instance: string, message: string): void {
141
+ if (instance) this.failures.set(instance, message);
142
+ }
143
+
144
+ clearFailure(instance: string): void {
145
+ this.failures.delete(instance);
146
+ }
147
+
148
+ lastFailure(instance: string): string | undefined {
149
+ return this.failures.get(instance);
150
+ }
151
+
152
+ private signature(): string {
153
+ return `${fileSignature(this.configPath)}|${fileSignature(this.tokenPath)}`;
154
+ }
155
+ }
156
+
157
+ function fileSignature(path: string): string {
158
+ try {
159
+ const stats = statSync(path);
160
+ return `${stats.mtimeMs}:${stats.size}`;
161
+ } catch {
162
+ return "missing";
163
+ }
164
+ }
165
+
166
+ /** 纯 enum 的字符串枚举:各供应商都接受,且能保留字面量类型。 */
167
+ function stringEnum<const T extends readonly string[]>(values: T, description: string) {
168
+ return Type.Unsafe<T[number]>({ type: "string", enum: [...values], description });
169
+ }
170
+
171
+ /** 搜索工具参数。 */
172
+ const searchParameters = Type.Object({
173
+ query: Type.String({ description: "搜索关键词" }),
174
+ instance: Type.Optional(Type.String({ description: "指定实例 id,跳过默认链" })),
175
+ chain: Type.Optional(Type.Array(Type.String(), { description: "临时覆盖实例顺序" })),
176
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "结果条数,默认 10,上限 20" })),
177
+ quality: Type.Optional(
178
+ stringEnum(["basic", "advanced", "deep"] as const, "搜索深度或推理档位,默认 basic,各供应商按自身能力映射"),
179
+ ),
180
+ sourceMode: Type.Optional(
181
+ stringEnum(
182
+ ["public", "authoritative", "mixed"] as const,
183
+ "信源范围,默认按供应商默认信源;腾讯云对应官方 Mode(0 公开 / 1 权威 / 2 混合)",
184
+ ),
185
+ ),
186
+ topic: Type.Optional(
187
+ stringEnum(["general", "news"] as const, "搜索主题,默认不传;news 映射各供应商的新闻入口"),
188
+ ),
189
+ country: Type.Optional(
190
+ Type.String({ description: "地区偏好,ISO 3166-1 alpha-2 两字母代码(如 US、JP),仅影响结果排序偏置" }),
191
+ ),
192
+ domains: Type.Optional(Type.Array(Type.String(), { description: "只保留这些域名" })),
193
+ excludeDomains: Type.Optional(Type.Array(Type.String(), { description: "排除这些域名" })),
194
+ freshness: Type.Optional(stringEnum(["day", "week", "month", "year"] as const, "结果时间范围")),
195
+ contents: Type.Optional(stringEnum(["none", "summary", "markdown"] as const, "结果正文的形式")),
196
+ answer: Type.Optional(Type.Boolean({ description: "同时返回整理后的答案,仅部分供应商支持" })),
197
+ });
198
+
199
+ /** 站点地图工具参数。 */
200
+ const mapParameters = Type.Object({
201
+ url: Type.String({ description: "要遍历的 http(s) 站点地址" }),
202
+ instructions: Type.Optional(
203
+ Type.String({ description: "站点地图指引,仅 Tavily 兑现;Firecrawl 跳过并写 notes" }),
204
+ ),
205
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "返回 URL 条数,默认 50,上限 100" })),
206
+ instance: Type.Optional(Type.String({ description: "指定实例 id,跳过默认链" })),
207
+ chain: Type.Optional(Type.Array(Type.String(), { description: "临时覆盖实例顺序" })),
208
+ });
209
+
210
+ /** 抓取工具参数。 */
211
+ const fetchParameters = Type.Object({
212
+ url: Type.String({ description: "要抓取的 http(s) 地址" }),
213
+ format: Type.Optional(
214
+ stringEnum(
215
+ FETCH_FORMATS,
216
+ "markdown(默认)、text、html、json、links;text 由 Tavily 原生 format=text 兑现,其余实例抓 markdown 再本地转换;html/json/links 仅 Firecrawl 与 Cloudflare 兑现,其余实例跳过",
217
+ ),
218
+ ),
219
+ schema: Type.Optional(
220
+ Type.Record(Type.String(), Type.Unknown(), {
221
+ description: "JSON 抓取结构;不传 format 时当作 json;Firecrawl 与 Cloudflare 支持",
222
+ }),
223
+ ),
224
+ instance: Type.Optional(Type.String({ description: "指定实例 id,跳过默认抓取链" })),
225
+ });
226
+
227
+ /** 搜索成功的结构化输出。 */
228
+ const searchSuccessOutput = Type.Object({
229
+ query: Type.String(),
230
+ instance: Type.String(),
231
+ providerUsed: Type.String(),
232
+ degraded: Type.Boolean(),
233
+ elapsedMs: Type.Number(),
234
+ notes: Type.Array(Type.String()),
235
+ answer: Type.Optional(Type.String()),
236
+ results: Type.Array(
237
+ Type.Object({
238
+ title: Type.String(),
239
+ url: Type.String(),
240
+ instance: Type.String(),
241
+ providerUsed: Type.String(),
242
+ snippet: Type.Optional(Type.String()),
243
+ content: Type.Optional(Type.String()),
244
+ date: Type.Optional(Type.String()),
245
+ score: Type.Optional(Type.Number()),
246
+ degraded: Type.Optional(Type.Boolean()),
247
+ }),
248
+ ),
249
+ });
250
+
251
+ /** 站点地图成功的结构化输出。 */
252
+ const mapSuccessOutput = Type.Object({
253
+ url: Type.String(),
254
+ instance: Type.String(),
255
+ providerUsed: Type.String(),
256
+ degraded: Type.Boolean(),
257
+ elapsedMs: Type.Number(),
258
+ notes: Type.Array(Type.String()),
259
+ links: Type.Array(
260
+ Type.Object({
261
+ url: Type.String(),
262
+ title: Type.Optional(Type.String()),
263
+ description: Type.Optional(Type.String()),
264
+ }),
265
+ ),
266
+ });
267
+
268
+ /** 抓取成功的结构化输出。 */
269
+ const fetchSuccessOutput = Type.Object({
270
+ url: Type.String(),
271
+ instance: Type.String(),
272
+ providerUsed: Type.String(),
273
+ degraded: Type.Boolean(),
274
+ elapsedMs: Type.Number(),
275
+ format: Type.String(),
276
+ chars: Type.Number(),
277
+ truncated: Type.Boolean(),
278
+ notes: Type.Array(Type.String()),
279
+ title: Type.Optional(Type.String()),
280
+ content: Type.String(),
281
+ });
282
+
283
+ /** 失败时的结构化输出:错误摘要、按顺序排列的尝试链与未尝试实例。 */
284
+ const failureOutput = Type.Object({
285
+ error: Type.String(),
286
+ attempts: Type.Array(
287
+ Type.Object({
288
+ instance: Type.String(),
289
+ provider: Type.String(),
290
+ code: Type.String(),
291
+ status: Type.Optional(Type.Number()),
292
+ message: Type.String(),
293
+ }),
294
+ ),
295
+ unattempted: Type.Array(
296
+ Type.Object({
297
+ instance: Type.String(),
298
+ provider: Type.String(),
299
+ }),
300
+ ),
301
+ });
302
+
303
+ /** 搜索工具的结构化输出,覆盖成功结果与失败尝试链。 */
304
+ const searchOutput = Type.Union([searchSuccessOutput, failureOutput]);
305
+
306
+ /** 抓取工具的结构化输出,覆盖成功正文与失败尝试链。 */
307
+ const fetchOutput = Type.Union([fetchSuccessOutput, failureOutput]);
308
+
309
+ /** 站点地图工具的结构化输出,覆盖成功链接与失败尝试链。 */
310
+ const mapOutput = Type.Union([mapSuccessOutput, failureOutput]);
311
+
312
+ type SearchParams = Static<typeof searchParameters>;
313
+
314
+ type FetchParams = Static<typeof fetchParameters>;
315
+
316
+ type MapToolParams = Static<typeof mapParameters>;
317
+
318
+ /** 搜索工具的结果详情,供 TUI 渲染与测试使用。 */
319
+ export interface SearchDetails {
320
+ instance: string;
321
+ providerUsed: string;
322
+ count: number;
323
+ elapsedMs: number;
324
+ degraded: boolean;
325
+ items: string[];
326
+ error?: string;
327
+ }
328
+
329
+ /** 抓取工具的结果详情。 */
330
+ export interface FetchDetails {
331
+ instance: string;
332
+ providerUsed: string;
333
+ chars: number;
334
+ elapsedMs: number;
335
+ degraded: boolean;
336
+ title?: string;
337
+ error?: string;
338
+ }
339
+
340
+ /** 站点地图工具的结果详情。 */
341
+ export interface MapDetails {
342
+ instance: string;
343
+ providerUsed: string;
344
+ count: number;
345
+ elapsedMs: number;
346
+ degraded: boolean;
347
+ items: string[];
348
+ error?: string;
349
+ }
350
+
351
+ function messageOf(error: unknown): string {
352
+ return error instanceof Error ? error.message : String(error);
353
+ }
354
+
355
+ /** 把失败翻译成用户能读懂的一句话,附带按顺序排列的尝试链,不重复上游 body。 */
356
+ export function failureText(error: unknown, configPath: string): string {
357
+ if (!(error instanceof ProviderError)) {
358
+ return `读取配置或请求失败:${messageOf(error)}。运行 /search 查看实例状态(${configPath})`;
359
+ }
360
+ if (error.code === "aborted") return "请求已取消";
361
+ const parts = [error.message];
362
+ if (error.attempts.length > 0) {
363
+ parts.push(`尝试链:${error.attempts.map(attemptLabel).join(" → ")}`);
364
+ }
365
+ if (error.requestId) parts.push(`请求 ${error.requestId}`);
366
+ if (error.retryAfter !== undefined) parts.push(`建议 ${error.retryAfter}s 后重试`);
367
+ const text = parts.join(";");
368
+ if (error.message.includes("没有可调用的实例") || error.message.includes("实例不可用")) {
369
+ return `${text}。运行 /search 查看实例状态(${configPath})`;
370
+ }
371
+ return text;
372
+ }
373
+
374
+ /** 尝试链的一环:实例、供应商与错误分类。 */
375
+ function attemptLabel(attempt: ProviderAttempt): string {
376
+ return `${attempt.instance}(${attempt.provider})${failureLabel(attempt.code, attempt.status)}`;
377
+ }
378
+
379
+ /** 失败结果的结构化内容;没有发出请求的配置或参数错误保持空尝试链,不编造供应商。 */
380
+ function failureJson(error: unknown, message: string): Record<string, JsonValue> {
381
+ if (!(error instanceof ProviderError)) return { error: message, attempts: [], unattempted: [] };
382
+ return {
383
+ error: message,
384
+ attempts: error.attempts.map(attemptJson),
385
+ unattempted: error.unattempted.map((item) => ({ instance: item.instance, provider: item.provider })),
386
+ };
387
+ }
388
+
389
+ /** 单次尝试的 JSON 形态,作为 structuredContent 的一部分。 */
390
+ function attemptJson(attempt: ProviderAttempt): JsonValue {
391
+ return {
392
+ instance: attempt.instance,
393
+ provider: attempt.provider,
394
+ code: attempt.code,
395
+ ...(attempt.status === undefined ? {} : { status: attempt.status }),
396
+ message: attempt.message,
397
+ };
398
+ }
399
+
400
+ /** 把链上每个失败实例的原因记到运行期状态,面板按实例显示;取消本身不算实例失败。 */
401
+ function rememberFailures(runtime: SearchRuntime, error: unknown): void {
402
+ if (!(error instanceof ProviderError)) return;
403
+ if (error.attempts.length === 0) {
404
+ if (error.code !== "aborted") {
405
+ runtime.recordFailure(error.instance, failureLabel(error.code, error.status));
406
+ }
407
+ return;
408
+ }
409
+ for (const failure of error.attempts) {
410
+ runtime.recordFailure(failure.instance, failureLabel(failure.code, failure.status));
411
+ }
412
+ }
413
+
414
+ function failureLabel(code: string, status: number | undefined): string {
415
+ return status === undefined ? code : `${code} ${status}`;
416
+ }
417
+
418
+ function clip(text: string, limit: number): string {
419
+ const value = text.trim();
420
+ return value.length > limit ? `${value.slice(0, limit)}…` : value;
421
+ }
422
+
423
+ /** 秒级与毫秒级的时长写法。 */
424
+ function formatDuration(elapsedMs: number): string {
425
+ return elapsedMs < 1_000 ? `${elapsedMs} ms` : `${(elapsedMs / 1_000).toFixed(1)} s`;
426
+ }
427
+
428
+ /** markdown 转纯文本:去掉标题、强调、链接与代码围栏标记,保留正文。 */
429
+ function toPlainText(markdown: string): string {
430
+ return markdown
431
+ .replace(/```[^\n]*\n([\s\S]*?)```/g, "$1")
432
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
433
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
434
+ .replace(/^\s{0,3}#{1,6}\s+/gm, "")
435
+ .replace(/(\*\*|__)(.*?)\1/g, "$2")
436
+ .replace(/`([^`]*)`/g, "$1")
437
+ .replace(/^\s*>\s?/gm, "")
438
+ .replace(/\n{3,}/g, "\n\n")
439
+ .trim();
440
+ }
441
+
442
+ /** 单条站点地图链接的 JSON 形态,作为 structuredContent 的一部分。 */
443
+ function linkJson(item: MapLink): Record<string, JsonValue> {
444
+ const json: Record<string, JsonValue> = { url: item.url };
445
+ if (item.title !== undefined) json.title = item.title;
446
+ if (item.description !== undefined) json.description = item.description;
447
+ return json;
448
+ }
449
+
450
+ /** 单条结果的 JSON 形态,作为 structuredContent 的一部分。 */
451
+ function resultJson(item: SearchResult): Record<string, JsonValue> {
452
+ const json: Record<string, JsonValue> = {
453
+ title: item.title,
454
+ url: item.url,
455
+ instance: item.instance,
456
+ providerUsed: item.providerUsed,
457
+ };
458
+ if (item.snippet !== undefined) json.snippet = item.snippet;
459
+ if (item.content !== undefined) json.content = item.content;
460
+ if (item.date !== undefined) json.date = item.date;
461
+ if (item.score !== undefined) json.score = item.score;
462
+ if (item.degraded !== undefined) json.degraded = item.degraded;
463
+ return json;
464
+ }
465
+
466
+ /** 模型看到的搜索结果文本。 */
467
+ function searchText(response: SearchResponse, elapsedMs: number): string {
468
+ const lines = [
469
+ `实例 ${response.instance}(${response.providerUsed})`,
470
+ `${response.results.length} 条结果,耗时 ${formatDuration(elapsedMs)}${response.degraded ? ",已降级" : ""}`,
471
+ ];
472
+ if (response.answer) lines.push("", `答案:${response.answer}`);
473
+ response.results.forEach((item, index) => {
474
+ lines.push("", `${index + 1}. ${item.title}`, ` ${item.url}`);
475
+ if (item.date) lines.push(` 日期:${item.date}`);
476
+ const body = item.snippet ?? item.content;
477
+ if (body) lines.push(` ${clip(body, item.snippet ? SNIPPET_CHARS : CONTENT_CHARS)}`);
478
+ });
479
+ if (response.notes.length > 0) lines.push("", `备注:${response.notes.join(";")}`);
480
+ return lines.join("\n");
481
+ }
482
+
483
+ /** 模型看到的站点地图结果文本。 */
484
+ function mapText(response: MapResponse, elapsedMs: number): string {
485
+ const lines = [
486
+ `实例 ${response.instance}(${response.providerUsed})`,
487
+ `${response.links.length} 条结果,耗时 ${formatDuration(elapsedMs)}${response.degraded ? ",已降级" : ""}`,
488
+ ];
489
+ response.links.forEach((item, index) => {
490
+ if (item.title) {
491
+ lines.push("", `${index + 1}. ${item.title}`, ` ${item.url}`);
492
+ } else {
493
+ lines.push("", `${index + 1}. ${item.url}`);
494
+ }
495
+ });
496
+ if (response.notes.length > 0) lines.push("", `备注:${response.notes.join(";")}`);
497
+ return lines.join("\n");
498
+ }
499
+
500
+ /** 模型看到的抓取结果文本。 */
501
+ function fetchText(response: ExtractResponse, content: string, truncated: boolean): string {
502
+ const lines = [`实例 ${response.instance}(${response.providerUsed})`, `地址:${response.url}`];
503
+ if (response.title) lines.push(`标题:${response.title}`);
504
+ lines.push("", content);
505
+ if (truncated) lines.push("", `正文已截断到 ${FETCH_CHARS} 字符`);
506
+ if (response.notes.length > 0) lines.push("", `备注:${response.notes.join(";")}`);
507
+ return lines.join("\n");
508
+ }
509
+
510
+ /** 搜索结果的 TUI 摘要:实例、供应商、结果数、耗时、是否降级。 */
511
+ function searchSummary(details: SearchDetails, theme: Theme, expanded: boolean): string {
512
+ if (details.error) return theme.fg("error", `失败:${details.error}`);
513
+ let text =
514
+ theme.fg("accent", details.instance) +
515
+ theme.fg("dim", `(${details.providerUsed}) · ${details.count} 条 · ${formatDuration(details.elapsedMs)}`);
516
+ if (details.degraded) text += theme.fg("warning", " · 降级");
517
+ if (expanded && details.items.length > 0) {
518
+ text += `\n${details.items.map((item) => theme.fg("muted", item)).join("\n")}`;
519
+ }
520
+ return text;
521
+ }
522
+
523
+ /** 抓取结果的 TUI 摘要:实例、供应商、字符数、耗时。 */
524
+ function fetchSummary(details: FetchDetails, theme: Theme, expanded: boolean): string {
525
+ if (details.error) return theme.fg("error", `失败:${details.error}`);
526
+ let text =
527
+ theme.fg("accent", details.instance) +
528
+ theme.fg("dim", `(${details.providerUsed}) · ${details.chars} 字符 · ${formatDuration(details.elapsedMs)}`);
529
+ if (details.degraded) text += theme.fg("warning", " · 降级");
530
+ if (expanded && details.title) text += `\n${theme.fg("muted", details.title)}`;
531
+ return text;
532
+ }
533
+
534
+ /** 搜索工具:参数校验交由 search-service,这里只负责翻译错误与组织输出。 */
535
+ export function createSearchTool(runtime: SearchRuntime): ToolDefinition<typeof searchParameters, SearchDetails> {
536
+ return {
537
+ name: "web-search",
538
+ label: "Web Search",
539
+ description: "搜索互联网并返回带供应商来源的统一结果;支持多实例自动故障切换,失败时返回尝试链与原因。",
540
+ promptSnippet: "Search the web through the configured provider chain",
541
+ promptGuidelines: [
542
+ "Use web-search for internet searches and cite the returned urls.",
543
+ "Use web-fetch when a page's full content is needed instead of a snippet.",
544
+ "Use web-map to discover URLs on a website.",
545
+ ],
546
+ parameters: searchParameters,
547
+ outputSchema: searchOutput,
548
+ async execute(_toolCallId, params: SearchParams, signal) {
549
+ const started = Date.now();
550
+ try {
551
+ const { service } = runtime.snapshot();
552
+ const response = await service.search({
553
+ query: params.query,
554
+ limit: params.limit,
555
+ quality: params.quality,
556
+ sourceMode: params.sourceMode,
557
+ topic: params.topic,
558
+ country: params.country,
559
+ domains: params.domains,
560
+ excludeDomains: params.excludeDomains,
561
+ freshness: params.freshness,
562
+ contents: params.contents,
563
+ answer: params.answer,
564
+ instance: params.instance,
565
+ chain: params.chain,
566
+ signal,
567
+ });
568
+ const elapsedMs = Date.now() - started;
569
+ runtime.clearFailure(response.instance);
570
+ return {
571
+ content: [{ type: "text", text: searchText(response, elapsedMs) }],
572
+ details: {
573
+ instance: response.instance,
574
+ providerUsed: response.providerUsed,
575
+ count: response.results.length,
576
+ elapsedMs,
577
+ degraded: response.degraded,
578
+ items: response.results.map((item) => item.title),
579
+ },
580
+ structuredContent: {
581
+ query: params.query,
582
+ instance: response.instance,
583
+ providerUsed: response.providerUsed,
584
+ degraded: response.degraded,
585
+ elapsedMs,
586
+ notes: response.notes,
587
+ ...(response.answer === undefined ? {} : { answer: response.answer }),
588
+ results: response.results.map(resultJson),
589
+ },
590
+ };
591
+ } catch (error) {
592
+ const message = failureText(error, runtime.configPath);
593
+ rememberFailures(runtime, error);
594
+ return {
595
+ content: [{ type: "text", text: message }],
596
+ details: {
597
+ instance: "",
598
+ providerUsed: "",
599
+ count: 0,
600
+ elapsedMs: Date.now() - started,
601
+ degraded: false,
602
+ items: [],
603
+ error: message,
604
+ },
605
+ structuredContent: failureJson(error, message),
606
+ isError: true,
607
+ };
608
+ }
609
+ },
610
+ renderCall(args, theme) {
611
+ let text = theme.fg("toolTitle", theme.bold("web-search ")) + theme.fg("muted", `"${args.query}"`);
612
+ const hints = [args.instance && `实例 ${args.instance}`, args.limit !== undefined && `${args.limit} 条`];
613
+ const visible = hints.filter((hint): hint is string => Boolean(hint));
614
+ if (visible.length > 0) text += theme.fg("dim", ` · ${visible.join(" · ")}`);
615
+ return new Text(text, 0, 0);
616
+ },
617
+ renderResult(result, { expanded }, theme) {
618
+ return new Text(searchSummary(result.details, theme, expanded), 0, 0);
619
+ },
620
+ };
621
+ }
622
+
623
+ /** 抓取工具:支持 markdown、text、html、json、links,正文截断后返回。 */
624
+ export function createFetchTool(runtime: SearchRuntime): ToolDefinition<typeof fetchParameters, FetchDetails> {
625
+ return {
626
+ name: "web-fetch",
627
+ label: "Web Fetch",
628
+ description: "抓取单个网页正文,默认返回实时 Markdown,也可转为纯文本,或按 html / json / links 提取;支持多实例自动故障切换。",
629
+ promptSnippet: "Fetch a web page as markdown, text, html, json, or links",
630
+ parameters: fetchParameters,
631
+ outputSchema: fetchOutput,
632
+ async execute(_toolCallId, params: FetchParams, signal) {
633
+ const started = Date.now();
634
+ const format: FetchFormat =
635
+ params.schema !== undefined && params.format === undefined
636
+ ? "json"
637
+ : (params.format ?? "markdown");
638
+
639
+ try {
640
+ const { service } = runtime.snapshot();
641
+ const response = await service.extract({
642
+ url: params.url,
643
+ format,
644
+ instance: params.instance,
645
+ signal,
646
+ ...(params.schema === undefined ? {} : { schema: params.schema }),
647
+ });
648
+ const body = format === "text" ? toPlainText(response.content) : response.content;
649
+ const truncated = body.length > FETCH_CHARS;
650
+ const content = truncated ? body.slice(0, FETCH_CHARS) : body;
651
+ const elapsedMs = Date.now() - started;
652
+ runtime.clearFailure(response.instance);
653
+ return {
654
+ content: [{ type: "text", text: fetchText(response, content, truncated) }],
655
+ details: {
656
+ instance: response.instance,
657
+ providerUsed: response.providerUsed,
658
+ chars: content.length,
659
+ elapsedMs,
660
+ degraded: response.degraded,
661
+ ...(response.title === undefined ? {} : { title: response.title }),
662
+ },
663
+ structuredContent: {
664
+ url: response.url,
665
+ instance: response.instance,
666
+ providerUsed: response.providerUsed,
667
+ degraded: response.degraded,
668
+ elapsedMs,
669
+ format,
670
+ chars: content.length,
671
+ truncated,
672
+ notes: response.notes,
673
+ ...(response.title === undefined ? {} : { title: response.title }),
674
+ content,
675
+ },
676
+ };
677
+ } catch (error) {
678
+ const message = failureText(error, runtime.configPath);
679
+ rememberFailures(runtime, error);
680
+ return {
681
+ content: [{ type: "text", text: message }],
682
+ details: {
683
+ instance: "",
684
+ providerUsed: "",
685
+ chars: 0,
686
+ elapsedMs: Date.now() - started,
687
+ degraded: false,
688
+ error: message,
689
+ },
690
+ structuredContent: failureJson(error, message),
691
+ isError: true,
692
+ };
693
+ }
694
+ },
695
+ renderCall(args, theme) {
696
+ let text = theme.fg("toolTitle", theme.bold("web-fetch ")) + theme.fg("muted", args.url);
697
+ const hints = [args.format && args.format, args.instance && `实例 ${args.instance}`];
698
+ const visible = hints.filter((hint): hint is string => Boolean(hint));
699
+ if (visible.length > 0) text += theme.fg("dim", ` · ${visible.join(" · ")}`);
700
+ return new Text(text, 0, 0);
701
+ },
702
+ renderResult(result, { expanded }, theme) {
703
+ return new Text(fetchSummary(result.details, theme, expanded), 0, 0);
704
+ },
705
+ };
706
+ }
707
+
708
+ /** 站点地图工具:遍历站点发现 URL,目前 Tavily 与 Firecrawl 兑现。 */
709
+ export function createMapTool(runtime: SearchRuntime): ToolDefinition<typeof mapParameters, MapDetails> {
710
+ return {
711
+ name: "web-map",
712
+ label: "Web Map",
713
+ description: "遍历站点发现 URL,目前 Tavily 与 Firecrawl 兑现,支持故障切换。",
714
+ promptSnippet: "Map a website to a list of URLs",
715
+ promptGuidelines: [
716
+ "Use web-map to discover which pages exist on a website.",
717
+ "Use web-fetch when a page's full content is needed.",
718
+ ],
719
+ parameters: mapParameters,
720
+ outputSchema: mapOutput,
721
+ async execute(_toolCallId, params: MapToolParams, signal) {
722
+ const started = Date.now();
723
+ try {
724
+ const { service } = runtime.snapshot();
725
+ const response = await service.map({
726
+ url: params.url,
727
+ instructions: params.instructions,
728
+ limit: params.limit,
729
+ instance: params.instance,
730
+ chain: params.chain,
731
+ signal,
732
+ });
733
+ const elapsedMs = Date.now() - started;
734
+ runtime.clearFailure(response.instance);
735
+ return {
736
+ content: [{ type: "text", text: mapText(response, elapsedMs) }],
737
+ details: {
738
+ instance: response.instance,
739
+ providerUsed: response.providerUsed,
740
+ count: response.links.length,
741
+ elapsedMs,
742
+ degraded: response.degraded,
743
+ items: response.links.map((item) => item.title ?? item.url),
744
+ },
745
+ structuredContent: {
746
+ url: response.url,
747
+ instance: response.instance,
748
+ providerUsed: response.providerUsed,
749
+ degraded: response.degraded,
750
+ elapsedMs,
751
+ notes: response.notes,
752
+ links: response.links.map(linkJson),
753
+ },
754
+ };
755
+ } catch (error) {
756
+ const message = failureText(error, runtime.configPath);
757
+ rememberFailures(runtime, error);
758
+ return {
759
+ content: [{ type: "text", text: message }],
760
+ details: {
761
+ instance: "",
762
+ providerUsed: "",
763
+ count: 0,
764
+ elapsedMs: Date.now() - started,
765
+ degraded: false,
766
+ items: [],
767
+ error: message,
768
+ },
769
+ structuredContent: failureJson(error, message),
770
+ isError: true,
771
+ };
772
+ }
773
+ },
774
+ renderCall(args, theme) {
775
+ let text = theme.fg("toolTitle", theme.bold("web-map ")) + theme.fg("muted", args.url);
776
+ const hints = [args.instance && `实例 ${args.instance}`, args.limit !== undefined && `${args.limit} 条`];
777
+ const visible = hints.filter((hint): hint is string => Boolean(hint));
778
+ if (visible.length > 0) text += theme.fg("dim", ` · ${visible.join(" · ")}`);
779
+ return new Text(text, 0, 0);
780
+ },
781
+ renderResult(result, { expanded }, theme) {
782
+ return new Text(searchSummary(result.details, theme, expanded), 0, 0);
783
+ },
784
+ };
785
+ }
786
+
787
+ /** 实例状态列表;配置文件缺失时提示去哪里创建。 */
788
+ export function statusText(runtime: SearchRuntime): string {
789
+ const header = `搜索配置:${runtime.configPath}`;
790
+ let config: LoadedConfig;
791
+ try {
792
+ config = runtime.snapshot().config;
793
+ } catch (error) {
794
+ return [header, `读取失败:${messageOf(error)}`].join("\n");
795
+ }
796
+ if (config.instances.length === 0) {
797
+ return [
798
+ header,
799
+ "还没有实例。在该文件里加入,例如:",
800
+ '{"instances": [{"id": "anysearch", "preset": "anysearch", "mode": "sdk", "keys": []}]}',
801
+ "保存后运行 /search 查看状态,/search test [实例] 发一次真实请求。",
802
+ ].join("\n");
803
+ }
804
+
805
+ const width = Math.max(...config.instances.map((instance) => instance.id.length));
806
+ const lines = [header, "实例:"];
807
+ for (const instance of config.instances) {
808
+ const state = !instance.enabled ? "已禁用" : callableInstance(instance) ? "已配置" : "未配置";
809
+ const quota = formatInstanceQuotaSummary(runtime.usage, instance, runtime.env);
810
+ const quotaPart = quota ? ` · ${quota}` : "";
811
+ const warnings = instance.warnings.length > 0 ? `(${instance.warnings.join(";")})` : "";
812
+ lines.push(` ${instance.id.padEnd(width)} ${instance.preset.id} · ${instance.mode} · ${state}${quotaPart}${warnings}`);
813
+ }
814
+ const token = runtime.oauthToken();
815
+ if (token || config.instances.some((instance) => instance.preset.id === "cloudflare")) {
816
+ const oauthLabel = token
817
+ ? token.account_id
818
+ ? `已登录(accountId ${token.account_id})`
819
+ : "已登录"
820
+ : "未登录(/search login cloudflare)";
821
+ lines.push(`Cloudflare OAuth:${oauthLabel}`);
822
+ }
823
+ lines.push(`搜索链:${config.searchChain.join(" → ") || "(空)"}`);
824
+ lines.push(`抓取链:${config.fetchChain.join(" → ") || "(空)"}`);
825
+ lines.push("测试连接:/search test [实例]");
826
+ return lines.join("\n");
827
+ }
828
+
829
+ /** /search 命令:无参数时在交互式终端打开面板,支持 status、test、login/logout cloudflare。 */
830
+ export function createSearchCommand(runtime: SearchRuntime): {
831
+ description: string;
832
+ handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
833
+ } {
834
+ return {
835
+ description: "打开设置面板、查看状态、测试连接或登录 Cloudflare OAuth:/search [status|test [实例]|login cloudflare|logout cloudflare]",
836
+ async handler(args, ctx) {
837
+ const [action, target] = args.trim().split(/\s+/).filter(Boolean);
838
+ if (action === "test") {
839
+ await testConnection(runtime, target, ctx);
840
+ return;
841
+ }
842
+ if (action === "login") {
843
+ if (target !== undefined && target !== "cloudflare") {
844
+ ctx.ui.notify("当前仅支持 Cloudflare OAuth 登录:/search login cloudflare", "warning");
845
+ return;
846
+ }
847
+ if (!ctx.hasUI) {
848
+ ctx.ui.notify("Cloudflare OAuth 登录需要在交互式终端中运行:/search login cloudflare", "warning");
849
+ return;
850
+ }
851
+ await runCloudflareLogin(ctx, { source: runtime, failureText });
852
+ return;
853
+ }
854
+ if (action === "logout") {
855
+ if (target !== undefined && target !== "cloudflare") {
856
+ ctx.ui.notify("当前仅支持 Cloudflare OAuth 退出:/search logout cloudflare", "warning");
857
+ return;
858
+ }
859
+ await runCloudflareLogout(ctx, { source: runtime, failureText });
860
+ return;
861
+ }
862
+ if (action === undefined) {
863
+ if (ctx.mode === "tui" && ctx.hasUI) {
864
+ await openSearchPanel(ctx, { source: runtime, failureText });
865
+ return;
866
+ }
867
+ const hint = "面板只在交互式终端可用:/search status 查看状态,/search test [实例] 测试连接";
868
+ ctx.ui.notify(`${statusText(runtime)}\n${hint}`, "info");
869
+ return;
870
+ }
871
+ if (action !== "status") {
872
+ ctx.ui.notify(
873
+ "用法:/search 打开设置面板;/search status 查看状态;/search test [实例] 测试连接;/search login|logout cloudflare",
874
+ "warning",
875
+ );
876
+ return;
877
+ }
878
+ ctx.ui.notify(statusText(runtime), "info");
879
+ },
880
+ };
881
+ }
882
+
883
+ const TEST_FETCH_URL = "https://example.com/";
884
+
885
+ async function testConnection(
886
+ runtime: SearchRuntime,
887
+ instance: string | undefined,
888
+ ctx: ExtensionCommandContext,
889
+ ): Promise<void> {
890
+ const started = Date.now();
891
+ try {
892
+ const { config, service } = runtime.snapshot();
893
+ const target = instance === undefined
894
+ ? config.searchChain.length === 0 && config.fetchChain.length > 0
895
+ ? config.instances.find((item) => item.id === config.fetchChain[0])
896
+ : undefined
897
+ : config.instances.find((item) => item.id === instance);
898
+
899
+ if (target?.preset.id === "cloudflare") {
900
+ const response = await service.extract({
901
+ url: TEST_FETCH_URL,
902
+ ...(instance === undefined ? {} : { instance }),
903
+ });
904
+ runtime.clearFailure(response.instance);
905
+ const lines = [
906
+ `连接正常:${response.instance}(${response.providerUsed})`,
907
+ `抓取 ${TEST_FETCH_URL} 返回 ${response.content.length} 字符,耗时 ${formatDuration(Date.now() - started)}${response.degraded ? ",已降级" : ""}`,
908
+ ];
909
+ ctx.ui.notify(lines.join("\n"), "info");
910
+ return;
911
+ }
912
+
913
+ const response = await service.search({
914
+ query: "pi coding agent",
915
+ limit: 3,
916
+ ...(instance === undefined ? {} : { instance }),
917
+ });
918
+ runtime.clearFailure(response.instance);
919
+ const lines = [
920
+ `连接正常:${response.instance}(${response.providerUsed})`,
921
+ `返回 ${response.results.length} 条,耗时 ${formatDuration(Date.now() - started)}${response.degraded ? ",已降级" : ""}`,
922
+ ];
923
+ for (const item of response.results) lines.push(` ${item.title} ${item.url}`);
924
+ ctx.ui.notify(lines.join("\n"), "info");
925
+ } catch (error) {
926
+ ctx.ui.notify(`连接失败:${failureText(error, runtime.configPath)}`, "error");
927
+ }
928
+ }