@jjanczur/tyran 0.1.31 → 0.1.33

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/scripts/cost.mjs CHANGED
@@ -45,10 +45,27 @@ import { StringDecoder } from 'node:string_decoder';
45
45
  import { fileURLToPath } from 'node:url';
46
46
  import { parse } from './yaml-lite.mjs';
47
47
  import { pricingOf, PRICING_RATE_KEYS } from './schema.mjs';
48
+ import { defaultRateCard, RATE_CARD_ID, planOfTier, PLAN_LABELS, SUBSCRIPTION_USD, periodStart } from './pricing.mjs';
48
49
  import { jsonEscapeInvisible } from './invisible.mjs';
49
50
 
50
51
  export const COST_FILE = 'cost.json';
51
- export const COST_SCHEMA = 1;
52
+
53
+ /**
54
+ * The version of BOTH the served report and the per-source scan cache, which
55
+ * share this file. Bump it whenever a field is added to a cached source —
56
+ * `readCache` discards a cache whose schema differs, and that discard is the
57
+ * only thing that makes an added field appear for transcripts that have not
58
+ * changed since the last run.
59
+ *
60
+ * Measured when this was missed: `first_ts` was added, every unchanged
61
+ * transcript kept its cached record with no such field, and the reported span
62
+ * came back as ONE day instead of nineteen — a wrong number, not a missing
63
+ * one, and it would have made a monthly comparison off by a factor of 19.
64
+ *
65
+ * 2: sources carry `first_ts`; counters split `cache_write` by TTL.
66
+ * 3: sources carry `by_day`, without which every windowed figure reads zero.
67
+ */
68
+ export const COST_SCHEMA = 3;
52
69
 
53
70
  /** Read buffer for the chunked line reader. Transcripts reach tens of MB. */
54
71
  const CHUNK_BYTES = 1 << 20;
@@ -76,10 +93,10 @@ class UsageError extends Error {}
76
93
 
77
94
  /** A fresh counter set. Kept flat so accumulation is a loop, not a schema. */
78
95
  export function emptyCounters() {
79
- return { requests: 0, input: 0, cache_write: 0, cache_read: 0, output: 0 };
96
+ return { requests: 0, input: 0, cache_write: 0, cache_write_1h: 0, cache_read: 0, output: 0 };
80
97
  }
81
98
 
82
- const COUNTER_KEYS = Object.freeze(['requests', 'input', 'cache_write', 'cache_read', 'output']);
99
+ const COUNTER_KEYS = Object.freeze(['requests', 'input', 'cache_write', 'cache_write_1h', 'cache_read', 'output']);
83
100
 
84
101
  /** b into a, in place. */
