@agentproto/corpus-cli 0.10.2 → 0.11.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
@@ -406,8 +406,8 @@ function resolveWorkspacePath(arg) {
406
406
  if (!arg) return process.cwd();
407
407
  return path.resolve(process.cwd(), arg);
408
408
  }
409
- function fail(msg9, code = 1) {
410
- process.stderr.write(`corpus: ${msg9}
409
+ function fail(msg10, code = 1) {
410
+ process.stderr.write(`corpus: ${msg10}
411
411
  `);
412
412
  return code;
413
413
  }
@@ -1071,6 +1071,77 @@ function stripTags(html) {
1071
1071
  if (!html) return "";
1072
1072
  return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1073
1073
  }
1074
+ var WHISPER_RESPONSE = z.object({ text: z.string().optional(), language: z.string().optional() }).loose();
1075
+ function isSttAuthError(e) {
1076
+ const m = (e instanceof Error ? e.message : String(e)).toLowerCase();
1077
+ return m.includes(" 401") || m.includes(" 403") || m.includes("unauthorized") || m.includes("forbidden") || m.includes("api key") || m.includes("api_key");
1078
+ }
1079
+ var WHISPER_MAX_BYTES = 25 * 1024 * 1024;
1080
+ var OpenAiWhisperStt = class {
1081
+ apiKey;
1082
+ model;
1083
+ baseUrl;
1084
+ constructor(opts) {
1085
+ this.apiKey = opts.apiKey;
1086
+ this.model = opts.model ?? "whisper-1";
1087
+ this.baseUrl = (opts.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "");
1088
+ }
1089
+ async transcribe(audioPath) {
1090
+ const bytes = await readFile(audioPath);
1091
+ if (bytes.byteLength > WHISPER_MAX_BYTES) {
1092
+ throw new Error(
1093
+ `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.`
1094
+ );
1095
+ }
1096
+ const form = new FormData();
1097
+ form.append("file", new Blob([bytes]), basename(audioPath));
1098
+ form.append("model", this.model);
1099
+ form.append("response_format", "verbose_json");
1100
+ const res = await this.postWithRetry(form);
1101
+ if (!res.ok) {
1102
+ const body = await res.text().catch(() => "");
1103
+ throw new Error(`Whisper STT ${res.status} ${res.statusText}: ${body.slice(0, 200)}`);
1104
+ }
1105
+ const data = WHISPER_RESPONSE.parse(await res.json());
1106
+ const language = normalizeLanguageTag(data.language);
1107
+ return {
1108
+ text: (data.text ?? "").trim(),
1109
+ ...language ? { language } : {}
1110
+ };
1111
+ }
1112
+ /**
1113
+ * POST the audio with bounded retry. Transcribing a long talk fans out
1114
+ * into many segment uploads (see ChunkedStt), so a single transient
1115
+ * network blip ("fetch failed") or a 429 / 5xx must not abort the whole
1116
+ * batch. Network errors and retryable statuses back off and retry;
1117
+ * client errors (401 auth, 400 bad request) return immediately so a real
1118
+ * misconfiguration still surfaces loudly.
1119
+ */
1120
+ async postWithRetry(form, attempts = 4) {
1121
+ const url = `${this.baseUrl}/audio/transcriptions`;
1122
+ let lastErr;
1123
+ for (let i = 0; i < attempts; i++) {
1124
+ try {
1125
+ const res = await fetch(url, {
1126
+ method: "POST",
1127
+ headers: { authorization: `Bearer ${this.apiKey}` },
1128
+ body: form
1129
+ });
1130
+ if (res.status !== 429 && res.status < 500) return res;
1131
+ lastErr = new Error(`Whisper STT ${res.status} ${res.statusText}`);
1132
+ } catch (e) {
1133
+ lastErr = e;
1134
+ }
1135
+ if (i < attempts - 1) await delay(500 * 2 ** i);
1136
+ }
1137
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
1138
+ }
1139
+ };
1140
+ function delay(ms) {
1141
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1142
+ }
1143
+
1144
+ // src/ports/ytdlp-whisper-fetcher.adapter.ts
1074
1145
  var execFileAsync = promisify(execFile);
1075
1146
  var YTDLP_INFO = z.object({ title: z.string().optional(), language: z.string().optional() }).loose();
1076
1147
  var YtDlpWhisperFetcher = class {
@@ -1122,7 +1193,7 @@ var YtDlpWhisperFetcher = class {
1122
1193
  } : {}
1123
1194
  };
1124
1195
  } catch (e) {
1125
- if (isAuthError(e)) throw e;
1196
+ if (isSttAuthError(e)) throw e;
1126
1197
  process.stderr.write(
1127
1198
  `corpus: transcription failed for ${url} \u2014 skipped (${msg(e)})
1128
1199
  `
@@ -1137,10 +1208,6 @@ var YtDlpWhisperFetcher = class {
1137
1208
  function msg(e) {
1138
1209
  return e instanceof Error ? e.message : String(e);
1139
1210
  }
1140
- function isAuthError(e) {
1141
- const m = msg(e).toLowerCase();
1142
- return m.includes(" 401") || m.includes(" 403") || m.includes("unauthorized") || m.includes("forbidden") || m.includes("api key") || m.includes("api_key");
1143
- }
1144
1211
  function buildYtDlpArgs(url, dir, opts) {
1145
1212
  const durationGuard = opts?.maxDurationSec && opts.maxDurationSec > 0 ? ["--match-filter", `duration <= ${Math.floor(opts.maxDurationSec)}`] : [];
1146
1213
  const cookieArgs = opts?.cookiesFromBrowser ? ["--cookies-from-browser", opts.cookiesFromBrowser] : opts?.cookiesFile ? ["--cookies", opts.cookiesFile] : [];
@@ -1350,70 +1417,69 @@ function defaultYtDlpCaptionDownloader(bin, opts) {
1350
1417
  }
1351
1418
  };
1352
1419
  }
1353
- var WHISPER_RESPONSE = z.object({ text: z.string().optional(), language: z.string().optional() }).loose();
1354
- var WHISPER_MAX_BYTES = 25 * 1024 * 1024;
1355
- var OpenAiWhisperStt = class {
1356
- apiKey;
1357
- model;
1358
- baseUrl;
1420
+ var LocalFileFetcher = class {
1421
+ stt;
1359
1422
  constructor(opts) {
1360
- this.apiKey = opts.apiKey;
1361
- this.model = opts.model ?? "whisper-1";
1362
- this.baseUrl = (opts.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "");
1423
+ this.stt = opts.stt;
1363
1424
  }
1364
- async transcribe(audioPath) {
1365
- const bytes = await readFile(audioPath);
1366
- if (bytes.byteLength > WHISPER_MAX_BYTES) {
1367
- throw new Error(
1368
- `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.`
1369
- );
1370
- }
1371
- const form = new FormData();
1372
- form.append("file", new Blob([bytes]), basename(audioPath));
1373
- form.append("model", this.model);
1374
- form.append("response_format", "verbose_json");
1375
- const res = await this.postWithRetry(form);
1376
- if (!res.ok) {
1377
- const body = await res.text().catch(() => "");
1378
- throw new Error(`Whisper STT ${res.status} ${res.statusText}: ${body.slice(0, 200)}`);
1425
+ async fetch(url) {
1426
+ const path6 = await resolveLocalPath(url);
1427
+ if (!path6) return null;
1428
+ let t;
1429
+ try {
1430
+ t = await this.stt.transcribe(path6);
1431
+ } catch (e) {
1432
+ if (isSttAuthError(e)) throw e;
1433
+ process.stderr.write(`corpus: transcription failed for ${path6} \u2014 skipped (${msg3(e)})
1434
+ `);
1435
+ return null;
1379
1436
  }
1380
- const data = WHISPER_RESPONSE.parse(await res.json());
1381
- const language = normalizeLanguageTag(data.language);
1437
+ if (!t.text.trim()) return null;
1438
+ const utterances = t.utterances ?? [];
1439
+ const diarized = utterances.length > 0;
1440
+ const speakers = diarized ? new Set(utterances.map((u) => u.speaker)).size : 0;
1382
1441
  return {
1383
- text: (data.text ?? "").trim(),
1384
- ...language ? { language } : {}
1442
+ title: basename(path6, extname(path6)),
1443
+ text: t.text,
1444
+ kind: "video",
1445
+ ...t.language ? { language: t.language } : {},
1446
+ via: diarized ? "diarized-transcription" : "transcription",
1447
+ ...diarized ? {
1448
+ metadata: {
1449
+ speech: {
1450
+ regime: "spoken",
1451
+ diarized: true,
1452
+ engine: t.engine ?? "unknown",
1453
+ speakers,
1454
+ ...t.speakerLabelsLocalToSegment ? { segmented: true } : {}
1455
+ }
1456
+ }
1457
+ } : {}
1385
1458
  };
1386
1459
  }
1387
- /**
1388
- * POST the audio with bounded retry. Transcribing a long talk fans out
1389
- * into many segment uploads (see ChunkedStt), so a single transient
1390
- * network blip ("fetch failed") or a 429 / 5xx must not abort the whole
1391
- * batch. Network errors and retryable statuses back off and retry;
1392
- * client errors (401 auth, 400 bad request) return immediately so a real
1393
- * misconfiguration still surfaces loudly.
1394
- */
1395
- async postWithRetry(form, attempts = 4) {
1396
- const url = `${this.baseUrl}/audio/transcriptions`;
1397
- let lastErr;
1398
- for (let i = 0; i < attempts; i++) {
1399
- try {
1400
- const res = await fetch(url, {
1401
- method: "POST",
1402
- headers: { authorization: `Bearer ${this.apiKey}` },
1403
- body: form
1404
- });
1405
- if (res.status !== 429 && res.status < 500) return res;
1406
- lastErr = new Error(`Whisper STT ${res.status} ${res.statusText}`);
1407
- } catch (e) {
1408
- lastErr = e;
1409
- }
1410
- if (i < attempts - 1) await delay(500 * 2 ** i);
1460
+ };
1461
+ async function resolveLocalPath(url) {
1462
+ let candidate;
1463
+ if (url.startsWith("file://")) {
1464
+ try {
1465
+ candidate = fileURLToPath(url);
1466
+ } catch {
1467
+ return null;
1411
1468
  }
1412
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
1469
+ } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) {
1470
+ return null;
1471
+ } else {
1472
+ candidate = url;
1413
1473
  }
1414
- };
1415
- function delay(ms) {
1416
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1474
+ try {
1475
+ const st = await stat(candidate);
1476
+ return st.isFile() ? candidate : null;
1477
+ } catch {
1478
+ return null;
1479
+ }
1480
+ }
1481
+ function msg3(e) {
1482
+ return e instanceof Error ? e.message : String(e);
1417
1483
  }
1418
1484
  var UPLOAD_RESPONSE = z.object({ upload_url: z.string() });
1419
1485
  var AAI_TRANSCRIPT = z.object({
@@ -1719,7 +1785,7 @@ var PdfFetcher = class {
1719
1785
  if (isPasswordProtected(e)) {
1720
1786
  throw new Error(`PDF is password-protected/encrypted: ${url}`);
1721
1787
  }
1722
- throw new Error(`failed to open PDF: ${url} (${msg3(e)})`);
1788
+ throw new Error(`failed to open PDF: ${url} (${msg4(e)})`);
1723
1789
  }
1724
1790
  const { totalPages, pageTexts, info } = extraction;
1725
1791
  const hasText = pageTexts.some((t) => t.trim().length > 0);
@@ -1785,7 +1851,7 @@ function titleFromUrl(url) {
1785
1851
  return url;
1786
1852
  }
1787
1853
  }
1788
- function msg3(e) {
1854
+ function msg4(e) {
1789
1855
  return e instanceof Error ? e.message : String(e);
1790
1856
  }
1791
1857
 
@@ -2098,16 +2164,6 @@ ${plan}`);
2098
2164
  process.stdout.write(`import-web
2099
2165
  ${plan}`);
2100
2166
  const chain = [];
2101
- if (!parsed.noCaptions) {
2102
- chain.push(
2103
- new YtDlpCaptionsFetcher({
2104
- ...parsed.lang ? { preferLang: parsed.lang } : {},
2105
- ...parsed.maxDurationSec ? { maxDurationSec: parsed.maxDurationSec } : {},
2106
- ...parsed.cookiesFromBrowser ? { cookiesFromBrowser: parsed.cookiesFromBrowser } : {},
2107
- ...parsed.cookiesFile ? { cookiesFile: parsed.cookiesFile } : {}
2108
- })
2109
- );
2110
- }
2111
2167
  let stt;
2112
2168
  if (parsed.diarize) {
2113
2169
  const aaiKey = process.env.ASSEMBLYAI_API_KEY;
@@ -2125,6 +2181,17 @@ ${plan}`);
2125
2181
  parsed.noCaptions ? "corpus: OPENAI_API_KEY not set \u2014 video URLs will be skipped (no transcription).\n" : "corpus: OPENAI_API_KEY not set \u2014 caption-less videos will be skipped (captioned videos still import).\n"
2126
2182
  );
2127
2183
  }
2184
+ if (stt) chain.push(new LocalFileFetcher({ stt }));
2185
+ if (!parsed.noCaptions) {
2186
+ chain.push(
2187
+ new YtDlpCaptionsFetcher({
2188
+ ...parsed.lang ? { preferLang: parsed.lang } : {},
2189
+ ...parsed.maxDurationSec ? { maxDurationSec: parsed.maxDurationSec } : {},
2190
+ ...parsed.cookiesFromBrowser ? { cookiesFromBrowser: parsed.cookiesFromBrowser } : {},
2191
+ ...parsed.cookiesFile ? { cookiesFile: parsed.cookiesFile } : {}
2192
+ })
2193
+ );
2194
+ }
2128
2195
  if (stt)
2129
2196
  chain.push(
2130
2197
  new YtDlpWhisperFetcher({
@@ -2141,7 +2208,7 @@ ${plan}`);
2141
2208
  const client = await connectBrowserMcp({ endpoint: parsed.scrapeMcp });
2142
2209
  chain.push(new ScrapeMcpFetcher({ client }));
2143
2210
  } catch (e) {
2144
- return fail(`could not connect to scrape MCP at ${parsed.scrapeMcp}: ${msg4(e)}`, 1);
2211
+ return fail(`could not connect to scrape MCP at ${parsed.scrapeMcp}: ${msg5(e)}`, 1);
2145
2212
  }
