@duanz/pi-d-reach 1.0.1 → 1.0.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.
package/plugin/pwa.ts CHANGED
@@ -19,27 +19,28 @@
19
19
  * 4) 可选,十档末尾补一档:["pi-web-access 正文", async () => extractReadable(url, maxChars)]
20
20
  */
21
21
 
22
- import { execFile } from "node:child_process";
23
22
  import { createHash, randomBytes } from "node:crypto";
24
23
  import { existsSync } from "node:fs";
25
- import { mkdir, writeFile } from "node:fs/promises";
26
24
  import { homedir } from "node:os";
27
25
  import { dirname, extname, join } from "node:path";
28
26
  import { fileURLToPath } from "node:url";
29
- import { promisify } from "node:util";
30
27
 
31
28
  import { Type } from "@earendil-works/pi-ai";
32
29
  import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
33
30
 
34
- const run = promisify(execFile);
31
+ import { abortedError, atomicWriteFile, isAborted, runCommand } from "./runtime.ts";
35
32
 
36
33
  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");
34
+ const SKILL_DIR = process.env.D_REACH_SKILL_DIR
35
+ ? process.env.D_REACH_SKILL_DIR
36
+ : existsSync(join(HERE, "..", "scripts", "fanout.sh"))
37
+ ? join(HERE, "..")
38
+ : existsSync(join(HERE, "scripts", "fanout.sh"))
39
+ ? HERE
40
+ : join(homedir(), ".agents/skills/d-reach");
40
41
  const FANOUT = join(SKILL_DIR, "scripts", "fanout.sh");
41
42
  const DATA_DIR = join(homedir(), ".agent-reach");
42
- const CHECK_DIR = join(DATA_DIR, "checks");
43
+ const checkDirPath = () => process.env.D_REACH_CHECK_DIR || join(DATA_DIR, "checks");
43
44
 
44
45
  /** pi-web-access 的安装目录。D_REACH_PWA_DIR 可覆盖(clone / 非标准安装时用)。 */
