@trazum/core 2.6.0 → 2.7.0

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/usage.ts CHANGED
@@ -799,6 +799,20 @@ export function parseUsageLine(line: string): UsageRecord | null {
799
799
  const geminiCached = geminiMeta
800
800
  ? readCount(geminiMeta.cachedContentTokenCount)
801
801
  : ({ kind: 'absent' } as Count);
802
+ /**
803
+ * The two Gemini counts that sit outside `promptTokenCount` and
804
+ * `candidatesTokenCount` and are still billed. The SDK's own definitions
805
+ * (`@google/genai`, `UsageMetadata`): `thoughtsTokenCount` is "the model's
806
+ * generated 'thoughts' output", priced as output, and
807
+ * `toolUsePromptTokenCount` is "the results from tool executions, which are
808
+ * provided back to the model as input", priced as input; and
809
+ * `totalTokenCount` "is the sum of prompt, candidates, tool-use prompt and
810
+ * thoughts". Reading only the first two priced every thinking model's
811
+ * reasoning at zero: on Gemini 2.5 Pro and 3.1 Pro that is often most of the
812
+ * output, and it was the flattering direction.
813
+ */
814
+ const geminiThoughts = geminiMeta ? readCount(geminiMeta.thoughtsTokenCount) : ({ kind: 'absent' } as Count);
815
+ const geminiToolPrompt = geminiMeta ? readCount(geminiMeta.toolUsePromptTokenCount) : ({ kind: 'absent' } as Count);
802
816
 
803
817
  const counts: Record<string, Count> = {
804
818
  input: readCount(
@@ -818,6 +832,8 @@ export function parseUsageLine(line: string): UsageRecord | null {
818
832
  openAiCached,
819
833
  openAiWrite,
820
834
  geminiCached,
835
+ geminiThoughts,
836
+ geminiToolPrompt,
821
837
  write5m,
822
838
  write1h,
823
839
  };
@@ -848,7 +864,7 @@ export function parseUsageLine(line: string): UsageRecord | null {
848
864
 
849
865
  return {
850
866
  model,
851
- inputTokens: Math.max(0, valueOf(counts.input!) - cached - openAiWritten),
867
+ inputTokens: Math.max(0, valueOf(counts.input!) - cached - openAiWritten) + valueOf(counts.geminiToolPrompt!),
852
868
  cacheReadTokens: counts.cacheRead!.kind === 'ok' ? counts.cacheRead!.value : cached,
853
869
  /**
854
870
  * The split when the log carries it, the flat number otherwise — and
@@ -859,7 +875,7 @@ export function parseUsageLine(line: string): UsageRecord | null {
859
875
  cacheWrite1hTokens: hasSplit ? split1h : 0,
860
876
  // `cache_write_tokens` names no TTL either; see the note in `profileUsage`.
861
877
  writeTtlKnown: hasSplit || (flatWrite === 0 && openAiWritten === 0),
862
- outputTokens: valueOf(counts.output!),
878
+ outputTokens: valueOf(counts.output!) + valueOf(counts.geminiThoughts!),
863
879
  /**
864
880
  * Trimmed and internally normalised: any whitespace run becomes one space.
865
881
  * A label is a workload name, and it is also used as half of structured keys
@@ -1593,6 +1609,97 @@ export function spendByMonth(report: Pick<UsageProfileReport, 'spendByDay' | 'to
1593
1609
  };
1594
1610
  }
1595
1611
 
1612
+ /** The calendar unit a bill is split by. Weeks are ISO weeks: Monday to Sunday, UTC. */
1613
+ export type BillPeriodUnit = 'day' | 'week' | 'month';
1614
+
1615
+ /** One period of a bill, UTC. */
1616
+ export interface PeriodSpend {
1617
+ /** `YYYY-MM-DD` for a day, `YYYY-Www` (ISO) for a week, `YYYY-MM` for a month. */
1618
+ period: string;
1619
+ /** The first and last UTC day of the period, the `--since`/`--until` that bill it alone. */
1620
+ firstDay: string;
1621
+ lastDay: string;
1622
+ calls: number;
1623
+ usd: number;
1624
+ }
1625
+
1626
+ /** A bill by day, week or month, and the part of it that sits in no period. */
1627
+ export interface SpendByPeriod {
1628
+ unit: BillPeriodUnit;
1629
+ /** Oldest first. Only periods with priced, dated calls appear. */
1630
+ periods: PeriodSpend[];
1631
+ /** Priced calls with no clock: in the total and in no period. */
1632
+ undated: { calls: number; usd: number };
1633
+ }
1634
+
1635
+ const isoDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
1636
+
1637
+ /** ISO 8601 week of a UTC day: the week belongs to the year of its Thursday. */
1638
+ function isoWeekOf(day: string): { key: string; monday: string; sunday: string } {
1639
+ const ms = Date.parse(`${day}T00:00:00Z`);
1640
+ const weekday = (new Date(ms).getUTCDay() + 6) % 7; // Monday = 0
1641
+ const monday = ms - weekday * 86_400_000;
1642
+ const thursday = new Date(monday + 3 * 86_400_000);
1643
+ const year = thursday.getUTCFullYear();
1644
+ const firstThursday = Date.UTC(year, 0, 4);
1645
+ const firstMonday = firstThursday - ((new Date(firstThursday).getUTCDay() + 6) % 7) * 86_400_000;
1646
+ const week = Math.round((monday - firstMonday) / (7 * 86_400_000)) + 1;
1647
+ return { key: `${year}-W${String(week).padStart(2, '0')}`, monday: isoDay(monday), sunday: isoDay(monday + 6 * 86_400_000) };
1648
+ }
1649
+
1650
+ /**
1651
+ * A bill by calendar day, ISO week or month, summed from the report's own days.
1652
+ *
1653
+ * The same rules as `spendByMonth`, which is this with `month`: UTC, priced
1654
+ * calls with a clock only, and the undated remainder returned beside the
1655
+ * periods so they reconcile to the total. A week is ISO 8601's, Monday to
1656
+ * Sunday, numbered by the year its Thursday falls in, so the last days of
1657
+ * December can belong to week 1 of the next year, as every ISO calendar says.
1658
+ */
1659
+ export function spendByPeriod(
1660
+ report: Pick<UsageProfileReport, 'spendByDay' | 'total'>,
1661
+ unit: BillPeriodUnit,
1662
+ ): SpendByPeriod {
1663
+ const byPeriod = new Map<string, { firstDay: string; lastDay: string; calls: number; usd: number }>();
1664
+ for (const day of report.spendByDay) {
1665
+ let key: string;
1666
+ let firstDay: string;
1667
+ let lastDay: string;
1668
+ if (unit === 'day') {
1669
+ key = day.day;
1670
+ firstDay = day.day;
1671
+ lastDay = day.day;
1672
+ } else if (unit === 'week') {
1673
+ const week = isoWeekOf(day.day);
1674
+ key = week.key;
1675
+ firstDay = week.monday;
1676
+ lastDay = week.sunday;
1677
+ } else {
1678
+ key = day.day.slice(0, 7);
1679
+ const [year, monthNumber] = key.split('-').map(Number);
1680
+ firstDay = `${key}-01`;
1681
+ lastDay = new Date(Date.UTC(year ?? 1970, monthNumber ?? 1, 0)).toISOString().slice(0, 10);
1682
+ }
1683
+ const entry = byPeriod.get(key) ?? { firstDay, lastDay, calls: 0, usd: 0 };
1684
+ entry.calls += day.calls;
1685
+ entry.usd += day.usd;
1686
+ byPeriod.set(key, entry);
1687
+ }
1688
+ const periods = [...byPeriod.entries()]
1689
+ .sort(([, a], [, b]) => a.firstDay.localeCompare(b.firstDay))
1690
+ .map(([period, { firstDay, lastDay, calls, usd }]) => ({ period, firstDay, lastDay, calls, usd }));
1691
+ const dated = periods.reduce((sum, p) => ({ calls: sum.calls + p.calls, usd: sum.usd + p.usd }), { calls: 0, usd: 0 });
1692
+ const undatedCalls = report.total.calls - dated.calls;
1693
+ return {
1694
+ unit,
1695
+ periods,
1696
+ undated:
1697
+ undatedCalls > 0
1698
+ ? { calls: undatedCalls, usd: Math.max(0, report.total.totalUsd - dated.usd) }
1699
+ : { calls: 0, usd: 0 },
1700
+ };
1701
+ }
1702
+
1596
1703
  /**
1597
1704
  * How much of the input that could have been cached was.
1598
1705
  *