@agentproto/corpus-cli 0.6.0 → 0.7.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/dist/cli.mjs CHANGED
@@ -11,6 +11,7 @@ import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowl
11
11
  import matter3 from 'gray-matter';
12
12
  import { execFile } from 'child_process';
13
13
  import { promisify } from 'util';
14
+ import { getDocumentProxy, extractText as extractText$1, getMeta } from 'unpdf';
14
15
  import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
15
16
  import { stitchReport, buildPacks, lintReportConfig, reportConfigSchema } from '@agentproto/corpus/report';
16
17
 
@@ -404,8 +405,8 @@ function resolveWorkspacePath(arg) {
404
405
  if (!arg) return process.cwd();
405
406
  return path.resolve(process.cwd(), arg);
406
407
  }
407
- function fail(msg8, code = 1) {
408
- process.stderr.write(`corpus: ${msg8}
408
+ function fail(msg9, code = 1) {
409
+ process.stderr.write(`corpus: ${msg9}
409
410
  `);
410
411
  return code;
411
412
  }
@@ -1602,6 +1603,126 @@ function extractReadable(html) {
1602
1603
  function decodeEntities(s) {
1603
1604
  return s.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)));
1604
1605
  }
1606
+ var PDF_MAGIC = "%PDF-";
1607
+ var DEFAULT_UA2 = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0 Safari/537.36";
1608
+ async function defaultPdfExtractor(bytes) {
1609
+ const pdf = await getDocumentProxy(bytes);
1610
+ const [extracted, meta] = await Promise.all([
1611
+ extractText$1(pdf, { mergePages: false }),
1612
+ getMeta(pdf, { parseDates: true })
1613
+ ]);
1614
+ return { totalPages: extracted.totalPages, pageTexts: extracted.text, info: meta.info };
1615
+ }
1616
+ var PdfFetcher = class {
1617
+ ua;
1618
+ timeoutMs;
1619
+ extract;
1620
+ constructor(opts = {}) {
1621
+ this.ua = opts.userAgent ?? DEFAULT_UA2;
1622
+ this.timeoutMs = opts.timeoutMs ?? 6e4;
1623
+ this.extract = opts.extract ?? defaultPdfExtractor;
1624
+ }
1625
+ async fetch(url) {
1626
+ let res;
1627
+ try {
1628
+ res = await fetch(url, {
1629
+ headers: { "user-agent": this.ua },
1630
+ redirect: "follow",
1631
+ signal: AbortSignal.timeout(this.timeoutMs)
1632
+ });
1633
+ } catch {
1634
+ return null;
1635
+ }
1636
+ if (!res.ok) return null;
1637
+ const contentType = res.headers.get("content-type") ?? "";
1638
+ const byExtension = isPdfExtension(url);
1639
+ const byContentType = contentType.toLowerCase().includes("application/pdf");
1640
+ if (!byExtension && !byContentType) return null;
1641
+ const buffer = await res.arrayBuffer();
1642
+ const bytes = new Uint8Array(buffer);
1643
+ const magic = decodeAscii(bytes.slice(0, 5));
1644
+ if (magic !== PDF_MAGIC) {
1645
+ throw new Error(
1646
+ `not a PDF: ${url} (magic bytes: ${JSON.stringify(magic)}, content-type: ${contentType || "none"})`
1647
+ );
1648
+ }
1649
+ const sha256 = "sha256:" + createHash("sha256").update(bytes).digest("hex");
1650
+ let extraction;
1651
+ try {
1652
+ extraction = await this.extract(bytes);
1653
+ } catch (e) {
1654
+ if (isPasswordProtected(e)) {
1655
+ throw new Error(`PDF is password-protected/encrypted: ${url}`);
1656
+ }
1657
+ throw new Error(`failed to open PDF: ${url} (${msg3(e)})`);
1658
+ }
1659
+ const { totalPages, pageTexts, info } = extraction;
1660
+ const hasText = pageTexts.some((t) => t.trim().length > 0);
1661
+ if (!hasText) {
1662
+ throw new Error(
1663
+ `PDF has no extractable text layer (scanned document, not OCR'd): ${url} \u2014 ${totalPages} page(s), 0 characters extracted`
1664
+ );
1665
+ }
1666
+ const text = pageTexts.map((t, i) => `--- page ${i + 1} of ${totalPages} ---
1667
+
1668
+ ${t.trim()}`).join("\n\n");
1669
+ const pdfTitle = stringField(info, "Title");
1670
+ const pdfAuthor = stringField(info, "Author");
1671
+ const pdfProducer = stringField(info, "Producer");
1672
+ const pdfCreatedAt = dateField(info, "CreationDate");
1673
+ const pdfModifiedAt = dateField(info, "ModDate");
1674
+ return {
1675
+ title: pdfTitle || titleFromUrl(url),
1676
+ text,
1677
+ kind: "pdf",
1678
+ via: "extraction",
1679
+ metadata: {
1680
+ pdfPageCount: totalPages,
1681
+ pdfSha256: sha256,
1682
+ ...pdfTitle ? { pdfTitle } : {},
1683
+ ...pdfAuthor ? { pdfAuthor } : {},
1684
+ ...pdfProducer ? { pdfProducer } : {},
1685
+ ...pdfCreatedAt ? { pdfCreatedAt } : {},
1686
+ ...pdfModifiedAt ? { pdfModifiedAt } : {}
1687
+ }
1688
+ };
1689
+ }
1690
+ };
1691
+ function isPdfExtension(url) {
1692
+ try {
1693
+ return /\.pdf$/i.test(new URL(url).pathname);
1694
+ } catch {
1695
+ return false;
1696
+ }
1697
+ }
1698
+ function decodeAscii(bytes) {
1699
+ let out = "";
1700
+ for (const b of bytes) out += String.fromCharCode(b);
1701
+ return out;
1702
+ }
1703
+ function isPasswordProtected(e) {
1704
+ if (!(e instanceof Error)) return false;
1705
+ return e.name === "PasswordException" || /password/i.test(e.message);
1706
+ }
1707
+ function stringField(info, key) {
1708
+ const v = info[key];
1709
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
1710
+ }
1711
+ function dateField(info, key) {
1712
+ const v = info[key];
1713
+ return v instanceof Date && !Number.isNaN(v.getTime()) ? v.toISOString() : void 0;
1714
+ }
1715
+ function titleFromUrl(url) {
1716
+ try {
1717
+ const last = new URL(url).pathname.split("/").filter(Boolean).pop();
1718
+ return last ? decodeURIComponent(last) : url;
1719
+ } catch {
1720
+ return url;
1721
+ }
1722
+ }
1723
+ function msg3(e) {
1724
+ return e instanceof Error ? e.message : String(e);
1725
+ }
1605
1726
 
