@duanz/pi-d-reach 0.0.0-stage → 1.0.0

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/plugin/pwa.ts ADDED
@@ -0,0 +1,1078 @@
1
+ /**
2
+ * d-reach × pi-web-access 融合层
3
+ *
4
+ * 目标:用户只装 d-reach 一套工具,但保留 pi-web-access 里 d-reach 没有的能力:
5
+ * - GitHub 仓库 / 文件 URL 克隆到本地,返回路径 + 真实文件内容
6
+ * - YouTube / 本地视频理解(Gemini);有 ffmpeg/yt-dlp 时按时间戳截帧
7
+ * - source_check 式的「为一个说法收集带出处证据」→ d_reach_check
8
+ *
9
+ * 实现策略:**不自带一份 37k 行副本**,而是在调用时从已安装的 pi-web-access
10
+ * 里 import 它的纯函数模块(MIT,作者 Nico Bailon,见 docs/pwa-fusion.md)。
11
+ * 这些模块不依赖 pi-web-access 的 curator 服务器,也不依赖扩展注册流程;
12
+ * 它们只读 web-search.json 的配置(和它自己的工具共享同一份 Gemini/GitHub 配置)。
13
+ *
14
+ * 本文件不修改 index.ts 的既有函数。接线(前两处已在 fix/pwa 分支加好,第三处留给主会话
15
+ * 在同事的抓取段改完后合并,避免冲突;细节见 docs/pwa-fusion.md「接线」):
16
+ * 1) index.ts 头部:import { registerPwaTools } from "./pwa.ts";
17
+ * 2) index.ts 末尾 dReachExtension 里:registerPwaTools(pi, fetchUrl);
18
+ * 3) fetchUrl 开头:const special = await routeSpecialUrl(url, { maxChars }); if (special) return ...
19
+ * 4) 可选,十档末尾补一档:["pi-web-access 正文", async () => extractReadable(url, maxChars)]
20
+ */
21
+
22
+ import { execFile } from "node:child_process";
23
+ import { createHash, randomBytes } from "node:crypto";
24
+ import { existsSync } from "node:fs";
25
+ import { mkdir, writeFile } from "node:fs/promises";
26
+ import { homedir } from "node:os";
27
+ import { dirname, extname, join } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import { promisify } from "node:util";
30
+
31
+ import { Type } from "@earendil-works/pi-ai";
32
+ import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
33
+
34
+ const run = promisify(execFile);
35
+
36
+ const HERE = dirname(fileURLToPath(import.meta.url));
37
+ const SKILL_DIR = existsSync(join(HERE, "scripts", "fanout.sh"))
38
+ ? HERE
39
+ : join(homedir(), ".agents/skills/d-reach");
40
+ const FANOUT = join(SKILL_DIR, "scripts", "fanout.sh");
41
+ const DATA_DIR = join(homedir(), ".agent-reach");
42
+ const CHECK_DIR = join(DATA_DIR, "checks");
43
+
44
+ /** pi-web-access 的安装目录。D_REACH_PWA_DIR 可覆盖(clone / 非标准安装时用)。 */
45
+ const PWA_DIRS = [
46
+ process.env.D_REACH_PWA_DIR,
47
+ process.env.PI_WEB_ACCESS_DIR,
48
+ join(homedir(), ".pi", "agent", "npm", "node_modules", "pi-web-access"),
49
+ join(homedir(), ".pi", "agent", "node_modules", "pi-web-access"),
50
+ ].filter((x): x is string => Boolean(x));
51
+
52
+ const VIDEO_EXT = new Set([
53
+ ".mp4", ".mov", ".webm", ".avi", ".mpeg", ".mpg", ".wmv", ".flv", ".3gp", ".3gpp",
54
+ ]);
55
+
56
+ let pwaDirCache: string | null | undefined;
57
+
58
+ function pwaDir(): string | null {
59
+ if (pwaDirCache !== undefined) return pwaDirCache;
60
+ pwaDirCache =
61
+ PWA_DIRS.find((d) => existsSync(join(d, "github-extract.ts"))) ?? null;
62
+ return pwaDirCache;
63
+ }
64
+
65
+ class PwaUnavailableError extends Error {
66
+ constructor() {
67
+ super(
68
+ "找不到已安装的 pi-web-access(需要它的 GitHub 克隆 / 视频理解模块)。" +
69
+ "请确认 ~/.pi/agent/npm/node_modules/pi-web-access 存在," +
70
+ "或用环境变量 D_REACH_PWA_DIR 指向它的安装目录。",
71
+ );
72
+ this.name = "PwaUnavailableError";
73
+ }
74
+ }
75
+
76
+ interface PwaModules {
77
+ extract: any;
78
+ gh: any;
79
+ ghPr: any;
80
+ yt: any;
81
+ video: any;
82
+ gemini: any;
83
+ geminiWeb: any;
84
+ perplexity: any;
85
+ }
86
+
87
+ let modulesPromise: Promise<PwaModules> | null = null;
88
+
89
+ async function loadPwaModules(): Promise<PwaModules> {
90
+ const dir = pwaDir();
91
+ if (!dir) throw new PwaUnavailableError();
92
+ if (modulesPromise) return modulesPromise;
93
+ modulesPromise = (async () => {
94
+ // 这些 .ts 由 pi 的 jiti 运行时转译;不要改成 require。
95
+ // 必须顺序 import:extract.ts 与 github-extract/youtube-extract 互相引用,
96
+ // 并发加载会让 jiti 拿到半初始化的模块(NON_CODE_SEGMENTS / undefined.join)。
97
+ const extract = await import(`${dir}/extract.ts`);
98
+ const gh = await import(`${dir}/github-extract.ts`);
99
+ const ghPr = await import(`${dir}/github-issue-pr.ts`);
100
+ const yt = await import(`${dir}/youtube-extract.ts`);
101
+ const video = await import(`${dir}/video-extract.ts`);
102
+ const gemini = await import(`${dir}/gemini-api.ts`);
103
+ const geminiWeb = await import(`${dir}/gemini-web.ts`);
104
+ const perplexity = await import(`${dir}/perplexity.ts`);
105
+ return { extract, gh, ghPr, yt, video, gemini, geminiWeb, perplexity };
106
+ })().catch((err) => {
107
+ modulesPromise = null;
108
+ throw err;
109
+ });
110
+ return modulesPromise;
111
+ }
112
+
113
+ function errText(err: unknown): string {
114
+ return err instanceof Error ? err.message : String(err);
115
+ }
116
+
117
+ // ---------------------------------------------------------------- 特殊 URL 分流
118
+
119
+ export interface RouteOptions {
120
+ maxChars?: number;
121
+ signal?: AbortSignal;
122
+ prompt?: string;
123
+ }
124
+
125
+ export interface SpecialFetch {
126
+ via: string;
127
+ text: string;
128
+ chars: number;
129
+ title?: string;
130
+ /** 能力在,但这次没成功(缺凭据 / 克隆失败);调用方可以据此标 isError。 */
131
+ problem?: boolean;
132
+ }
133
+
134
+ const YOUTUBE_RE =
135
+ /(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?.*v=|shorts\/|live\/|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
136
+
137
+ function isYouTubeUrl(url: string): boolean {
138
+ try {
139
+ if (new URL(url).pathname === "/playlist") return false;
140
+ } catch {
141
+ /* 不是 URL 就当普通字符串继续匹配 */
142
+ }
143
+ return YOUTUBE_RE.test(url);
144
+ }
145
+
146
+ function isLocalVideoPath(input: string): boolean {
147
+ if (
148
+ !input.startsWith("/") &&
149
+ !input.startsWith("./") &&
150
+ !input.startsWith("../") &&
151
+ !input.startsWith("file://")
152
+ )
153
+ return false;
154
+ const path = input.startsWith("file://") ? input.slice(7) : input;
155
+ return VIDEO_EXT.has(extname(path.split("?")[0]).toLowerCase());
156
+ }
157
+
158
+ function clip(text: string, maxChars: number): string {
159
+ return text.length > maxChars ? `${text.slice(0, maxChars)}\n…(已截断)` : text;
160
+ }
161
+
162
+ function fromExtracted(r: any, via: string, maxChars: number): SpecialFetch {
163
+ const text = typeof r?.content === "string" ? r.content : "";
164
+ return {
165
+ via,
166
+ text: clip(text, maxChars),
167
+ chars: text.length,
168
+ title: typeof r?.title === "string" && r.title ? r.title : undefined,
169
+ problem: Boolean(r?.error),
170
+ };
171
+ }
172
+
173
+ /** 没有 Gemini/Perplexity 凭据时,给一句人能照做的说明,而不是抛错。 */
174
+ async function videoCredentialHint(modules: PwaModules, forYouTube: boolean): Promise<string | null> {
175
+ let api = false;
176
+ let web = false;
177
+ try {
178
+ api = Boolean(modules.gemini.isGeminiApiAvailableWithVideo());
179
+ } catch {
180
+ /* 配置坏了也不该让工具崩 */
181
+ }
182
+ try {
183
+ web = Boolean(await modules.geminiWeb.isGeminiWebAvailable());
184
+ } catch {
185
+ /* 浏览器 cookie 读不到就算没有 */
186
+ }
187
+ let perplexity = false;
188
+ try {
189
+ perplexity = Boolean(modules.perplexity.isPerplexityAvailable());
190
+ } catch {
191
+ /* ignore */
192
+ }
193
+ if (api || web || (forYouTube && perplexity)) return null;
194
+ return (
195
+ "没有检测到视频理解凭据:设置 GEMINI_API_KEY(或 ~/.pi/agent/web-search.json 的 geminiApiKey)," +
196
+ "或在 web-search.json 里开 allowBrowserCookies 复用浏览器里的 Gemini 登录态" +
197
+ (forYouTube ? ",或设置 PERPLEXITY_API_KEY 作为纯文字兜底" : "") +
198
+ "。截帧(timestamp/frames)只需要本机 ffmpeg" +
199
+ (forYouTube ? " + yt-dlp" : "") +
200
+ ",不依赖这些凭据。"
201
+ );
202
+ }
203
+
204
+ async function routeGitHub(
205
+ url: string,
206
+ maxChars: number,
207
+ signal?: AbortSignal,
208
+ ): Promise<SpecialFetch | null> {
209
+ let modules: PwaModules;
210
+ try {
211
+ modules = await loadPwaModules();
212
+ } catch (err) {
213
+ return {
214
+ via: "GitHub 克隆",
215
+ text: errText(err),
216
+ chars: errText(err).length,
217
+ problem: true,
218
+ };
219
+ }
220
+ // PR / issue 走 gh CLI 拉正文 + 评论 + review thread;普通仓库/文件走 clone。
221
+ // 顺序:先按 URL 形状判断,避免对每个仓库 URL 都试一遍 issue 路径。
222
+ if (modules.ghPr?.parseGitHubIssuePrUrl?.(url)) {
223
+ try {
224
+ const r = await modules.ghPr.extractGitHubIssuePr(url, signal);
225
+ if (r) return fromExtracted(r, "GitHub PR/Issue", maxChars);
226
+ } catch (err) {
227
+ return {
228
+ via: "GitHub PR/Issue",
229
+ text: `GitHub PR/Issue 读取失败:${errText(err).slice(0, 500)}`,
230
+ chars: 0,
231
+ problem: true,
232
+ };
233
+ }
234
+ }
235
+ try {
236
+ if (!modules.gh.parseGitHubUrl(url)) return null;
237
+ const r = await modules.gh.extractGitHub(url, signal);
238
+ if (!r) return null;
239
+ return fromExtracted(r, "GitHub 克隆", maxChars);
240
+ } catch (err) {
241
+ return {
242
+ via: "GitHub 克隆",
243
+ text: `GitHub 克隆失败:${errText(err).slice(0, 500)}`,
244
+ chars: 0,
245
+ problem: true,
246
+ };
247
+ }
248
+ }
249
+
250
+ async function routeYouTube(
251
+ url: string,
252
+ maxChars: number,
253
+ opts: RouteOptions,
254
+ ): Promise<SpecialFetch | null> {
255
+ try {
256
+ const modules = await loadPwaModules();
257
+ if (!modules.yt.isYouTubeURL(url).isYouTube) return null;
258
+ const hint = await videoCredentialHint(modules, true);
259
+ if (hint) {
260
+ return { via: "YouTube 视频理解", text: hint, chars: hint.length, problem: true };
261
+ }
262
+ const r = await modules.yt.extractYouTube(url, opts.signal, opts.prompt);
263
+ if (!r) {
264
+ return {
265
+ via: "YouTube 视频理解",
266
+ text: "YouTube 视频理解没有返回内容(Gemini/Perplexity 都失败)。",
267
+ chars: 0,
268
+ problem: true,
269
+ };
270
+ }
271
+ const got = fromExtracted(r, "YouTube 视频理解", maxChars);
272
+ if (r.error && !got.text) got.text = `YouTube 视频理解失败:${r.error}`;
273
+ return got;
274
+ } catch (err) {
275
+ const text = `YouTube 视频理解不可用:${errText(err).slice(0, 500)}`;
276
+ return { via: "YouTube 视频理解", text, chars: text.length, problem: true };
277
+ }
278
+ }
279
+
280
+ async function routeLocalVideo(
281
+ input: string,
282
+ maxChars: number,
283
+ opts: RouteOptions,
284
+ ): Promise<SpecialFetch | null> {
285
+ try {
286
+ const modules = await loadPwaModules();
287
+ const info = modules.video.isVideoFile(input);
288
+ if (!info) return null;
289
+ const hint = await videoCredentialHint(modules, false);
290
+ if (hint) {
291
+ return { via: "本地视频理解", text: hint, chars: hint.length, problem: true };
292
+ }
293
+ const r = await modules.video.extractVideo(info, opts.signal, { prompt: opts.prompt });
294
+ if (!r) return null;
295
+ return fromExtracted(r, "本地视频理解", maxChars);
296
+ } catch (err) {
297
+ const text = `本地视频理解不可用:${errText(err).slice(0, 500)}`;
298
+ return { via: "本地视频理解", text, chars: text.length, problem: true };
299
+ }
300
+ }
301
+
302
+ /**
303
+ * 普通网页的「可选兜底档」:pi-web-access 的 Readability 正文 + RSC(Next.js flight)解析
304
+ * + 直链 PDF 抽取。d-reach 的十档已经覆盖大部分站点,所以这个函数**不自动接进**
305
+ * fetchUrl;主会话想给十档再加一档时,把它插在 archive.today 之后即可:
306
+ *
307
+ * ["pi-web-access 正文", () => extractReadable(url, maxChars)]
308
+ *
309
+ * 返回 null 表示「没拿到东西」,与十档里其它档的约定一致。
310
+ */
311
+ export async function extractReadable(
312
+ url: string,
313
+ maxChars = 12000,
314
+ signal?: AbortSignal,
315
+ ): Promise<{ via: string; text: string; chars: number } | null> {
316
+ if (!/^https?:\/\//i.test(url)) return null;
317
+ let modules: PwaModules;
318
+ try {
319
+ modules = await loadPwaModules();
320
+ } catch {
321
+ return null;
322
+ }
323
+ try {
324
+ const r = await modules.extract.extractContent(url, signal, { timeoutMs: 25000 });
325
+ if (!r || r.error || !r.content) return null;
326
+ const text = r.content.trim();
327
+ if (text.length < 200) return null;
328
+ return { via: "pi-web-access 正文", text: clip(text, maxChars), chars: text.length };
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+
334
+ /** 直链图片(按扩展名判断):交给 pi-web-access 的图片分支解码,避免十档把二进制当正文。 */
335
+ const IMAGE_EXT_RE = /\.(?:png|jpe?g|gif|webp|bmp|avif|svg)(?:[?#]|$)/i;
336
+
337
+ async function routeImage(
338
+ url: string,
339
+ maxChars: number,
340
+ opts: RouteOptions,
341
+ ): Promise<SpecialFetch | null> {
342
+ if (!/^https?:\/\//i.test(url) || !IMAGE_EXT_RE.test(url)) return null;
343
+ try {
344
+ const modules = await loadPwaModules();
345
+ const r = await modules.extract.extractContent(url, opts.signal, { timeoutMs: 20000 });
346
+ if (!r) return null;
347
+ if (r.error) {
348
+ return { via: "图片", text: `图片读取失败:${r.error.slice(0, 300)}`, chars: 0, problem: true };
349
+ }
350
+ // 这里只回传尺寸/mime 这类文字元信息:d_reach_fetch 的返回是纯文本,
351
+ // 二进制图片本体不回传(要看图让 agent 直接用读图能力打开该 URL)。
352
+ const text = `${r.title ? `${r.title}\n` : ""}${r.content ?? ""}`.trim();
353
+ return { via: "图片", text: clip(text, maxChars), chars: text.length, title: r.title };
354
+ } catch (err) {
355
+ const text = `图片读取不可用:${errText(err).slice(0, 300)}`;
356
+ return { via: "图片", text, chars: text.length, problem: true };
357
+ }
358
+ }
359
+
360
+ /**
361
+ * 特殊 URL 分流入口。返回 null = 不归我管,交还原来的十档流程。
362
+ *
363
+ * 识别顺序:GitHub(仓库/文件/PR/issue)→ YouTube → 本地视频 → 直链图片。
364
+ * 只做「能力判断」,不做重活;普通网页在这里只花几个正则的时间。
365
+ */
366
+ export async function routeSpecialUrl(
367
+ url: string,
368
+ opts: RouteOptions = {},
369
+ ): Promise<SpecialFetch | null> {
370
+ const maxChars = Math.min(Math.max(opts.maxChars ?? 12000, 500), 200000);
371
+ if (/^https?:\/\/(?:www\.)?github\.com\//i.test(url)) {
372
+ return routeGitHub(url, maxChars, opts.signal);
373
+ }
374
+ if (/^https?:\/\//i.test(url) && isYouTubeUrl(url)) {
375
+ return routeYouTube(url, maxChars, opts);
376
+ }
377
+ if (isLocalVideoPath(url)) {
378
+ return routeLocalVideo(url, maxChars, opts);
379
+ }
380
+ return routeImage(url, maxChars, opts);
381
+ }
382
+
383
+ // ---------------------------------------------------------------- 视频截帧
384
+
385
+ function parseTime(value: string): number | null {
386
+ const parts = value.trim().split(":").map((p) => Number.parseFloat(p));
387
+ if (parts.some((p) => !Number.isFinite(p) || p < 0)) return null;
388
+ if (parts.length === 1) return parts[0];
389
+ if (parts.length === 2) return parts[0] * 60 + parts[1];
390
+ if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
391
+ return null;
392
+ }
393
+
394
+ function formatTime(seconds: number): string {
395
+ const s = Math.max(0, seconds);
396
+ const h = Math.floor(s / 3600);
397
+ const m = Math.floor((s % 3600) / 60);
398
+ const sec = Math.floor(s % 60);
399
+ return h > 0
400
+ ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`
401
+ : `${m}:${String(sec).padStart(2, "0")}`;
402
+ }
403
+
404
+ /** 与 pi-web-access 的 timestamp/frames 语义一致:区间均分、单点每 5s、无时间戳则全片采样。 */
405
+ function planTimestamps(
406
+ timestamp: string | undefined,
407
+ frames: number | undefined,
408
+ duration: number | null,
409
+ ): { times: number[]; error?: string } {
410
+ const want = Math.min(Math.max(Math.round(frames ?? (timestamp?.includes("-") ? 6 : 1)), 1), 12);
411
+ if (timestamp) {
412
+ const [a, b] = timestamp.split("-").map((p) => p.trim());
413
+ const start = parseTime(a);
414
+ if (start === null) return { times: [], error: `看不懂的时间戳:${timestamp}` };
415
+ if (b !== undefined) {
416
+ const end = parseTime(b);
417
+ if (end === null || end <= start) return { times: [], error: `时间区间不合法:${timestamp}` };
418
+ const n = Math.max(want, 2);
419
+ return {
420
+ times: Array.from({ length: n }, (_, i) => start + ((end - start) * i) / (n - 1)),
421
+ };
422
+ }
423
+ return {
424
+ times: Array.from({ length: want }, (_, i) => start + i * 5).filter(
425
+ (t) => duration === null || t < Math.max(duration, 1),
426
+ ),
427
+ };
428
+ }
429
+ if (frames && duration && duration > 0) {
430
+ return {
431
+ times: Array.from({ length: want }, (_, i) => ((i + 0.5) * duration) / want),
432
+ };
433
+ }
434
+ return { times: [], error: "需要 timestamp 或 frames(整片采样还需要能读到视频时长)" };
435
+ }
436
+
437
+ // ---------------------------------------------------------------- 证据核查
438
+
439
+ export interface CheckDeps {
440
+ /** d-reach 的 fetchUrl。传给 d_reach_check 做页面抓取;不传则只用搜索摘要。 */
441
+ fetchUrl?: (url: string, maxChars: number) => Promise<any>;
442
+ }
443
+
444
+ interface SearchHit {
445
+ title: string;
446
+ url: string;
447
+ snippet: string;
448
+ channel: string;
449
+ }
450
+
451
+ const MARK_LINE = /^###\s+(✅|⚪|❌|⚠️|🔇|💬)\s+(.+)$/;
452
+ const HIT_LINE = /^-\s+\[(.+?)\]\((.+?)\)(?:\s+—\s+(.*))?$/;
453
+
454
+ /** 解析 fanout.sh 的 markdown。只取真实条目,跳过合并段(否则同一 URL 出现两次)。 */
455
+ function parseFanoutHits(md: string): { hits: SearchHit[]; errors: string[] } {
456
+ const hits: SearchHit[] = [];
457
+ const errors: string[] = [];
458
+ let channel = "";
459
+ let skippedConsensus = false;
460
+ for (const raw of md.split("\n")) {
461
+ const line = raw.trimEnd();
462
+ if (line.startsWith("### 🔀")) {
463
+ channel = "";
464
+ skippedConsensus = true;
465
+ continue;
466
+ }
467
+ const head = line.match(MARK_LINE);
468
+ if (head) {
469
+ const [, mark, rest] = head;
470
+ channel = rest.split("——")[0].trim();
471
+ if (mark === "❌" || mark === "⚠️" || mark === "🔇") {
472
+ errors.push(`${channel}:${rest.split("——").slice(1).join("——").trim() || mark}`);
473
+ }
474
+ skippedConsensus = false;
475
+ continue;
476
+ }
477
+ if (skippedConsensus || !channel) continue;
478
+ const item = line.match(HIT_LINE);
479
+ if (!item) continue;
480
+ const url = item[2].trim();
481
+ if (!/^https?:\/\//i.test(url)) continue;
482
+ hits.push({
483
+ title: item[1].trim(),
484
+ url,
485
+ snippet: (item[3] ?? "").replace(/\*\*/g, "").trim(),
486
+ channel,
487
+ });
488
+ }
489
+ return { hits, errors };
490
+ }
491
+
492
+ async function fanoutForCheck(
493
+ query: string,
494
+ channels: string,
495
+ perChannel: number,
496
+ ): Promise<{ hits: SearchHit[]; errors: string[] }> {
497
+ const args = [FANOUT, query, "--n", String(perChannel)];
498
+ if (channels) args.push("--on", channels);
499
+ try {
500
+ const { stdout } = await run("bash", args, {
501
+ timeout: 150_000,
502
+ maxBuffer: 16 * 1024 * 1024,
503
+ env: process.env,
504
+ });
505
+ return parseFanoutHits(stdout);
506
+ } catch (err: any) {
507
+ const stdout = typeof err?.stdout === "string" ? err.stdout : "";
508
+ const parsed = stdout ? parseFanoutHits(stdout) : { hits: [], errors: [] };
509
+ parsed.errors.push(`检索失败:${errText(err).slice(0, 300)}`);
510
+ return parsed;
511
+ }
512
+ }
513
+
514
+ const STOP_WORDS = new Set([
515
+ "the", "and", "for", "that", "this", "with", "from", "was", "were", "are", "has", "have",
516
+ "have", "not", "but", "you", "your", "its", "does", "did", "can", "will", "would", "been",
517
+ "在", "了", "是", "的", "和", "与", "也", "都", "就", "而", "及", "或",
518
+ ]);
519
+
520
+ function tokens(text: string): string[] {
521
+ const out: string[] = [];
522
+ const lower = text.toLowerCase();
523
+ for (const m of lower.matchAll(/[a-z0-9][a-z0-9_+.#'-]{0,}/g)) {
524
+ const t = m[0];
525
+ if (t.length >= 2 && !STOP_WORDS.has(t)) out.push(t);
526
+ }
527
+ for (const m of lower.matchAll(/[\u4e00-\u9fff]{2,}/g)) {
528
+ const run = m[0];
529
+ if (run.length <= 3) out.push(run);
530
+ else for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2));
531
+ }
532
+ return out;
533
+ }
534
+
535
+ function scoreSentence(sentence: string, claimTokens: Set<string>): number {
536
+ let score = 0;
537
+ for (const t of new Set(tokens(sentence))) {
538
+ if (claimTokens.has(t)) score += t.length >= 4 ? 2 : 1;
539
+ }
540
+ return score;
541
+ }
542
+
543
+ interface Passage {
544
+ id: string;
545
+ text: string;
546
+ offset: number | null;
547
+ score: number;
548
+ origin: "page" | "snippet";
549
+ }
550
+
551
+ function passagesFromPage(
552
+ text: string,
553
+ claim: string,
554
+ sourceRank: number,
555
+ max = 3,
556
+ ): Passage[] {
557
+ const claimTokens = new Set(tokens(claim));
558
+ const flat = text.replace(/\r/g, "");
559
+ const chunks = flat
560
+ .split(/(?<=[。!?!?.;])\s+|\n{2,}/)
561
+ .map((s) => s.replace(/^[#>*\-\s]+/, "").replace(/\s+/g, " ").trim())
562
+ .filter((s) => s.length >= 30 && s.length <= 1200);
563
+ const scored = chunks
564
+ .map((sentence) => {
565
+ const score = scoreSentence(sentence, claimTokens);
566
+ return { sentence, score, offset: flat.indexOf(sentence) };
567
+ })
568
+ .filter((x) => x.score > 0)
569
+ .sort((a, b) => b.score - a.score)
570
+ .slice(0, max);
571
+ const chosen = scored.length > 0 ? scored : chunks.slice(0, 1).map((s) => ({
572
+ sentence: s,
573
+ score: 0,
574
+ offset: flat.indexOf(s),
575
+ }));
576
+ return chosen.map((x, i) => ({
577
+ id: `p-${sourceRank}-${i}`,
578
+ text: x.sentence.length > 400 ? `${x.sentence.slice(0, 400)}…` : x.sentence,
579
+ offset: x.offset >= 0 ? x.offset : null,
580
+ score: x.score,
581
+ origin: "page" as const,
582
+ }));
583
+ }
584
+
585
+ function classifySource(url: string): string {
586
+ let host = "";
587
+ try {
588
+ host = new URL(url).hostname.toLowerCase();
589
+ } catch {
590
+ return "unknown";
591
+ }
592
+ const is = (re: RegExp) => re.test(host);
593
+ if (is(/(^|\.)github\.com$/) || is(/(^|\.)gitlab\.com$/)) return "repo_issue";
594
+ if (is(/(^|\.)stackoverflow\.com$/) || is(/(^|\.)stackexchange\.com$/) || is(/^(news\.)?ycombinator\.com$/) ||
595
+ is(/(^|\.)reddit\.com$/) || is(/(^|\.)discuss\./) || is(/(^|\.)forum\./))
596
+ return "forum";
597
+ if (is(/(^|\.)(reuters|apnews|bbc|nytimes|theguardian|techcrunch|theverge|arstechnica)\.com$/))
598
+ return "news";
599
+ if (is(/(^|\.)(medium|dev\.to|substack|blog|hashnode)\./) || is(/^blog\./) || is(/(^|\.)medium\.com$/))
600
+ return "blog";
601
+ if (is(/(^|\.)(readthedocs\.io|python\.org|nodejs\.org|mozilla\.org|w3\.org|ietf\.org)$/) ||
602
+ is(/^docs?\./) || is(/^developer\./) || is(/(^|\.)docs?\./))
603
+ return "official_docs";
604
+ if (is(/^www\./) || is(/(^|\.)(vercel\.app|netlify\.app)$/)) return "unknown";
605
+ return "unknown";
606
+ }
607
+
608
+ function sha(text: string): string {
609
+ return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
610
+ }
611
+
612
+ function checkId(): string {
613
+ return `chk-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`;
614
+ }
615
+
616
+ interface CheckArtifact {
617
+ id: string;
618
+ type: "d-reach-source-check";
619
+ timestamp: number;
620
+ claim: string;
621
+ queries: string[];
622
+ channels: string;
623
+ sources: Array<{
624
+ rank: number;
625
+ url: string;
626
+ title: string;
627
+ quality: string;
628
+ hash: string;
629
+ fetched: boolean;
630
+ fetch_error?: string;
631
+ passages: Array<{
632
+ id: string;
633
+ text: string;
634
+ offset: number | null;
635
+ score: number;
636
+ origin: "page" | "snippet";
637
+ hash: string;
638
+ }>;
639
+ }>;
640
+ assessment: {
641
+ status: "unclear" | "missing-evidence";
642
+ rationale: string;
643
+ confidence: number;
644
+ };
645
+ search_errors: string[];
646
+ fetch_errors: Array<{ url: string; error: string }>;
647
+ }
648
+
649
+ async function buildCheck(
650
+ claim: string,
651
+ queries: string[],
652
+ channels: string,
653
+ numResults: number,
654
+ fetchContent: boolean,
655
+ deps: CheckDeps,
656
+ ): Promise<CheckArtifact> {
657
+ const searchErrors: string[] = [];
658
+ const hitMap = new Map<string, SearchHit>();
659
+ for (const q of queries) {
660
+ const { hits, errors } = await fanoutForCheck(q, channels, numResults);
661
+ searchErrors.push(...errors.map((e) => `${q} → ${e}`));
662
+ for (const h of hits) if (!hitMap.has(h.url)) hitMap.set(h.url, h);
663
+ }
664
+ const hits = [...hitMap.values()].slice(0, 20);
665
+
666
+ const fetchErrors: Array<{ url: string; error: string }> = [];
667
+ const pages = new Map<string, string>();
668
+ const doFetch = deps.fetchUrl;
669
+ if (fetchContent && doFetch) {
670
+ const top = hits.slice(0, 5);
671
+ for (let i = 0; i < top.length; i += 2) {
672
+ await Promise.all(
673
+ top.slice(i, i + 2).map(async (hit) => {
674
+ try {
675
+ const r = await doFetch(hit.url, 20000);
676
+ if (r?.ok && r.got?.text) pages.set(hit.url, r.got.text);
677
+ else {
678
+ const why =
679
+ (Array.isArray(r?.skipped) && r.skipped[0]?.detail) ||
680
+ (r?.fatal ? r.fatal : "") ||
681
+ "抓取失败";
682
+ fetchErrors.push({ url: hit.url, error: String(why).slice(0, 200) });
683
+ }
684
+ } catch (err) {
685
+ fetchErrors.push({ url: hit.url, error: errText(err).slice(0, 200) });
686
+ }
687
+ }),
688
+ );
689
+ }
690
+ }
691
+
692
+ const sources: CheckArtifact["sources"] = hits.map((hit, idx) => {
693
+ const rank = idx + 1;
694
+ const page = pages.get(hit.url);
695
+ let passages: CheckArtifact["sources"][number]["passages"] = [];
696
+ if (page) {
697
+ passages = passagesFromPage(page, claim, rank).map((p) => ({ ...p, hash: sha(p.text) }));
698
+ }
699
+ if (passages.length === 0 && hit.snippet) {
700
+ const text = hit.snippet.length > 400 ? `${hit.snippet.slice(0, 400)}…` : hit.snippet;
701
+ passages = [
702
+ { id: `p-${rank}-0`, text, offset: null, score: 0, origin: "snippet", hash: sha(text) },
703
+ ];
704
+ }
705
+ const fetchError = fetchErrors.find((e) => e.url === hit.url)?.error;
706
+ return {
707
+ rank,
708
+ url: hit.url,
709
+ title: hit.title,
710
+ quality: classifySource(hit.url),
711
+ hash: page ? sha(page) : sha(hit.snippet),
712
+ fetched: Boolean(page),
713
+ ...(fetchError ? { fetch_error: fetchError } : {}),
714
+ passages,
715
+ };
716
+ });
717
+
718
+ const passageCount = sources.reduce((n, s) => n + s.passages.length, 0);
719
+ return {
720
+ id: checkId(),
721
+ type: "d-reach-source-check",
722
+ timestamp: Date.now(),
723
+ claim,
724
+ queries,
725
+ channels,
726
+ sources,
727
+ assessment: passageCount
728
+ ? {
729
+ status: "unclear",
730
+ rationale: `已取到 ${passageCount} 条可引段落,但没有做语义判定;请按出处自行判断支持 / 反驳。`,
731
+ confidence: 0.3,
732
+ }
733
+ : {
734
+ status: "missing-evidence",
735
+ rationale: "没有取到任何可引段落。",
736
+ confidence: 0.2,
737
+ },
738
+ search_errors: searchErrors,
739
+ fetch_errors: fetchErrors,
740
+ };
741
+ }
742
+
743
+ function renderCheck(a: CheckArtifact, file: string): string {
744
+ const lines: string[] = [
745
+ `证据核查:${a.claim}`,
746
+ `结论:${a.assessment.status}(${a.assessment.rationale})`,
747
+ `检索:${a.queries.join(" | ")}(通道:${a.channels || "默认清单"})`,
748
+ `来源:${a.sources.length} 条(抓到正文 ${a.sources.filter((s) => s.fetched).length} 条)`,
749
+ "",
750
+ ];
751
+ let budget = 4000;
752
+ for (const s of a.sources) {
753
+ if (budget <= 0) break;
754
+ lines.push(`- [${s.quality}] ${s.title} — ${s.url}`);
755
+ if (s.fetch_error) lines.push(` ! 抓取失败:${s.fetch_error}`);
756
+ for (const p of s.passages.slice(0, 2)) {
757
+ if (budget <= 0) break;
758
+ const tag = p.offset === null ? "摘要" : `offset ${p.offset}`;
759
+ const text = ` · ${p.text}(${tag};${p.id};sha ${p.hash})`;
760
+ lines.push(text);
761
+ budget -= text.length;
762
+ }
763
+ }
764
+ if (a.search_errors.length) {
765
+ lines.push("", `检索告警:${a.search_errors.slice(0, 5).join(";")}`);
766
+ }
767
+ lines.push("", `完整 artifact:${file}`, `responseId:${a.id}`);
768
+ return lines.join("\n");
769
+ }
770
+
771
+ // ---------------------------------------------------------------- 工具注册
772
+
773
+ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUrl"]): void {
774
+ const deps: CheckDeps = { fetchUrl };
775
+
776
+ interface CheckParams {
777
+ claim: string;
778
+ queries?: string[];
779
+ num_results?: number;
780
+ fetch_content?: boolean;
781
+ channels?: string;
782
+ domain_filter?: string[];
783
+ }
784
+
785
+ const checkTool = defineTool({
786
+ name: "d_reach_check",
787
+ label: "d-reach 证据核查",
788
+ description:
789
+ "为一个说法收集带出处的证据(对应 pi-web-access 的 source_check)。" +
790
+ "用 d-reach 的多通道检索找来源,抓前 5 篇正文,挑与说法词面最相关的原句," +
791
+ "给出来源质量、精确 offset、内容 sha,并落盘成 JSON artifact。" +
792
+ "它不替你下「真/假」结论:取到段落=unclear(需按出处判读),一句没取到=missing-evidence。",
793
+ parameters: Type.Object({
794
+ claim: Type.String({ description: "要核查的说法(一句话,越具体越好)" }),
795
+ queries: Type.Optional(
796
+ Type.Array(Type.String(), { description: "检索词;默认用 claim 本身,最多 8 条" }),
797
+ ),
798
+ num_results: Type.Optional(
799
+ Type.Number({ description: "每条检索最多取几条结果,默认 5,最大 20" }),
800
+ ),
801
+ fetch_content: Type.Optional(
802
+ Type.Boolean({ description: "是否抓取前 5 条来源的正文(默认 true)" }),
803
+ ),
804
+ channels: Type.Optional(
805
+ Type.String({
806
+ description:
807
+ "fanout 通道白名单,逗号分隔;默认 hn,se,youcom,parallel,tavily(免 key 优先)",
808
+ }),
809
+ ),
810
+ domain_filter: Type.Optional(
811
+ Type.Array(Type.String(), {
812
+ description: "只保留这些域名;以 - 开头表示排除(抓取后本地过滤)",
813
+ }),
814
+ ),
815
+ }),
816
+
817
+ async execute(_id: string, params: CheckParams, _signal?: AbortSignal) {
818
+ const claim: string = params.claim.trim();
819
+ if (!claim) {
820
+ return { content: [{ type: "text", text: "claim 不能为空" }], isError: true };
821
+ }
822
+ const rawQueries: string[] = (params.queries ?? [])
823
+ .map((q: string) => q.trim())
824
+ .filter(Boolean);
825
+ const queries: string[] = [
826
+ ...new Set<string>(rawQueries.length ? rawQueries : [claim]),
827
+ ].slice(0, 8);
828
+ const numResults = Math.min(Math.max(Math.round(params.num_results ?? 5), 1), 20);
829
+ const fetchContent = params.fetch_content !== false;
830
+ const channels: string = (params.channels ?? "hn,se,youcom,parallel,tavily").trim();
831
+ const t0 = Date.now();
832
+
833
+ let artifact: CheckArtifact;
834
+ try {
835
+ artifact = await buildCheck(claim, queries, channels, numResults, fetchContent, deps);
836
+ } catch (err) {
837
+ return {
838
+ content: [{ type: "text", text: `证据核查失败:${errText(err).slice(0, 500)}` }],
839
+ isError: true,
840
+ };
841
+ }
842
+
843
+ const filters: string[] = params.domain_filter ?? [];
844
+ const include = filters.filter((d) => !d.startsWith("-")).map((d) => d.toLowerCase());
845
+ const exclude = filters.filter((d) => d.startsWith("-")).map((d) => d.slice(1).toLowerCase());
846
+ if (include.length || exclude.length) {
847
+ const keep = (url: string) => {
848
+ let host = "";
849
+ try {
850
+ host = new URL(url).hostname.toLowerCase();
851
+ } catch {
852
+ return false;
853
+ }
854
+ const match = (d: string) => host === d || host.endsWith(`.${d}`);
855
+ if (exclude.some(match)) return false;
856
+ return include.length === 0 || include.some(match);
857
+ };
858
+ artifact.sources = artifact.sources.filter((s) => keep(s.url));
859
+ if (artifact.sources.length === 0) {
860
+ artifact.assessment = {
861
+ status: "missing-evidence",
862
+ rationale: "域名过滤后没有剩下任何来源。",
863
+ confidence: 0.2,
864
+ };
865
+ }
866
+ }
867
+
868
+ await mkdir(CHECK_DIR, { recursive: true });
869
+ const file = join(CHECK_DIR, `${artifact.id}.json`);
870
+ await writeFile(file, JSON.stringify(artifact, null, 2), "utf8");
871
+ const secs = ((Date.now() - t0) / 1000).toFixed(1);
872
+ const text = `${renderCheck(artifact, file)}\n用时 ${secs}s`;
873
+ return {
874
+ content: [{ type: "text", text }],
875
+ details: {
876
+ responseId: artifact.id,
877
+ file,
878
+ status: artifact.assessment.status,
879
+ sources: artifact.sources.length,
880
+ fetched: artifact.sources.filter((s) => s.fetched).length,
881
+ passages: artifact.sources.reduce((n, s) => n + s.passages.length, 0),
882
+ searchErrors: artifact.search_errors,
883
+ fetchErrors: artifact.fetch_errors,
884
+ },
885
+ };
886
+ },
887
+ });
888
+
889
+ interface VideoParams {
890
+ url: string;
891
+ prompt?: string;
892
+ timestamp?: string;
893
+ frames?: number;
894
+ model?: string;
895
+ }
896
+
897
+ const videoTool = defineTool({
898
+ name: "d_reach_video",
899
+ label: "d-reach 视频理解",
900
+ description:
901
+ "理解 YouTube 视频或本地视频(对应 pi-web-access 的 YouTube/本地视频能力):" +
902
+ "整片摘要 / 逐字稿 / 画面描述,或按 timestamp、frames 截帧回传图片。" +
903
+ "整片理解需要 Gemini 凭据(GEMINI_API_KEY 或 web-search.json),YouTube 还可用 Perplexity 文字兜底;" +
904
+ "截帧只需本机 ffmpeg(YouTube 另需 yt-dlp),不需要任何凭据。",
905
+ parameters: Type.Object({
906
+ url: Type.String({ description: "YouTube URL,或本地视频路径(/、./、../、file://)" }),
907
+ prompt: Type.Optional(
908
+ Type.String({ description: "针对视频内容的问题;省略则抽完整内容(摘要+逐字稿+画面)" }),
909
+ ),
910
+ timestamp: Type.Optional(
911
+ Type.String({
912
+ description: "截帧时间点:'23:41'、'1:23:45' 或区间 '23:41-25:00'(区间默认 6 帧)",
913
+ }),
914
+ ),
915
+ frames: Type.Optional(
916
+ Type.Number({ description: "截帧数量 1-12;与 timestamp 合用,或单独用于整片采样" }),
917
+ ),
918
+ model: Type.Optional(Type.String({ description: "Gemini 模型,默认用配置里的视频模型" })),
919
+ }),
920
+
921
+ async execute(_id: string, params: VideoParams, signal?: AbortSignal) {
922
+ const input: string = params.url.trim();
923
+ const t0 = Date.now();
924
+ let modules: PwaModules;
925
+ try {
926
+ modules = await loadPwaModules();
927
+ } catch (err) {
928
+ return {
929
+ content: [{ type: "text", text: errText(err) }],
930
+ isError: true,
931
+ };
932
+ }
933
+
934
+ const youtube = /^https?:\/\//i.test(input) && modules.yt.isYouTubeURL(input).isYouTube;
935
+ const local = modules.video.isVideoFile(input);
936
+ if (!youtube && !local) {
937
+ return {
938
+ content: [
939
+ {
940
+ type: "text",
941
+ text: "只支持 YouTube URL 或本地视频文件(mp4/mov/webm/avi 等)。",
942
+ },
943
+ ],
944
+ isError: true,
945
+ };
946
+ }
947
+
948
+ // 截帧路径:不需要 Gemini
949
+ if (params.timestamp || params.frames) {
950
+ try {
951
+ let duration: number | null = null;
952
+ let times: number[];
953
+ if (youtube) {
954
+ const info = await modules.yt.getYouTubeStreamInfo(modules.yt.isYouTubeURL(input).videoId);
955
+ if ("error" in info) {
956
+ return { content: [{ type: "text", text: info.error }], isError: true };
957
+ }
958
+ duration = info.duration;
959
+ const plan = planTimestamps(params.timestamp, params.frames, duration);
960
+ if (plan.error) return { content: [{ type: "text", text: plan.error }], isError: true };
961
+ times = plan.times;
962
+ const out = await modules.yt.extractYouTubeFrames(
963
+ modules.yt.isYouTubeURL(input).videoId,
964
+ times,
965
+ info,
966
+ );
967
+ if (out.error && out.frames.length === 0) {
968
+ return { content: [{ type: "text", text: out.error }], isError: true };
969
+ }
970
+ return {
971
+ content: [
972
+ {
973
+ type: "text",
974
+ text: `YouTube 截帧 ${out.frames.length} 张:${times.map(formatTime).join(", ")}(${((Date.now() - t0) / 1000).toFixed(1)}s)`,
975
+ },
976
+ ...out.frames.map((f: any) => ({
977
+ type: "image" as const,
978
+ data: f.data,
979
+ mimeType: f.mimeType,
980
+ })),
981
+ ],
982
+ details: { timestamps: times, frames: out.frames.length, duration },
983
+ };
984
+ }
985
+
986
+ const dur = await modules.video.getLocalVideoDuration(local.absolutePath);
987
+ if (typeof dur === "number") duration = dur;
988
+ const plan = planTimestamps(params.timestamp, params.frames, duration);
989
+ if (plan.error) return { content: [{ type: "text", text: plan.error }], isError: true };
990
+ const frames: any[] = [];
991
+ const failed: string[] = [];
992
+ for (const seconds of plan.times) {
993
+ const f = await modules.video.extractVideoFrame(local.absolutePath, seconds);
994
+ if ("error" in f) failed.push(`${formatTime(seconds)}: ${f.error}`);
995
+ else frames.push({ ...f, seconds });
996
+ }
997
+ if (frames.length === 0) {
998
+ return {
999
+ content: [{ type: "text", text: `截帧失败:${failed.join(";")}` }],
1000
+ isError: true,
1001
+ };
1002
+ }
1003
+ return {
1004
+ content: [
1005
+ {
1006
+ type: "text",
1007
+ text: `本地视频截帧 ${frames.length} 张:${frames.map((f) => formatTime(f.seconds)).join(", ")}(${((Date.now() - t0) / 1000).toFixed(1)}s)${failed.length ? `\n失败:${failed.join(";")}` : ""}`,
1008
+ },
1009
+ ...frames.map((f) => ({
1010
+ type: "image" as const,
1011
+ data: f.data,
1012
+ mimeType: f.mimeType,
1013
+ })),
1014
+ ],
1015
+ details: { timestamps: plan.times, frames: frames.length, duration },
1016
+ };
1017
+ } catch (err) {
1018
+ return {
1019
+ content: [{ type: "text", text: `截帧失败:${errText(err).slice(0, 400)}` }],
1020
+ isError: true,
1021
+ };
1022
+ }
1023
+ }
1024
+
1025
+ // 整片理解路径:先看凭据,缺了给人话
1026
+ const hint = await videoCredentialHint(modules, youtube);
1027
+ if (hint) {
1028
+ return { content: [{ type: "text", text: hint }], isError: true };
1029
+ }
1030
+
1031
+ try {
1032
+ const r = youtube
1033
+ ? await modules.yt.extractYouTube(input, signal, params.prompt, params.model)
1034
+ : await modules.video.extractVideo(local, signal, {
1035
+ prompt: params.prompt,
1036
+ model: params.model,
1037
+ });
1038
+ if (!r) {
1039
+ return {
1040
+ content: [
1041
+ { type: "text", text: "视频理解没有返回内容(Gemini 调用失败,请检查凭据与网络)。" },
1042
+ ],
1043
+ isError: true,
1044
+ };
1045
+ }
1046
+ if (r.error && !r.content) {
1047
+ return { content: [{ type: "text", text: r.error }], isError: true };
1048
+ }
1049
+ const content: any[] = [
1050
+ {
1051
+ type: "text",
1052
+ text: `${r.title || (youtube ? "YouTube 视频" : local.absolutePath)}(${((Date.now() - t0) / 1000).toFixed(1)}s)\n\n${r.content}`,
1053
+ },
1054
+ ];
1055
+ if (r.thumbnail?.data) {
1056
+ content.push({
1057
+ type: "image",
1058
+ data: r.thumbnail.data,
1059
+ mimeType: r.thumbnail.mimeType,
1060
+ });
1061
+ }
1062
+ return {
1063
+ content,
1064
+ details: { url: input, title: r.title, error: r.error ?? null },
1065
+ ...(r.error ? { isError: true } : {}),
1066
+ };
1067
+ } catch (err) {
1068
+ return {
1069
+ content: [{ type: "text", text: `视频理解失败:${errText(err).slice(0, 500)}` }],
1070
+ isError: true,
1071
+ };
1072
+ }
1073
+ },
1074
+ });
1075
+
1076
+ pi.registerTool(checkTool);
1077
+ pi.registerTool(videoTool);
1078
+ }