@trazum/cli 2.4.1 → 2.4.3

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/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readdirSync, readFileSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
- import { cpus, tmpdir } from 'node:os';
5
+ import { cpus, homedir, tmpdir } from 'node:os';
6
6
  import { createInterface } from 'node:readline/promises';
7
7
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
@@ -182,6 +182,7 @@ import type {
182
182
  EvalReport,
183
183
  FleetSource,
184
184
  HistoryRun,
185
+ ProfileCsvShape,
185
186
  MeasuredUsage,
186
187
  PruneReport,
187
188
  PlanDocument,
@@ -285,7 +286,9 @@ import {
285
286
  renderRankMarkdown,
286
287
  renderProfileMarkdown,
287
288
  } from './markdown.js';
289
+ import type { ProfileMarkdownInput } from './markdown.js';
288
290
  import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.js';
291
+ import { renderProfilePdf } from './pdf.js';
289
292
  import type { CliMessages } from './i18n/index.js';
290
293
 
291
294
  // --------------------------------------------------------------------------
@@ -297,6 +300,7 @@ import type { CliMessages } from './i18n/index.js';
297
300
  // style.test.js holds the contract: stripped colour output is byte-identical
298
301
  // to plain output, and a pipe stays plain.
299
302
  import { bar, c, sectionHeading, table } from './style.js';
303
+ import type { TableColumn } from './style.js';
300
304
 
301
305
  // --------------------------------------------------------------------------
302
306
  // Argument parsing
@@ -382,6 +386,7 @@ const VALUE_FLAGS = new Set([
382
386
  'config',
383
387
  'markdown-out',
384
388
  'html-out',
389
+ 'pdf-out',
385
390
  'otlp-out',
386
391
  'pricing',
387
392
  'prompt',
@@ -515,6 +520,45 @@ function levelFlag(args: Args, config: TrazumConfig, t: CliMessages): RuleLevel
515
520
  */
516
521
  const LOG_EXTENSIONS = ['.jsonl', '.ndjson', '.log', '.json'];
517
522
 
523
+ /**
524
+ * Whether a directory walk reads this file: one of `LOG_EXTENSIONS`, plain or
525
+ * gzipped, in any case.
526
+ *
527
+ * The list above said one list, and six walks still kept four of their own:
528
+ * `bill` skipped `.log`, which `profile` read, so the same directory billed
529
+ * $7.51 by one verb and $15.01 by the other, and `bill` did not even count
530
+ * the file it skipped. A predicate every walk calls is the only form of "one
531
+ * list" that cannot drift.
532
+ */
533
+ function isUsageLogName(name: string): boolean {
534
+ const lower = name.toLowerCase();
535
+ return LOG_EXTENSIONS.some((extension) => lower.endsWith(extension) || lower.endsWith(`${extension}.gz`));
536
+ }
537
+
538
+ /**
539
+ * How many positional arguments a command reads. One unless listed.
540
+ *
541
+ * Every command used to read `positional[0]` and ignore the rest, so
542
+ * `trazum bill logs/*.jsonl`, which the shell expands to every file, priced
543
+ * the first file alone and reported no gap: a bill understated with the
544
+ * confidence of a complete one, and a spend gate judging one day of seven.
545
+ * A command now either reads every path it is given or refuses the extras.
546
+ */
547
+ const POSITIONAL_LIMIT: Readonly<Record<string, number>> = {
548
+ bill: Number.POSITIVE_INFINITY,
549
+ rollup: Number.POSITIVE_INFINITY,
550
+ diff: 2,
551
+ };
552
+
553
+ function rejectExtraPositionals(args: Args, t: CliMessages): void {
554
+ if (!COMMAND_FLAGS[args.command]) return;
555
+ const limit = POSITIONAL_LIMIT[args.command] ?? 1;
556
+ if (args.positional.length <= limit) return;
557
+ throw new Error(
558
+ t.errors.extraPositional(args.command, limit, args.positional.length, args.positional[limit] ?? ''),
559
+ );
560
+ }
561
+
518
562
  /**
519
563
  * One usage log, gzip included, shared by every command that reads one.
520
564
  *
@@ -697,7 +741,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
697
741
  ],
698
742
  check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from'],
699
743
  baseline: ['model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch', 'exact-tokens', 'out', 'o'],
700
- profile: ['json', 'pricing', 'pricing-live', 'against', 'what-if', 'markdown-out', 'html-out', 'csv-out', 'csv-shape', 'max-usd', 'max-growth-usd', 'max-cache-loss-usd', 'max-day-usd', 'max-session-usd', 'label', 'since', 'until', 'dry-run', 'markdown-summary', 'by-source', 'allow-empty'],
744
+ profile: ['json', 'pricing', 'pricing-live', 'against', 'what-if', 'markdown-out', 'html-out', 'pdf-out', 'csv-out', 'csv-shape', 'max-usd', 'max-growth-usd', 'max-cache-loss-usd', 'max-day-usd', 'max-session-usd', 'label', 'since', 'until', 'dry-run', 'markdown-summary', 'by-source', 'allow-empty'],
701
745
  plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live'],
702
746
  verify: ['against', 'gate', 'json', 'markdown-out', 'pricing', 'pricing-live'],
703
747
  history: ['store', 'json', 'markdown-out'],
@@ -724,7 +768,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
724
768
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
725
769
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
726
770
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
727
- bill: ['label', 'out', 'o', 'stamp', 'pricing', 'pricing-live'],
771
+ bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape'],
728
772
  'from-helicone': ['out', 'o'],
729
773
  'from-langsmith': ['out', 'o'],
730
774
  switch: ['to', 'migration-usd', 'cases'],
@@ -3377,33 +3421,82 @@ function usageSourcesOf(text: string): UsageSource[] {
3377
3421
  * a bill rather than usage, and pointed at `reconcile`.
3378
3422
  */
3379
3423
  async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3380
- const target = args.positional[0];
3381
- if (target === undefined) throw new Error(t.bill.noPath());
3424
+ /* Refused before any file is read: a bad shape found after the receipt
3425
+ printed would end a run that looked finished with an error. */
3426
+ const csvShape = csvShapeOf(args, t);
3382
3427
 
3383
- let info;
3384
- try {
3385
- info = await stat(target);
3386
- } catch {
3387
- throw new Error(t.bill.notFound(target));
3428
+ /*
3429
+ No path is the most common first run, and it used to be a refusal: the
3430
+ person had to know where Claude Code keeps its sessions before the one
3431
+ line on the README worked. Claude Code's own folders are searched
3432
+ instead, and the ones found are named, so nothing is read silently.
3433
+ */
3434
+ let targets = args.positional;
3435
+ if (targets.length === 0) {
3436
+ const { found, tried } = await claudeProjectFolders(process.env);
3437
+ if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
3438
+ console.error(t.bill.defaultPath(found.join(', ')));
3439
+ targets = found;
3388
3440
  }
3441
+
3442
+ /*
3443
+ Every path given, files and directories alike, because a shell glob hands
3444
+ over many and reading the first was a bill missing the rest. A file named
3445
+ twice (a directory and a file inside it) is read once: counting it twice
3446
+ would be the opposite mistake.
3447
+ */
3389
3448
  const files: string[] = [];
3390
- if (info.isDirectory()) {
3391
- const entries = await readdir(target, { recursive: true, withFileTypes: true });
3392
- for (const entry of entries) {
3393
- if (entry.isFile() && /\.(json|jsonl|ndjson)(\.gz)?$/i.test(entry.name)) {
3394
- files.push(join(entry.parentPath, entry.name));
3395
- }
3449
+ const seen = new Set<string>();
3450
+ /* Reached through a directory: where a project folder can name the work. */
3451
+ const walked = new Set<string>();
3452
+ const add = (file: string, fromDirectory: boolean): void => {
3453
+ const key = resolvePath(file);
3454
+ if (fromDirectory) walked.add(file);
3455
+ if (seen.has(key)) return;
3456
+ seen.add(key);
3457
+ files.push(file);
3458
+ };
3459
+ for (const target of targets) {
3460
+ let info;
3461
+ try {
3462
+ info = await stat(target);
3463
+ } catch {
3464
+ throw new Error(t.bill.notFound(target));
3465
+ }
3466
+ if (info.isDirectory()) {
3467
+ const entries = await readdir(target, { recursive: true, withFileTypes: true });
3468
+ const found = entries
3469
+ .filter((entry) => entry.isFile() && isUsageLogName(entry.name))
3470
+ .map((entry) => join(entry.parentPath, entry.name))
3471
+ .sort();
3472
+ if (found.length === 0) throw new Error(t.bill.noFiles(target));
3473
+ for (const file of found) add(file, true);
3474
+ } else {
3475
+ add(target, false);
3396
3476
  }
3397
- files.sort();
3398
- if (files.length === 0) throw new Error(t.bill.noFiles(target));
3399
- } else {
3400
- files.push(target);
3401
3477
  }
3402
3478
 
3403
3479
  const label = stringFlag(args, 'label');
3404
3480
  const withLabel = label === undefined ? {} : { label };
3481
+ /*
3482
+ Claude Code keeps one folder per project, and "per project" is the
3483
+ question this door is for. `from-claude-code` has labelled a directory by
3484
+ its project folders since 1.77; `bill` read the same transcripts with no
3485
+ label at all, so the bill it printed could not say which project spent
3486
+ the money. Same default, same function, same way to decline.
3487
+ */
3488
+ const labelFromProject = boolFlag(args, 'label-from-project', true);
3489
+ let labelledByProject = 0;
3405
3490
  const lines: string[] = [];
3406
3491
  let sources = 0;
3492
+ /*
3493
+ One line per file is right for a handful and noise for a Claude Code
3494
+ folder of hundreds. Past a handful, the lines are per shape, and the
3495
+ files no shape claims are named for the first few and counted after.
3496
+ */
3497
+ const perFile = files.length <= 8;
3498
+ const unclaimed: string[] = [];
3499
+ const byShape = new Map<string, { files: number; records: number | null; leftOut: number }>();
3407
3500
 
3408
3501
  for (const file of files) {
3409
3502
  const text = await readUsageLog(file, t);
@@ -3413,7 +3506,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3413
3506
  if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
3414
3507
  console.error(t.bill.costReport(file));
3415
3508
  } else {
3416
- console.error(t.bill.unknown(file));
3509
+ unclaimed.push(file);
3417
3510
  }
3418
3511
  continue;
3419
3512
  }
@@ -3428,7 +3521,10 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3428
3521
  let leftOut = 0;
3429
3522
  switch (shape) {
3430
3523
  case 'claude-code': {
3431
- const c = claudeCodeRecords(text, withLabel);
3524
+ const project =
3525
+ label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
3526
+ if (project !== undefined && project !== '') labelledByProject += 1;
3527
+ const c = claudeCodeRecords(text, project !== undefined && project !== '' ? { label: project } : withLabel);
3432
3528
  records = c.records;
3433
3529
  leftOut = c.assistantWithoutUsage + c.unparseable;
3434
3530
  break;
@@ -3484,8 +3580,22 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3484
3580
  }
3485
3581
  for (const record of records) lines.push(JSON.stringify(record));
3486
3582
  sources += 1;
3487
- console.error(t.bill.file(file, shape, shape === 'usage-log' ? null : records.length, leftOut));
3583
+ const count = shape === 'usage-log' ? null : records.length;
3584
+ if (perFile) {
3585
+ console.error(t.bill.file(file, shape, count, leftOut));
3586
+ } else {
3587
+ const sum = byShape.get(shape) ?? { files: 0, records: count === null ? null : 0, leftOut: 0 };
3588
+ sum.files += 1;
3589
+ if (sum.records !== null && count !== null) sum.records += count;
3590
+ sum.leftOut += leftOut;
3591
+ byShape.set(shape, sum);
3592
+ }
3488
3593
  }
3594
+ for (const [shape, sum] of byShape) console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
3595
+ const named = perFile ? unclaimed : unclaimed.slice(0, 3);
3596
+ for (const file of named) console.error(t.bill.unknown(file));
3597
+ if (unclaimed.length > named.length) console.error(t.bill.unknownMore(unclaimed.length - named.length));
3598
+ if (labelledByProject > 0) console.error(t.bill.labelledByProject(labelledByProject));
3489
3599
 
3490
3600
  if (sources === 0) throw new Error(t.bill.nothingRead());
3491
3601
 
@@ -3493,15 +3603,27 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3493
3603
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3494
3604
  const json = JSON.stringify(document, null, 2);
3495
3605
 
3606
+ /*
3607
+ A terminal gets a statement a person can read; a pipe gets the receipt.
3608
+ The receipt on a terminal was 60 lines of JSON before the first figure a
3609
+ reader wanted, which is the screen a first run ends on. Scripts are
3610
+ untouched: they pipe, and a pipe is not a TTY. `--receipt` forces the
3611
+ receipt and `--table` forces the statement, either way round. Not
3612
+ `--json`: that flag means a documented contract in docs/format.md, and
3613
+ the receipt is `trazum receipt`'s document, emitted here unchanged.
3614
+ */
3496
3615
  const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3616
+ const statement = !boolFlag(args, 'receipt') && boolFlag(args, 'table', process.stdout.isTTY === true);
3497
3617
  if (out !== undefined) {
3498
3618
  await writeFile(out, json + '\n', 'utf8');
3499
3619
  console.error(t.bill.written(out));
3500
- } else {
3620
+ } else if (!statement) {
3501
3621
  console.log(json);
3502
3622
  }
3503
3623
  console.error(t.bill.sources(sources, files.length));
3504
3624
  printReceiptSummary(document, t);
3625
+ if (statement) printBillStatement(report, labelledByProject > 0, t);
3626
+ await writeBillSideFiles(args, report, pricing, csvShape, t);
3505
3627
 
3506
3628
  /*
3507
3629
  A slug with a slash in it is how OpenRouter names a model, and the bundled
@@ -3517,6 +3639,158 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3517
3639
  }
3518
3640
  }
3519
3641
 
3642
+ /**
3643
+ * Where Claude Code keeps its sessions, in the order it looks itself.
3644
+ *
3645
+ * `CLAUDE_CONFIG_DIR` first, because a person who set it moved the folder on
3646
+ * purpose; then the two defaults Claude Code has used. Every folder that
3647
+ * exists is returned, deduplicated, so a machine with both is billed for
3648
+ * both, once each. `tried` is every candidate, for the refusal to name.
3649
+ */
3650
+ async function claudeProjectFolders(env: NodeJS.ProcessEnv): Promise<{ found: string[]; tried: string[] }> {
3651
+ const home = homedir();
3652
+ const tried = [
3653
+ ...(env.CLAUDE_CONFIG_DIR ? [join(env.CLAUDE_CONFIG_DIR, 'projects')] : []),
3654
+ join(home, '.claude', 'projects'),
3655
+ join(home, '.config', 'claude', 'projects'),
3656
+ ];
3657
+ const found: string[] = [];
3658
+ const seen = new Set<string>();
3659
+ for (const candidate of tried) {
3660
+ const key = resolvePath(candidate);
3661
+ if (seen.has(key)) continue;
3662
+ seen.add(key);
3663
+ try {
3664
+ if ((await stat(candidate)).isDirectory()) found.push(candidate);
3665
+ } catch {
3666
+ // Not there, which is the ordinary case for two of the three.
3667
+ }
3668
+ }
3669
+ return { found, tried };
3670
+ }
3671
+
3672
+ /**
3673
+ * The bill as a person reads it: the total, by project, by model, and what
3674
+ * is not in the total, on stdout. The receipt's figures, rendered: nothing
3675
+ * here is computed that the receipt does not carry.
3676
+ */
3677
+ function printBillStatement(report: UsageProfileReport, byProject: boolean, t: CliMessages): void {
3678
+ const n = (value: number): string => value.toLocaleString(t.numberLocale);
3679
+ const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
3680
+ const total = report.total.totalUsd;
3681
+ const LIMIT = 12;
3682
+ const rowsOf = (entries: { name: string; calls: number; usd: number }[]): string[][] => {
3683
+ const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) => {
3684
+ const share = total > 0 ? usd / total : 0;
3685
+ return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3686
+ });
3687
+ if (entries.length > LIMIT) shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '']);
3688
+ return shown;
3689
+ };
3690
+ const columns = (first: string): TableColumn[] => [
3691
+ { header: first, align: 'left' },
3692
+ { header: t.bill.colCalls(), align: 'right' },
3693
+ { header: 'USD', align: 'right' },
3694
+ { header: t.bill.colShare(), align: 'left' },
3695
+ ];
3696
+
3697
+ console.log();
3698
+ console.log(sectionHeading(t.bill.statementHeading()));
3699
+ console.log(` ${c.bold(t.bill.statementTotal(formatUsd(total), report.total.calls))}`);
3700
+ if (report.span !== null) {
3701
+ const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
3702
+ console.log(c.dim(` ${wrap(span, 74, ' ')}`));
3703
+ }
3704
+
3705
+ const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
3706
+ if (labelled.length > 0) {
3707
+ console.log();
3708
+ const entries = report.byLabel.map((row) => ({
3709
+ name: row.label === UNLABELLED ? t.profile.unlabelled() : row.label,
3710
+ calls: row.breakdown.calls,
3711
+ usd: row.breakdown.totalUsd,
3712
+ }));
3713
+ for (const line of table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries))) {
3714
+ console.log(line);
3715
+ }
3716
+ }
3717
+
3718
+ const priced = report.byModel.filter((row) => !report.unpricedModels.includes(row.model));
3719
+ if (priced.length > 0) {
3720
+ console.log();
3721
+ const entries = priced.map((row) => ({ name: row.model, calls: row.breakdown.calls, usd: row.breakdown.totalUsd }));
3722
+ for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
3723
+ }
3724
+
3725
+ console.log();
3726
+ if (report.unpricedModels.length > 0) {
3727
+ console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
3728
+ }
3729
+ if (report.skippedLines.length > 0) console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
3730
+ console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
3731
+ console.log();
3732
+ }
3733
+
3734
+ /**
3735
+ * The bill as a document for somebody else: PDF, HTML, Markdown, CSV.
3736
+ *
3737
+ * The receipt on stdout is for a machine. The person who signs the bill off
3738
+ * reads a PDF in an email, and until now reaching one meant knowing the log
3739
+ * was a usage log and rerunning `profile` on it, which a converted Claude Code
3740
+ * transcript is not. These are `profile`'s own renderers fed the report `bill`
3741
+ * just priced, so the files and the receipt cannot disagree: one report, five
3742
+ * envelopes. The stale-price caveat travels with them, computed the way
3743
+ * `profile` computes it, for the providers this bill actually used.
3744
+ */
3745
+ async function writeBillSideFiles(
3746
+ args: Args,
3747
+ report: UsageProfileReport,
3748
+ pricing: PricingCatalogue,
3749
+ csvShape: ProfileCsvShape,
3750
+ t: CliMessages,
3751
+ ): Promise<void> {
3752
+ const markdownOut = stringFlag(args, 'markdown-out');
3753
+ const htmlOut = stringFlag(args, 'html-out');
3754
+ const pdfOut = stringFlag(args, 'pdf-out');
3755
+ const csvOut = stringFlag(args, 'csv-out');
3756
+ if (markdownOut === undefined && htmlOut === undefined && pdfOut === undefined && csvOut === undefined) return;
3757
+
3758
+ const reviewed = reviewedForModels(report.byModel.map((row) => row.model), pricing);
3759
+ const ageDays = reviewAgeDays(reviewed, new Date());
3760
+ const renderInput: ProfileMarkdownInput = {
3761
+ report,
3762
+ levers: billLevers(report, { catalogue: pricing }),
3763
+ cache: cacheEconomics(report.total),
3764
+ t,
3765
+ ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3766
+ };
3767
+ if (markdownOut !== undefined) {
3768
+ await writeFile(markdownOut, renderProfileMarkdown(renderInput), 'utf8');
3769
+ console.error(t.report.reportWritten(markdownOut));
3770
+ }
3771
+ if (htmlOut !== undefined) {
3772
+ await writeFile(htmlOut, renderProfileHtml(renderInput), 'utf8');
3773
+ console.error(t.html.written(htmlOut));
3774
+ }
3775
+ if (pdfOut !== undefined) {
3776
+ await writeFile(pdfOut, renderProfilePdf(renderInput));
3777
+ console.error(t.pdf.written(pdfOut));
3778
+ }
3779
+ if (csvOut !== undefined) {
3780
+ await writeFile(csvOut, profileToCsv(report, { unlabelled: t.profile.unlabelled(), shape: csvShape }), 'utf8');
3781
+ console.error(t.report.reportWritten(csvOut));
3782
+ }
3783
+ }
3784
+
3785
+ /** `--csv-shape`, checked: one list of shapes for `profile` and `bill`. */
3786
+ function csvShapeOf(args: Args, t: CliMessages): ProfileCsvShape {
3787
+ const shape = stringFlag(args, 'csv-shape') ?? 'slice';
3788
+ if (shape !== 'slice' && shape !== 'day' && shape !== 'hour' && shape !== 'model-day') {
3789
+ throw new Error(t.profile.badCsvShape(shape));
3790
+ }
3791
+ return shape;
3792
+ }
3793
+
3520
3794
  /**
3521
3795
  * `trazum from-otel <file|dir>` — OpenTelemetry GenAI spans as a usage log.
3522
3796
  *
@@ -8990,7 +9264,8 @@ async function writeProfileSideFiles(context: {
8990
9264
  */
