@agentproto/corpus-cli 0.10.2 → 0.11.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.
Files changed (25) hide show
  1. package/dist/cli.mjs +164 -93
  2. package/dist/cli.mjs.map +1 -1
  3. package/dist/ports/index.d.ts +37 -1
  4. package/dist/ports/index.mjs +141 -74
  5. package/dist/ports/index.mjs.map +1 -1
  6. package/dist/specs/resources/aip-10/draft/KNOWLEDGE.schema.json +2 -2
  7. package/dist/specs/resources/aip-18/draft/COLLECTION.schema.json +9 -2
  8. package/dist/specs/resources/aip-19/draft/SECRETS.schema.json +8 -2
  9. package/dist/specs/resources/aip-20/draft/WORK.schema.json +232 -206
  10. package/dist/specs/resources/aip-34/draft/EXPORT.schema.json +29 -0
  11. package/dist/specs/resources/aip-34/draft/LOCK.schema.json +76 -0
  12. package/dist/specs/resources/aip-34/draft/TYPES.schema.json +78 -0
  13. package/dist/specs/resources/aip-34/draft/WORKSPACE.schema.json +236 -105
  14. package/dist/specs/resources/aip-42/draft/AGENT.schema.json +5 -0
  15. package/dist/specs/resources/aip-49/draft/ASSET.schema.json +10 -0
  16. package/dist/specs/resources/aip-53/draft/APP.schema.json +862 -43
  17. package/dist/specs/resources/aip-58/draft/event.schema.json +3 -2
  18. package/dist/specs/resources/aip-62/draft/ATTESTATION.schema.json +368 -62
  19. package/dist/specs/resources/aip-62/draft/REVIEW.schema.json +201 -43
  20. package/dist/specs/resources/aip-63/draft/BROWSER.schema.json +427 -0
  21. package/dist/specs/resources/aip-63/draft/RECORDING.schema.json +292 -0
  22. package/dist/specs/resources/aip-7/draft/GOVERNANCE.schema.json +2 -2
  23. package/dist/specs/resources/pending/memory/draft/MEMORY.schema.json +321 -0
  24. package/dist/specs/resources/pending/services/SERVICES.schema.json +35 -0
  25. package/package.json +7 -7