1606
1727
  // src/ports/composite-fetcher.ts
1607
1728
  var CompositeFetcher = class {
@@ -1949,12 +2070,13 @@ ${plan}`);
1949
2070
  ...parsed.ffmpegLocation ? { ffmpegLocation: parsed.ffmpegLocation } : {}
1950
2071
  })
1951
2072
  );
2073
+ chain.push(new PdfFetcher());
1952
2074
  if (parsed.scrapeMcp) {
1953
2075
  try {
1954
2076
  const client = await connectBrowserMcp({ endpoint: parsed.scrapeMcp });
1955
2077
  chain.push(new ScrapeMcpFetcher({ client }));
1956
2078
  } catch (e) {
1957
- return fail(`could not connect to scrape MCP at ${parsed.scrapeMcp}: ${msg3(e)}`, 1);
2079
+ return fail(`could not connect to scrape MCP at ${parsed.scrapeMcp}: ${msg4(e)}`, 1);
1958
2080
  }
1959
2081
  }
1960
2082
  if (parsed.browserMcp) {
@@ -1963,7 +2085,7 @@ ${plan}`);
1963
2085
  browser = await connectBrowserMcp({ endpoint: parsed.browserMcp });
1964
2086
  chain.push(new BrowserMcpFetcher({ browser }));
1965
2087
  } catch (e) {
1966
- return fail(`could not connect to browser MCP at ${parsed.browserMcp}: ${msg3(e)}`, 1);
2088
+ return fail(`could not connect to browser MCP at ${parsed.browserMcp}: ${msg4(e)}`, 1);
1967
2089
  }
1968
2090
  }
1969
2091
  chain.push(new HttpReadabilityFetcher());
@@ -1994,7 +2116,7 @@ ${plan}`);
1994
2116
  }
1995
2117
  });
1996
2118
  } catch (e) {
1997
- return fail(`import failed: ${msg3(e)}`, 1);
2119
+ return fail(`import failed: ${msg4(e)}`, 1);
1998
2120
  }
1999
2121
  process.stdout.write(
2000
2122
  `import-web \u2192 ${target}
@@ -2014,7 +2136,7 @@ knowledge engine (RAG) via the WriterPort. Import only stages the sources.
2014
2136
  );
2015
2137
  return 0;
2016
2138
  }
