@trazum/cli 2.7.0 → 2.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trazum/cli",
3
- "version": "2.7.0",
3
+ "version": "2.7.2",
4
4
  "description": "What your AI agents cost, per project, offline: one bill across Claude Code, Codex and Gemini CLI sessions, plus Anthropic, OpenAI, Gemini, OpenRouter, OTel and LiteLLM usage, written as PDF, HTML or CSV, with budgets enforced in CI.",
5
5
  "license": "MIT",
6
6
  "author": "David Mu\u00f1oz Rey",
@@ -53,7 +53,7 @@
53
53
  "prepublishOnly": "npm run build && npm test"
54
54
  },
55
55
  "dependencies": {
56
- "@trazum/core": "2.7.0"
56
+ "@trazum/core": "2.7.2"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/node": "^26.6.6",
@@ -366,6 +366,8 @@ function describe(body: string, provider: string, modelFromPath: string | null):
366
366
  maxOutputTokens: number | null;
367
367
  label: string | null;
368
368
  session: string | null;
369
+ speed: string | null;
370
+ serviceTier: string | null;
369
371
  } | null {
370
372
  let parsed: unknown;
371
373
  try {
@@ -431,6 +433,18 @@ function describe(body: string, provider: string, modelFromPath: string | null):
431
433
  * recorded, or printed.
432
434
  */
433
435
  session: metadataField(request, 'trazum_session'),
436
+ /**
437
+ * Anthropic's `speed: "fast"`: a setting, not content, and one that bills
438
+ * the call at a multiple of the standard rates, so the estimate a budget
439
+ * is judged by has to know it.
440
+ */
441
+ speed: typeof request.speed === 'string' && request.speed !== '' ? request.speed : null,
442
+ /**
443
+ * OpenAI's `service_tier`: Flex bills about half the standard rate and
444
+ * Fast up to twice, so the estimate a budget is judged by has to know it.
445
+ * The response says which tier ran, and the spend is recorded from that.
446
+ */
447
+ serviceTier: typeof request.service_tier === 'string' && request.service_tier !== '' ? request.service_tier : null,
434
448
  };
435
449
  }
436
450
 
@@ -87,7 +87,7 @@ export class GatewaySpend {
87
87
  (usage.cacheWrite5mTokens !== undefined && usage.cacheWrite1hTokens !== undefined &&
88
88
  usage.cacheWrite5mTokens + usage.cacheWrite1hTokens === usage.cacheWriteTokens));
89
89
  if (usage === null || !writesKnown ||
90
- Object.values(usage).some((value) => !Number.isFinite(value) || value < 0)) {
90
+ Object.values(usage).some((value) => typeof value === 'number' && (!Number.isFinite(value) || value < 0))) {
91
91
  // A flat write count has no TTL. Assuming 5m undercharges a 1h write.
92
92
  this.unknown = true;
93
93
  return;
@@ -102,6 +102,10 @@ export class GatewaySpend {
102
102
  ephemeral_5m_input_tokens: usage.cacheWrite5mTokens ?? 0,
103
103
  ephemeral_1h_input_tokens: usage.cacheWrite1hTokens ?? 0,
104
104
  },
105
+ // Fast mode bills at a multiple of standard; the response said which ran.
106
+ ...(usage.speed === undefined ? {} : { speed: usage.speed }),
107
+ // So does OpenAI's service tier, each priced from its own table.
108
+ ...(usage.serviceTier === undefined ? {} : { service_tier: usage.serviceTier }),
105
109
  }));
106
110
  const index = record === null ? null : indexUsage([record], { catalogue: this.catalogue, on: new Date(now) });