2146
2213
  }
2147
2214
  if (parsed.browserMcp) {
@@ -2150,7 +2217,7 @@ ${plan}`);
2150
2217
  browser = await connectBrowserMcp({ endpoint: parsed.browserMcp });
2151
2218
  chain.push(new BrowserMcpFetcher({ browser }));
2152
2219
  } catch (e) {
2153
- return fail(`could not connect to browser MCP at ${parsed.browserMcp}: ${msg4(e)}`, 1);
2220
+ return fail(`could not connect to browser MCP at ${parsed.browserMcp}: ${msg5(e)}`, 1);
2154
2221
  }
2155
2222
  }
2156
2223
  chain.push(new HttpReadabilityFetcher());
@@ -2181,7 +2248,7 @@ ${plan}`);
2181
2248
  }
2182
2249
  });
2183
2250
  } catch (e) {
2184
- return fail(`import failed: ${msg4(e)}`, 1);
2251
+ return fail(`import failed: ${msg5(e)}`, 1);
2185
2252
  }
2186
2253
  process.stdout.write(
2187
2254
  `import-web \u2192 ${target}
@@ -2201,7 +2268,7 @@ knowledge engine (RAG) via the WriterPort. Import only stages the sources.
2201
2268
  );
2202
2269
  return 0;
2203
2270
  }
2204
- function msg4(e) {
2271
+ function msg5(e) {
2205
2272
  return e instanceof Error ? e.message : String(e);
2206
2273
  }
2207
2274
  function parse3(args) {
@@ -2294,7 +2361,7 @@ ${plan}`);
2294
2361
  count++;
