@trazum/cli 2.4.0 → 2.4.2

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
@@ -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
  // --------------------------------------------------------------------------
@@ -382,6 +385,7 @@ const VALUE_FLAGS = new Set([
382
385
  'config',
383
386
  'markdown-out',
384
387
  'html-out',
388
+ 'pdf-out',
385
389
  'otlp-out',
386
390
  'pricing',
387
391
  'prompt',
@@ -515,6 +519,45 @@ function levelFlag(args: Args, config: TrazumConfig, t: CliMessages): RuleLevel
515
519
  */
516
520
  const LOG_EXTENSIONS = ['.jsonl', '.ndjson', '.log', '.json'];
517
521
 
522
+ /**
523
+ * Whether a directory walk reads this file: one of `LOG_EXTENSIONS`, plain or
524
+ * gzipped, in any case.
525
+ *
526
+ * The list above said one list, and six walks still kept four of their own:
527
+ * `bill` skipped `.log`, which `profile` read, so the same directory billed
528
+ * $7.51 by one verb and $15.01 by the other, and `bill` did not even count
529
+ * the file it skipped. A predicate every walk calls is the only form of "one
530
+ * list" that cannot drift.
531
+ */
532
+ function isUsageLogName(name: string): boolean {
533
+ const lower = name.toLowerCase();
534
+ return LOG_EXTENSIONS.some((extension) => lower.endsWith(extension) || lower.endsWith(`${extension}.gz`));
535
+ }
536
+
537
+ /**
538
+ * How many positional arguments a command reads. One unless listed.
539
+ *
540
+ * Every command used to read `positional[0]` and ignore the rest, so
541
+ * `trazum bill logs/*.jsonl`, which the shell expands to every file, priced
542
+ * the first file alone and reported no gap: a bill understated with the
543
+ * confidence of a complete one, and a spend gate judging one day of seven.
544
+ * A command now either reads every path it is given or refuses the extras.
545
+ */
546
+ const POSITIONAL_LIMIT: Readonly<Record<string, number>> = {
547
+ bill: Number.POSITIVE_INFINITY,
548
+ rollup: Number.POSITIVE_INFINITY,
549
+ diff: 2,
550
+ };
551
+
552
+ function rejectExtraPositionals(args: Args, t: CliMessages): void {
553
+ if (!COMMAND_FLAGS[args.command]) return;
554
+ const limit = POSITIONAL_LIMIT[args.command] ?? 1;
555
+ if (args.positional.length <= limit) return;
556
+ throw new Error(
557
+ t.errors.extraPositional(args.command, limit, args.positional.length, args.positional[limit] ?? ''),
558
+ );
559
+ }
560
+
518
561
  /**
519
562
  * One usage log, gzip included, shared by every command that reads one.
520
563
  *
@@ -697,7 +740,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
697
740
  ],
698
741
  check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from'],
699
742
  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'],
743
+ 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
744
  plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live'],
702
745
  verify: ['against', 'gate', 'json', 'markdown-out', 'pricing', 'pricing-live'],
703
746
  history: ['store', 'json', 'markdown-out'],
@@ -724,7 +767,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
724
767
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
725
768
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
726
769
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
727
- bill: ['label', 'out', 'o', 'stamp', 'pricing', 'pricing-live'],
770
+ bill: ['label', 'out', 'o', 'stamp', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape'],
728
771
  'from-helicone': ['out', 'o'],
729
772
  'from-langsmith': ['out', 'o'],
730
773
  switch: ['to', 'migration-usd', 'cases'],
@@ -3377,27 +3420,43 @@ function usageSourcesOf(text: string): UsageSource[] {
3377
3420
  * a bill rather than usage, and pointed at `reconcile`.
3378
3421
  */
3379
3422
  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());
3423
+ if (args.positional.length === 0) 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));
3388
- }
3428
+ /*
3429
+ Every path given, files and directories alike, because a shell glob hands
3430
+ over many and reading the first was a bill missing the rest. A file named
3431
+ twice (a directory and a file inside it) is read once: counting it twice
3432
+ would be the opposite mistake.
3433
+ */
3389
3434
  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
