@agentproto/corpus-cli 0.7.2 → 0.9.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
@@ -7,11 +7,12 @@ import { fileURLToPath, pathToFileURL } from 'url';
7
7
  import { z } from 'zod';
8
8
  import { randomBytes, randomUUID, createHash } from 'crypto';
9
9
  import { readFileSync, existsSync } from 'fs';
10
- import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowledge, DistillIndex, DistillRunner, systemClock, WebImporter, ImporterRunner, CorpusEventEmitter, CorpusWorkspaceReader, CorpusLinter, CorpusValidator, ReadOnlyFs, normalizeLanguageTag, CodeImporter, PrReviewImporter, lensAspect } from '@agentproto/corpus';
10
+ import { buildDistillPrompt, parseItems, isRefinedKind, SyncRunner, resolveKnowledge, hasDistillMany, DistillIndex, DistillRunner, systemClock, WebImporter, ImporterRunner, CorpusEventEmitter, CorpusWorkspaceReader, CorpusLinter, CorpusValidator, ReadOnlyFs, normalizeLanguageTag, CodeImporter, PrReviewImporter, lensAspect } from '@agentproto/corpus';
11
11
  import matter3 from 'gray-matter';
12
12
  import { execFile } from 'child_process';
13
13
  import { promisify } from 'util';
14
14
  import { getDocumentProxy, extractText as extractText$1, getMeta } from 'unpdf';
15
+ import { BatchStore, openrouterBatchDriver, anthropicBatchDriver, validateForBatch, pollUntilEnded, collectResults, expiredCustomIds } from '@agentproto/batch';
15
16
  import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
16
17
  import { stitchReport, buildPacks, lintReportConfig, reportConfigSchema } from '@agentproto/corpus/report';
17
18
 
@@ -2891,6 +2892,118 @@ var AnthropicDistiller = class {
2891
2892
  return parseItems(text);
2892
2893
  }
2893
2894
  };