85
102
  export function addCounters(a, b) {
@@ -87,9 +104,18 @@ export function addCounters(a, b) {
87
104
  return a;
88
105
  }
89
106
 
90
- /** Total tokens billed, whatever the rate. Requests are not tokens. */
107
+ /**
108
+ * Total tokens billed, whatever the rate. Requests are not tokens.
109
+ *
110
+ * `cache_write` and `cache_write_1h` are DISJOINT — the 5-minute and 1-hour
111
+ * halves of what the API reports as one `cache_creation_input_tokens` figure.
112
+ * Adding both is correct precisely because neither contains the other; if one
113
+ * were ever made a total, this line would double-count every cached token, and
114
+ * cache writes are the second-largest line in a real session. A test pins the
115
+ * partition against the raw aggregate rather than trusting this comment.
116
+ */
91
117
  export function tokensOf(counters) {
92
- return counters.input + counters.cache_write + counters.cache_read + counters.output;
118
+ return counters.input + counters.cache_write + counters.cache_write_1h + counters.cache_read + counters.output;
93
119
  }
94
120
 
95
121
  /** Own-property read on a prototype-free view of foreign JSON. */
@@ -103,6 +129,37 @@ function finiteCount(value) {
103
129
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
104
130
  }
105
131
 
132
+ /**
133
+ * Split one request's cache writes across the two rates they are billed at.
134
+ *
135
+ * `usage.cache_creation_input_tokens` is the TOTAL; `usage.cache_creation`
136
+ * carries the same number split into `ephemeral_5m_input_tokens` and
137
+ * `ephemeral_1h_input_tokens`. Reading both the total and the split would
138
+ * double-count, so this reads the split when it is present and the total
139
+ * otherwise — never both. Verified across 1168 consecutive live records: the
140
+ * two ephemeral fields summed to the aggregate every time, zero exceptions.
141
+ *
142
+ * The distinction is worth the code: a 1-hour write costs 2x base input where
143
+ * a 5-minute write costs 1.25x, so a session that caches for an hour — which
144
+ * is what a long agent run does — is 60% under-billed by the flat reading.
145
+ */
146
+ function addCacheWrites(into, usage) {
147
+ const split = field(usage, 'cache_creation');
148
+ if (split !== null && typeof split === 'object') {
149
+ const fiveMin = finiteCount(field(split, 'ephemeral_5m_input_tokens'));
150
+ const oneHour = finiteCount(field(split, 'ephemeral_1h_input_tokens'));
151
+ if (fiveMin > 0 || oneHour > 0) {
152
+ into.cache_write += fiveMin;
153
+ into.cache_write_1h += oneHour;
154
+ return;
155
+ }
156
+ }
157
+ // No split, or a split that is all zeroes while the aggregate is not: fall
158
+ // back to the total and attribute it to the 5-minute rate, which is the
159
+ // platform default TTL and therefore the right guess when nobody said.
160
+ into.cache_write += finiteCount(field(usage, 'cache_creation_input_tokens'));
161
+ }
162
+
106
163
  /**
107
164
  * What one request cost, in dollars, or null when the model has no rate.
108
165
  * Null is not zero and callers must not treat it as zero — that distinction
@@ -112,10 +169,26 @@ export function costOf(model, counters, models) {
112
169
  const rates = Object.prototype.hasOwnProperty.call(models, model) ? models[model] : undefined;
113
170
  if (rates === undefined) return null;
114
171
  let total = 0;
115
- for (const key of PRICING_RATE_KEYS) total += (counters[key] ?? 0) * rates[key];
172
+ for (const key of PRICING_RATE_KEYS) total += (counters[key] ?? 0) * rateOf(rates, key);
116
173
  return total / 1e6;
117
174
  }
118
175
 
176
+ /**
177
+ * One rate from a table that may predate a rate key.
178
+ *
179
+ * `pricingOf` already defaults `cache_write_1h` to the 5-minute rate, but this
180
+ * function is also handed tables built by hand — by tests, and by any caller
181
+ * using the exported `rollup` directly. A missing rate multiplied into the sum
182
+ * yields NaN, which propagates through every total and renders as an amount
183
+ * that is not a number rather than as a visible gap. Repeating the fallback
184
+ * here costs one line and removes that whole failure mode.
185
+ */
186
+ function rateOf(rates, key) {
187
+ const rate = rates[key];
188
+ if (typeof rate === 'number' && Number.isFinite(rate)) return rate;
189
+ return key === 'cache_write_1h' && typeof rates.cache_write === 'number' ? rates.cache_write : 0;
190
+ }
191
+
119
192
  /**
120
193
  * Sum a per-model table to dollars, counting only the models that have a rate.
121
194
  *
@@ -224,6 +297,16 @@ export function forEachLine(path, onLine, { maxBytes = Infinity } = {}) {
224
297
  */
225
298
  export function scanTranscript(path) {
226
299
  const byModel = Object.create(null);
300
+ // The same counters, bucketed by UTC day. This is what makes a window
301
+ // possible at all — a subscription is billed monthly, and a total summed
302
+ // over every transcript on the machine cannot be compared against a monthly
303
+ // price. It is also the per-day series, which nothing else could produce
304
+ // from a fold that only ever kept running totals.
305
+ //
306
+ // UTC, not local: two machines in different zones must attribute the same
307
+ // request to the same day, or the same journal produces two different
308
+ // series. The boundary is stated in the docs rather than left to be found.
309
+ const byDay = Object.create(null);
227
310
  const seen = new Set();
228
311
  let malformed = 0;
229
312
  let firstTs = null;
@@ -253,14 +336,34 @@ export function scanTranscript(path) {
253
336
  }
254
337
  const model = typeof field(message, 'model') === 'string' ? field(message, 'model') : 'unknown';
255
338
  if (byModel[model] === undefined) byModel[model] = emptyCounters();
256
- const into = byModel[model];
257
- into.requests += 1;
258
- into.input += finiteCount(field(usage, 'input_tokens'));
259
- into.cache_write += finiteCount(field(usage, 'cache_creation_input_tokens'));
260
- into.cache_read += finiteCount(field(usage, 'cache_read_input_tokens'));
261
- into.output += finiteCount(field(usage, 'output_tokens'));
339
+ // Written into BOTH tables from one read of the record, so the two can
340
+ // never disagree about a request. A record with no usable timestamp is
341
+ // counted in the total and omitted from the day buckets — the alternative
342
+ // is inventing a day for it, and a windowed figure built on an invented
343
+ // date is worse than one that is honestly short.
344
+ const day = dayOf(ts);
345
+ const into = [byModel[model]];
346
+ if (day !== null) {
347
+ if (byDay[day] === undefined) byDay[day] = Object.create(null);
348
+ if (byDay[day][model] === undefined) byDay[day][model] = emptyCounters();
349
+ into.push(byDay[day][model]);
350
+ }
351
+ for (const counters of into) {
352
+ counters.requests += 1;
353
+ counters.input += finiteCount(field(usage, 'input_tokens'));
354
+ addCacheWrites(counters, usage);
355
+ counters.cache_read += finiteCount(field(usage, 'cache_read_input_tokens'));
356
+ counters.output += finiteCount(field(usage, 'output_tokens'));
357
+ }
262
358
  });