2295
2362
  }
2296
2363
  } catch (e) {
2297
- return fail(`enumerate failed: ${msg5(e)}`, 1);
2364
+ return fail(`enumerate failed: ${msg6(e)}`, 1);
2298
2365
  }
2299
2366
  if (count > 20) process.stdout.write(` \u2026 +${count - 20} more
2300
2367
  `);
@@ -2316,7 +2383,7 @@ ${plan}`);
2316
2383
  try {
2317
2384
  report = await runner.run(importer, importerTarget);
2318
2385
  } catch (e) {
2319
- return fail(`import failed: ${msg5(e)}`, 1);
2386
+ return fail(`import failed: ${msg6(e)}`, 1);
2320
2387
  }
2321
2388
  process.stdout.write(
2322
2389
  `import-code \u2192 ${target}
@@ -2336,7 +2403,7 @@ graph construction is the code-brain subsystem's job, not this importer.
2336
2403
  );
2337
2404
  return 0;
2338
2405
  }
2339
- function msg5(e) {
2406
+ function msg6(e) {
2340
2407
  return e instanceof Error ? e.message : String(e);
2341
2408
  }
2342
2409
  var execFileAsync4 = promisify(execFile);
@@ -2400,7 +2467,7 @@ var GhPrSourceAdapter = class {
2400
2467
  pr = await this.viewPr(query, n);
2401
2468
  } catch (e) {
2402
2469
  process.stderr.write(
2403
- `corpus: skipping ${query.repo}#${n} \u2014 ${msg6(e)}
2470
+ `corpus: skipping ${query.repo}#${n} \u2014 ${msg7(e)}
2404
2471
  `
2405
2472
  );
2406
2473
  continue;
@@ -2508,7 +2575,7 @@ function parseJson(out) {
2508
2575
  if (!trimmed) return [];
2509
2576
  return JSON.parse(trimmed);
2510
2577
  }
2511
- function msg6(e) {
2578
+ function msg7(e) {
2512
2579
  return e instanceof Error ? e.message : String(e);
2513
2580
  }
2514
2581
  function defaultGhRunner(bin) {
@@ -2628,7 +2695,7 @@ ${plan}`);
2628
2695
  }
2629
2696
  });