- }
3435
+ const seen = new Set<string>();
3436
+ const add = (file: string): void => {
3437
+ const key = resolvePath(file);
3438
+ if (seen.has(key)) return;
3439
+ seen.add(key);
3440
+ files.push(file);
3441
+ };
3442
+ for (const target of args.positional) {
3443
+ let info;
3444
+ try {
3445
+ info = await stat(target);
3446
+ } catch {
3447
+ throw new Error(t.bill.notFound(target));
3448
+ }
3449
+ if (info.isDirectory()) {
3450
+ const entries = await readdir(target, { recursive: true, withFileTypes: true });
3451
+ const found = entries
3452
+ .filter((entry) => entry.isFile() && isUsageLogName(entry.name))
3453
+ .map((entry) => join(entry.parentPath, entry.name))
3454
+ .sort();
3455
+ if (found.length === 0) throw new Error(t.bill.noFiles(target));
3456
+ for (const file of found) add(file);
3457
+ } else {
3458
+ add(target);
3396
3459
  }
3397
- files.sort();
3398
- if (files.length === 0) throw new Error(t.bill.noFiles(target));
3399
- } else {
3400
- files.push(target);
3401
3460
  }
3402
3461
 
3403
3462
  const label = stringFlag(args, 'label');
@@ -3502,6 +3561,80 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3502
3561
  }
3503
3562
  console.error(t.bill.sources(sources, files.length));
3504
3563
  printReceiptSummary(document, t);
3564
+ await writeBillSideFiles(args, report, pricing, csvShape, t);
3565
+
3566
+ /*
3567
+ A slug with a slash in it is how OpenRouter names a model, and the bundled
3568
+ catalogue does not carry those: the live overlay does. Said only when the
3569
+ receipt's own unpriced gap holds one, so the hint is derived from what was
3570
+ refused rather than from which shape the file happened to be.
3571
+ */
3572
+ const slugged = document.gaps.flatMap((gap) =>
3573
+ gap.kind === 'unpriced' ? gap.models.filter((model) => model.includes('/')) : [],
3574
+ );
3575
+ if (slugged.length > 0 && !boolFlag(args, 'pricing-live')) {
3576
+ console.error(t.bill.pricingLiveHint(slugged.length));
3577
+ }
3578
+ }
3579
+
3580
+ /**
3581
+ * The bill as a document for somebody else: PDF, HTML, Markdown, CSV.
3582
+ *
3583
+ * The receipt on stdout is for a machine. The person who signs the bill off
3584
+ * reads a PDF in an email, and until now reaching one meant knowing the log
3585
+ * was a usage log and rerunning `profile` on it, which a converted Claude Code
3586
+ * transcript is not. These are `profile`'s own renderers fed the report `bill`
3587
+ * just priced, so the files and the receipt cannot disagree: one report, five
3588
+ * envelopes. The stale-price caveat travels with them, computed the way
3589
+ * `profile` computes it, for the providers this bill actually used.
3590
+ */
3591
+ async function writeBillSideFiles(
3592
+ args: Args,
3593
+ report: UsageProfileReport,
3594
+ pricing: PricingCatalogue,
3595
+ csvShape: ProfileCsvShape,
3596
+ t: CliMessages,
3597
+ ): Promise<void> {
3598
+ const markdownOut = stringFlag(args, 'markdown-out');
3599
+ const htmlOut = stringFlag(args, 'html-out');
3600
+ const pdfOut = stringFlag(args, 'pdf-out');
3601
+ const csvOut = stringFlag(args, 'csv-out');
3602
+ if (markdownOut === undefined && htmlOut === undefined && pdfOut === undefined && csvOut === undefined) return;
3603
+
3604
+ const reviewed = reviewedForModels(report.byModel.map((row) => row.model), pricing);
3605
+ const ageDays = reviewAgeDays(reviewed, new Date());
3606
+ const renderInput: ProfileMarkdownInput = {
3607
+ report,
3608
+ levers: billLevers(report, { catalogue: pricing }),
3609
+ cache: cacheEconomics(report.total),
3610
+ t,
3611
+ ...(ageDays !== null && ageDays > STALE_PRICING_DAYS ? { stalePricing: { date: reviewed, days: ageDays } } : {}),
3612
+ };
3613
+ if (markdownOut !== undefined) {
3614
+ await writeFile(markdownOut, renderProfileMarkdown(renderInput), 'utf8');
3615
+ console.error(t.report.reportWritten(markdownOut));
3616
+ }
3617
+ if (htmlOut !== undefined) {
3618
+ await writeFile(htmlOut, renderProfileHtml(renderInput), 'utf8');
3619
+ console.error(t.html.written(htmlOut));
3620
+ }
3621
+ if (pdfOut !== undefined) {
3622
+ await writeFile(pdfOut, renderProfilePdf(renderInput));
3623
+ console.error(t.pdf.written(pdfOut));
3624
+ }
3625
+ if (csvOut !== undefined) {
3626
+ await writeFile(csvOut, profileToCsv(report, { unlabelled: t.profile.unlabelled(), shape: csvShape }), 'utf8');
3627
+ console.error(t.report.reportWritten(csvOut));
3628
+ }
3629
+ }
3630
+
3631
+ /** `--csv-shape`, checked: one list of shapes for `profile` and `bill`. */
3632
+ function csvShapeOf(args: Args, t: CliMessages): ProfileCsvShape {
3633
+ const shape = stringFlag(args, 'csv-shape') ?? 'slice';
3634
+ if (shape !== 'slice' && shape !== 'day' && shape !== 'hour' && shape !== 'model-day') {
3635
+ throw new Error(t.profile.badCsvShape(shape));
3636
+ }
3637
+ return shape;
3505
3638
  }