107
111
  if (index === null || index.unpriced > 0 || index.dayUsd === null) {
package/src/i18n/en.ts CHANGED
@@ -3002,6 +3002,10 @@ ${bold('EXAMPLES')}
3002
3002
  `--what-if does not know "${value}". Priced models: ${available}. Add it with --pricing if you have its rates.`,
3003
3003
  badGzip: (file, detail) =>
3004
3004
  `${file} is gzipped and would not decompress: ${detail}. Reading the rest and saying nothing would report a bill missing whatever that file held, so this stops instead. Check the file, or move it out of the directory.`,
3005
+ readInParts: (file, megabytes, slimmed) =>
3006
+ `${file}: ${megabytes} MB, too large to hold whole, so it was read line by line; the message text in ${slimmed} line(s) was set aside. Token counts and models are read as usual: text is never what a call is billed by here.`,
3007
+ tooLargeToRead: (file, megabytes) =>
3008
+ `${file} is ${megabytes} MB, and even with its message text set aside it is more than one read can hold. Split it into smaller files (for example \`split -l 500000\`) and pass the pieces.`,
3005
3009
  dryRunHeading: () => 'What this log can answer, no bill was produced',
3006
3010
  dryRunParsed: (parsed, skipped) =>
3007
3011
  `${parsed} records parse; ${skipped} lines could not be read. A dry run prices nothing: the point is what the gates you are about to wire would stand on.`,
package/src/i18n/es.ts CHANGED
@@ -3032,6 +3032,10 @@ ${bold('EJEMPLOS')}
3032
3032
  `--what-if no conoce "${value}". Modelos con precio: ${available}. Añádelo con --pricing si tienes sus tarifas.`,
3033
3033
  badGzip: (file, detail) =>
3034
3034
  `${file} está comprimido con gzip y no se ha podido descomprimir: ${detail}. Leer el resto y no decir nada daría una factura a la que le falta lo que hubiera en ese fichero, así que se para aquí. Revisa el fichero, o sácalo del directorio.`,
3035
+ readInParts: (file, megabytes, slimmed) =>
3036
+ `${file}: ${megabytes} MB, demasiado grande para leerlo entero, así que se ha leído línea a línea; el texto de los mensajes de ${slimmed} línea(s) se ha dejado aparte. Los tokens y los modelos se leen como siempre: aquí ninguna llamada se factura por su texto.`,
3037
+ tooLargeToRead: (file, megabytes) =>
3038
+ `${file} ocupa ${megabytes} MB, y ni dejando aparte el texto de los mensajes cabe en una sola lectura. Divídelo en ficheros más pequeños (por ejemplo \`split -l 500000\`) y pásalos.`,
3035
3039
  dryRunHeading: () => 'Qué puede responder este registro, no se ha producido factura',
3036
3040
  dryRunParsed: (parsed, skipped) =>
3037
3041
  `${parsed} registros se leen; ${skipped} líneas no se pudieron leer. Un dry run no valora nada: el punto es sobre qué se apoyarían los gates que vas a cablear.`,
package/src/i18n/types.ts CHANGED
@@ -1825,6 +1825,18 @@ export interface CliMessages {
1825
1825
  * a skip: a total quietly missing a day is the failure this refuses.
1826
1826
  */
1827
1827
  badGzip(file: string, detail: string): string;
1828
+ /**
1829
+ * A file too large to hold whole, read line by line with its message
1830
+ * text set aside. Said, because a bill read differently from the others
1831
+ * should say how.
1832
+ */
1833
+ readInParts(file: string, megabytes: number, slimmed: number): string;
1834
+ /**
1835
+ * A file that even line by line, with its text set aside, is more than
1836
+ * one read can hold. An error naming the file and what to do, never the
1837
+ * runtime's own "Invalid string length".
1838
+ */
1839
+ tooLargeToRead(file: string, megabytes: number): string;
1828
1840
  /**
1829
1841
  * `--dry-run`: readiness per capability, no bill. The question somebody
1830
1842
  * has before wiring CI, answered without making them read a report to
package/src/index.ts CHANGED
@@ -2,11 +2,13 @@
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 type { FileHandle } from 'node:fs/promises';
5
6
  import { cpus, homedir, tmpdir } from 'node:os';
6
7
  import { createInterface } from 'node:readline/promises';
7
8
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
9
  import { fileURLToPath } from 'node:url';
9
- import { gunzipSync } from 'node:zlib';
10
+ import { createGunzip, gunzipSync } from 'node:zlib';
11
+ import { Readable } from 'node:stream';
10
12
 
11
13
  import {
12
14
  CONTRACT_NAMES,
@@ -118,6 +120,7 @@ import {
118
120
  looksLikeCodexTranscript,
119
121
  geminiCliRecords,
120
122
  looksLikeGeminiCliSession,
123
+ slimUsageLine,
121
124
  type CwdLabel,
122
125
  type WorkspaceLabel,
123
126
  type ProjectLabel,
@@ -599,14 +602,94 @@ async function usageIndexFrom(
599
602
  return indexUsage(records, { catalogue: pricing });
600
603
  }
601
604
 
605
+ /*
606
+ Past this many bytes a usage file is read line by line, its message text set
607
+ aside, rather than held as one string. JavaScript cannot hold a string much
608
+ past 512 MiB, and an agent session that read large files or ran chatty
609
+ commands outgrows that: reading one whole failed with the runtime's
610
+ "Invalid string length" and took the rest of the bill with it. The
611
+ environment variable exists so the tests can cross the line without writing
612
+ a quarter of a gigabyte.
613
+ */
614
+ const WHOLE_READ_MAX_BYTES = ((): number => {
615
+ const fromEnv = Number(process.env.TRAZUM_WHOLE_READ_MAX_BYTES);
616
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 256 * 1024 * 1024;
617
+ })();
618
+ /*
619
+ What the lines kept may add up to: under the runtime's own string ceiling
620
+ (just short of 512 MiB). Its own variable, for the same reason as the one
621
+ above: so the refusal can be tested without filling a disk.
622
+ */
623
+ const SLIMMED_MAX_CHARS = ((): number => {
624
+ const fromEnv = Number(process.env.TRAZUM_SLIMMED_MAX_CHARS);
625
+ return Number.isSafeInteger(fromEnv) && fromEnv > 0 ? fromEnv : 500 * 1024 * 1024;
626
+ })();
627
+ const megabytesOf = (bytes: number): number => Math.round(bytes / 1_000_000);
628
+
602
629
  async function readUsageLog(file: string, t: CliMessages): Promise<string> {
603
- if (!file.endsWith('.gz')) return readFile(file, 'utf8');
604
- const compressed = await readFile(file);
630
+ /*
631
+ One open file, measured and read through the same handle, so the size
632
+ that chose the path is the size of what is read: a stat by name and a
633
+ read by name could see two different files.
634
+ */
635
+ const handle = await open(file, 'r');
605
636
  try {
606
- return gunzipSync(compressed).toString('utf8');
637
+ return await readUsageHandle(handle, file, t);
638
+ } finally {
639
+ await handle.close();
640
+ }
641
+ }
642
+
643
+ async function readUsageHandle(handle: FileHandle, file: string, t: CliMessages): Promise<string> {
644
+ const size = (await handle.stat()).size;
645
+ if (!file.endsWith('.gz')) {
646
+ if (size <= WHOLE_READ_MAX_BYTES) return handle.readFile('utf8');
647
+ return readInParts(handle.createReadStream({ autoClose: false }), file, size, t);
648
+ }
649
+ const compressed = await handle.readFile();
650
+ let inflated: Buffer;
651
+ try {
652
+ // Bounded, so a file that inflates past the line is streamed rather than refused.
653
+ inflated = gunzipSync(compressed, { maxOutputLength: WHOLE_READ_MAX_BYTES });
607
654
  } catch (error) {
655
+ if (error instanceof RangeError && (error as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE') {
656
+ const gunzip = createGunzip();
657
+ let failure: Error | undefined;
658
+ gunzip.on('error', (cause: Error) => { failure = cause; });
659
+ Readable.from([compressed]).pipe(gunzip);
660
+ const text = await readInParts(gunzip, file, size, t);
661
+ if (failure !== undefined) throw new Error(t.profile.badGzip(file, failure.message));
662
+ return text;
663
+ }
608
664
  throw new Error(t.profile.badGzip(file, error instanceof Error ? error.message : String(error)));
609
665
  }
666
+ return inflated.toString('utf8');
667
+ }
668
+
669
+ /**
670
+ * A file too large to hold whole, line by line, each line with its long
671
+ * strings set aside by `slimUsageLine`: the converters read the same short
672
+ * fields from it that they would have read from the whole file.
673
+ */
674
+ async function readInParts(input: NodeJS.ReadableStream, file: string, size: number, t: CliMessages): Promise<string> {
675
+ const kept: string[] = [];
676
+ let held = 0;
677
+ let slimmed = 0;
678
+ try {
679
+ for await (const line of createInterface({ input, crlfDelay: Infinity })) {
680
+ const next = slimUsageLine(line);
681
+ if (next !== line) slimmed += 1;
682
+ held += next.length + 1;
683
+ if (held > SLIMMED_MAX_CHARS) throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
684
+ kept.push(next);
685
+ }
686
+ } catch (error) {
687
+ // A single line past the runtime's ceiling fails inside the line reader.
688
+ if (error instanceof RangeError) throw new Error(t.profile.tooLargeToRead(file, megabytesOf(size)));
689
+ throw error;
690
+ }
691
+ console.error(t.profile.readInParts(file, megabytesOf(size), slimmed));
692
+ return kept.join('\n');
610
693
  }
611
694
 
612
695
  function usageFrom(