2895
+ var BatchDistiller = class {
2896
+ driver;
2897
+ store;
2898
+ model;
2899
+ maxItems;
2900
+ lang;
2901
+ pollIntervalMs;
2902
+ onUsage;
2903
+ onProgress;
2904
+ batchId;
2905
+ constructor(opts) {
2906
+ this.driver = opts.driver;
2907
+ this.store = opts.store;
2908
+ this.model = opts.model ?? "claude-sonnet-5";
2909
+ this.maxItems = opts.maxItems ?? 8;
2910
+ this.lang = opts.lang;
2911
+ this.pollIntervalMs = opts.pollIntervalMs;
2912
+ this.onUsage = opts.onUsage;
2913
+ this.onProgress = opts.onProgress;
2914
+ this.batchId = opts.batchId;
2915
+ }
2916
+ async distill(input) {
2917
+ const key = "single";
2918
+ const results = await this.distillMany([{ key, input }]);
2919
+ return results.get(key) ?? [];
2920
+ }
2921
+ async distillMany(inputs) {
2922
+ const requests = inputs.map(({ key, input }) => ({
2923
+ customId: key,
2924
+ body: {
2925
+ model: this.model,
2926
+ max_tokens: 4096,
2927
+ messages: [
2928
+ { role: "user", content: buildDistillPrompt(input, this.maxItems, { lang: this.lang }) }
2929
+ ]
2930
+ }
2931
+ }));
2932
+ for (const request of requests) validateForBatch(request);
2933
+ const handle = await this.resolveHandle(requests);
2934
+ await pollUntilEnded(this.driver, handle, {
2935
+ ...this.pollIntervalMs !== void 0 ? { intervalMs: this.pollIntervalMs } : {},
2936
+ onTick: (status) => {
2937
+ process.stderr.write(
2938
+ ` batch ${handle.id}: ${status.state} \u2014 processing ${status.counts.processing} \xB7 succeeded ${status.counts.succeeded} \xB7 errored ${status.counts.errored} \xB7 expired ${status.counts.expired}
2939
+ `
2940
+ );
2941
+ this.onProgress?.(status);
2942
+ }
2943
+ });
2944
+ const results = await collectResults(this.driver, handle);
2945
+ await this.store.appendResults(handle.id, Array.from(results.values()));
2946
+ const inputByKey = new Map(inputs.map((entry) => [entry.key, entry.input]));
2947
+ const errored = [];
2948
+ const out = /* @__PURE__ */ new Map();
2949
+ for (const result of results.values()) {
2950
+ if (result.outcome === "succeeded") {
2951
+ this.reportUsage(result, inputByKey);
2952
+ out.set(result.customId, parseItems(extractText3(result)));
2953
+ } else if (result.outcome === "errored") {
2954
+ errored.push(result.customId);
2955
+ }
2956
+ }
2957
+ const expired = expiredCustomIds(results.values());
2958
+ if (expired.length > 0) {
2959
+ process.stderr.write(
2960
+ ` batch ${handle.id}: expired, left undistilled (resubmit next run): ${expired.join(", ")}
2961
+ `
2962
+ );
2963
+ }
2964
+ if (errored.length > 0) {
2965
+ process.stderr.write(
2966
+ ` batch ${handle.id}: errored, left undistilled: ${errored.join(", ")}
2967
+ `
2968
+ );
2969
+ }
2970
+ return out;
2971
+ }
2972
+ async resolveHandle(requests) {
2973
+ if (this.batchId) {
2974
+ const record = await this.store.load(this.batchId);
2975
+ if (!record) throw new Error(`--batch-id ${this.batchId}: no such batch in the store`);
2976
+ return record.handle;
2977
+ }
2978
+ const handle = await this.driver.submit(requests);
2979
+ await this.store.create(handle, requests);
2980
+ process.stderr.write(
2981
+ ` batch id: ${handle.id} \u2014 re-attach with --batch-id ${handle.id} if this run is interrupted
2982
+ `
2983
+ );
2984
+ return handle;
2985
+ }
2986
+ reportUsage(result, inputByKey) {
2987
+ if (!this.onUsage || !result.message) return;
2988
+ const input = inputByKey.get(result.customId);
2989
+ this.onUsage({
2990
+ model: result.message.model,
2991
+ inputTokens: result.message.usage.input_tokens,
2992
+ outputTokens: result.message.usage.output_tokens,
2993
+ label: input?.title ?? result.customId,
2994
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2995
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2996
+ billing: "batch",
2997
+ ...result.message.usage.cache_read_input_tokens !== void 0 ? { cacheReadInputTokens: result.message.usage.cache_read_input_tokens } : {}
2998
+ });
2999
+ }
3000
+ };
3001
+ function extractText3(result) {
3002
+ for (const block of result.message?.content ?? []) {
3003
+ if (block.type === "text" && typeof block.text === "string") return block.text;
3004
+ }
3005
+ return "";
3006
+ }
2894
3007
  var CliAgentDistiller = class {
2895
3008
  engine;
2896
3009
  model;
@@ -3014,8 +3127,9 @@ function priceFor(model) {
3014
3127
  }
3015
3128
  function costUsd(u) {
3016
3129
  const { inPerM, outPerM } = priceFor(u.model);
3017
- const input = u.inputTokens / 1e6 * inPerM;
3018
- const output = u.outputTokens / 1e6 * outPerM;
3130
+ const discount = u.billing === "batch" ? 0.5 : 1;
3131
+ const input = u.inputTokens / 1e6 * inPerM * discount;
3132
+ const output = u.outputTokens / 1e6 * outPerM * discount;
3019
3133
  return { input, output, total: input + output };
3020
3134
  }
3021
3135
  function readLangfuseConfig() {
@@ -3099,19 +3213,30 @@ function createUsageSink(opts) {
3099
3213
  for (const u of records) {
3100
3214
  const c = costUsd(u);
3101
3215
  grandTotal += c.total;
3102
- const m = byModel.get(u.model) ?? { input: 0, output: 0, cost: 0, calls: 0 };
3216
+ const m = byModel.get(u.model) ?? {
3217
+ input: 0,
3218
+ output: 0,
3219
+ cost: 0,
3220
+ calls: 0,
3221
+ cacheRead: 0,
3222
+ batchCalls: 0
3223
+ };
3103
3224
  m.input += u.inputTokens;
3104
3225
  m.output += u.outputTokens;
3105
3226
  m.cost += c.total;
3106
3227
  m.calls += 1;
3228
+ if (u.cacheReadInputTokens) m.cacheRead += u.cacheReadInputTokens;
3229
+ if (u.billing === "batch") m.batchCalls += 1;
3107
3230
  byModel.set(u.model, m);
3108
3231
  }
3109
3232
  process.stderr.write(`
3110
3233
  usage \u2014 ${records.length} metered call(s):
3111
3234
  `);
3112
3235
  for (const [model, m] of byModel) {
3236
+ const batchNote = m.batchCalls > 0 ? ` (${m.batchCalls} batch-billed, \xD70.5)` : "";
3237
+ const cacheNote = m.cacheRead > 0 ? ` \xB7 cache-read ${fmt(m.cacheRead)}` : "";
3113
3238
  process.stderr.write(
3114
- ` ${model} ${m.calls} call(s) \xB7 in ${fmt(m.input)} \xB7 out ${fmt(m.output)} \xB7 ~${usd(m.cost)} est.
3239
+ ` ${model} ${m.calls} call(s)${batchNote} \xB7 in ${fmt(m.input)} \xB7 out ${fmt(m.output)}${cacheNote} \xB7 ~${usd(m.cost)} est.
3115
3240
  `
3116
3241
  );
3117
3242
  }
@@ -3251,10 +3376,13 @@ async function readEntryLayout(target) {
3251
3376
  return void 0;
3252
3377
  }
3253
3378
  }
3379
+ var ANTHROPIC_BATCH_ENGINE = "anthropic-batch";
3380
+ var OPENROUTER_BATCH_ENGINE = "openrouter-batch";
3381
+ var OPENROUTER_DEFAULT_MODEL = "anthropic/claude-sonnet-5";
3254
3382
  var DISTILLER_ENGINES = {
3255
3383
  [DEFAULT_ENGINE]: {
3256
3384
  id: DEFAULT_ENGINE,
3257
- needsApiKey: true,
3385
+ envKey: "ANTHROPIC_API_KEY",
3258
3386
  create: ({ apiKey, model, onUsage, lang }) => new AnthropicDistiller({
3259
3387
  apiKey,
3260
3388
  ...model ? { model } : {},
@@ -3262,12 +3390,37 @@ var DISTILLER_ENGINES = {
3262
3390
  ...lang ? { lang } : {}
3263
3391
  })
3264
3392
  },
3393
+ [ANTHROPIC_BATCH_ENGINE]: {
3394
+ id: ANTHROPIC_BATCH_ENGINE,
3395
+ envKey: "ANTHROPIC_API_KEY",
3396
+ create: ({ apiKey, model, onUsage, lang, store, driver, batchId, pollIntervalMs }) => new BatchDistiller({
3397
+ driver: driver ?? anthropicBatchDriver({ apiKey }),
3398
+ store,
3399
+ ...model ? { model } : {},
3400
+ ...onUsage ? { onUsage } : {},
3401
+ ...lang ? { lang } : {},
3402
+ ...batchId ? { batchId } : {},
3403
+ ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {}
3404
+ })
3405
+ },
3406
+ [OPENROUTER_BATCH_ENGINE]: {
3407
+ id: OPENROUTER_BATCH_ENGINE,
3408
+ envKey: "OPENROUTER_API_KEY",
3409
+ create: ({ apiKey, model, onUsage, lang, store, driver, batchId, pollIntervalMs }) => new BatchDistiller({
3410
+ driver: driver ?? openrouterBatchDriver({ apiKey }),
3411
+ store,
3412
+ model: model ?? OPENROUTER_DEFAULT_MODEL,
3413
+ ...onUsage ? { onUsage } : {},
3414
+ ...lang ? { lang } : {},
3415
+ ...batchId ? { batchId } : {},
3416
+ ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {}
3417
+ })
3418
+ },
3265
3419
  ...Object.fromEntries(
3266
3420
  Object.values(CLI_ENGINES).map((engine) => [
3267
3421
  engine.id,
3268
3422
  {
3269
3423
  id: engine.id,
3270
- needsApiKey: false,
3271
3424
  create: ({ model, lang }) => new CliAgentDistiller({
3272
3425
  engine,
3273
3426
  ...model ? { model } : {},
@@ -3287,7 +3440,8 @@ function parse6(args) {
3287
3440
  engine: DEFAULT_ENGINE,
3288
3441
  lang: void 0,
3289
3442
  lens: void 0,
3290
- lensFile: void 0
3443
+ lensFile: void 0,
3444
+ batchId: void 0
3291
3445
  };
3292
3446
  for (let i = 0; i < args.length; i++) {
3293
3447
  const a = args[i];
@@ -3323,6 +3477,9 @@ function parse6(args) {
3323
3477
  case "--lens-file":
3324
3478
  out.lensFile = next();
3325
3479
  break;
3480
+ case "--batch-id":
3481
+ out.batchId = next();
3482
+ break;
3326
3483
  default:
3327
3484
  if (!a.startsWith("-") && out.workspace === void 0) out.workspace = a;
3328
3485
  }
@@ -3391,6 +3548,15 @@ function applyLens(src, lens) {
3391
3548
  aspect: lensAspect(lens)
3392
3549
  };
3393
3550
  }
3551
+ function toDistillInput(source) {
3552
+ return {
3553
+ title: source.title,
3554
+ body: source.body,
3555
+ ...source.tags ? { tags: source.tags } : {},
3556
+ ...source.kinds ? { kinds: source.kinds } : {},
3557
+ ...source.instruction ? { instruction: source.instruction } : {}
3558
+ };
3559
+ }
3394
3560
  async function runDistill(args, deps = {}) {
3395
3561
  const parsed = parse6(args);
3396
3562
  const target = resolveWorkspacePath(parsed.workspace);
@@ -3407,6 +3573,7 @@ async function runDistill(args, deps = {}) {
3407
3573
  }
3408
3574
  }
3409
3575
  const usage = createUsageSink({ runName: basename(target) });
3576
+ const store = new BatchStore({ stateDir: join(target, ".distill") });
3410
3577
  let distiller;
3411
3578
  let engineLabel;
3412
3579
  if (deps.distiller) {
@@ -3420,79 +3587,147 @@ async function runDistill(args, deps = {}) {
3420
3587
  2
3421
3588
  );
3422
3589
  }
3423
- const apiKey = process.env.ANTHROPIC_API_KEY;
3424
- if (engine.needsApiKey && !apiKey) {
3425
- return fail(`distill engine "${engine.id}" needs ANTHROPIC_API_KEY in the environment.`, 2);
3590
+ const apiKey = engine.envKey ? process.env[engine.envKey] : void 0;
3591
+ if (engine.envKey && !apiKey && !deps.driver) {
3592
+ return fail(`distill engine "${engine.id}" needs ${engine.envKey} in the environment.`, 2);
3426
3593
  }
3427
3594
  distiller = engine.create({
3428
3595
  ...apiKey ? { apiKey } : {},
3429
3596
  ...parsed.model ? { model: parsed.model } : {},
3430
3597
  onUsage: usage.record,
3431
- ...parsed.lang ? { lang: parsed.lang } : {}
3598
+ ...parsed.lang ? { lang: parsed.lang } : {},
3599
+ store,
3600
+ ...deps.driver ? { driver: deps.driver } : {},
3601
+ ...parsed.batchId ? { batchId: parsed.batchId } : {}
3432
3602
  });
3433
3603
  engineLabel = engine.id;
3434
3604
  }
3605
+ const batchDistiller = hasDistillMany(distiller) ? distiller : void 0;
3435
3606
  const fs = new NodeFsAdapter({ root: target });
3436
3607
  const all = await readSources(target);
3437
3608
  if (all.length === 0) return fail("no sources found under sources/ \u2014 run import-web first.", 2);
3438
3609
  const index = new DistillIndex({ fs });
3439
- let pool;
3440
- if (parsed.sourceId) {
3441
- pool = all.filter((s) => s.id === parsed.sourceId);
3442
- } else if (lens) {
3443
- pool = [];
3444
- for (const s of all) {
3445
- if (!await index.isDistilled(s.id, s.contentHash, lens.id)) pool.push(s);
3610
+ let batch;
3611
+ let poolLength;
3612
+ if (parsed.batchId) {
3613
+ const record = await store.load(parsed.batchId);
3614
+ if (!record) {
3615
+ return fail(`--batch-id ${parsed.batchId}: no batch found under ${target}/.distill`, 2);
3616
+ }
3617
+ const byId = new Map(all.map((s) => [s.id, s]));
3618
+ batch = [];
3619
+ for (const req of record.requests) {
3620
+ const src = byId.get(req.customId);
3621
+ if (src) batch.push(src);
3622
+ else process.stdout.write(` ! ${req.customId} \u2014 source no longer found on disk, skipping
3623
+ `);
3446
3624
  }
3625
+ poolLength = batch.length;
3447
3626
  } else {
3448
- const done = await scanDistilledSourceIds(target);
3449
- pool = all.filter((s) => !done.has(s.id));
3627
+ let pool;
3628
+ if (parsed.sourceId) {
3629
+ pool = all.filter((s) => s.id === parsed.sourceId);
3630
+ } else if (lens) {
3631
+ pool = [];
3632
+ for (const s of all) {
3633
+ if (!await index.isDistilled(s.id, s.contentHash, lens.id)) pool.push(s);
3634
+ }
3635
+ } else {
3636
+ const done = await scanDistilledSourceIds(target);
3637
+ pool = all.filter((s) => !done.has(s.id));
3638
+ }
3639
+ poolLength = pool.length;
3640
+ batch = parsed.max !== void 0 ? pool.slice(0, parsed.max) : pool;
3450
3641
  }
3451
- const batch = parsed.max !== void 0 ? pool.slice(0, parsed.max) : pool;
3452
3642
  process.stdout.write(
3453
3643
  `distill \u2192 ${target}
3454
3644
  engine: ${engineLabel}
3455
3645
  ` + (lens ? ` lens: ${lens.id} (aspect:${lensAspect(lens)})
3456
- ` : "") + ` sources: ${all.length} total \xB7 ${all.length - pool.length} already distilled \xB7 ${pool.length} to do
3646
+ ` : "") + (parsed.batchId ? ` batch-id: ${parsed.batchId} \u2014 re-attaching, skipping submit
3647
+ ` : ` sources: ${all.length} total \xB7 ${all.length - poolLength} already distilled \xB7 ${poolLength} to do
3457
3648
  this run: ${batch.length}${parsed.max !== void 0 ? ` (--max ${parsed.max})` : ""}
3458
- `
3649
+ `) + (batchDistiller ? " note: --throttle is ignored for batch engines\n" : "")
3459
3650
  );
3460
3651
  if (batch.length === 0) {
3461
3652
  process.stdout.write(" nothing to do.\n");
3462
3653
  return 0;
3463
3654
  }
3464
3655
  const layout = await readEntryLayout(target);
3465
- const runner = new DistillRunner({
3466
- fs,
3467
- clock: systemClock,
3468
- ...layout ? { layout } : {},
3469
- distiller
3470
- });
3471
3656
  let totalEntries = 0;
3472
- for (let i = 0; i < batch.length; i++) {
3473
- const raw = batch[i];
3474
- const src = lens ? applyLens(raw, lens) : raw;
3475
- if (i > 0 && parsed.throttleMs > 0) await sleep(parsed.throttleMs);
3476
- try {
3477
- const report = await runner.run(src);
3478
- totalEntries += report.entryPaths.length;
3479
- if (lens) {
3480
- await index.record({
3481
- sourceId: raw.id,
3482
- lensId: lens.id,
3483
- title: raw.title,
3484
- distilledAt: systemClock.now().toISOString(),
3485
- engine: engineLabel,
3486
- contentHash: raw.contentHash,
3487
- entryCount: report.entryPaths.length,
3488
- ...report.entryPaths.length ? { entryPaths: report.entryPaths } : {}
3489
- });
3657
+ if (batchDistiller) {
3658
+ const inputs = batch.map((raw) => ({
3659
+ key: raw.id,
3660
+ input: toDistillInput(lens ? applyLens(raw, lens) : raw)
3661
+ }));
3662
+ const resultsByKey = await batchDistiller.distillMany(inputs);
3663
+ for (const raw of batch) {
3664
+ const src = lens ? applyLens(raw, lens) : raw;
3665
+ const items = resultsByKey.get(raw.id);
3666
+ if (items === void 0) {
3667
+ process.stdout.write(` ! ${raw.id} \u2014 not distilled this run (errored or expired in the batch)
3668
+ `);
3669
+ continue;
3490
3670
  }
3491
- process.stdout.write(` \u2713 ${raw.id} \u2192 ${report.entryPaths.length} entries
3671
+ const oneShotRunner = new DistillRunner({
3672
+ fs,
3673
+ clock: systemClock,
3674
+ ...layout ? { layout } : {},
3675
+ distiller: { distill: async () => items }
3676
+ });
3677
+ try {
3678
+ const report = await oneShotRunner.run(src);
3679
+ totalEntries += report.entryPaths.length;
3680
+ if (lens) {
3681
+ await index.record({
3682
+ sourceId: raw.id,
3683
+ lensId: lens.id,
3684
+ title: raw.title,
3685
+ distilledAt: systemClock.now().toISOString(),
3686
+ engine: engineLabel,
3687
+ contentHash: raw.contentHash,
3688
+ entryCount: report.entryPaths.length,
3689
+ ...report.entryPaths.length ? { entryPaths: report.entryPaths } : {}
3690
+ });
3691
+ }
3692
+ process.stdout.write(` \u2713 ${raw.id} \u2192 ${report.entryPaths.length} entries
3492
3693
  `);
3493
- } catch (e) {
3494
- process.stdout.write(` ! ${raw.id} \u2014 ${e instanceof Error ? e.message : String(e)}
3694
+ } catch (e) {
3695
+ process.stdout.write(` ! ${raw.id} \u2014 ${e instanceof Error ? e.message : String(e)}
3696
+ `);
3697
+ }
3698
+ }
3699
+ } else {
3700
+ const runner = new DistillRunner({
3701
+ fs,
3702
+ clock: systemClock,
3703
+ ...layout ? { layout } : {},
3704
+ distiller
3705
+ });
3706
+ for (let i = 0; i < batch.length; i++) {
3707
+ const raw = batch[i];
3708
+ const src = lens ? applyLens(raw, lens) : raw;
3709
+ if (i > 0 && parsed.throttleMs > 0) await sleep(parsed.throttleMs);
3710
+ try {
3711
+ const report = await runner.run(src);
3712
+ totalEntries += report.entryPaths.length;
3713
+ if (lens) {
3714
+ await index.record({
3715
+ sourceId: raw.id,
3716
+ lensId: lens.id,
3717
+ title: raw.title,
3718
+ distilledAt: systemClock.now().toISOString(),
3719
+ engine: engineLabel,
3720
+ contentHash: raw.contentHash,
3721
+ entryCount: report.entryPaths.length,
3722
+ ...report.entryPaths.length ? { entryPaths: report.entryPaths } : {}
3723
+ });
3724
+ }
3725
+ process.stdout.write(` \u2713 ${raw.id} \u2192 ${report.entryPaths.length} entries
3726
+ `);
3727
+ } catch (e) {
3728
+ process.stdout.write(` ! ${raw.id} \u2014 ${e instanceof Error ? e.message : String(e)}
3495
3729
  `);
3730
+ }
3496
3731
  }
3497
3732
  }
3498
3733
  process.stdout.write(`
@@ -3632,7 +3867,7 @@ async function runReportPacks(args) {
3632
3867
  await reportFs.writeFile(file.path, file.content);
3633
3868
  }
3634
3869
  process.stdout.write(
3635
- `report packs \u2192 ${result.files.length} files \xB7 ${result.bibliography} sources
3870
+ `report packs \u2192 ${result.files.length} files \xB7 ${result.bibliography} sources \xB7 bib-sha ${result.bibliographySha}
3636
3871
  ` + result.chapters.map((c) => ` ${c.id}: ${c.entryCount}`).join("\n") + "\n"
3637
3872
  );
3638
3873
  return 0;
@@ -3677,12 +3912,21 @@ async function runReportStitch(args) {
3677
3912
  );
3678
3913
  }
3679
3914
  const reportFs = new NodeFsAdapter({ root });
3680
- const { content, wordCount } = await stitchReport({
3681
- config,
3682
- report: reportFs,
3683
- ...chaptersDir ? { chaptersDir } : {},
3684
- ...viewsDir ? { viewsDir } : {}
3685
- });
3915
+ let stitched;
3916
+ try {
3917
+ stitched = await stitchReport({
3918
+ config,
3919
+ report: reportFs,
3920
+ ...chaptersDir ? { chaptersDir } : {},
3921
+ ...viewsDir ? { viewsDir } : {}
3922
+ });
3923
+ } catch (err) {
3924
+ return fail(
3925
+ `report stitch failed: ${err instanceof Error ? err.message : String(err)}`,
3926
+ 1
3927
+ );
3928
+ }
3929
+ const { content, wordCount } = stitched;
3686
3930
  await reportFs.writeFile(out ?? "REPORT.md", content);
3687
3931
  process.stdout.write(`report stitch \u2192 ${out ?? "REPORT.md"} \xB7 ${wordCount} words
3688
3932
  `);