2017
- function msg3(e) {
2139
+ function msg4(e) {
2018
2140
  return e instanceof Error ? e.message : String(e);
2019
2141
  }
2020
2142
  function parse3(args) {
@@ -2107,7 +2229,7 @@ ${plan}`);
2107
2229
  count++;
2108
2230
  }
2109
2231
  } catch (e) {
2110
- return fail(`enumerate failed: ${msg4(e)}`, 1);
2232
+ return fail(`enumerate failed: ${msg5(e)}`, 1);
2111
2233
  }
2112
2234
  if (count > 20) process.stdout.write(` \u2026 +${count - 20} more
2113
2235
  `);
@@ -2129,7 +2251,7 @@ ${plan}`);
2129
2251
  try {
2130
2252
  report = await runner.run(importer, importerTarget);
2131
2253
  } catch (e) {
2132
- return fail(`import failed: ${msg4(e)}`, 1);
2254
+ return fail(`import failed: ${msg5(e)}`, 1);
2133
2255
  }
2134
2256
  process.stdout.write(
2135
2257
  `import-code \u2192 ${target}
@@ -2149,7 +2271,7 @@ graph construction is the code-brain subsystem's job, not this importer.
2149
2271
  );
2150
2272
  return 0;
2151
2273
  }
2152
- function msg4(e) {
2274
+ function msg5(e) {
2153
2275
  return e instanceof Error ? e.message : String(e);
2154
2276
  }
2155
2277
  var execFileAsync4 = promisify(execFile);
@@ -2213,7 +2335,7 @@ var GhPrSourceAdapter = class {
2213
2335
  pr = await this.viewPr(query, n);
2214
2336
  } catch (e) {
2215
2337
  process.stderr.write(
2216
- `corpus: skipping ${query.repo}#${n} \u2014 ${msg5(e)}
2338
+ `corpus: skipping ${query.repo}#${n} \u2014 ${msg6(e)}
2217
2339
  `
2218
2340
  );
2219
2341
  continue;
@@ -2321,7 +2443,7 @@ function parseJson(out) {
2321
2443
  if (!trimmed) return [];
2322
2444
  return JSON.parse(trimmed);
2323
2445
  }
2324
- function msg5(e) {
2446
+ function msg6(e) {
2325
2447
  return e instanceof Error ? e.message : String(e);
2326
2448
  }
2327
2449
  function defaultGhRunner(bin) {
@@ -2441,7 +2563,7 @@ ${plan}`);
2441
2563
  }
2442
2564
  });
2443
2565
  } catch (e) {
2444
- return fail(`import failed: ${msg6(e)}`, 1);
2566
+ return fail(`import failed: ${msg7(e)}`, 1);
2445
2567
  }
2446
2568
  process.stdout.write(
2447
2569
  `import-prs \u2192 ${target}
@@ -2461,7 +2583,7 @@ sources into refined knowledge.entry/v1 (pattern/critique/summary).
2461
2583
  );
2462
2584
  return 0;
2463
2585
  }
2464
- function msg6(e) {
2586
+ function msg7(e) {
2465
2587
  return e instanceof Error ? e.message : String(e);
2466
2588
  }
2467
2589
  function parse5(args) {
@@ -3721,10 +3843,10 @@ var SseMcpClient = class {
3721
3843
  try {
3722
3844
  const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
3723
3845
  if (!parsed.success) return;
3724
- const msg8 = parsed.data;
3725
- if (typeof msg8.id === "number" && this.pending.has(msg8.id)) {
3726
- this.pending.get(msg8.id)(msg8);
3727
- this.pending.delete(msg8.id);
3846
+ const msg9 = parsed.data;
3847
+ if (typeof msg9.id === "number" && this.pending.has(msg9.id)) {
3848
+ this.pending.get(msg9.id)(msg9);
3849
+ this.pending.delete(msg9.id);
3728
3850
  }
3729
3851
  } catch {
3730
3852
  }
@@ -3793,7 +3915,7 @@ var McpSink = class {
3793
3915
  try {
3794
3916
  client = await this.ensure();
3795
3917
  } catch (e) {
3796
- return { uri: item.uri, ok: false, error: `connect: ${msg7(e)}` };
3918
+ return { uri: item.uri, ok: false, error: `connect: ${msg8(e)}` };
3797
3919
  }
3798
3920
  const args = template(this.config.args, item);
3799
3921
  const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
@@ -3802,7 +3924,7 @@ var McpSink = class {
3802
3924
  if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
3803
3925
  return { uri: item.uri, ok: true };
3804
3926
  } catch (e) {
3805
- return { uri: item.uri, ok: false, error: msg7(e) };
3927
+ return { uri: item.uri, ok: false, error: msg8(e) };
3806
3928
  }
3807
3929
  }
3808
3930
  };
@@ -3846,7 +3968,7 @@ function stringify(v) {
3846
3968
  if (Array.isArray(v)) return v.join(", ");
3847
3969
  return v == null ? "" : String(v);
3848
3970
  }
3849
- function msg7(e) {
3971
+ function msg8(e) {
3850
3972
  return e instanceof Error ? e.message : String(e);
3851
3973
  }
3852
3974