8991
9265
  const markdownOut = stringFlag(args, 'markdown-out');
8992
9266
  const htmlOut = stringFlag(args, 'html-out');
8993
- if (markdownOut !== undefined || htmlOut !== undefined) {
9267
+ const pdfOut = stringFlag(args, 'pdf-out');
9268
+ if (markdownOut !== undefined || htmlOut !== undefined || pdfOut !== undefined) {
8994
9269
  /**
8995
9270
  * Derived here, not borrowed from the terminal path. Under `--json`
8996
9271
  * that path never runs, and the outer `levers` this block used to
@@ -9052,12 +9327,16 @@ async function writeProfileSideFiles(context: {
9052
9327
  });
9053
9328
  if (markdownOut !== undefined) {
9054
9329
  await writeFile(markdownOut, renderProfileMarkdown(renderInput), 'utf8');
9055
- notice(c.dim(t.report.wroteTo(markdownOut)));
9330
+ notice(c.dim(t.report.reportWritten(markdownOut)));
9056
9331
  }
9057
9332
  if (htmlOut !== undefined) {
9058
9333
  await writeFile(htmlOut, renderProfileHtml(renderInput), 'utf8');
9059
9334
  notice(c.dim(t.html.written(htmlOut)));
9060
9335
  }
9336
+ if (pdfOut !== undefined) {
9337
+ await writeFile(pdfOut, renderProfilePdf(renderInput));
9338
+ notice(c.dim(t.pdf.written(pdfOut)));
9339
+ }
9061
9340
  }
9062
9341
 
9063
9342
  /**
@@ -9073,16 +9352,13 @@ async function writeProfileSideFiles(context: {
9073
9352
  * spreadsheet that has to filter before it can sum is a spreadsheet
9074
9353
  * somebody sums wrong.
9075
9354
  */
9076
- const shape = stringFlag(args, 'csv-shape') ?? 'slice';
9077
- if (shape !== 'slice' && shape !== 'day' && shape !== 'hour' && shape !== 'model-day') {
9078
- throw new Error(t.profile.badCsvShape(shape));
9079
- }
9355
+ const shape = csvShapeOf(args, t);
9080
9356
  await writeFile(
9081
9357
  csvOut,
9082
9358
  profileToCsv(report, { unlabelled: t.profile.unlabelled(), shape }),
9083
9359
  'utf8',
9084
9360
  );
9085
- notice(c.dim(t.report.wroteTo(csvOut)));
9361
+ notice(c.dim(t.report.reportWritten(csvOut)));
9086
9362
  }
9087
9363
  }
9088
9364
 
@@ -13059,6 +13335,7 @@ async function main(): Promise<void> {
13059
13335
  }
13060
13336
 
13061
13337
  rejectUnknownFlags(args, t);
13338
+ rejectExtraPositionals(args, t);
13062
13339
 
13063
13340
  // Loaded before dispatch so every command sees the same settings, and after
13064
13341
  // flag validation so a typo is reported before any file is touched. An