263
- return { byModel, malformed, skippedLines, firstTs, lastTs };
359
+ return { byModel, byDay, malformed, skippedLines, firstTs, lastTs };
360
+ }
361
+
362
+ /** The UTC day of an ISO timestamp, `YYYY-MM-DD`, or null if unusable. */
363
+ export function dayOf(ts) {
364
+ if (typeof ts !== 'string' || ts.length < 10) return null;
365
+ const day = ts.slice(0, 10);
366
+ return /^\d{4}-\d{2}-\d{2}$/.test(day) && Number.isFinite(Date.parse(ts)) ? day : null;
264
367
  }
265
368
 
266
369
  /**
@@ -478,7 +581,9 @@ export function scanAll(sources, cache) {
478
581
  mtime_ms: stat.mtimeMs,
479
582
  size: stat.size,
480
583
  by_model: before.by_model,
584
+ by_day: before.by_day ?? null,
481
585
  last_ts: before.last_ts ?? null,
586
+ first_ts: before.first_ts ?? null,
482
587
  // Carried through the cache too: a damaged transcript stays damaged,
483
588
  // and a gap that disappears on the second render is worse than one
484
589
  // that was never reported.
@@ -499,7 +604,9 @@ export function scanAll(sources, cache) {
499
604
  mtime_ms: stat.mtimeMs,
500
605
  size: stat.size,
501
606
  by_model: result.byModel,
607
+ by_day: result.byDay,
502
608
  last_ts: result.lastTs,
609
+ first_ts: result.firstTs,
503
610
  malformed: result.malformed,
504
611
  skipped_lines: result.skippedLines,
505
612
  });
@@ -535,7 +642,12 @@ function rows(table, nameKey, models) {
535
642
  * argument, so the shape is testable without touching a filesystem.
536
643
  */
