@trazum/cli 2.5.0 → 2.5.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.
Files changed (64) hide show
  1. package/README.md +75 -6
  2. package/dist/filter.d.ts +2 -0
  3. package/dist/filter.d.ts.map +1 -0
  4. package/dist/filter.js +151 -0
  5. package/dist/filter.js.map +1 -0
  6. package/dist/gateway-server.d.ts +2 -0
  7. package/dist/gateway-server.d.ts.map +1 -1
  8. package/dist/gateway-server.js +49 -9
  9. package/dist/gateway-server.js.map +1 -1
  10. package/dist/gateway-spend.d.ts +32 -0
  11. package/dist/gateway-spend.d.ts.map +1 -0
  12. package/dist/gateway-spend.js +116 -0
  13. package/dist/gateway-spend.js.map +1 -0
  14. package/dist/html.d.ts.map +1 -1
  15. package/dist/html.js +25 -2
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +50 -6
  19. package/dist/i18n/en.js.map +1 -1
  20. package/dist/i18n/es.d.ts.map +1 -1
  21. package/dist/i18n/es.js +51 -6
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +28 -1
  24. package/dist/i18n/types.d.ts.map +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +225 -41
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts +7 -0
  29. package/dist/markdown.d.ts.map +1 -1
  30. package/dist/markdown.js +24 -2
  31. package/dist/markdown.js.map +1 -1
  32. package/dist/pdf.d.ts.map +1 -1
  33. package/dist/pdf.js +41 -2
  34. package/dist/pdf.js.map +1 -1
  35. package/dist/serve-savings-schema.d.ts +65 -0
  36. package/dist/serve-savings-schema.d.ts.map +1 -0
  37. package/dist/serve-savings-schema.js +54 -0
  38. package/dist/serve-savings-schema.js.map +1 -0
  39. package/dist/serve-savings.d.ts +55 -0
  40. package/dist/serve-savings.d.ts.map +1 -0
  41. package/dist/serve-savings.js +144 -0
  42. package/dist/serve-savings.js.map +1 -0
  43. package/dist/serve-schema.d.ts +536 -0
  44. package/dist/serve-schema.d.ts.map +1 -0
  45. package/dist/serve-schema.js +143 -0
  46. package/dist/serve-schema.js.map +1 -0
  47. package/dist/serve.d.ts.map +1 -1
  48. package/dist/serve.js +30 -5
  49. package/dist/serve.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/filter.ts +114 -0
  52. package/src/gateway-server.ts +46 -10
  53. package/src/gateway-spend.ts +120 -0
  54. package/src/html.ts +27 -2
  55. package/src/i18n/en.ts +57 -7
  56. package/src/i18n/es.ts +58 -7
  57. package/src/i18n/types.ts +29 -1
  58. package/src/index.ts +227 -43
  59. package/src/markdown.ts +32 -2
  60. package/src/pdf.ts +38 -2
  61. package/src/serve-savings-schema.ts +53 -0
  62. package/src/serve-savings.ts +140 -0
  63. package/src/serve-schema.ts +147 -0
  64. package/src/serve.ts +31 -5