@@ -120,6 +120,13 @@ interface Transcript {
120
120
  interface SttPort {
121
121
  transcribe(audioPath: string): Promise<Transcript>;
122
122
  }
123
+ /**
124
+ * A 401/403 or "api key" error from any SttPort fails every subsequent
125
+ * call the same way — fetchers that wrap a transcribe() call rethrow on
126
+ * this instead of treating it as a per-item skip, so a misconfigured key
127
+ * surfaces loudly rather than silently skipping an entire batch.
128
+ */
129
+ declare function isSttAuthError(e: unknown): boolean;
123
130
  interface OpenAiWhisperSttOptions {
124
131
  readonly apiKey: string;
125
132
  /** Default "whisper-1". */
@@ -230,6 +237,35 @@ declare class YtDlpWhisperFetcher implements FetcherPort {
230
237
  fetch(url: string): Promise<FetchedSource | null>;
231
238
  }
232
239
 
240
+ /**
241
+ * LocalFileFetcher — a FetcherPort for an audio/video file that already
242
+ * sits on disk (`file:///abs/path.mp3` or a bare path such as
243
+ * `/abs/path.mp3`). No yt-dlp, no network fetch: the "URL" IS the file,
244
+ * so this tier just hands it straight to the injected SttPort.
245
+ *
246
+ * Exists because the two video tiers above it (captions, yt-dlp+Whisper)
247
+ * both require a real http(s) URL — a local recording (a downloaded
248
+ * Twitter Space, a Zoom export, …) has neither captions nor a remote host
249
+ * to pull from. Reusing WebImporter/ImporterRunner for it means a local
250
+ * file gets the exact same diarization, slugging, dedup, and corpus
251
+ * materialisation as a YouTube URL — only the "how do we get audio bytes"
252
+ * step differs.
253
+ *
254
+ * Sits ahead of the video/article tiers in the import-web chain: it only
255
+ * claims strings that resolve to a real file on disk, so it's a no-op for
256
+ * every http(s) URL (one `stat` that fails fast) and never competes with
257
+ * them.
258
+ */
259
+
260
+ interface LocalFileFetcherOptions {
261
+ readonly stt: SttPort;
262
+ }
263
+ declare class LocalFileFetcher implements FetcherPort {
264
+ private readonly stt;
265
+ constructor(opts: LocalFileFetcherOptions);
266
+ fetch(url: string): Promise<FetchedSource | null>;
267
+ }
268
+
233
269
  /**
234
270
  * AssemblyAiStt — a diarizing SttPort. Where OpenAiWhisperStt returns a
235
271
  * flat transcript, this returns SPEAKER-LABELLED text (`Speaker A: … /
@@ -766,4 +802,4 @@ declare class McpSink implements SinkPort {
766
802
  push(item: SinkItem): Promise<SinkPushResult>;
767
803
  }
768
804
 
769
- export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BatchDistiller, type BatchDistillerOptions, 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 };
805
+ export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BatchDistiller, type BatchDistillerOptions, 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, LocalFileFetcher, type LocalFileFetcherOptions, 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, isSttAuthError };
@@ -1,6 +1,6 @@
1
1
  import { randomBytes, createHash } from 'crypto';
2
2
  import { stat, readFile, mkdir, writeFile, rename, appendFile, readdir, rm, mkdtemp } from 'fs/promises';
3
- import path, { join, basename, extname } from 'path';
3
+ import path, { basename, join, extname } from 'path';
4
4
  import { existsSync } from 'fs';
5
5
  import os, { tmpdir } from 'os';
6
6
  import { z } from 'zod';
@@ -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 { fileURLToPath } from 'url';
11
12
  import { getDocumentProxy, extractText as extractText$1, getMeta } from 'unpdf';
12
13
  import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
13
14
  import { validateForBatch, pollUntilEnded, collectResults, expiredCustomIds } from '@agentproto/batch';
@@ -330,6 +331,77 @@ function stripTags(html) {
330
331
  if (!html) return "";
331
332
  return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
332
333
  }
334
+ var WHISPER_RESPONSE = z.object({ text: z.string().optional(), language: z.string().optional() }).loose();
335
+ function isSttAuthError(e) {
336
+ const m = (e instanceof Error ? e.message : String(e)).toLowerCase();
337
+ return m.includes(" 401") || m.includes(" 403") || m.includes("unauthorized") || m.includes("forbidden") || m.includes("api key") || m.includes("api_key");
338
+ }
339
+ var WHISPER_MAX_BYTES = 25 * 1024 * 1024;
340
+ var OpenAiWhisperStt = class {
341
+ apiKey;
342
+ model;
343
+ baseUrl;
344
+ constructor(opts) {
345
+ this.apiKey = opts.apiKey;
346
+ this.model = opts.model ?? "whisper-1";
347
+ this.baseUrl = (opts.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "");
348
+ }
349
+ async transcribe(audioPath) {
350
+ const bytes = await readFile(audioPath);
351
+ if (bytes.byteLength > WHISPER_MAX_BYTES) {
352
+ throw new Error(
353
+ `audio ${basename(audioPath)} is ${(bytes.byteLength / 1024 / 1024).toFixed(1)} MB \u2014 over Whisper's 25 MB cap. Lower the bitrate or chunk the media.`
354
+ );
355
+ }
356
+ const form = new FormData();
357
+ form.append("file", new Blob([bytes]), basename(audioPath));
358
+ form.append("model", this.model);
359
+ form.append("response_format", "verbose_json");
360
+ const res = await this.postWithRetry(form);
361
+ if (!res.ok) {
362
+ const body = await res.text().catch(() => "");
363
+ throw new Error(`Whisper STT ${res.status} ${res.statusText}: ${body.slice(0, 200)}`);
364
+ }
365
+ const data = WHISPER_RESPONSE.parse(await res.json());
366
+ const language = normalizeLanguageTag(data.language);
367
+ return {
368
+ text: (data.text ?? "").trim(),
369
+ ...language ? { language } : {}
370
+ };
371
+ }
372
+ /**
373
+ * POST the audio with bounded retry. Transcribing a long talk fans out
374
+ * into many segment uploads (see ChunkedStt), so a single transient
375
+ * network blip ("fetch failed") or a 429 / 5xx must not abort the whole
376
+ * batch. Network errors and retryable statuses back off and retry;
377
+ * client errors (401 auth, 400 bad request) return immediately so a real
378
+ * misconfiguration still surfaces loudly.
379
+ */
380
+ async postWithRetry(form, attempts = 4) {
381
+ const url = `${this.baseUrl}/audio/transcriptions`;
382
+ let lastErr;
383
+ for (let i = 0; i < attempts; i++) {
384
+ try {
385
+ const res = await fetch(url, {
386
+ method: "POST",
387
+ headers: { authorization: `Bearer ${this.apiKey}` },
388
+ body: form
389
+ });
390
+ if (res.status !== 429 && res.status < 500) return res;
391
+ lastErr = new Error(`Whisper STT ${res.status} ${res.statusText}`);
392
+ } catch (e) {
393
+ lastErr = e;
394
+ }
395
+ if (i < attempts - 1) await delay(500 * 2 ** i);
396
+ }
397
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
398
+ }
399
+ };
400
+ function delay(ms) {
401
+ return new Promise((resolve) => setTimeout(resolve, ms));
402
+ }
403
+
404
+ // src/ports/ytdlp-whisper-fetcher.adapter.ts
333
405
  var execFileAsync = promisify(execFile);
334
406
  var YTDLP_INFO = z.object({ title: z.string().optional(), language: z.string().optional() }).loose();
335
407
  var YtDlpWhisperFetcher = class {
@@ -381,7 +453,7 @@ var YtDlpWhisperFetcher = class {
381
453
  } : {}
382
454
  };
383
455
  } catch (e) {
384
- if (isAuthError(e)) throw e;
456
+ if (isSttAuthError(e)) throw e;
385
457
  process.stderr.write(
386
458
  `corpus: transcription failed for ${url} \u2014 skipped (${msg(e)})
387
459
  `
@@ -396,10 +468,6 @@ var YtDlpWhisperFetcher = class {
396
468
  function msg(e) {
397
469
  return e instanceof Error ? e.message : String(e);
398
470
  }
399
- function isAuthError(e) {
400
- const m = msg(e).toLowerCase();
401
- return m.includes(" 401") || m.includes(" 403") || m.includes("unauthorized") || m.includes("forbidden") || m.includes("api key") || m.includes("api_key");
402
- }
403
471
  function buildYtDlpArgs(url, dir, opts) {
404
472
  const durationGuard = opts?.maxDurationSec && opts.maxDurationSec > 0 ? ["--match-filter", `duration <= ${Math.floor(opts.maxDurationSec)}`] : [];
405
473
  const cookieArgs = opts?.cookiesFromBrowser ? ["--cookies-from-browser", opts.cookiesFromBrowser] : opts?.cookiesFile ? ["--cookies", opts.cookiesFile] : [];
@@ -469,70 +537,69 @@ function defaultYtDlpDownloader(bin, opts) {
469
537
  }
470
538
  };
471
539
  }
472
- var WHISPER_RESPONSE = z.object({ text: z.string().optional(), language: z.string().optional() }).loose();
473
- var WHISPER_MAX_BYTES = 25 * 1024 * 1024;
474
- var OpenAiWhisperStt = class {
475
- apiKey;
476
- model;
477
- baseUrl;
540
+ var LocalFileFetcher = class {
541
+ stt;
478
542
  constructor(opts) {
479
- this.apiKey = opts.apiKey;
480
- this.model = opts.model ?? "whisper-1";
481
- this.baseUrl = (opts.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "");
543
+ this.stt = opts.stt;
482
544
  }
483
- async transcribe(audioPath) {
484
- const bytes = await readFile(audioPath);
485
- if (bytes.byteLength > WHISPER_MAX_BYTES) {
486
- throw new Error(
487
- `audio ${basename(audioPath)} is ${(bytes.byteLength / 1024 / 1024).toFixed(1)} MB \u2014 over Whisper's 25 MB cap. Lower the bitrate or chunk the media.`
488
- );
489
- }
490
- const form = new FormData();
491
- form.append("file", new Blob([bytes]), basename(audioPath));
492
- form.append("model", this.model);
493
- form.append("response_format", "verbose_json");
494
- const res = await this.postWithRetry(form);
495
- if (!res.ok) {
496
- const body = await res.text().catch(() => "");
497
- throw new Error(`Whisper STT ${res.status} ${res.statusText}: ${body.slice(0, 200)}`);
545
+ async fetch(url) {
546
+ const path3 = await resolveLocalPath(url);
547
+ if (!path3) return null;
548
+ let t;
549
+ try {
550
+ t = await this.stt.transcribe(path3);
551
+ } catch (e) {
552
+ if (isSttAuthError(e)) throw e;
553
+ process.stderr.write(`corpus: transcription failed for ${path3} \u2014 skipped (${msg2(e)})
554
+ `);
555
+ return null;
498
556
  }
499
- const data = WHISPER_RESPONSE.parse(await res.json());
500
- const language = normalizeLanguageTag(data.language);
557
+ if (!t.text.trim()) return null;
558
+ const utterances = t.utterances ?? [];
559
+ const diarized = utterances.length > 0;
560
+ const speakers = diarized ? new Set(utterances.map((u) => u.speaker)).size : 0;
501
561
  return {
502
- text: (data.text ?? "").trim(),
503
- ...language ? { language } : {}
562
+ title: basename(path3, extname(path3)),
563
+ text: t.text,
564
+ kind: "video",
565
+ ...t.language ? { language: t.language } : {},
566
+ via: diarized ? "diarized-transcription" : "transcription",
567
+ ...diarized ? {
568
+ metadata: {
569
+ speech: {
570
+ regime: "spoken",
571
+ diarized: true,
572
+ engine: t.engine ?? "unknown",
573
+ speakers,
574
+ ...t.speakerLabelsLocalToSegment ? { segmented: true } : {}
575
+ }
576
+ }
577
+ } : {}
504
578
  };
505
579
  }
506
- /**
507
- * POST the audio with bounded retry. Transcribing a long talk fans out
508
- * into many segment uploads (see ChunkedStt), so a single transient
509
- * network blip ("fetch failed") or a 429 / 5xx must not abort the whole
510
- * batch. Network errors and retryable statuses back off and retry;
511
- * client errors (401 auth, 400 bad request) return immediately so a real
512
- * misconfiguration still surfaces loudly.
513
- */
514
- async postWithRetry(form, attempts = 4) {
515
- const url = `${this.baseUrl}/audio/transcriptions`;
516
- let lastErr;
517
- for (let i = 0; i < attempts; i++) {
518
- try {
519
- const res = await fetch(url, {
520
- method: "POST",
521
- headers: { authorization: `Bearer ${this.apiKey}` },
522
- body: form
523
- });
524
- if (res.status !== 429 && res.status < 500) return res;
525
- lastErr = new Error(`Whisper STT ${res.status} ${res.statusText}`);
526
- } catch (e) {
527
- lastErr = e;
528
- }
529
- if (i < attempts - 1) await delay(500 * 2 ** i);
580
+ };
581
+ async function resolveLocalPath(url) {
582
+ let candidate;
583
+ if (url.startsWith("file://")) {
584
+ try {
585
+ candidate = fileURLToPath(url);
586
+ } catch {
587
+ return null;
530
588
  }
531
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
589
+ } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) {
590
+ return null;
591
+ } else {
592
+ candidate = url;
593
+ }
594
+ try {
595
+ const st = await stat(candidate);
596
+ return st.isFile() ? candidate : null;
597
+ } catch {
598
+ return null;
532
599
  }
533
- };
534
- function delay(ms) {
535
- return new Promise((resolve) => setTimeout(resolve, ms));
600
+ }
601
+ function msg2(e) {
602
+ return e instanceof Error ? e.message : String(e);
536
603
  }
537
604
  var UPLOAD_RESPONSE = z.object({ upload_url: z.string() });
538
605
  var AAI_TRANSCRIPT = z.object({
@@ -878,7 +945,7 @@ var PdfFetcher = class {
878
945
  if (isPasswordProtected(e)) {
879
946
  throw new Error(`PDF is password-protected/encrypted: ${url}`);
880
947
  }
881
- throw new Error(`failed to open PDF: ${url} (${msg2(e)})`);
948
+ throw new Error(`failed to open PDF: ${url} (${msg3(e)})`);
882
949
  }
883
950
  const { totalPages, pageTexts, info } = extraction;
884
951
  const hasText = pageTexts.some((t) => t.trim().length > 0);
@@ -944,7 +1011,7 @@ function titleFromUrl(url) {
944
1011
  return url;
945
1012
  }
946
1013
  }
947
- function msg2(e) {
1014
+ function msg3(e) {
948
1015
  return e instanceof Error ? e.message : String(e);
949
1016
  }
950
1017
  var execFileAsync3 = promisify(execFile);
@@ -1008,7 +1075,7 @@ var GhPrSourceAdapter = class {
1008
1075
  pr = await this.viewPr(query, n);
1009
1076
  } catch (e) {
1010
1077
  process.stderr.write(
1011
- `corpus: skipping ${query.repo}#${n} \u2014 ${msg3(e)}
1078
+ `corpus: skipping ${query.repo}#${n} \u2014 ${msg4(e)}
1012
1079
  `
1013
1080
  );
1014
1081
  continue;
@@ -1116,7 +1183,7 @@ function parseJson(out) {
1116
1183
  if (!trimmed) return [];
1117
1184
  return JSON.parse(trimmed);
1118
1185
  }
1119
- function msg3(e) {
1186
+ function msg4(e) {
1120
1187
  return e instanceof Error ? e.message : String(e);
1121
1188
  }
1122
1189
  function defaultGhRunner(bin) {
@@ -1562,10 +1629,10 @@ var SseMcpClient = class {
1562
1629
  try {
1563
1630
  const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
1564
1631
  if (!parsed.success) return;
1565
- const msg5 = parsed.data;
1566
- if (typeof msg5.id === "number" && this.pending.has(msg5.id)) {
1567
- this.pending.get(msg5.id)(msg5);
1568
- this.pending.delete(msg5.id);
1632
+ const msg6 = parsed.data;
1633
+ if (typeof msg6.id === "number" && this.pending.has(msg6.id)) {
1634
+ this.pending.get(msg6.id)(msg6);
1635
+ this.pending.delete(msg6.id);
1569
1636
  }
1570
1637
  } catch {
1571
1638
  }
@@ -1632,7 +1699,7 @@ var McpSink = class {
1632
1699
  try {
1633
1700
  client = await this.ensure();
1634
1701
  } catch (e) {
1635
- return { uri: item.uri, ok: false, error: `connect: ${msg4(e)}` };
1702
+ return { uri: item.uri, ok: false, error: `connect: ${msg5(e)}` };
1636
1703
  }
1637
1704
  const args = template(this.config.args, item);
1638
1705
  const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
@@ -1641,7 +1708,7 @@ var McpSink = class {
1641
1708
  if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
1642
1709
  return { uri: item.uri, ok: true };
1643
1710
  } catch (e) {
1644
- return { uri: item.uri, ok: false, error: msg4(e) };
1711
+ return { uri: item.uri, ok: false, error: msg5(e) };
1645
1712
  }
1646
1713
  }
1647
1714
  };
@@ -1685,10 +1752,10 @@ function stringify(v) {
1685
1752
  if (Array.isArray(v)) return v.join(", ");
1686
1753
  return v == null ? "" : String(v);
1687
1754
  }
1688
- function msg4(e) {
1755
+ function msg5(e) {
1689
1756
  return e instanceof Error ? e.message : String(e);
1690
1757
  }
1691
1758
 
1692
- export { AnthropicDistiller, AssemblyAiStt, BatchDistiller, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, PdfFetcher, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
1759
+ export { AnthropicDistiller, AssemblyAiStt, BatchDistiller, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, LocalFileFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, PdfFetcher, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp, isSttAuthError };
1693
1760
  //# sourceMappingURL=index.mjs.map
1694
1761
  //# sourceMappingURL=index.mjs.map