537
644
  export function rollup(scanned, pricing, extra = {}) {
538
- const { models, rate_card: rateCard } = pricing;
645
+ // The shipped list prices, for exactly the model ids these transcripts
646
+ // actually name, with any configured rate laid over the top. Computed here
647
+ // rather than in `costReport` so every caller of `rollup` — including the
648
+ // tests that hand it a literal scan — gets priced output without inventing
649
+ // a rate card first.
650
+ const { models, rate_card: rateCard } = effectiveRateCard(pricing, observedModels(scanned));
539
651
  const totals = emptyCounters();
540
652
  const totalsByModel = Object.create(null);
541
653
  const conductor = { byModel: Object.create(null), counters: emptyCounters() };
@@ -543,21 +655,42 @@ export function rollup(scanned, pricing, extra = {}) {
543
655
  const byAgentType = Object.create(null);
544
656
  const byTicket = Object.create(null);
545
657
  const unpriced = new Set();
658
+ // Per-UTC-day model counters across every source. This is both the series
659
+ // the Spend tab draws and the raw material any window is summed from.
660
+ const perDay = Object.create(null);
661
+ const window = extra.window ?? null;
546
662
  let agentTranscripts = 0;
547
663
  let attributed = 0;
548
664
  let newestTs = null;
665
+ let oldestTs = null;
549
666
  let malformed = 0;
550
667
  let skippedLines = 0;
668
+ let undated = 0;
551
669
 
552
670
  for (const source of scanned) {
553
671
  malformed += source.malformed ?? 0;
554
672
  skippedLines += source.skipped_lines ?? 0;
673
+ for (const [day, byDayModel] of Object.entries(source.by_day ?? {})) {
674
+ if (perDay[day] === undefined) perDay[day] = Object.create(null);
675
+ for (const [model, counters] of Object.entries(byDayModel)) {
676
+ if (perDay[day][model] === undefined) perDay[day][model] = emptyCounters();
677
+ addCounters(perDay[day][model], counters);
678
+ }
679
+ }
555
680
  if (source.kind === 'agent') agentTranscripts += 1;
556
681
  if (source.kind === 'agent' && source.ticket !== null) attributed += 1;
682
+ // The OLDEST record, not just the newest. Without it the report cannot say
683
+ // what period its total covers — and a total that does not name its period
684
+ // cannot honestly be compared against a monthly subscription price.
685
+ if (typeof source.first_ts === 'string' && (oldestTs === null || source.first_ts < oldestTs)) {
686
+ oldestTs = source.first_ts;
687
+ }
557
688
  if (typeof source.last_ts === 'string' && (newestTs === null || source.last_ts > newestTs)) {
558
689
  newestTs = source.last_ts;
559
690
  }
560
- for (const [model, counters] of Object.entries(source.by_model)) {
691
+ const restricted = windowedModels(source, window);
692
+ undated += restricted.undated;
693
+ for (const [model, counters] of Object.entries(restricted.models)) {
561
694
  addCounters(totals, counters);
562
695
  if (totalsByModel[model] === undefined) totalsByModel[model] = emptyCounters();
563
696
  addCounters(totalsByModel[model], counters);
@@ -583,7 +716,33 @@ export function rollup(scanned, pricing, extra = {}) {
583
716
  return {
584
717
  schema: COST_SCHEMA,
585
718
  rate_card: rateCard,
719
+ // Null whenever the plan cannot be established, and the board renders
720
+ // nothing at all in that case rather than a comparison against a guess.
721
+ subscription: extra.subscription ?? null,
586
722
  as_of: newestTs,
723
+ // The window these numbers actually describe. A subscription is billed
724
+ // MONTHLY; a total summed over every transcript on the machine is not a
725
+ // month of anything, and putting the two side by side without saying so
726
+ // invites a comparison that is off by however long the operator has been
727
+ // using the tool. Named, not implied.
728
+ covers: spanOf(oldestTs, newestTs),
729
+ // The window applied, or null for everything. `undated` is the count of
730
+ // sources a window could not place in time — reported rather than folded
731
+ // in, because a windowed total that quietly includes undatable spend is
732
+ // the error this feature exists to remove.
733
+ window: window === null ? null : { ...window, undated },
734
+ // The per-day series, priced. Ordered oldest first so a renderer can draw
735
+ // it without sorting, and always the FULL series regardless of the window
736
+ // — the window selects what the totals describe, not what the chart may
737
+ // show, and a chart that shrinks with the window cannot show you that
738
+ // last month was worse.
739
+ per_day: Object.keys(perDay)
740
+ .sort()
741
+ .map((day) => ({
742
+ day,
743
+ tokens: tokensOf(Object.values(perDay[day]).reduce(addCounters, emptyCounters())),
744
+ usd: costOfTable(perDay[day], models),
745
+ })),
587
746
  totals: {
588
747
  ...totals,
589
748
  tokens: tokensOf(totals),
@@ -660,15 +819,33 @@ function table(headers, body) {
660
819
  }
661
820
 
662
821
  /** The human report. */
822
+ /** The one line that says what period the total above describes. */
823
+ function periodLine(report) {
824
+ const window = report.window;
825
+ const covers = report.covers;
826
+ if (window === null) {
827
+ return covers === null
828
+ ? 'all time'
829
+ : `all time — ${covers.from.slice(0, 10)} to ${covers.to.slice(0, 10)}, ${covers.days} day(s)`;
830
+ }
831
+ const undated = window.undated > 0 ? `, ${window.undated} transcript(s) with no dates omitted` : '';
832
+ const name = window.name === 'period' ? 'this billing period' : 'last 30 days';
833
+ return `${name} — ${window.from} to ${window.to}${undated}`;
834
+ }
835
+
663
836
  export function renderReport(report) {
664
837
  const out = [];
665
838
  const card = report.rate_card === null ? 'no rate card — tokens only' : `rate card ${report.rate_card}`;
666
839
  out.push(`Spend — ${tokens(report.totals.tokens)} tokens, ${money(report.totals.usd)} (${card})`);
840
+ // The period, on the line with the number. Everything below is a breakdown
841
+ // of a total, and a total whose window is only visible in a flag someone
842
+ // typed a minute ago gets quoted without it.
843
+ out.push(periodLine(report));
667
844
  out.push('');
668
845
  out.push(
669
846
  table(
670
847
  ['what', 'tokens', 'usd'],
671
- report.composition.map((c) => [c.kind.replace('_', ' '), tokens(c.tokens), money(c.usd)])
848
+ report.composition.map((c) => [compositionLabel(c.kind), tokens(c.tokens), money(c.usd)])
672
849
  )
673
850
  );
674
851
  for (const [title, key, rowsOf] of [
@@ -729,6 +906,174 @@ function pricingOfDoc(doc) {
729
906
  return pricingOf(doc ?? {});
730
907
  }
731
908
 
909
+ /**
910
+ * The configured rate card laid over the shipped one.
911
+ *
912
+ * Before this, `pricing:` was hand-authored or absent, and absent was the
913
+ * normal case — a fresh install rendered every amount as an em dash, so the
914
+ * Spend tab could say how many tokens and never how much. Nobody was going to
915
+ * transcribe fourteen models × four rates into YAML, least of all the
916
+ * non-technical operators this is now for.
917
+ *
918
+ * Precedence is one-directional and per MODEL, not all-or-nothing: an operator
919
+ * who prices one model at a negotiated rate keeps the shipped numbers for the
920
+ * rest, rather than losing every other amount as the price of overriding one.
921
+ * The label follows whoever supplied the models — an amount computed from list
922
+ * prices must not claim to come from someone's private card.
923
+ */
924
+ /** Where Claude Code stores the account it is signed in as. */
925
+ export const CLAUDE_CONFIG_RELPATH = '.claude.json';
926
+
927
+ /** The windows the ledger can describe. `30d` is the default — see below. */
928
+ export const WINDOWS = Object.freeze(['30d', 'period', 'all']);
929
+
930
+ /**
931
+ * A named window as `{ name, from, to }` in UTC days, or null for `all`.
932
+ *
933
+ * `30d` is the DEFAULT rather than `period`, and deliberately: it needs
934
+ * nothing from the account, so it means the same thing on every machine, and
935
+ * it is directly comparable to a monthly price without the reader knowing
936
+ * when their subscription renews. `period` is the more precise answer and is
937
+ * offered only when the subscription date is actually readable — a period
938
+ * window guessed from a default anniversary would be wrong for 29 operators
939
+ * in 30.
940
+ */
941
+ export function resolveWindow(name, { now = new Date().toISOString(), subscriptionCreatedAt = null } = {}) {
942
+ const today = dayOf(now);
943
+ if (name === 'all' || today === null) return null;
944
+ if (name === 'period') {
945
+ const from = periodStart(subscriptionCreatedAt, now);
946
+ return from === null ? null : { name: 'period', from, to: today };
947
+ }
948
+ // 30 days INCLUSIVE of today, so the window is 30 days long rather than 31.
949
+ const from = dayOf(new Date(Date.parse(today) - 29 * 86_400_000).toISOString());
950
+ return from === null ? null : { name: '30d', from, to: today };
951
+ }
952
+
953
+ /**
954
+ * The subscription this machine is signed in on, or null when it cannot be
955
+ * established. Never throws — every figure on the Spend tab must survive an
956
+ * absent, unreadable or reshaped config.
957
+ *
958
+ * WHY THIS IS WORTH READING AT ALL: the API-equivalent total is a number with
959
+ * nothing to compare it against. A subscriber's marginal cost per token is
960
+ * zero, so "this cost $1,379" is true of the API and false of their bank
961
+ * account, and a dashboard that shows only the first number is inviting
962
+ * exactly the wrong conclusion. The plan is what turns it into a comparison.
963
+ *
964
+ * ONLY the rate-limit tier is read. That file also holds the account uuid, the
965
+ * email address and the organization id, and none of them are touched, copied
966
+ * into the report, or logged — a spend tile is not a reason to move identity
967
+ * around.
968
+ */
969
+ export function subscriptionOf({ home = homedir(), readFile = readFileSync } = {}) {
970
+ let tier = null;
971
+ let createdAt = null;
972
+ try {
973
+ const doc = JSON.parse(readFile(join(home, CLAUDE_CONFIG_RELPATH), 'utf8'));
974
+ const account = doc !== null && typeof doc === 'object' ? doc.oauthAccount : null;
975
+ if (account !== null && typeof account === 'object') {
976
+ tier = account.organizationRateLimitTier ?? null;
977
+ // The billing anniversary, and the only thing that makes a "this
978
+ // period" window mean the operator's actual period rather than a
979
+ // calendar month someone assumed.
980
+ createdAt = typeof account.subscriptionCreatedAt === 'string' ? account.subscriptionCreatedAt : null;
981
+ }
982
+ } catch {
983
+ // Not signed in, no config, unreadable, or not JSON. All the same answer.
984
+ return null;
985
+ }
986
+ const plan = planOfTier(tier);
987
+ if (plan === null) return null;
988
+ return { plan, label: PLAN_LABELS[plan], monthly_usd: SUBSCRIPTION_USD[plan], created_at: createdAt };
989
+ }
990
+
991
+ /**
992
+ * A rate key as a person would read it.
993
+ *
994
+ * Not `key.replace('_', ' ')`: that replaces only the FIRST underscore, so
995
+ * `cache_write_1h` renders as "cache write_1h" — visibly a variable name that
996
+ * escaped. The two cache-write rows also have to be distinguishable at a
997
+ * glance, since the whole reason they are separate is that one costs 60% more.
998
+ */
999
+ export function compositionLabel(kind) {
1000
+ if (kind === 'cache_write') return 'cache write (5 min)';
1001
+ if (kind === 'cache_write_1h') return 'cache write (1 hour)';
1002
+ return kind.replace(/_/g, ' ');
1003
+ }
1004
+
1005
+ /**
1006
+ * The period a report covers: `{ from, to, days }`, or null when there are no
1007
+ * timestamps to measure it from.
1008
+ *
1009
+ * `days` is inclusive of both ends and never below 1 — an hour of work is one
1010
+ * day of usage, not zero, and a zero would produce a division by zero the one
1011
+ * time someone normalises this to a monthly rate.
1012
+ */
1013
+ export function spanOf(from, to) {
1014
+ if (typeof from !== 'string' || typeof to !== 'string') return null;
1015
+ const start = Date.parse(from);
1016
+ const end = Date.parse(to);
1017
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return null;
1018
+ return { from, to, days: Math.max(1, Math.round((end - start) / 86_400_000)) };
1019
+ }
1020
+
1021
+ /**
1022
+ * One source's counters, restricted to a window — or its whole `by_model`
1023
+ * when there is no window.
1024
+ *
1025
+ * A source whose `by_day` is missing (an older cache, or records with no
1026
+ * usable timestamp) contributes NOTHING to a windowed figure, and the count
1027
+ * of such sources is reported as `undated`. The alternative — falling back to
1028
+ * the unwindowed totals — would silently put a year of spend inside a
1029
+ * thirty-day window, which is the exact error this whole feature exists to
1030
+ * remove.
1031
+ */
1032
+ function windowedModels(source, window) {
1033
+ if (window === null) return { models: source.by_model, undated: 0 };
1034
+ if (source.by_day === null || source.by_day === undefined) {
1035
+ return { models: Object.create(null), undated: 1 };
1036
+ }
1037
+ const models = Object.create(null);
1038
+ for (const [day, byModel] of Object.entries(source.by_day)) {
1039
+ if (day < window.from || day > window.to) continue;
1040
+ for (const [model, counters] of Object.entries(byModel)) {
1041
+ if (models[model] === undefined) models[model] = emptyCounters();
1042
+ addCounters(models[model], counters);
1043
+ }
1044
+ }
1045
+ return { models, undated: 0 };
1046
+ }
1047
+
1048
+ /** Every model id these scanned transcripts name, in no particular order. */
1049
+ function observedModels(scanned) {
1050
+ const ids = new Set();
1051
+ for (const source of scanned) {
1052
+ for (const id of Object.keys(source.by_model ?? {})) ids.add(id);
1053
+ }
1054
+ return ids;
1055
+ }
1056
+
1057
+ export function effectiveRateCard(pricing, modelIds) {
1058
+ const shipped = defaultRateCard(modelIds);
1059
+ const models = Object.create(null);
1060
+ for (const [id, rates] of Object.entries(shipped)) models[id] = rates;
1061
+ let overridden = 0;
1062
+ for (const [id, rates] of Object.entries(pricing.models)) {
1063
+ if (Object.prototype.hasOwnProperty.call(models, id)) overridden += 1;
1064
+ models[id] = rates;
1065
+ }
1066
+ const configured = Object.keys(pricing.models).length > 0;
1067
+ return {
1068
+ models,
1069
+ // A config's own label wins whenever it named one. Otherwise: the shipped
1070
+ // id, marked when a config has partly overridden it, so a reader can tell
1071
+ // a pure list-price figure from a mixed one.
1072
+ rate_card: pricing.rate_card ?? (configured ? `${RATE_CARD_ID}+config` : RATE_CARD_ID),
1073
+ overridden,
1074
+ };
1075
+ }
1076
+
732
1077
  function readCache(path) {
733
1078
  try {
734
1079
  const cached = JSON.parse(readFileSync(path, 'utf8'));
@@ -756,10 +1101,17 @@ function writeAtomic(path, text) {
756
1101
  * served board benefits too — cannot drift between the derived-dir path and
757
1102
  * the explicit-dirs path below.
758
1103
  */
759
- function finishReport({ sources, pricing, tyranDir, session, transcriptDirsUsed, transcriptDirsMissing }) {
1104
+ function finishReport({ sources, pricing, tyranDir, session, transcriptDirsUsed, transcriptDirsMissing, window: windowName }) {
760
1105
  const cachePath = join(tyranDir, 'state', COST_FILE);
761
1106
  const { scanned, unreadable, reused } = scanAll(sources, readCache(cachePath));
762
- const report = rollup(scanned, pricing, { unreadable, reused });
1107
+ const subscription = subscriptionOf();
1108
+ // Resolved HERE, where the subscription is already in hand: a `period`
1109
+ // window needs the billing anniversary, and asking every caller to fetch it
1110
+ // first would put the same read in three places.
1111
+ const window = resolveWindow(windowName ?? 'all', {
1112
+ subscriptionCreatedAt: subscription?.created_at ?? null,
1113
+ });
1114
+ const report = rollup(scanned, pricing, { unreadable, reused, subscription, window });
763
1115
  report.transcripts_found = true;
764
1116
  report.transcript_dirs = transcriptDirsUsed;
765
1117
  report.transcript_dirs_missing = transcriptDirsMissing;
@@ -772,9 +1124,15 @@ function finishReport({ sources, pricing, tyranDir, session, transcriptDirsUsed,
772
1124
  agent_type: s.agent_type ?? null,
773
1125
  ticket: s.ticket ?? null,
774
1126
  last_ts: s.last_ts ?? null,
1127
+ // This projection is a WHITELIST, so a field added to the scan and not
1128
+ // added here is computed, cached as absent, and read back as null on
1129
+ // every subsequent run — which is how the reported span came back as one
1130
+ // day instead of nineteen.
1131
+ first_ts: s.first_ts ?? null,
775
1132
  malformed: s.malformed ?? 0,
776
1133
  skipped_lines: s.skipped_lines ?? 0,
777
1134
  by_model: s.by_model,
1135
+ by_day: s.by_day ?? null,
778
1136
  }));
779
1137
  // Persisting is the whole point of the cache, and it has to happen HERE
780
1138
  // rather than only in the `--json` branch: the board server calls this per
@@ -822,7 +1180,7 @@ function finishReport({ sources, pricing, tyranDir, session, transcriptDirsUsed,
822
1180
  * missing the report reads exactly like "no transcripts found" — gaps are
823
1181
  * reported, never zeroed (property 3 above).
824
1182
  */
825
- export function costReport({ tyranDir, projectsRoot, session = null, repoRoot = null, transcriptDirs = [] } = {}) {
1183
+ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot = null, transcriptDirs = [], window = 'all' } = {}) {
826
1184
  const root = repoRoot ?? resolve(tyranDir, '..');
827
1185
  // Read ONCE and handed to both readers below: `pricingOfDoc` and
828
1186
  // `spendTranscriptDirsOf` used to each open and parse config.yaml
@@ -841,7 +1199,7 @@ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot =
841
1199
  const present = explicit.filter((d) => existsSync(d));
842
1200
  const missing = explicit.filter((d) => !existsSync(d));
843
1201
  if (present.length === 0) {
844
- const empty = rollup([], pricing, {});
1202
+ const empty = rollup([], pricing, { subscription: subscriptionOf() });
845
1203
  empty.transcripts_found = false;
846
1204
  empty.transcript_dirs = [];
847
1205
  empty.transcript_dirs_missing = missing;
@@ -855,12 +1213,13 @@ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot =
855
1213
  session,
856
1214
  transcriptDirsUsed: present,
857
1215
  transcriptDirsMissing: missing,
1216
+ window,
858
1217
  });
859
1218
  }
860
1219
 
861
1220
  const dir = transcriptDirFor(root, projectsRoot ?? join(homedir(), '.claude', 'projects'));
862
1221
  if (dir === null) {
863
- const empty = rollup([], pricing, {});
1222
+ const empty = rollup([], pricing, { subscription: subscriptionOf() });
864
1223
  empty.transcripts_found = false;
865
1224
  empty.transcript_dirs = [];
866
1225
  empty.transcript_dirs_missing = [];
@@ -873,11 +1232,12 @@ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot =
873
1232
  session,
874
1233
  transcriptDirsUsed: [dir],
875
1234
  transcriptDirsMissing: [],
1235
+ window,
876
1236
  });
877
1237
  }
878
1238
 
879
1239
  function parseArgs(argv) {
880
- const flags = { dir: '.tyran', session: null, projects: null, json: false, transcripts: [] };
1240
+ const flags = { dir: '.tyran', session: null, projects: null, json: false, transcripts: [], window: 'all' };
881
1241
  for (let i = 0; i < argv.length; i += 1) {
882
1242
  const arg = argv[i];
883
1243
  if (arg === '--json') flags.json = true;
@@ -887,6 +1247,14 @@ function parseArgs(argv) {
887
1247
  // Repeatable: sources are the union over every directory given.
888
1248
  flags.transcripts.push(value);
889
1249
  i += 1;
1250
+ } else if (arg === '--window') {
1251
+ const value = argv[i + 1];
1252
+ // Validated against the closed list HERE rather than deep in the report:
1253
+ // an operator who mistypes a window should be told, not handed the
1254
+ // all-time total under a name they thought meant something narrower.
1255
+ if (!WINDOWS.includes(value)) throw new UsageError(`--window must be one of ${WINDOWS.join(' | ')}`);
1256
+ flags.window = value;
1257
+ i += 1;
890
1258
  } else if (arg === '--dir' || arg === '--session' || arg === '--projects') {
891
1259
  const value = argv[i + 1];
892
1260
  if (value === undefined || value.startsWith('--')) throw new UsageError(`${arg} needs a value`);
@@ -905,7 +1273,7 @@ function main(argv) {
905
1273
  console.error(String(err.message ?? err));
906
1274
  console.error(
907
1275
  'usage: cost.mjs [--dir <.tyran>] [--session <id>] [--projects <dir>] ' +
908
- '[--transcripts <dir>]... [--json]'
1276
+ '[--transcripts <dir>]... [--window 30d|period|all] [--json]'
909
1277
  );
910
1278
  return 2;
911
1279
  }
@@ -919,6 +1287,7 @@ function main(argv) {
919
1287
  projectsRoot: flags.projects,
920
1288
  session: flags.session,
921
1289
  transcriptDirs: flags.transcripts,
1290
+ window: flags.window,
922
1291
  });
923
1292
  if (report.transcripts_found === false) {
924
1293
  // Two different gaps, two different sentences: a `--transcripts` (or