2630
2697
  } catch (e) {
2631
- return fail(`import failed: ${msg7(e)}`, 1);
2698
+ return fail(`import failed: ${msg8(e)}`, 1);
2632
2699
  }
2633
2700
  process.stdout.write(
2634
2701
  `import-prs \u2192 ${target}
@@ -2648,7 +2715,7 @@ sources into refined knowledge.entry/v1 (pattern/critique/summary).
2648
2715
  );
2649
2716
  return 0;
2650
2717
  }
2651
- function msg7(e) {
2718
+ function msg8(e) {
2652
2719
  return e instanceof Error ? e.message : String(e);
2653
2720
  }
2654
2721
  function parse5(args) {
@@ -4151,10 +4218,10 @@ var SseMcpClient = class {
4151
4218
  try {
4152
4219
  const parsed = RPC_MESSAGE.safeParse(JSON.parse(payload));
4153
4220
  if (!parsed.success) return;
4154
- const msg9 = parsed.data;
4155
- if (typeof msg9.id === "number" && this.pending.has(msg9.id)) {
4156
- this.pending.get(msg9.id)(msg9);
4157
- this.pending.delete(msg9.id);
4221
+ const msg10 = parsed.data;
4222
+ if (typeof msg10.id === "number" && this.pending.has(msg10.id)) {
4223
+ this.pending.get(msg10.id)(msg10);
4224
+ this.pending.delete(msg10.id);
4158
4225
  }
4159
4226
  } catch {
4160
4227
  }
@@ -4223,7 +4290,7 @@ var McpSink = class {
4223
4290
  try {
4224
4291
  client = await this.ensure();
4225
4292
  } catch (e) {
4226
- return { uri: item.uri, ok: false, error: `connect: ${msg8(e)}` };
4293
+ return { uri: item.uri, ok: false, error: `connect: ${msg9(e)}` };
4227
4294
  }
4228
4295
  const args = template(this.config.args, item);
4229
4296
  const call = this.config.importedAlias ? { name: "mcp_imported_call", args: { alias: this.config.importedAlias, toolName: this.config.tool, args } } : { name: this.config.tool, args };
@@ -4232,7 +4299,7 @@ var McpSink = class {
4232
4299
  if (res.isError) return { uri: item.uri, ok: false, error: "tool returned isError" };
4233
4300
  return { uri: item.uri, ok: true };
4234
4301
  } catch (e) {
4235
- return { uri: item.uri, ok: false, error: msg8(e) };
4302
+ return { uri: item.uri, ok: false, error: msg9(e) };
4236
4303
  }
4237
4304
  }
4238
4305
  };
@@ -4276,7 +4343,7 @@ function stringify(v) {
4276
4343
  if (Array.isArray(v)) return v.join(", ");
4277
4344
  return v == null ? "" : String(v);
4278
4345
  }
4279
- function msg8(e) {
4346
+ function msg9(e) {
4280
4347
  return e instanceof Error ? e.message : String(e);
4281
4348
  }
4282
4349
 
@@ -4403,6 +4470,10 @@ Commands:
4403
4470
  scrape MCP server (stealth + clean Markdown) for
4404
4471
  walled/JS pages, ahead of plain readability.
4405
4472
  --diarize: AssemblyAI speaker labels (interviews).
4473
+ A --url can also be a local audio/video file path
4474
+ or file:// URI (e.g. an already-extracted MP3) \u2014
4475
+ it skips yt-dlp entirely and goes straight to the
4476
+ configured STT (needs --diarize or OPENAI_API_KEY).
4406
4477
  import-code [path] --root <dir> [--include glob \u2026 --granularity file|module --max n --tags t --lang l --dry-run]
4407
4478
  Import a source tree as knowledge sources, one note
4408
4479
  per code unit (file or module). Notes-only: ZERO