45
46
  const PWA_DIRS = [
@@ -206,10 +207,12 @@ async function routeGitHub(
206
207
  maxChars: number,
207
208
  signal?: AbortSignal,
208
209
  ): Promise<SpecialFetch | null> {
210
+ if (signal?.aborted) throw abortedError();
209
211
  let modules: PwaModules;
210
212
  try {
211
213
  modules = await loadPwaModules();
212
214
  } catch (err) {
215
+ if (isAborted(err, signal)) throw abortedError();
213
216
  return {
214
217
  via: "GitHub 克隆",
215
218
  text: errText(err),
@@ -217,13 +220,16 @@ async function routeGitHub(
217
220
  problem: true,
218
221
  };
219
222
  }
223
+ if (signal?.aborted) throw abortedError();
220
224
  // PR / issue 走 gh CLI 拉正文 + 评论 + review thread;普通仓库/文件走 clone。
221
225
  // 顺序:先按 URL 形状判断,避免对每个仓库 URL 都试一遍 issue 路径。
222
226
  if (modules.ghPr?.parseGitHubIssuePrUrl?.(url)) {
223
227
  try {
224
228
  const r = await modules.ghPr.extractGitHubIssuePr(url, signal);
229
+ if (signal?.aborted) throw abortedError();
225
230
  if (r) return fromExtracted(r, "GitHub PR/Issue", maxChars);
226
231
  } catch (err) {
232
+ if (isAborted(err, signal)) throw abortedError();
227
233
  return {
228
234
  via: "GitHub PR/Issue",
229
235
  text: `GitHub PR/Issue 读取失败:${errText(err).slice(0, 500)}`,
@@ -235,9 +241,11 @@ async function routeGitHub(
235
241
  try {
236
242
  if (!modules.gh.parseGitHubUrl(url)) return null;
237
243
  const r = await modules.gh.extractGitHub(url, signal);
244
+ if (signal?.aborted) throw abortedError();
238
245
  if (!r) return null;
239
246
  return fromExtracted(r, "GitHub 克隆", maxChars);
240
247
  } catch (err) {
248
+ if (isAborted(err, signal)) throw abortedError();
241
249
  return {
242
250
  via: "GitHub 克隆",
243
251
  text: `GitHub 克隆失败:${errText(err).slice(0, 500)}`,
@@ -252,14 +260,18 @@ async function routeYouTube(
252
260
  maxChars: number,
253
261
  opts: RouteOptions,
254
262
  ): Promise<SpecialFetch | null> {
263
+ if (opts.signal?.aborted) throw abortedError();
255
264
  try {
256
265
  const modules = await loadPwaModules();
266
+ if (opts.signal?.aborted) throw abortedError();
257
267
  if (!modules.yt.isYouTubeURL(url).isYouTube) return null;
258
268
  const hint = await videoCredentialHint(modules, true);
269
+ if (opts.signal?.aborted) throw abortedError();
259
270
  if (hint) {
260
271
  return { via: "YouTube 视频理解", text: hint, chars: hint.length, problem: true };
261
272
  }
262
273
  const r = await modules.yt.extractYouTube(url, opts.signal, opts.prompt);
274
+ if (opts.signal?.aborted) throw abortedError();
263
275
  if (!r) {
264
276
  return {
265
277
  via: "YouTube 视频理解",
@@ -272,6 +284,7 @@ async function routeYouTube(
272
284
  if (r.error && !got.text) got.text = `YouTube 视频理解失败:${r.error}`;
273
285
  return got;
274
286
  } catch (err) {
287
+ if (isAborted(err, opts.signal)) throw abortedError();
275
288
  const text = `YouTube 视频理解不可用:${errText(err).slice(0, 500)}`;
276
289
  return { via: "YouTube 视频理解", text, chars: text.length, problem: true };
277
290
  }
@@ -282,18 +295,23 @@ async function routeLocalVideo(
282
295
  maxChars: number,
283
296
  opts: RouteOptions,
284
297
  ): Promise<SpecialFetch | null> {
298
+ if (opts.signal?.aborted) throw abortedError();
285
299
  try {
286
300
  const modules = await loadPwaModules();
301
+ if (opts.signal?.aborted) throw abortedError();
287
302
  const info = modules.video.isVideoFile(input);
288
303
  if (!info) return null;
289
304
  const hint = await videoCredentialHint(modules, false);
305
+ if (opts.signal?.aborted) throw abortedError();
290
306
  if (hint) {
291
307
  return { via: "本地视频理解", text: hint, chars: hint.length, problem: true };
292
308
  }
293
309
  const r = await modules.video.extractVideo(info, opts.signal, { prompt: opts.prompt });
310
+ if (opts.signal?.aborted) throw abortedError();
294
311
  if (!r) return null;
295
312
  return fromExtracted(r, "本地视频理解", maxChars);
296
313
  } catch (err) {
314
+ if (isAborted(err, opts.signal)) throw abortedError();
297
315
  const text = `本地视频理解不可用:${errText(err).slice(0, 500)}`;
298
316
  return { via: "本地视频理解", text, chars: text.length, problem: true };
299
317
  }
@@ -313,20 +331,24 @@ export async function extractReadable(
313
331
  maxChars = 12000,
314
332
  signal?: AbortSignal,
315
333
  ): Promise<{ via: string; text: string; chars: number } | null> {
334
+ if (signal?.aborted) throw abortedError();
316
335
  if (!/^https?:\/\//i.test(url)) return null;
317
336
  let modules: PwaModules;
318
337
  try {
319
338
  modules = await loadPwaModules();
320
- } catch {
339
+ } catch (err) {
340
+ if (isAborted(err, signal)) throw abortedError();
321
341
  return null;
322
342
  }
323
343
  try {
324
344
  const r = await modules.extract.extractContent(url, signal, { timeoutMs: 25000 });
345
+ if (signal?.aborted) throw abortedError();
325
346
  if (!r || r.error || !r.content) return null;
326
347
  const text = r.content.trim();
327
348
  if (text.length < 200) return null;
328
349
  return { via: "pi-web-access 正文", text: clip(text, maxChars), chars: text.length };
329
- } catch {
350
+ } catch (err) {
351
+ if (isAborted(err, signal)) throw abortedError();
330
352
  return null;
331
353
  }
332
354
  }
@@ -339,10 +361,13 @@ async function routeImage(
339
361
  maxChars: number,
340
362
  opts: RouteOptions,
341
363
  ): Promise<SpecialFetch | null> {
364
+ if (opts.signal?.aborted) throw abortedError();
342
365
  if (!/^https?:\/\//i.test(url) || !IMAGE_EXT_RE.test(url)) return null;
343
366
  try {
344
367
  const modules = await loadPwaModules();
368
+ if (opts.signal?.aborted) throw abortedError();
345
369
  const r = await modules.extract.extractContent(url, opts.signal, { timeoutMs: 20000 });
370
+ if (opts.signal?.aborted) throw abortedError();
346
371
  if (!r) return null;
347
372
  if (r.error) {
348
373
  return { via: "图片", text: `图片读取失败:${r.error.slice(0, 300)}`, chars: 0, problem: true };
@@ -352,6 +377,7 @@ async function routeImage(
352
377
  const text = `${r.title ? `${r.title}\n` : ""}${r.content ?? ""}`.trim();
353
378
  return { via: "图片", text: clip(text, maxChars), chars: text.length, title: r.title };
354
379
  } catch (err) {
380
+ if (isAborted(err, opts.signal)) throw abortedError();
355
381
  const text = `图片读取不可用:${errText(err).slice(0, 300)}`;
356
382
  return { via: "图片", text, chars: text.length, problem: true };
357
383
  }
@@ -367,6 +393,7 @@ export async function routeSpecialUrl(
367
393
  url: string,
368
394
  opts: RouteOptions = {},
369
395
  ): Promise<SpecialFetch | null> {
396
+ if (opts.signal?.aborted) throw abortedError();
370
397
  const maxChars = Math.min(Math.max(opts.maxChars ?? 12000, 500), 200000);
371
398
  if (/^https?:\/\/(?:www\.)?github\.com\//i.test(url)) {
372
399
  return routeGitHub(url, maxChars, opts.signal);
@@ -438,7 +465,7 @@ function planTimestamps(
438
465
 
439
466
  export interface CheckDeps {
440
467
  /** d-reach 的 fetchUrl。传给 d_reach_check 做页面抓取;不传则只用搜索摘要。 */
441
- fetchUrl?: (url: string, maxChars: number) => Promise<any>;
468
+ fetchUrl?: (url: string, maxChars: number, signal?: AbortSignal) => Promise<any>;
442
469
  }
443
470
 
444
471
  interface SearchHit {
@@ -493,17 +520,21 @@ async function fanoutForCheck(
493
520
  query: string,
494
521
  channels: string,
495
522
  perChannel: number,
523
+ signal?: AbortSignal,
496
524
  ): Promise<{ hits: SearchHit[]; errors: string[] }> {
525
+ if (signal?.aborted) throw abortedError();
497
526
  const args = [FANOUT, query, "--n", String(perChannel)];
498
527
  if (channels) args.push("--on", channels);
499
528
  try {
500
- const { stdout } = await run("bash", args, {
501
- timeout: 150_000,
529
+ const { stdout } = await runCommand("bash", args, {
530
+ timeoutMs: 150_000,
502
531
  maxBuffer: 16 * 1024 * 1024,
503
532
  env: process.env,
533
+ signal,
504
534
  });
505
535
  return parseFanoutHits(stdout);
506
536
  } catch (err: any) {
537
+ if (isAborted(err, signal)) throw abortedError();
507
538
  const stdout = typeof err?.stdout === "string" ? err.stdout : "";
508
539
  const parsed = stdout ? parseFanoutHits(stdout) : { hits: [], errors: [] };
509
540
  parsed.errors.push(`检索失败:${errText(err).slice(0, 300)}`);
@@ -653,11 +684,14 @@ async function buildCheck(
653
684
  numResults: number,
654
685
  fetchContent: boolean,
655
686
  deps: CheckDeps,
687
+ signal?: AbortSignal,
656
688
  ): Promise<CheckArtifact> {
689
+ if (signal?.aborted) throw abortedError();
657
690
  const searchErrors: string[] = [];
658
691
  const hitMap = new Map<string, SearchHit>();
659
692
  for (const q of queries) {
660
- const { hits, errors } = await fanoutForCheck(q, channels, numResults);
693
+ if (signal?.aborted) throw abortedError();
694
+ const { hits, errors } = await fanoutForCheck(q, channels, numResults, signal);
661
695
  searchErrors.push(...errors.map((e) => `${q} → ${e}`));
662
696
  for (const h of hits) if (!hitMap.has(h.url)) hitMap.set(h.url, h);
663
697
  }
@@ -669,10 +703,11 @@ async function buildCheck(
669
703
  if (fetchContent && doFetch) {
670
704
  const top = hits.slice(0, 5);
671
705
  for (let i = 0; i < top.length; i += 2) {
706
+ if (signal?.aborted) throw abortedError();
672
707
  await Promise.all(
673
708
  top.slice(i, i + 2).map(async (hit) => {
674
709
  try {
675
- const r = await doFetch(hit.url, 20000);
710
+ const r = await doFetch(hit.url, 20000, signal);
676
711
  if (r?.ok && r.got?.text) pages.set(hit.url, r.got.text);
677
712
  else {
678
713
  const why =
@@ -682,6 +717,7 @@ async function buildCheck(
682
717
  fetchErrors.push({ url: hit.url, error: String(why).slice(0, 200) });
683
718
  }
684
719
  } catch (err) {
720
+ if (isAborted(err, signal)) throw abortedError();
685
721
  fetchErrors.push({ url: hit.url, error: errText(err).slice(0, 200) });
686
722
  }
687
723
  }),
@@ -814,7 +850,10 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
814
850
  ),
815
851
  }),
816
852
 
817
- async execute(_id: string, params: CheckParams, _signal?: AbortSignal) {
853
+ async execute(_id: string, params: CheckParams, signal?: AbortSignal) {
854
+ if (signal?.aborted) {
855
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
856
+ }
818
857
  const claim: string = params.claim.trim();
819
858
  if (!claim) {
820
859
  return { content: [{ type: "text", text: "claim 不能为空" }], isError: true };
@@ -832,13 +871,19 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
832
871
 
833
872
  let artifact: CheckArtifact;
834
873
  try {
835
- artifact = await buildCheck(claim, queries, channels, numResults, fetchContent, deps);
874
+ artifact = await buildCheck(claim, queries, channels, numResults, fetchContent, deps, signal);
836
875
  } catch (err) {
876
+ if (isAborted(err, signal)) {
877
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
878
+ }
837
879
  return {
838
880
  content: [{ type: "text", text: `证据核查失败:${errText(err).slice(0, 500)}` }],
839
881
  isError: true,
840
882
  };
841
883
  }
884
+ if (signal?.aborted) {
885
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
886
+ }
842
887
 
843
888
  const filters: string[] = params.domain_filter ?? [];
844
889
  const include = filters.filter((d) => !d.startsWith("-")).map((d) => d.toLowerCase());
@@ -865,9 +910,9 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
865
910
  }
866
911
  }
867
912
 
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");
913
+ const checkDir = checkDirPath();
914
+ const file = join(checkDir, `${artifact.id}.json`);
915
+ await atomicWriteFile(file, JSON.stringify(artifact, null, 2));
871
916
  const secs = ((Date.now() - t0) / 1000).toFixed(1);
872
917
  const text = `${renderCheck(artifact, file)}\n用时 ${secs}s`;
873
918
  return {
@@ -919,17 +964,26 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
919
964
  }),
920
965
 
921
966
  async execute(_id: string, params: VideoParams, signal?: AbortSignal) {
967
+ if (signal?.aborted) {
968
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
969
+ }
922
970
  const input: string = params.url.trim();
923
971
  const t0 = Date.now();
924
972
  let modules: PwaModules;
925
973
  try {
926
974
  modules = await loadPwaModules();
927
975
  } catch (err) {
976
+ if (isAborted(err, signal)) {
977
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
978
+ }
928
979
  return {
929
980
  content: [{ type: "text", text: errText(err) }],
930
981
  isError: true,
931
982
  };
932
983
  }
984
+ if (signal?.aborted) {
985
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
986
+ }
933
987
 
934
988
  const youtube = /^https?:\/\//i.test(input) && modules.yt.isYouTubeURL(input).isYouTube;
935
989
  const local = modules.video.isVideoFile(input);
@@ -951,7 +1005,9 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
951
1005
  let duration: number | null = null;
952
1006
  let times: number[];
953
1007
  if (youtube) {
1008
+ if (signal?.aborted) throw abortedError();
954
1009
  const info = await modules.yt.getYouTubeStreamInfo(modules.yt.isYouTubeURL(input).videoId);
1010
+ if (signal?.aborted) throw abortedError();
955
1011
  if ("error" in info) {
956
1012
  return { content: [{ type: "text", text: info.error }], isError: true };
957
1013
  }
@@ -964,6 +1020,7 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
964
1020
  times,
965
1021
  info,
966
1022
  );
1023
+ if (signal?.aborted) throw abortedError();
967
1024
  if (out.error && out.frames.length === 0) {
968
1025
  return { content: [{ type: "text", text: out.error }], isError: true };
969
1026
  }
@@ -983,14 +1040,18 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
983
1040
  };
984
1041
  }
985
1042
 
1043
+ if (signal?.aborted) throw abortedError();
986
1044
  const dur = await modules.video.getLocalVideoDuration(local.absolutePath);
1045
+ if (signal?.aborted) throw abortedError();
987
1046
  if (typeof dur === "number") duration = dur;
988
1047
  const plan = planTimestamps(params.timestamp, params.frames, duration);
989
1048
  if (plan.error) return { content: [{ type: "text", text: plan.error }], isError: true };
990
1049
  const frames: any[] = [];
991
1050
  const failed: string[] = [];
992
1051
  for (const seconds of plan.times) {
1052
+ if (signal?.aborted) throw abortedError();
993
1053
  const f = await modules.video.extractVideoFrame(local.absolutePath, seconds);
1054
+ if (signal?.aborted) throw abortedError();
994
1055
  if ("error" in f) failed.push(`${formatTime(seconds)}: ${f.error}`);
995
1056
  else frames.push({ ...f, seconds });
996
1057
  }
@@ -1015,6 +1076,9 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
1015
1076
  details: { timestamps: plan.times, frames: frames.length, duration },
1016
1077
  };
1017
1078
  } catch (err) {
1079
+ if (isAborted(err, signal)) {
1080
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
1081
+ }
1018
1082
  return {
1019
1083
  content: [{ type: "text", text: `截帧失败:${errText(err).slice(0, 400)}` }],
1020
1084
  isError: true,
@@ -1024,6 +1088,9 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
1024
1088
 
1025
1089
  // 整片理解路径:先看凭据,缺了给人话
1026
1090
  const hint = await videoCredentialHint(modules, youtube);
1091
+ if (signal?.aborted) {
1092
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
1093
+ }
1027
1094
  if (hint) {
1028
1095
  return { content: [{ type: "text", text: hint }], isError: true };
1029
1096
  }
@@ -1035,6 +1102,7 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
1035
1102
  prompt: params.prompt,
1036
1103
  model: params.model,
1037
1104
  });
1105
+ if (signal?.aborted) throw abortedError();
1038
1106
  if (!r) {
1039
1107
  return {
1040
1108
  content: [
@@ -1046,10 +1114,11 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
1046
1114
  if (r.error && !r.content) {
1047
1115
  return { content: [{ type: "text", text: r.error }], isError: true };
1048
1116
  }
1117
+ const safeContent = clip(String(r.content ?? ""), 40_000);
1049
1118
  const content: any[] = [
1050
1119
  {
1051
1120
  type: "text",
1052
- text: `${r.title || (youtube ? "YouTube 视频" : local.absolutePath)}(${((Date.now() - t0) / 1000).toFixed(1)}s)\n\n${r.content}`,
1121
+ text: `${r.title || (youtube ? "YouTube 视频" : local.absolutePath)}(${((Date.now() - t0) / 1000).toFixed(1)}s)\n\n${safeContent}`,
1053
1122
  },
1054
1123
  ];
1055
1124
  if (r.thumbnail?.data) {
@@ -1065,6 +1134,9 @@ export function registerPwaTools(pi: ExtensionAPI, fetchUrl?: CheckDeps["fetchUr
1065
1134
  ...(r.error ? { isError: true } : {}),
1066
1135
  };
1067
1136
  } catch (err) {
1137
+ if (isAborted(err, signal)) {
1138
+ return { content: [{ type: "text", text: "已中止" }], details: { aborted: true } };
1139
+ }
1068
1140
  return {
1069
1141
  content: [{ type: "text", text: `视频理解失败:${errText(err).slice(0, 500)}` }],
1070
1142
  isError: true,