@@ -0,0 +1,120 @@
1
+ import { indexUsage, parseUsageLine, usageFromResponse } from '@trazum/core';
2
+ import type { GatewayCall, GatewayDecision, GatewayStanding, MeasuredPosition, PricingCatalogue } from '@trazum/core';
3
+
4
+ type GatewayUsage = NonNullable<ReturnType<typeof usageFromResponse>>;
5
+
6
+ type Admitted = Exclude<GatewayDecision, { kind: 'refuse' }>;
7
+ const DAY_MS = 86_400_000;
8
+ const empty = (): MeasuredPosition => ({ dayUsd: null, sessionUsd: null, labelUsd: null });
9
+
10
+ /** Process-local additions to a startup snapshot. Reservations are never measured spend. */
11
+ export class GatewaySpend {
12
+ private usd = 0;
13
+ private unknown = false;
14
+ private days = new Map<number, number>();
15
+ private labels = new Map<string, number>();
16
+ private sessions = new Map<string, number>();
17
+ private pending = new Map<symbol, { call: GatewayCall; usd: number | null }>();
18
+ private started = Date.now();
19
+
20
+ constructor(private catalogue: PricingCatalogue) {}
21
+
22
+ standing(base: GatewayStanding | null): GatewayStanding | null {
23
+ // A new month's imported balance is unknown until the operator reloads it.
24
+ const start = new Date(this.started);
25
+ const now = new Date();
26
+ if (this.unknown || start.getUTCMonth() !== now.getUTCMonth() || start.getUTCFullYear() !== now.getUTCFullYear()) return null;
27
+ return base === null ? null : { ...base, consumedUsd: base.consumedUsd + this.usd };
28
+ }
29
+
30
+ position(base: MeasuredPosition, call: GatewayCall): MeasuredPosition {
31
+ if (this.unknown) return empty();
32
+ const day = Math.floor(Date.now() / DAY_MS) * DAY_MS;
33
+ const add = (base: number | null, delta: number): number | null => base === null ? null : base + delta;
34
+ // Do not carry yesterday's spend into today's daily allowance.
35
+ const dayBase = base.dayWindow && base.dayWindow.toMs <= day ? 0 : base.dayUsd;
36
+ return {
37
+ ...base,
38
+ dayUsd: add(dayBase, this.days.get(day) ?? 0),
39
+ dayWindow: dayBase === null ? null : { fromMs: day, toMs: day + DAY_MS },
40
+ labelUsd: add(base.labelUsd, call.label === null ? 0 : this.labels.get(call.label) ?? 0),
41
+ sessionUsd: add(base.sessionUsd, call.session === null ? 0 : this.sessions.get(call.session) ?? 0),
42
+ };
43
+ }
44
+
45
+ /** Synchronous check + reservation: no await can admit two calls against the same remainder. */
46
+ reserve(call: GatewayCall, decision: Admitted, standing: GatewayStanding | null, failClosed: boolean):
47
+ { ticket: symbol; refusal?: never } | { ticket?: never; refusal: Record<string, unknown> } {
48
+ const pending = [...this.pending.values()];
49
+ const unknown = pending.some((entry) => entry.usd === null);
50
+ const estimate = decision.estimatedUsd;
51
+ const unbounded = estimate === null || !Number.isFinite(estimate) || estimate < 0 ||
52
+ call.maxOutputTokens === null || !Number.isFinite(call.maxOutputTokens) || call.maxOutputTokens < 0;
53
+ const sum = (matches: (entry: typeof pending[number]) => boolean): number =>
54
+ pending.filter(matches).reduce((total, entry) => total + (entry.usd ?? 0), 0);
55
+ const reservedUsd = sum(() => true);
56
+ // Configured substitution explicitly permits continued spending past the monthly cap.
57
+ const globalOver = decision.kind !== 'substitute' && standing !== null && estimate !== null &&
58
+ standing.consumedUsd + reservedUsd + estimate > standing.limitUsd;
59
+ const scopeOver = decision.policy.judgements.some((entry) => {
60
+ if (entry.waived !== null || entry.measuredUsd === null || estimate === null) return false;
61
+ const reserved = sum((pending) => entry.scope === 'day' ||
62
+ (entry.scope === 'label' ? pending.call.label === call.label : pending.call.session === call.session));
63
+ return entry.measuredUsd + reserved + estimate > entry.limitUsd;
64
+ });
65
+ if (((unknown || unbounded) && failClosed) || globalOver || scopeOver) {
66
+ return { refusal: {
67
+ schemaVersion: 1,
68
+ error: { type: 'trazum_budget_refusal', message: unbounded
69
+ ? 'This call has no bounded cost; provide a valid output-token limit before spending.'
70
+ : unknown
71
+ ? 'An in-flight call has no bounded cost; wait for its usage before spending again.'
72
+ : 'In-flight calls have reserved the remaining budget.' },
73
+ reason: unbounded ? 'call-unbounded' : unknown ? 'in-flight-unmeasured' : 'budget-reserved',
74
+ standing, reservedUsd, estimatedUsd: estimate, policy: decision.policy,
75
+ } };
76
+ }
77
+ const ticket = Symbol();
78
+ this.pending.set(ticket, { call, usd: unbounded ? null : estimate });
79
+ return { ticket };
80
+ }
81
+
82
+ settle(ticket: symbol, model: string, usage: GatewayUsage | null): void {
83
+ const pending = this.pending.get(ticket);
84
+ if (pending === undefined) return;
85
+ this.pending.delete(ticket);
86
+ const writesKnown = usage !== null && (usage.cacheWriteTokens === 0 ||
87
+ (usage.cacheWrite5mTokens !== undefined && usage.cacheWrite1hTokens !== undefined &&
88
+ usage.cacheWrite5mTokens + usage.cacheWrite1hTokens === usage.cacheWriteTokens));
89
+ if (usage === null || !writesKnown ||
90
+ Object.values(usage).some((value) => !Number.isFinite(value) || value < 0)) {
91
+ // A flat write count has no TTL. Assuming 5m undercharges a 1h write.
92
+ this.unknown = true;
93
+ return;
94
+ }
95
+ const now = Date.now();
96
+ const record = parseUsageLine(JSON.stringify({
97
+ model, ts: new Date(now).toISOString(),
98
+ input_tokens: usage.inputTokens, output_tokens: usage.outputTokens,
99
+ cache_read_input_tokens: usage.cacheReadTokens,
100
+ cache_creation_input_tokens: usage.cacheWriteTokens,
101
+ cache_creation: {
102
+ ephemeral_5m_input_tokens: usage.cacheWrite5mTokens ?? 0,
103
+ ephemeral_1h_input_tokens: usage.cacheWrite1hTokens ?? 0,
104
+ },
105
+ }));
106
+ const index = record === null ? null : indexUsage([record], { catalogue: this.catalogue, on: new Date(now) });
107
+ if (index === null || index.unpriced > 0 || index.dayUsd === null) {
108
+ this.unknown = true;
109
+ return;
110
+ }
111
+ const usd = index.dayUsd;
112
+ this.usd += usd;
113
+ const day = Math.floor(now / DAY_MS) * DAY_MS;
114
+ this.days.set(day, (this.days.get(day) ?? 0) + usd);
115
+ if (pending.call.label !== null) this.labels.set(pending.call.label, (this.labels.get(pending.call.label) ?? 0) + usd);
116
+ if (pending.call.session !== null) this.sessions.set(pending.call.session, (this.sessions.get(pending.call.session) ?? 0) + usd);
117
+ }
118
+
119
+ release(ticket: symbol): void { this.pending.delete(ticket); }
120
+ }
package/src/html.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { UNLABELLED, formatUsd, sharesOf } from '@trazum/core';
1
+ import { UNLABELLED, formatUsd, sharesOf, spendByMonth } from '@trazum/core';
2
2
  import type { PositionDocument, RollupDocument, UsageBreakdown } from '@trazum/core';
