@agentproto/corpus-cli 0.6.0 → 0.7.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/dist/cli.mjs +142 -20
- package/dist/cli.mjs.map +1 -1
- package/dist/ports/index.d.ts +75 -1
- package/dist/ports/index.mjs +132 -11
- package/dist/ports/index.mjs.map +1 -1
- package/package.json +4 -3
package/dist/ports/index.d.ts
CHANGED
|
@@ -357,6 +357,80 @@ declare class HttpReadabilityFetcher implements FetcherPort {
|
|
|
357
357
|
fetch(url: string): Promise<FetchedSource | null>;
|
|
358
358
|
}
|
|
359
359
|
|
|
360
|
+
/**
|
|
361
|
+
* PdfFetcher — a browser-free FetcherPort for PDF documents. Downloads
|
|
362
|
+
* the file with plain `fetch` (no headless browser needed) and extracts
|
|
363
|
+
* text with `unpdf` — a pure-JS wrapper around a serverless build of
|
|
364
|
+
* Mozilla's pdf.js, no native binary (no poppler/pdftotext install
|
|
365
|
+
* required). Mirrors {@link HttpReadabilityFetcher}'s shape: same
|
|
366
|
+
* fetch-then-sniff routing, same "return null when it's not mine, throw
|
|
367
|
+
* on a hard failure" contract.
|
|
368
|
+
*
|
|
369
|
+
* Routing (first-non-null-wins CompositeFetcher, see composite-fetcher.ts):
|
|
370
|
+
* claims a URL when EITHER the path ends in `.pdf` (query string
|
|
371
|
+
* ignored) OR the response's `content-type` is `application/pdf` — the
|
|
372
|
+
* second case matters most in practice: court registries and
|
|
373
|
+
* jurisprudence portals routinely serve PDFs from extension-less URLs
|
|
374
|
+
* (`/decisions/12345`, not `/decisions/12345.pdf`). Anything else
|
|
375
|
+
* returns `null` so a downstream fetcher (readability, browser) takes it.
|
|
376
|
+
*
|
|
377
|
+
* A legal/regulatory PDF is cited BY PAGE, so page boundaries are
|
|
378
|
+
* preserved in the extracted text as explicit `--- page N of M ---`
|
|
379
|
+
* markers rather than being merged into one undifferentiated blob.
|
|
380
|
+
*
|
|
381
|
+
* Fails LOUDLY — never returns an empty/partial source in silence — on:
|
|
382
|
+
* - a URL that matched by extension/content-type but isn't really a
|
|
383
|
+
* PDF (magic-bytes check: must start with `%PDF-`)
|
|
384
|
+
* - a password-protected / encrypted PDF (pdf.js throws
|
|
385
|
+
* `PasswordException` before any page can be read)
|
|
386
|
+
* - a scanned PDF with no text layer (0 characters extracted across
|
|
387
|
+
* every page) — this is the case that must NOT look like "checked,
|
|
388
|
+
* nothing there": it means "this needs OCR", a different problem.
|
|
389
|
+
*
|
|
390
|
+
* Provenance survives into the corpus frontmatter via
|
|
391
|
+
* `FetchedSource.metadata`, which `WebImporter` merges verbatim into
|
|
392
|
+
* `corpusMetadata` (→ `metadata.corpus.*` in the archived source's
|
|
393
|
+
* frontmatter): page count, the PDF file's own sha256 (what makes the
|
|
394
|
+
* source independently verifiable), and the document-info title/author/
|
|
395
|
+
* producer/creation/modification dates when the PDF carries them.
|
|
396
|
+
*
|
|
397
|
+
* The actual PDF decoding (bytes → per-page text + doc info) is injected
|
|
398
|
+
* as `extract` — same pattern as {@link YtDlpWhisperFetcher}'s
|
|
399
|
+
* `download`/`stt` seams — so this adapter is unit-testable with a fake
|
|
400
|
+
* extractor and no real PDF parsing, while the default wires the real
|
|
401
|
+
* `unpdf` engine.
|
|
402
|
+
*/
|
|
403
|
+
|
|
404
|
+
/** Per-page text + the PDF's own Info dictionary, decoded from raw bytes. */
|
|
405
|
+
interface PdfExtraction {
|
|
406
|
+
readonly totalPages: number;
|
|
407
|
+
readonly pageTexts: readonly string[];
|
|
408
|
+
/** The PDF Info dictionary as pdf.js reports it (Title/Author/Producer/CreationDate/ModDate/…). */
|
|
409
|
+
readonly info: Readonly<Record<string, unknown>>;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Decode PDF bytes into per-page text + document info. Rejects with a
|
|
413
|
+
* pdf.js `PasswordException` (`.name === "PasswordException"`) for an
|
|
414
|
+
* encrypted/password-protected document — the fetcher classifies that
|
|
415
|
+
* itself; this function does not swallow it. Real implementation uses
|
|
416
|
+
* `unpdf`; inject a fake for tests.
|
|
417
|
+
*/
|
|
418
|
+
type PdfExtractor = (bytes: Uint8Array) => Promise<PdfExtraction>;
|
|
419
|
+
interface PdfFetcherOptions {
|
|
420
|
+
readonly userAgent?: string;
|
|
421
|
+
/** Abort the download after this many ms. Default 60_000. */
|
|
422
|
+
readonly timeoutMs?: number;
|
|
423
|
+
/** Defaults to a real `unpdf`-backed extractor. Inject a fake for tests. */
|
|
424
|
+
readonly extract?: PdfExtractor;
|
|
425
|
+
}
|
|
426
|
+
declare class PdfFetcher implements FetcherPort {
|
|
427
|
+
private readonly ua;
|
|
428
|
+
private readonly timeoutMs;
|
|
429
|
+
private readonly extract;
|
|
430
|
+
constructor(opts?: PdfFetcherOptions);
|
|
431
|
+
fetch(url: string): Promise<FetchedSource | null>;
|
|
432
|
+
}
|
|
433
|
+
|
|
360
434
|
/**
|
|
361
435
|
* GhPrSourceAdapter — a PrSourcePort backed by the GitHub CLI (`gh`). This is
|
|
362
436
|
* how the local `corpus` runtime resolves a repo query to its pull requests:
|
|
@@ -609,4 +683,4 @@ declare class McpSink implements SinkPort {
|
|
|
609
683
|
push(item: SinkItem): Promise<SinkPushResult>;
|
|
610
684
|
}
|
|
611
685
|
|
|
612
|
-
export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, GhPrSourceAdapter, type GhPrSourceAdapterOptions, type GhRunner, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
|
|
686
|
+
export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, GhPrSourceAdapter, type GhPrSourceAdapterOptions, type GhRunner, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, type PdfExtraction, type PdfExtractor, PdfFetcher, type PdfFetcherOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
|
package/dist/ports/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomBytes } from 'crypto';
|
|
1
|
+
import { randomBytes, createHash } from 'crypto';
|
|
2
2
|
import { stat, readFile, mkdir, writeFile, rename, appendFile, readdir, rm, mkdtemp } from 'fs/promises';
|
|
3
3
|
import path, { join, basename, extname } from 'path';
|
|
4
4
|
import { existsSync } from 'fs';
|
|
@@ -8,6 +8,7 @@ import { execFile } from 'child_process';
|
|
|
8
8
|
import { promisify } from 'util';
|
|
9
9
|
import { normalizeLanguageTag, buildDistillPrompt, parseItems } from '@agentproto/corpus';
|
|
10
10
|
export { buildDistillPrompt, parseItems } from '@agentproto/corpus';
|
|
11
|
+
import { getDocumentProxy, extractText as extractText$1, getMeta } from 'unpdf';
|
|
11
12
|
import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -761,6 +762,126 @@ function extractReadable(html) {
|
|
|
761
762
|
function decodeEntities(s) {
|
|
762
763
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, " ").replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)));
|
|
763
764
|
}
|
|
765
|
+
var PDF_MAGIC = "%PDF-";
|
|
766
|
+
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";
|
|
767
|
+
async function defaultPdfExtractor(bytes) {
|
|
768
|
+
const pdf = await getDocumentProxy(bytes);
|
|
769
|
+
const [extracted, meta] = await Promise.all([
|
|
770
|
+
extractText$1(pdf, { mergePages: false }),
|
|
771
|
+
getMeta(pdf, { parseDates: true })
|
|
772
|
+
]);
|
|
773
|
+
return { totalPages: extracted.totalPages, pageTexts: extracted.text, info: meta.info };
|
|
774
|
+
}
|
|
775
|
+
var PdfFetcher = class {
|
|
776
|
+
ua;
|
|
777
|
+
timeoutMs;
|
|
778
|
+
extract;
|
|
779
|
+
constructor(opts = {}) {
|
|
780
|
+
this.ua = opts.userAgent ?? DEFAULT_UA2;
|
|
781
|
+
this.timeoutMs = opts.timeoutMs ?? 6e4;
|
|
782
|
+
this.extract = opts.extract ?? defaultPdfExtractor;
|
|
783
|
+
}
|
|
784
|
+
async fetch(url) {
|
|
785
|
+
let res;
|
|
786
|
+
try {
|
|
787
|
+
res = await fetch(url, {
|
|
788
|
+
headers: { "user-agent": this.ua },
|
|
789
|
+
redirect: "follow",
|
|
790
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
791
|
+
});
|
|
792
|
+
} catch {
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
if (!res.ok) return null;
|
|
796
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
797
|
+
const byExtension = isPdfExtension(url);
|
|
798
|
+
const byContentType = contentType.toLowerCase().includes("application/pdf");
|
|
799
|
+
if (!byExtension && !byContentType) return null;
|
|
800
|
+
const buffer = await res.arrayBuffer();
|
|
801
|
+
const bytes = new Uint8Array(buffer);
|
|
802
|
+
const magic = decodeAscii(bytes.slice(0, 5));
|
|
803
|
+
if (magic !== PDF_MAGIC) {
|
|
804
|
+
throw new Error(
|
|
805
|
+
`not a PDF: ${url} (magic bytes: ${JSON.stringify(magic)}, content-type: ${contentType || "none"})`
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
const sha256 = "sha256:" + createHash("sha256").update(bytes).digest("hex");
|
|
809
|
+
let extraction;
|
|
810
|
+
try {
|
|
811
|
+
extraction = await this.extract(bytes);
|
|
812
|
+
} catch (e) {
|
|
813
|
+
if (isPasswordProtected(e)) {
|
|
814
|
+
throw new Error(`PDF is password-protected/encrypted: ${url}`);
|
|
815
|
+
}
|
|
816
|
+
throw new Error(`failed to open PDF: ${url} (${msg2(e)})`);
|
|
817
|
+
}
|
|
818
|
+
const { totalPages, pageTexts, info } = extraction;
|
|
819
|
+
const hasText = pageTexts.some((t) => t.trim().length > 0);
|
|
820
|
+
if (!hasText) {
|
|
821
|
+
throw new Error(
|
|
822
|
+
`PDF has no extractable text layer (scanned document, not OCR'd): ${url} \u2014 ${totalPages} page(s), 0 characters extracted`
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
const text = pageTexts.map((t, i) => `--- page ${i + 1} of ${totalPages} ---
|
|
826
|
+
|
|
827
|
+
${t.trim()}`).join("\n\n");
|
|
828
|
+
const pdfTitle = stringField(info, "Title");
|
|
829
|
+
const pdfAuthor = stringField(info, "Author");
|
|
830
|
+
const pdfProducer = stringField(info, "Producer");
|
|
831
|
+
const pdfCreatedAt = dateField(info, "CreationDate");
|
|
832
|
+
const pdfModifiedAt = dateField(info, "ModDate");
|
|
833
|
+
return {
|
|
834
|
+
title: pdfTitle || titleFromUrl(url),
|
|
835
|
+
text,
|
|
836
|
+
kind: "pdf",
|
|
837
|
+
via: "extraction",
|
|
838
|
+
metadata: {
|
|
839
|
+
pdfPageCount: totalPages,
|
|
840
|
+
pdfSha256: sha256,
|
|
841
|
+
...pdfTitle ? { pdfTitle } : {},
|
|
842
|
+
...pdfAuthor ? { pdfAuthor } : {},
|
|
843
|
+
...pdfProducer ? { pdfProducer } : {},
|
|
844
|
+
...pdfCreatedAt ? { pdfCreatedAt } : {},
|
|
845
|
+
...pdfModifiedAt ? { pdfModifiedAt } : {}
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
function isPdfExtension(url) {
|
|
851
|
+
try {
|
|
852
|
+
return /\.pdf$/i.test(new URL(url).pathname);
|
|
853
|
+
} catch {
|
|
854
|
+
return false;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function decodeAscii(bytes) {
|
|
858
|
+
let out = "";
|
|
859
|
+
for (const b of bytes) out += String.fromCharCode(b);
|
|
860
|
+
return out;
|
|
861
|
+
}
|
|
862
|
+
function isPasswordProtected(e) {
|
|
863
|
+
if (!(e instanceof Error)) return false;
|
|
864
|
+
return e.name === "PasswordException" || /password/i.test(e.message);
|
|
865
|
+
}
|
|
866
|
+
function stringField(info, key) {
|
|
867
|
+
const v = info[key];
|
|
868
|
+
return typeof v === "string" && v.trim() ? v.trim() : void 0;
|
|
869
|
+
}
|
|
870
|
+
function dateField(info, key) {
|
|
871
|
+
const v = info[key];
|
|
872
|
+
return v instanceof Date && !Number.isNaN(v.getTime()) ? v.toISOString() : void 0;
|
|
873
|
+
}
|
|
874
|
+
function titleFromUrl(url) {
|
|
875
|
+
try {
|
|
876
|
+
const last = new URL(url).pathname.split("/").filter(Boolean).pop();
|
|
877
|
+
return last ? decodeURIComponent(last) : url;
|
|
878
|
+
} catch {
|
|
879
|
+
return url;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
function msg2(e) {
|
|
883
|
+
return e instanceof Error ? e.message : String(e);
|
|
884
|
+
}
|
|
764
885
|
var execFileAsync3 = promisify(execFile);
|
|
765
886
|
var GH_ACTOR = z.object({ login: z.string().optional(), name: z.string().optional() }).loose();
|
|
766
887
|
var GH_PR_LIST_ITEM = z.object({ number: z.number() }).loose();
|
|
@@ -822,7 +943,7 @@ var GhPrSourceAdapter = class {
|
|
|
822
943
|
pr = await this.viewPr(query, n);
|
|
823
944
|
} catch (e) {
|
|
824
945
|
process.stderr.write(
|
|
825
|
-
`corpus: skipping ${query.repo}#${n} \u2014 ${
|
|
946
|
+
`corpus: skipping ${query.repo}#${n} \u2014 ${msg3(e)}
|
|
826
947
|
`
|
|
827
948
|
);
|
|
828
949
|
continue;
|
|
@@ -930,7 +1051,7 @@ function parseJson(out) {
|
|
|
930
1051
|
if (!trimmed) return [];
|
|
931
1052
|
return JSON.parse(trimmed);
|
|
932
1053
|
}
|
|
933
|
-
function
|
|
1054
|
+
function msg3(e) {
|
|
934
1055
|
return e instanceof Error ? e.message : String(e);
|
|
935
1056
|
}
|
|
936
1057
|
function defaultGhRunner(bin) {
|
|
@@ -1264,10 +1385,10 @@ var SseMcpClient = class {
|
|
|
1264
1385
|
try {
|
|
1265
1386
|
const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
|
|
1266
1387
|
if (!parsed.success) return;
|
|
1267
|
-
const
|
|
1268
|
-
if (typeof
|
|
1269
|
-
this.pending.get(
|
|
1270
|
-
this.pending.delete(
|
|
1388
|
+
const msg5 = parsed.data;
|
|
1389
|
+
if (typeof msg5.id === "number" && this.pending.has(msg5.id)) {
|
|
1390
|
+
this.pending.get(msg5.id)(msg5);
|
|
1391
|
+
this.pending.delete(msg5.id);
|
|
1271
1392
|
}
|
|
1272
1393
|
} catch {
|
|
1273
1394
|
}
|
|
@@ -1334,7 +1455,7 @@ var McpSink = class {
|
|
|
1334
1455
|
try {
|
|
1335
1456
|
client = await this.ensure();
|
|
1336
1457
|
} catch (e) {
|
|
1337
|
-
return { uri: item.uri, ok: false, error: `connect: ${
|
|
1458
|
+
return { uri: item.uri, ok: false, error: `connect: ${msg4(e)}` };
|
|
1338
1459
|
}
|
|
1339
1460
|
const args = template(this.config.args, item);
|
|
1340
1461
|
const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
|
|
@@ -1343,7 +1464,7 @@ var McpSink = class {
|
|
|
1343
1464
|
if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
|
|
1344
1465
|
return { uri: item.uri, ok: true };
|
|
1345
1466
|
} catch (e) {
|
|
1346
|
-
return { uri: item.uri, ok: false, error:
|
|
1467
|
+
return { uri: item.uri, ok: false, error: msg4(e) };
|
|
1347
1468
|
}
|
|
1348
1469
|
}
|
|
1349
1470
|
};
|
|
@@ -1387,10 +1508,10 @@ function stringify(v) {
|
|
|
1387
1508
|
if (Array.isArray(v)) return v.join(", ");
|
|
1388
1509
|
return v == null ? "" : String(v);
|
|
1389
1510
|
}
|
|
1390
|
-
function
|
|
1511
|
+
function msg4(e) {
|
|
1391
1512
|
return e instanceof Error ? e.message : String(e);
|
|
1392
1513
|
}
|
|
1393
1514
|
|
|
1394
|
-
export { AnthropicDistiller, AssemblyAiStt, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
|
|
1515
|
+
export { AnthropicDistiller, AssemblyAiStt, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, PdfFetcher, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
|
|
1395
1516
|
//# sourceMappingURL=index.mjs.map
|
|
1396
1517
|
//# sourceMappingURL=index.mjs.map
|