3506
3639
 
3507
3640
  /**
@@ -8977,7 +9110,8 @@ async function writeProfileSideFiles(context: {
8977
9110
  */
8978
9111
  const markdownOut = stringFlag(args, 'markdown-out');
8979
9112
  const htmlOut = stringFlag(args, 'html-out');
8980
- if (markdownOut !== undefined || htmlOut !== undefined) {
9113
+ const pdfOut = stringFlag(args, 'pdf-out');
9114
+ if (markdownOut !== undefined || htmlOut !== undefined || pdfOut !== undefined) {
8981
9115
  /**
8982
9116
  * Derived here, not borrowed from the terminal path. Under `--json`
8983
9117
  * that path never runs, and the outer `levers` this block used to
@@ -9039,12 +9173,16 @@ async function writeProfileSideFiles(context: {
9039
9173
  });
9040
9174
  if (markdownOut !== undefined) {
9041
9175
  await writeFile(markdownOut, renderProfileMarkdown(renderInput), 'utf8');
9042
- notice(c.dim(t.report.wroteTo(markdownOut)));
9176
+ notice(c.dim(t.report.reportWritten(markdownOut)));
9043
9177
  }
9044
9178
  if (htmlOut !== undefined) {
9045
9179
  await writeFile(htmlOut, renderProfileHtml(renderInput), 'utf8');
9046
9180
  notice(c.dim(t.html.written(htmlOut)));
9047
9181
  }
9182
+ if (pdfOut !== undefined) {
9183
+ await writeFile(pdfOut, renderProfilePdf(renderInput));
9184
+ notice(c.dim(t.pdf.written(pdfOut)));
9185
+ }
9048
9186
  }
9049
9187
 
9050
9188
  /**
@@ -9060,16 +9198,13 @@ async function writeProfileSideFiles(context: {
9060
9198
  * spreadsheet that has to filter before it can sum is a spreadsheet
9061
9199
  * somebody sums wrong.
9062
9200
  */
9063
- const shape = stringFlag(args, 'csv-shape') ?? 'slice';
9064
- if (shape !== 'slice' && shape !== 'day' && shape !== 'hour' && shape !== 'model-day') {
9065
- throw new Error(t.profile.badCsvShape(shape));
9066
- }
9201
+ const shape = csvShapeOf(args, t);
9067
9202
  await writeFile(
9068
9203
  csvOut,
9069
9204
  profileToCsv(report, { unlabelled: t.profile.unlabelled(), shape }),
9070
9205
  'utf8',
9071
9206
  );
9072
- notice(c.dim(t.report.wroteTo(csvOut)));
9207
+ notice(c.dim(t.report.reportWritten(csvOut)));
9073
9208
  }
9074
9209
  }