3
3
  import type { CliMessages } from './i18n/index.js';
4
4
  import { tierCeilingCaveat } from './markdown.js';
@@ -96,7 +96,7 @@ function breakdownTable(rows: Row[], totalUsd: number, t: ProfileMarkdownInput['
96
96
 
97
97
  /** The profile as one self-contained page. Same input as the Markdown door. */
98
98
  export function renderProfileHtml(input: ProfileMarkdownInput): string {
99
- const { report, levers, cache, t, gates, window, stalePricing } = input;
99
+ const { report, levers, cache, t, gates, window, stalePricing, apiEquivalent } = input;
100
100
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
101
101
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
102
102
  const showLabel = (label: string): string => (label === UNLABELLED ? t.profile.unlabelled() : label);
@@ -154,6 +154,7 @@ export function renderProfileHtml(input: ProfileMarkdownInput): string {
154
154
  if (stalePricing !== undefined) {
155
155
  caveats.push(esc(t.profile.pricesStale(stalePricing.date, stalePricing.days)));
156
156
  }
157
+ if (apiEquivalent === true) caveats.push(esc(t.bill.apiEquivalent()));
157
158
  if (caveats.length > 0) {
158
159
  parts.push(
159
160
  `<div class="caveats"><h2>${esc(t.html.caveatsHeading())}</h2><ul>${caveats
@@ -186,6 +187,30 @@ export function renderProfileHtml(input: ProfileMarkdownInput): string {
186
187
  ),
187
188
  );
188
189
 
190
+ /*
191
+ * By month, once the report spans two: a document handed to whoever pays
192
+ * for a year of use answers which month cost what. Every month, oldest
193
+ * first, since a page has room the terminal's twelve rows do not; and the
194
+ * part with no clock said under it, so the rows do not add up short of the
195
+ * total in silence.
196
+ */
197
+ const { months, undated } = spendByMonth(report);
198
+ if (months.length >= 2) {
199
+ parts.push(`<h2>${esc(t.html.byMonthHeading())}</h2>`);
200
+ const body = months
201
+ .map(({ month, calls, usd }) => {
202
+ const share = report.total.totalUsd > 0 ? pct(usd / report.total.totalUsd) : '—';
203
+ return `<tr><td>${esc(month)}</td><td class="n">${n(calls)}</td><td class="n">${esc(formatUsd(usd))}</td><td class="n">${share}</td></tr>`;
204
+ })
205
+ .join('\n');
206
+ parts.push(
207
+ `<table><thead><tr><th>${esc(t.bill.colMonth())}</th><th class="n">${esc(t.html.colCalls())}</th><th class="n">USD</th><th class="n">%</th></tr></thead><tbody>\n${body}\n</tbody></table>`,
208
+ );
209
+ if (undated.calls > 0) {
210
+ parts.push(`<p class="muted">${esc(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)))}</p>`);
211
+ }
212
+ }
213
+
189
214
  // The findings, as the sentences the terminal already says — the copy is
190
215
  // the product's, not this file's, so the two surfaces cannot drift apart.
191
216
  const findings: string[] = [];
package/src/i18n/en.ts CHANGED
@@ -59,10 +59,11 @@ ${bold('USAGE')}
59
59
  trazum schema <contract>
60
60
  trazum rollup <document...|dir> [--json] [--html-out <file>]
61
61
  trazum position <usage.jsonl>
62
- trazum receipt <usage.jsonl|dir> [--stamp] [-o <file>]
62
+ trazum receipt <usage.jsonl|dir> [--stamp] [--since <when>] [--until <when>] [-o <file>]
63
63
  trazum bill [<file|dir>...] [--label <name>] [--no-label-from-project] [--receipt|--table] [--stamp] [-o <file>]
64
- [--pdf-out|--html-out|--markdown-out|--csv-out <file>]
64
+ [--since <when>] [--until <when>] [--pdf-out|--html-out|--markdown-out|--csv-out <file>]
65
65
  trazum from-claude-code <file|dir> [--label <name>] [-o <file>]
66
+ trazum from-codex <file|dir> [--label <name>] [-o <file>]
66
67
  trazum from-otel <file|dir> [--label-from-service] [-o <file>]
67
68
  trazum from-litellm <file|dir> [-o <file>]
68
69
  trazum from-anthropic <usage.json> [--label <name>] [--label-by-workspace <file>] [-o <file>]
@@ -87,6 +88,7 @@ ${bold('USAGE')}
87
88
  trazum owners <log>
88
89
  trazum ladder <log>
89
90
  trazum feedback
91
+ trazum filter compact|restore|instructions [--recovery-dir <directory>]
90
92
  trazum --version
91
93
 
92
94
  ${bold('OPTIONS FOR init')}
@@ -226,6 +228,12 @@ ${bold('OPTIONS FOR from-openai')}
226
228
  ${bold('OPTIONS FOR bill')}
227
229
  --label <name> The project this usage belongs to, for the
228
230
  shapes that take one.
231
+ --since <when> Bill only the calls in this period: a UTC day
232
+ --until <when> (2026-10-01), a full ISO 8601 timestamp, a
233
+ relative window (30d, 24h) or "now". A bare day
234
+ means the whole of it. Calls with no timestamp
235
+ cannot be placed and are left out, counted on
236
+ the receipt as a gap, never dropped silently.
229
237
  --stamp Stamp the receipt with the time it was written.
230
238
  -o, --out <file> Write the receipt there instead of stdout.
231
239
 
@@ -299,6 +307,15 @@ ${bold('OPTIONS FOR from-otel')}
299
307
  verdicts read "cannot tell" rather than a guessed one. Non-LLM spans are
300
308
  counted and skipped, said on stderr.
301
309
 
310
+ ${bold('OPTIONS FOR from-codex')}
311
+ --label <name> Stamp every record with one label.
312
+ -o, --out <file> Write normalized usage instead of stdout.
313
+
314
+ Read an explicit Codex rollout file or directory, locally. Corroborated
315
+ counters only: replayed snapshots collapse, ambiguous usage is excluded.
316
+ Conversion gaps are reported on stderr. Prices are API equivalents,
317
+ never your subscription invoice. Prompt content is discarded.
318
+
302
319
  ${bold('OPTIONS FOR from-claude-code')}
303
320
  --label <name> Stamp every record with one label.
304
321
  --label-from-project Label each record with its transcript's project
@@ -335,6 +352,10 @@ ${bold('OPTIONS FOR receipt')}
335
352
  output. The summary always goes to standard
336
353
  error, so a redirect writes a document and not a
337
354
  document with a summary stapled to the front.
355
+ --since <when> The period the receipt covers, as bill takes it:
356
+ --until <when> a UTC day, a timestamp, 30d or "now". Calls with
357
+ no timestamp are left out and named as an
358
+ undated-excluded gap.
338
359
  --pricing <file> Price it with your own card instead of the
339
360
  bundled catalogue.
340
361
  --pricing-live Price it against live rates via OpenRouter.
@@ -407,6 +428,10 @@ ${bold('OPTIONS FOR rules')}
407
428
  "Inert" is always said about the corpus. A rule that finds nothing in these
408
429
  files has not been shown to find nothing anywhere.
409
430
 
431
+ ${bold('OPTIONS FOR filter')}
432
+ --recovery-dir <directory> Private recovery directory; required for compact/restore.
433
+ Run trazum filter --help for the opt-in stdin log-filter workflow.
434
+
410
435
  ${bold('OPTIONS FOR feedback')}
411
436
  (none)
412
437
 
@@ -1301,7 +1326,7 @@ ${bold('EXAMPLES')}
1301
1326
  diff: () => 'Diff',
1302
1327
  tokensOnlyHeading: (host) => `What this buys on ${host}`,
1303
1328
  tokensOnlyWhy: (host) =>
1304
- `${host} bills by subscription, so there is no bill to reduce and no monthly figure to print.`,
1329
+ `${host} identifies the tool, not your payment mode. Tokens are shown by default; invoice savings are unknown.`,
1305
1330
  tokensOnlyAsked: () => 'Costs hidden because you asked for tokens only.',
1306
1331
  // `tokens` arrives already formatted for the locale, so the singular is
1307
1332
  // decided on the string rather than on a number that is no longer here.
@@ -1877,9 +1902,22 @@ ${bold('EXAMPLES')}
1877
1902
  unread: (count) => `${count} line(s) of the log could not be read, and the receipt says so.`,
1878
1903
  noClock: () =>
1879
1904
  'The log carries no clock, so the receipt is unbounded in time and states that rather than inventing a period.',
1905
+ undatedExcluded: (calls) =>
1906
+ `${count(calls)} ${calls === 1 ? 'call carries' : 'calls carry'} no timestamp and cannot be placed in this period, so ${calls === 1 ? 'it is' : 'they are'} not in this bill: the total is a floor on the period.`,
1880
1907
  nothingToBill: () => 'Nothing in this log could be priced, so the receipt has no lines.',
1881
1908
  },
1882
1909
 
1910
+ fromCodex: {
1911
+ noPath: () => 'from-codex needs an explicit rollout file or directory: trazum from-codex ./sessions',
1912
+ notFound: (path) => `Cannot read ${path}`,
1913
+ noFiles: (path) => `No JSONL rollout files in ${path}`,
1914
+ noUsage: () => 'No attributable Codex usage. Inspect the named gaps; no zero-cost log was written.',
1915
+ summary: (files, records, duplicates) => `${files} Codex file(s), ${records} corroborated usage record(s), ${duplicates} repeated snapshot(s) collapsed.`,
1916
+ gaps: (missingModel, unsupported, unparseable) => `Codex gaps: ${missingModel} without model context, ${unsupported} unsupported or uncorroborated snapshots, ${unparseable} unreadable lines. These are not zero-cost calls.`,
1917
+ caveat: () => 'Codex telemetry is priced at catalogue API rates, not your subscription invoice. Restored totals, counter resets and ambiguous deltas are excluded, not guessed.',
1918
+ written: (file) => `Wrote normalized usage to ${file}`,
1919
+ },
1920
+
1883
1921
  fromOtel: {
1884
1922
  noPath: () => 'from-otel needs an OTLP file or directory: trazum from-otel spans.json',
1885
1923
  notFound: (path) => `${path}: not found`,
@@ -2019,6 +2057,11 @@ ${bold('EXAMPLES')}
2019
2057
  colCalls: () => 'calls',
2020
2058
  colShare: () => 'share',
2021
2059
  moreRows: (count) => `… and ${count} more`,
2060
+ colMonth: () => 'month',
2061
+ earlierMonths: (count) => `… and ${count} earlier month(s)`,
2062
+ monthsUndated: (calls, usd) =>
2063
+ `${usd} from ${calls} call(s) with no timestamp is in the total and in no month.`,
2064
+ monthHint: (since, until) => `One month on its own: --since ${since} --until ${until}.`,
2022
2065
  statementUnpriced: (models, calls) =>
2023
2066
  `Not in the total: ${calls} call(s) to ${models}, which the catalogue does not price. Named, never counted as $0.`,
2024
2067
  statementUnread: (lines) => `${lines} line(s) could not be read as usage and are not in the total.`,
@@ -2037,7 +2080,13 @@ ${bold('EXAMPLES')}
2037
2080
  nothingRead: () => 'Nothing here was a usage source this tool reads, so there is nothing to bill.',
2038
2081
  sources: (read, seen) => `${read} of ${seen} file(s) read as usage.`,
2039
2082
  pricingLiveHint: (count) =>
2040
- `${count} unpriced model id(s) are OpenRouter slugs, which the bundled catalogue does not carry. Run again with --pricing-live to price them from OpenRouter's own list.`,
2083
+ `${count} unpriced model id(s) carry a provider prefix, the way OpenRouter and LiteLLM name models, and the bundled catalogue does not carry those. Run again with --pricing-live to price OpenRouter's slugs from its own list.`,
2084
+ apiEquivalent: () =>
2085
+ 'Claude Code and Codex transcripts are priced at catalogue API rates. On a subscription you paid the plan, not this API-equivalent estimate; missing telemetry and custom rates can change the result.',
2086
+ prefixedKnown: (ids) =>
2087
+ `${ids}: the model after the slash is priced here under its own name. The prefix is not stripped for you, because the same model through a router can bill differently. If those calls went straight to the provider, log the model without the prefix.`,
2088
+ windowMatchesNothing: (from, to) =>
2089
+ `No call falls inside this period. What was read covers ${from} → ${to}. A period with nothing in it is not a $0 bill: check the dates, or leave --since/--until off to bill everything.`,
2041
2090
  written: (file) => `Wrote ${file}.`,
2042
2091
  },
2043
2092
 
@@ -2226,6 +2275,7 @@ ${bold('EXAMPLES')}
2226
2275
  noSessions: () => 'No record carried a session, so conversation growth and per-conversation costs are not in this report.',
2227
2276
  byLabelHeading: () => 'By workload',
2228
2277
  byModelHeading: () => 'By model',
2278
+ byMonthHeading: () => 'By month',
2229
2279
  findingsHeading: () => 'What would move this bill',
2230
2280
  colLabel: () => 'workload',
2231
2281
  colModel: () => 'model',
@@ -2285,8 +2335,8 @@ ${bold('EXAMPLES')}
2285
2335
 
2286
2336
  where: {
2287
2337
  hostHeading: () => 'Running inside',
2288
- subscription: (host) =>
2289
- `${host} bills by subscription, not by the token. A monthly saving below is arithmetic about tokens, not money you get back, what you gain is context window and rate-limit headroom.`,
2338
+ billingUnknown: (host) =>
2339
+ `${host} identifies the execution host only. Payment mode is unknown; token prices do not establish invoice savings.`,
2290
2340
  noTarget: () => 'Pass a source file to see which provider its prompts are sent to.',
2291
2341
  sourceHeading: (path) => `Prompts in ${path} go to`,
2292
2342
  conflict: () => 'Cannot tell: the file names more than one provider.',
@@ -3062,7 +3112,7 @@ ${bold('EXAMPLES')}
3062
3112
  sinceAfterUntil: () =>
3063
3113
  '--since is at or after --until, so the window contains no time at all. Check the two dates.',
3064
3114
  badWhen: (flag, value) =>
3065
- `--${flag} could not read "${value}". It takes a UTC day (2026-08-14) or a full ISO 8601 timestamp (2026-08-14T09:30:00Z).`,
3115
+ `--${flag} could not read "${value}". It takes a UTC day (2026-08-14), a full ISO 8601 timestamp (2026-08-14T09:30:00Z), a relative window (7d, 24h) or "now".`,
3066
3116
  singleTurnCeiling: (label, model, single, sessions, usd) =>
3067
3117
  `${label} on ${model}: ${single} of ${sessions} conversations ended after their first turn, and their cache writes, ${usd}, paid for reuse their own conversation never made. Another conversation sharing the same prefix within the TTL could have read them; the log cannot see whose write a read hit, so that figure is a ceiling on the waste, not a bill.`,
3068
3118
  singleTurnConfirmed: (label, model, single, sessions, usd) =>
package/src/i18n/es.ts CHANGED
@@ -46,10 +46,11 @@ ${bold('USO')}
46
46
  trazum schema <contrato>
47
47
  trazum rollup <documento...|dir> [--json] [--html-out <fichero>]
48
48
  trazum position <uso.jsonl>
49
- trazum receipt <uso.jsonl|dir> [--stamp] [-o <fichero>]
49
+ trazum receipt <uso.jsonl|dir> [--stamp] [--since <cuándo>] [--until <cuándo>] [-o <fichero>]
50
50
  trazum bill [<fichero|dir>...] [--label <nombre>] [--no-label-from-project] [--receipt|--table] [--stamp] [-o <fichero>]
51
- [--pdf-out|--html-out|--markdown-out|--csv-out <fichero>]
51
+ [--since <cuándo>] [--until <cuándo>] [--pdf-out|--html-out|--markdown-out|--csv-out <fichero>]
52
52
  trazum from-claude-code <fichero|dir> [--label <nombre>] [-o <fichero>]
53
+ trazum from-codex <fichero|dir> [--label <nombre>] [-o <fichero>]
53
54
  trazum from-otel <fichero|dir> [--label-from-service] [-o <fichero>]
54
55
  trazum from-litellm <fichero|dir> [-o <fichero>]
55
56
  trazum from-anthropic <usage.json> [--label <name>] [--label-by-workspace <file>] [-o <file>]
@@ -74,6 +75,7 @@ ${bold('USO')}
74
75
  trazum owners <log>
75
76
  trazum ladder <log>
76
77
  trazum feedback
78
+ trazum filter compact|restore|instructions [--recovery-dir <directory>]
77
79
  trazum --version
78
80
 
79
81
  ${bold('OPCIONES DE init')}
@@ -140,6 +142,10 @@ ${bold('OPCIONES DE receipt')}
140
142
  estándar, así que una redirección escribe un
141
143
  documento y no un documento con un resumen
142
144
  pegado delante.
145
+ --since <cuándo> El periodo que cubre el recibo, como lo toma
146
+ --until <cuándo> bill: un día UTC, una marca de tiempo, 30d o
147
+ "now". Las llamadas sin marca de tiempo quedan
148
+ fuera y se nombran como hueco undated-excluded.
143
149
  --pricing <fichero> Lo precia con tu propia tarjeta de precios en
144
150
  vez de con el catálogo incluido.
145
151
  --pricing-live Lo precia con tarifas en vivo vía OpenRouter.
@@ -253,6 +259,13 @@ ${bold('OPCIONES DE from-openai')}
253
259
  ${bold('OPCIONES DE bill')}
254
260
  --label <nombre> El proyecto al que pertenece este uso, para las
255
261
  formas que lo admiten.
262
+ --since <cuándo> Factura solo las llamadas de este periodo: un día
263
+ --until <cuándo> UTC (2026-10-01), una marca ISO 8601 completa,
264
+ una ventana relativa (30d, 24h) o "now". Un día
265
+ solo significa el día entero. Las llamadas sin
266
+ marca de tiempo no se pueden situar y quedan
267
+ fuera, contadas en el recibo como hueco, nunca
268
+ tiradas en silencio.
256
269
  --stamp Sella el recibo con la hora en que se escribió.
257
270
  -o, --out <archivo> Escribe el recibo ahí en vez de en stdout.
258
271
 
@@ -333,6 +346,15 @@ ${bold('OPCIONES DE from-otel')}
333
346
  puede saber" en vez de uno inventado. Los spans que no son de LLM se cuentan
334
347
  y se omiten, dicho en stderr.
335
348
 
349
+ ${bold('OPCIONES DE from-codex')}
350
+ --label <nombre> Marca cada registro con una etiqueta.
351
+ -o, --out <fichero> Escribe el uso normalizado en vez de stdout.
352
+
353
+ Lee un archivo o directorio de Codex indicado explícitamente, en local.
354
+ Solo contadores corroborados: colapsa duplicados y excluye uso ambiguo.
355
+ Los huecos se indican en stderr. Los precios son equivalentes API,
356
+ nunca tu factura de suscripción. El contenido de prompts se descarta.
357
+
336
358
  ${bold('OPCIONES DE from-claude-code')}
337
359
  --label <nombre> Marca cada registro con una etiqueta.
338
360
  --label-from-project Etiqueta cada registro con el nombre del
@@ -410,6 +432,10 @@ ${bold('OPCIONES DE rules')}
410
432
  "Inerte" se dice siempre sobre el corpus. Una regla que no encuentra nada en
411
433
  estos ficheros no ha demostrado no encontrar nada en ninguna parte.
412
434
 
435
+ ${bold('OPCIONES DE filter')}
436
+ --recovery-dir <directorio> Directorio privado; obligatorio para compact/restore.
437
+ trazum filter --help explica el filtro opcional (ayuda en inglés).
438
+
413
439
  ${bold('OPCIONES DE feedback')}
414
440
  (ninguna)
415
441
 
@@ -1342,7 +1368,7 @@ ${bold('EJEMPLOS')}
1342
1368
  diff: () => 'Diff',
1343
1369
  tokensOnlyHeading: (host) => `Qué ganas con esto en ${host}`,
1344
1370
  tokensOnlyWhy: (host) =>
1345
- `${host} cobra por suscripción, así que no hay factura que reducir ni cifra mensual que imprimir.`,
1371
+ `${host} identifica la herramienta, no tu forma de pago. Se muestran tokens por defecto; el ahorro en factura es desconocido.`,
1346
1372
  tokensOnlyAsked: () => 'Costes ocultos porque has pedido solo tokens.',
1347
1373
  tokensSaved: (tokens) =>
1348
1374
  `${tokens} token${tokens === '1' ? '' : 's'} de vuelta, en cada llamada.`,
@@ -1905,9 +1931,22 @@ ${bold('EJEMPLOS')}
1905
1931
  unread: (count) => `${count} línea(s) del log no se pudieron leer, y el recibo lo dice.`,
1906
1932
  noClock: () =>
1907
1933
  'El log no lleva reloj, así que el recibo no está acotado en el tiempo y lo declara en vez de inventarse un periodo.',
1934
+ undatedExcluded: (calls) =>
1935
+ `${count(calls)} ${calls === 1 ? 'llamada no trae' : 'llamadas no traen'} marca de tiempo y no se ${calls === 1 ? 'puede' : 'pueden'} situar en este periodo, así que no ${calls === 1 ? 'está' : 'están'} en esta factura: el total es un suelo del periodo.`,
1908
1936
  nothingToBill: () => 'Nada de este log se pudo precificar, así que el recibo no tiene líneas.',
1909
1937
  },
1910
1938
 
1939
+ fromCodex: {
1940
+ noPath: () => 'from-codex necesita una ruta explícita: trazum from-codex ./sesiones',
1941
+ notFound: (path) => `No se puede leer ${path}`,
1942
+ noFiles: (path) => `No hay archivos JSONL en ${path}`,
1943
+ noUsage: () => 'No hay uso de Codex atribuible. Revisa los huecos indicados; no se escribió un registro de coste cero.',
1944
+ summary: (files, records, duplicates) => `${files} archivo(s) Codex, ${records} registro(s) corroborados, ${duplicates} instantáneas repetidas descartadas.`,
1945
+ gaps: (missingModel, unsupported, unparseable) => `Huecos Codex: ${missingModel} sin contexto de modelo, ${unsupported} instantáneas no admitidas o sin corroborar, ${unparseable} líneas ilegibles. No son llamadas de coste cero.`,
1946
+ caveat: () => 'La telemetría Codex se valora a tarifas API del catálogo, no como factura de suscripción. Totales restaurados, reinicios y deltas ambiguos quedan excluidos.',
1947
+ written: (file) => `Registro normalizado escrito en ${file}`,
1948
+ },
1949
+
1911
1950
  fromOtel: {
1912
1951
  noPath: () => 'from-otel necesita un archivo o directorio OTLP: trazum from-otel spans.json',
1913
1952
  notFound: (path) => `${path}: no existe`,
@@ -2047,6 +2086,11 @@ ${bold('EJEMPLOS')}
2047
2086
  colCalls: () => 'llamadas',
2048
2087
  colShare: () => 'parte',
2049
2088
  moreRows: (count) => `… y ${count} más`,
2089
+ colMonth: () => 'mes',
2090
+ earlierMonths: (count) => `… y ${count} mes(es) anterior(es)`,
2091
+ monthsUndated: (calls, usd) =>
2092
+ `${usd} de ${calls} llamada(s) sin marca de tiempo está en el total y en ningún mes.`,
2093
+ monthHint: (since, until) => `Un mes por separado: --since ${since} --until ${until}.`,
2050
2094
  statementUnpriced: (models, calls) =>
2051
2095
  `Fuera del total: ${calls} llamada(s) a ${models}, que el catálogo no tiene con precio. Se nombran, nunca se cuentan como $0.`,
2052
2096
  statementUnread: (lines) => `${lines} línea(s) no se pudieron leer como uso y no están en el total.`,
@@ -2065,7 +2109,13 @@ ${bold('EJEMPLOS')}
2065
2109
  nothingRead: () => 'Nada de esto era una fuente de uso que esta herramienta lea, así que no hay nada que facturar.',
2066
2110
  sources: (read, seen) => `${read} de ${seen} archivo(s) leído(s) como uso.`,
2067
2111
  pricingLiveHint: (count) =>
2068
- `${count} id(s) de modelo sin precio son slugs de OpenRouter, que el catálogo incluido no trae. Vuelve a ejecutar con --pricing-live para cobrarlos desde la propia lista de OpenRouter.`,
2112
+ `${count} id(s) de modelo sin precio llevan prefijo de proveedor, como nombran los modelos OpenRouter y LiteLLM, y el catálogo incluido no los trae. Vuelve a ejecutar con --pricing-live para cobrar los slugs de OpenRouter desde su propia lista.`,
2113
+ apiEquivalent: () =>
2114
+ 'Las sesiones de Claude Code y Codex se valoran a tarifas API del catálogo. Si pagas una suscripción, pagaste el plan, no esta estimación equivalente; los datos ausentes y las tarifas propias pueden cambiar el resultado.',
2115
+ prefixedKnown: (ids) =>
2116
+ `${ids}: el modelo tras la barra tiene precio aquí con su propio nombre. El prefijo no se quita por ti, porque el mismo modelo a través de un router puede facturarse distinto. Si esas llamadas fueron directas al proveedor, registra el modelo sin el prefijo.`,
2117
+ windowMatchesNothing: (from, to) =>
2118
+ `Ninguna llamada cae dentro de este periodo. Lo leído cubre ${from} → ${to}. Un periodo sin nada dentro no es una factura de $0: revisa las fechas, o quita --since/--until para facturarlo todo.`,
2069
2119
  written: (file) => `Escrito ${file}.`,
2070
2120
  },
2071
2121
 
@@ -2255,6 +2305,7 @@ ${bold('EJEMPLOS')}
2255
2305
  noSessions: () => 'Ningún registro traía sesión, así que el crecimiento de conversación y los costes por conversación no están en este informe.',
2256
2306
  byLabelHeading: () => 'Por carga de trabajo',
2257
2307
  byModelHeading: () => 'Por modelo',
2308
+ byMonthHeading: () => 'Por mes',
2258
2309
  findingsHeading: () => 'Qué movería esta factura',
2259
2310
  colLabel: () => 'carga',
2260
2311
  colModel: () => 'modelo',
@@ -2314,8 +2365,8 @@ ${bold('EJEMPLOS')}
2314
2365
 
2315
2366
  where: {
2316
2367
  hostHeading: () => 'Ejecutándose dentro de',
2317
- subscription: (host) =>
2318
- `${host} cobra por suscripción, no por token. Un ahorro mensual de los de abajo es aritmética sobre tokens, no dinero que recuperes: lo que ganas es margen de ventana de contexto y de rate limit.`,
2368
+ billingUnknown: (host) =>
2369
+ `${host} solo identifica el entorno de ejecución. La forma de pago es desconocida; los precios por token no demuestran ahorro en factura.`,
2319
2370
  noTarget: () => 'Pasa un fichero fuente para ver a qué proveedor van sus prompts.',
2320
2371
  sourceHeading: (path) => `Los prompts de ${path} van a`,
2321
2372
  conflict: () => 'No se puede saber: el fichero nombra más de un proveedor.',
@@ -3088,7 +3139,7 @@ ${bold('EJEMPLOS')}
3088
3139
  sinceAfterUntil: () =>
3089
3140
  '--since es igual o posterior a --until, así que la ventana no contiene tiempo alguno. Revisa las dos fechas.',
3090
3141
  badWhen: (flag, value) =>
3091
- `--${flag} no pudo leer "${value}". Acepta un día UTC (2026-08-14) o una marca ISO 8601 completa (2026-08-14T09:30:00Z).`,
3142
+ `--${flag} no pudo leer "${value}". Acepta un día UTC (2026-08-14), una marca ISO 8601 completa (2026-08-14T09:30:00Z), una ventana relativa (7d, 24h) o "now".`,
3092
3143
  singleTurnCeiling: (label, model, single, sessions, usd) =>
3093
3144
  `${label} en ${model}: ${single} de ${sessions} conversaciones terminaron tras su primer turno, y sus escrituras de caché (${usd}) pagaron una reutilización que su propia conversación nunca hizo. Otra conversación con el mismo prefijo dentro del TTL pudo haberlas leído; el registro no puede ver de quién era la escritura que una lectura encontró, así que esa cifra es un techo del desperdicio, no una factura.`,
3094
3145
  singleTurnConfirmed: (label, model, single, sessions, usd) =>
package/src/i18n/types.ts CHANGED
@@ -620,9 +620,22 @@ export interface CliMessages {
620
620
  unpriced(models: number, calls: number): string;
621
621
  unread(count: number): string;
622
622
  noClock(): string;
623
+ /** Calls a --since/--until window left out because they carry no timestamp. */
624
+ undatedExcluded(calls: number): string;
623
625
  nothingToBill(): string;
624
626
  };
625
627
 
628
+ fromCodex: {
629
+ noPath(): string;
630
+ notFound(path: string): string;
631
+ noFiles(path: string): string;
632
+ noUsage(): string;
633
+ summary(files: number, records: number, duplicates: number): string;
634
+ gaps(missingModel: number, unsupported: number, unparseable: number): string;
635
+ caveat(): string;
636
+ written(file: string): string;
637
+ };
638
+
626
639
  fromOtel: {
627
640
  noPath(): string;
628
641
  notFound(path: string): string;
@@ -747,6 +760,13 @@ export interface CliMessages {
747
760
  colCalls(): string;
748
761
  colShare(): string;
749
762
  moreRows(count: number): string;
763
+ /** The by-month table, shown when a bill spans two calendar months or more. */
764
+ colMonth(): string;
765
+ earlierMonths(count: number): string;
766
+ /** Priced calls with no timestamp: in the total, in no month. */
767
+ monthsUndated(calls: number, usd: string): string;
768
+ /** How to bill the newest month on its own. */
769
+ monthHint(since: string, until: string): string;
750
770
  statementUnpriced(models: string, calls: number): string;
751
771
  statementUnread(lines: number): string;
752
772
  statementNext(): string;
@@ -764,6 +784,12 @@ export interface CliMessages {
764
784
  sources(read: number, seen: number): string;
765
785
  /** An unpriced slug with a slash is OpenRouter's, and --pricing-live prices it. */
766
786
  pricingLiveHint(count: number): string;
787
+ /** Prefixed ids whose part after the slash the catalogue prices under its own name. */
788
+ prefixedKnown(ids: string): string;
789
+ /** Claude Code transcripts are priced at API list rates; on a plan, that is not what was paid. */
790
+ apiEquivalent(): string;
791
+ /** A --since/--until window no record falls in: refused, never a $0 bill. */
792
+ windowMatchesNothing(from: string, to: string): string;
767
793
  written(file: string): string;
768
794
  };
769
795
 
@@ -911,6 +937,8 @@ export interface CliMessages {
911
937
  noSessions(): string;
912
938
  byLabelHeading(): string;
913
939
  byModelHeading(): string;
940
+ /** Shown once a report spans two calendar months; the column is `bill.colMonth`. */
941
+ byMonthHeading(): string;
914
942
  findingsHeading(): string;
915
943
  colLabel(): string;
916
944
  colModel(): string;
@@ -962,7 +990,7 @@ export interface CliMessages {
962
990
 
963
991
  where: {
964
992
  hostHeading(): string;
965
- subscription(host: string): string;
993
+ billingUnknown(host: string): string;
966
994
  noTarget(): string;
967
995
  sourceHeading(path: string): string;
968
996
  conflict(): string;