9075
9210
 
@@ -13046,6 +13181,7 @@ async function main(): Promise<void> {
13046
13181
  }
13047
13182
 
13048
13183
  rejectUnknownFlags(args, t);
13184
+ rejectExtraPositionals(args, t);
13049
13185
 
13050
13186
  // Loaded before dispatch so every command sees the same settings, and after
13051
13187
  // flag validation so a typo is reported before any file is touched. An
package/src/pdf.ts ADDED
@@ -0,0 +1,318 @@
1
+ import { PdfDocument, UNLABELLED, formatUsd, pdfFit, pdfWrap, sharesOf } from '@trazum/core';
2
+ import type { PdfColor, PdfFont, UsageBreakdown } from '@trazum/core';
3
+ import type { ProfileMarkdownInput } from './markdown.js';
4
+ import { dayOf, spanDays } from './time.js';
5
+
6
+ /**
7
+ * The profile as a PDF, for the person who signs the bill off.
8
+ *
9
+ * The same input object the HTML and Markdown doors take, and the same
10
+ * sentences from the same message catalogue, so the three files are one
11
+ * report in three envelopes: a figure that differed between them would be a
12
+ * second computation, and there is none. The rules the HTML door applies are
13
+ * applied here, for the same reasons:
14
+ *
15
+ * - **The caveats are furniture.** What the report cannot say renders in a
16
+ * bordered block ahead of every table, at the weight of the totals it
17
+ * qualifies. A PDF is the format most likely to be forwarded without the
18
+ * terminal it came from, which makes it the one where a caveat that can be
19
+ * cropped out matters most.
20
+ * - **Every page carries the footer** that says where the figures came from,
21
+ * because a printed page gets separated from its first one.
22
+ *
23
+ * Written with core's `PdfDocument`: no dependency, no embedded font, the
24
+ * same bytes for the same report.
25
+ */
26
+
27
+ const INK: PdfColor = '#1f2328';
28
+ const MUTED: PdfColor = '#59606a';
29
+ const RULE: PdfColor = '#d9d5cc';
30
+ const ZEBRA: PdfColor = '#f7f6f3';
31
+ const CAVEAT_EDGE: PdfColor = '#8a6d1a';
32
+ const CAVEAT_FILL: PdfColor = '#fbf6e9';
33
+ const CAVEAT_INK: PdfColor = '#6d5510';
34
+ const FAIL_EDGE: PdfColor = '#b42318';
35
+ const FAIL_FILL: PdfColor = '#fdf1f0';
36
+ const FAIL_INK: PdfColor = '#7a1a12';
37
+ const PASS_INK: PdfColor = '#365f37';
38
+
39
+ const MARGIN = 48;
40
+ const TOP = 56;
41
+ /** Below this the footer lives; content that would cross it starts a page. */
42
+ const FOOTER_SPACE = 70;
43
+
44
+ export interface ProfilePdfOptions {
45
+ /** Written into the file's metadata only when given, so tests can compare bytes. */
46
+ createdAt?: Date;
47
+ }
48
+
49
+ /** The profile as one PDF. Same input as the HTML and Markdown doors. */
50
+ export function renderProfilePdf(input: ProfileMarkdownInput, options: ProfilePdfOptions = {}): Uint8Array {
51
+ const { report, levers, cache, t, gates, window, stalePricing } = input;
52
+ const n = (value: number): string => value.toLocaleString(t.numberLocale);
53
+ const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
54
+ const showLabel = (label: string): string => (label === UNLABELLED ? t.profile.unlabelled() : label);
55
+
56
+ const doc = new PdfDocument();
57
+ const width = doc.width - MARGIN * 2;
58
+ const bottom = doc.height - FOOTER_SPACE;
59
+ let y = TOP;
60
+
61
+ const need = (height: number): boolean => {
62
+ if (y + height <= bottom) return false;
63
+ doc.addPage();
64
+ y = TOP;
65
+ return true;
66
+ };
67
+
68
+ /** A wrapped paragraph; returns nothing, moves the cursor. */
69
+ const paragraph = (text: string, font: PdfFont, size: number, color: PdfColor, after = 4): void => {
70
+ const leading = size * 1.35;
71
+ for (const line of pdfWrap(text, font, size, width)) {
72
+ need(leading);
73
+ doc.text(MARGIN, y + size, line, { font, size, color });
74
+ y += leading;
75
+ }
76
+ y += after;
77
+ };
78
+
79
+ const heading = (text: string): void => {
80
+ need(40);
81
+ y += 14;
82
+ doc.text(MARGIN, y + 11, text, { font: 'bold', size: 11.5, color: INK });
83
+ y += 17;
84
+ doc.line(MARGIN, y, MARGIN + width, y, { color: RULE, width: 0.75 });
85
+ y += 8;
86
+ };
87
+
88
+ /**
89
+ * A box of sentences: the caveats and the gate verdict. Measured before it
90
+ * is drawn so the border fits what is inside it, and moved whole to the
91
+ * next page rather than split, because half a caveat is a different claim.
92
+ */
93
+ const box = (
94
+ title: string | null,
95
+ lines: string[],
96
+ colors: { edge: PdfColor; fill: PdfColor; ink: PdfColor },
97
+ bullet: boolean,
98
+ ): void => {
99
+ const size = 9;
100
+ const leading = size * 1.4;
101
+ const pad = 10;
102
+ const indent = bullet ? 10 : 0;
103
+ const wrapped = lines.map((line) => pdfWrap(line, bullet ? 'regular' : 'bold', size, width - pad * 2 - indent));
104
+ const titleHeight = title === null ? 0 : 18;
105
+ const height = pad * 2 + titleHeight + wrapped.reduce((sum, w) => sum + w.length * leading + 2, 0);
106
+ need(height + 8);
107
+ doc.rect(MARGIN, y, width, height, { fill: colors.fill, stroke: colors.edge, lineWidth: 1.5 });
108
+ let inner = y + pad;
109
+ if (title !== null) {
110
+ doc.text(MARGIN + pad, inner + 10, title, { font: 'bold', size: 10.5, color: colors.ink });
111
+ inner += titleHeight;
112
+ }
113
+ for (const lineSet of wrapped) {
114
+ lineSet.forEach((line, i) => {
115
+ if (bullet && i === 0) doc.text(MARGIN + pad, inner + size, '•', { size, color: colors.ink });
116
+ doc.text(MARGIN + pad + indent, inner + size, line, { font: bullet ? 'regular' : 'bold', size, color: colors.ink });
117
+ inner += leading;
118
+ });
119
+ inner += 2;
120
+ }
121
+ y += height + 10;
122
+ };
123
+
124
+ interface Row {
125
+ name: string;
126
+ breakdown: UsageBreakdown;
127
+ /** Money as a dash, never `$0`, as in the HTML door: zero claims the calls were free. */
128
+ unpriced?: boolean;
129
+ }
130
+
131
+ /** The breakdown table, its header repeated on every page it crosses. */
132
+ const table = (rows: Row[], nameHeading: string): void => {
133
+ const size = 7.5;
134
+ const rowHeight = 13;
135
+ const figureColumns = [
136
+ t.html.colCalls(),
137
+ t.html.colInput(),
138
+ t.html.colCacheRead(),
139
+ t.html.colCacheWrite(),
140
+ t.html.colOutput(),
141
+ 'USD',
142
+ '%',
143
+ ];
144
+ const figureWidth = 54;
145
+ const nameWidth = width - figureWidth * figureColumns.length;
146
+ const right = (column: number): number => MARGIN + nameWidth + figureWidth * (column + 1) - 4;
147
+
148
+ /* A heading wraps to two lines rather than being cut: "lecturas de
149
+ caché" cut to "lecturas de…" no longer says which column it is. */
150
+ const headings = figureColumns.map((column) => pdfWrap(column, 'bold', size, figureWidth - 6).slice(0, 2));
151
+ const headerLines = Math.max(1, ...headings.map((lines) => lines.length));
152
+ const header = (): void => {
153
+ const base = y + 9 + (headerLines - 1) * (size + 1.5);
154
+ doc.text(MARGIN + 4, base, pdfFit(nameHeading, 'bold', size, nameWidth - 8), { font: 'bold', size, color: INK });
155
+ headings.forEach((lines, i) => {
156
+ lines.forEach((line, j) => {
157
+ const lineY = base - (lines.length - 1 - j) * (size + 1.5);
158
+ doc.textRight(right(i), lineY, pdfFit(line, 'bold', size, figureWidth - 6), { font: 'bold', size, color: INK });
159
+ });
160
+ });
161
+ y += rowHeight + (headerLines - 1) * (size + 1.5);
162
+ doc.line(MARGIN, y, MARGIN + width, y, { color: RULE, width: 1.25 });
163
+ y += 2;
164
+ };
165
+
166
+ need(rowHeight * 3);
167
+ header();
168
+ rows.forEach(({ name, breakdown: b, unpriced }, index) => {
169
+ if (need(rowHeight)) header();
170
+ if (index % 2 === 1) doc.rect(MARGIN, y, width, rowHeight, { fill: ZEBRA });
171
+ const share = report.total.totalUsd > 0 && !unpriced ? pct(b.totalUsd / report.total.totalUsd) : '—';
172
+ const cells = [
173
+ n(b.calls),
174
+ n(b.inputTokens),
175
+ n(b.cacheReadTokens),
176
+ n(b.cacheWriteTokens),
177
+ n(b.outputTokens),
178
+ unpriced ? '—' : formatUsd(b.totalUsd),
179
+ share,
180
+ ];
181
+ doc.text(MARGIN + 4, y + 9, pdfFit(name, 'regular', size, nameWidth - 8), { size, color: INK });
182
+ cells.forEach((cell, i) => {
183
+ doc.textRight(right(i), y + 9, pdfFit(cell, 'regular', size, figureWidth - 6), { size, color: INK });
184
+ });
185
+ y += rowHeight;
186
+ });
187
+ y += 6;
188
+ };
189
+
190
+ // The masthead: what this is and the one figure a reader came for.
191
+ doc.text(MARGIN, y + 9, 'trazum', { font: 'bold', size: 9, color: MUTED });
192
+ y += 16;
193
+ doc.line(MARGIN, y, MARGIN + width, y, { color: RULE, width: 0.75 });
194
+ y += 14;
195
+ paragraph(t.profile.heading(), 'bold', 19, INK, 2);
196
+ paragraph(t.profile.spent(t.profile.calls(report.total.calls), formatUsd(report.total.totalUsd)), 'bold', 14, INK, 4);
197
+ if (report.span !== null) {
198
+ paragraph(
199
+ t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)),
200
+ 'regular',
201
+ 9.5,
202
+ MUTED,
203
+ 0,
204
+ );
205
+ }
206
+ if (window !== undefined) paragraph(t.profile.windowLine(window.since, window.until), 'regular', 9.5, MUTED, 0);
207
+ y += 8;
208
+
209
+ if (gates !== undefined && gates.lines.length > 0) {
210
+ if (gates.failed) {
211
+ box(null, gates.lines, { edge: FAIL_EDGE, fill: FAIL_FILL, ink: FAIL_INK }, false);
212
+ } else {
213
+ for (const line of gates.lines) paragraph(line, 'regular', 9.5, PASS_INK, 0);
214
+ y += 6;
215
+ }
216
+ }
217
+
218
+ // The caveats, ahead of every table, as in the HTML door.
219
+ const caveats: string[] = [];
220
+ if (report.unpricedModels.length > 0) {
221
+ caveats.push(t.profile.unpriced(report.unpricedModels.join(', '), report.unpriced.calls));
222
+ }
223
+ if (report.skippedLines.length > 0) {
224
+ const shown = report.skippedLines.slice(0, 5).join(', ');
225
+ caveats.push(t.profile.skipped(report.skippedLines.length, report.skippedLines.length > 5 ? `${shown}…` : shown));
226
+ }
227
+ if (report.span === null) caveats.push(t.html.noClock());
228
+ if (!report.hasSessions) caveats.push(t.html.noSessions());
229
+ if (report.total.assumedWriteTtlCalls > 0) {
230
+ caveats.push(
231
+ t.profile.cacheTtlUnsettled(
232
+ report.total.assumedWriteTtlCalls,
233
+ formatUsd(-cache.deltaUsd),
234
+ formatUsd(cache.worstCaseDeltaUsd),
235
+ ),
236
+ );
237
+ }
238
+ if (stalePricing !== undefined) caveats.push(t.profile.pricesStale(stalePricing.date, stalePricing.days));
239
+ if (caveats.length > 0) {
240
+ box(t.html.caveatsHeading(), caveats, { edge: CAVEAT_EDGE, fill: CAVEAT_FILL, ink: CAVEAT_INK }, true);
241
+ }
242
+
243
+ heading(t.html.byLabelHeading());
244
+ table(
245
+ report.byLabel.map((row) => ({ name: showLabel(row.label), breakdown: row.breakdown })),
246
+ t.html.colLabel(),
247
+ );
248
+
249
+ heading(t.html.byModelHeading());
250
+ table(
251
+ report.byModel.map((row) => ({
252
+ name: row.model,
253
+ breakdown: row.breakdown,
254
+ unpriced: report.unpricedModels.includes(row.model),
255
+ })),
256
+ t.html.colModel(),
257
+ );
258
+
259
+ // The findings, as the sentences the terminal says.
260
+ const findings: string[] = [];
261
+ for (const lever of levers.slices.slice(0, 5)) {
262
+ findings.push(
263
+ t.profile.leverSlice(showLabel(lever.label), lever.modelName, formatUsd(lever.combinedUsd), pct(lever.shareOfBill)),
264
+ );
265
+ }
266
+ if (report.total.cacheReadTokens + report.total.cacheWriteTokens > 0) {
267
+ findings.push(
268
+ cache.deltaUsd > 0
269
+ ? t.profile.cacheLost(formatUsd(cache.deltaUsd), n(report.total.cacheWriteTokens), n(report.total.cacheReadTokens))
270
+ : t.profile.cachePaidOff(formatUsd(-cache.deltaUsd)),
271
+ );
272
+ }
273
+ if (findings.length > 0) {
274
+ heading(t.html.findingsHeading());
275
+ const size = 9.5;
276
+ const leading = size * 1.4;
277
+ for (const finding of findings) {
278
+ const lines = pdfWrap(finding, 'regular', size, width - 12);
279
+ need(lines.length * leading);
280
+ doc.text(MARGIN, y + size, '•', { size, color: INK });
281
+ for (const line of lines) {
282
+ doc.text(MARGIN + 12, y + size, line, { size, color: INK });
283
+ y += leading;
284
+ }
285
+ y += 3;
286
+ }
287
+ }
288
+
289
+ const shares = sharesOf(report.total);
290
+ y += 6;
291
+ paragraph(
292
+ t.html.sharesLine(pct(shares.input), pct(shares.cacheRead), pct(shares.cacheWrite), pct(shares.output)),
293
+ 'regular',
294
+ 9,
295
+ MUTED,
296
+ );
297
+
298
+ // The footer on every page, now that the page count is known.
299
+ const footerSize = 7.5;
300
+ const pageLabelWidth = 70;
301
+ const footerLines = pdfWrap(t.html.footer(), 'regular', footerSize, width - pageLabelWidth);
302
+ for (let page = 0; page < doc.pageCount; page += 1) {
303
+ doc.setPage(page);
304
+ const top = doc.height - FOOTER_SPACE + 22;
305
+ doc.line(MARGIN, top, MARGIN + width, top, { color: RULE, width: 0.75 });
306
+ footerLines.forEach((line, i) => {
307
+ doc.text(MARGIN, top + 11 + i * footerSize * 1.35, line, { size: footerSize, color: MUTED });
308
+ });
309
+ doc.textRight(MARGIN + width, top + 11, t.pdf.page(page + 1, doc.pageCount), { size: footerSize, color: MUTED });
310
+ }
311
+
312
+ return doc.toBytes({
313
+ title: t.profile.heading(),
314
+ subject: t.profile.spent(t.profile.calls(report.total.calls), formatUsd(report.total.totalUsd)),
315
+ ...(options.createdAt !== undefined ? { createdAt: options.createdAt } : {}),
316
+ });
317
+ }
318
+