@trazum/cli 3.0.1 → 3.0.3

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 (109) hide show
  1. package/README.md +4 -1
  2. package/assets/trazum-statusline.sh +45 -0
  3. package/dist/base-cost.d.ts +173 -0
  4. package/dist/base-cost.d.ts.map +1 -0
  5. package/dist/base-cost.js +244 -0
  6. package/dist/base-cost.js.map +1 -0
  7. package/dist/bill-range.d.ts +118 -0
  8. package/dist/bill-range.d.ts.map +1 -0
  9. package/dist/bill-range.js +122 -0
  10. package/dist/bill-range.js.map +1 -0
  11. package/dist/command-help.d.ts +17 -0
  12. package/dist/command-help.d.ts.map +1 -0
  13. package/dist/command-help.js +69 -0
  14. package/dist/command-help.js.map +1 -0
  15. package/dist/filter.d.ts +7 -1
  16. package/dist/filter.d.ts.map +1 -1
  17. package/dist/filter.js +10 -18
  18. package/dist/filter.js.map +1 -1
  19. package/dist/gateway-metrics.d.ts +83 -0
  20. package/dist/gateway-metrics.d.ts.map +1 -0
  21. package/dist/gateway-metrics.js +181 -0
  22. package/dist/gateway-metrics.js.map +1 -0
  23. package/dist/gateway-server.d.ts +23 -5
  24. package/dist/gateway-server.d.ts.map +1 -1
  25. package/dist/gateway-server.js +26 -1
  26. package/dist/gateway-server.js.map +1 -1
  27. package/dist/gateway-spend.d.ts +11 -1
  28. package/dist/gateway-spend.d.ts.map +1 -1
  29. package/dist/gateway-spend.js +44 -32
  30. package/dist/gateway-spend.js.map +1 -1
  31. package/dist/git.d.ts +70 -0
  32. package/dist/git.d.ts.map +1 -1
  33. package/dist/git.js +145 -0
  34. package/dist/git.js.map +1 -1
  35. package/dist/i18n/en.d.ts.map +1 -1
  36. package/dist/i18n/en.js +358 -6
  37. package/dist/i18n/en.js.map +1 -1
  38. package/dist/i18n/es.d.ts +0 -1
  39. package/dist/i18n/es.d.ts.map +1 -1
  40. package/dist/i18n/es.js +456 -35
  41. package/dist/i18n/es.js.map +1 -1
  42. package/dist/i18n/types.d.ts +205 -0
  43. package/dist/i18n/types.d.ts.map +1 -1
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +942 -59
  46. package/dist/index.js.map +1 -1
  47. package/dist/loopback-guard.d.ts +37 -0
  48. package/dist/loopback-guard.d.ts.map +1 -0
  49. package/dist/loopback-guard.js +65 -0
  50. package/dist/loopback-guard.js.map +1 -0
  51. package/dist/markdown.d.ts +23 -0
  52. package/dist/markdown.d.ts.map +1 -1
  53. package/dist/markdown.js +105 -0
  54. package/dist/markdown.js.map +1 -1
  55. package/dist/plan-edits.d.ts +63 -0
  56. package/dist/plan-edits.d.ts.map +1 -0
  57. package/dist/plan-edits.js +96 -0
  58. package/dist/plan-edits.js.map +1 -0
  59. package/dist/proactive.d.ts +17 -2
  60. package/dist/proactive.d.ts.map +1 -1
  61. package/dist/proactive.js +16 -9
  62. package/dist/proactive.js.map +1 -1
  63. package/dist/receipt-send.d.ts +44 -0
  64. package/dist/receipt-send.d.ts.map +1 -0
  65. package/dist/receipt-send.js +71 -0
  66. package/dist/receipt-send.js.map +1 -0
  67. package/dist/serve.d.ts +7 -0
  68. package/dist/serve.d.ts.map +1 -1
  69. package/dist/serve.js +22 -1
  70. package/dist/serve.js.map +1 -1
  71. package/dist/session-guard.d.ts +210 -0
  72. package/dist/session-guard.d.ts.map +1 -0
  73. package/dist/session-guard.js +463 -0
  74. package/dist/session-guard.js.map +1 -0
  75. package/dist/task.d.ts +7 -1
  76. package/dist/task.d.ts.map +1 -1
  77. package/dist/task.js +7 -26
  78. package/dist/task.js.map +1 -1
  79. package/dist/waste.d.ts +25 -0
  80. package/dist/waste.d.ts.map +1 -0
  81. package/dist/waste.js +39 -0
  82. package/dist/waste.js.map +1 -0
  83. package/dist/zone.d.ts +27 -0
  84. package/dist/zone.d.ts.map +1 -0
  85. package/dist/zone.js +96 -0
  86. package/dist/zone.js.map +1 -0
  87. package/package.json +2 -2
  88. package/src/base-cost.ts +384 -0
  89. package/src/bill-range.ts +206 -0
  90. package/src/command-help.ts +65 -0
  91. package/src/filter.ts +11 -18
  92. package/src/gateway-metrics.ts +209 -0
  93. package/src/gateway-server.ts +43 -6
  94. package/src/gateway-spend.ts +45 -33
  95. package/src/git.ts +158 -0
  96. package/src/i18n/en.ts +424 -6
  97. package/src/i18n/es.ts +542 -35
  98. package/src/i18n/types.ts +208 -0
  99. package/src/index.ts +952 -58
  100. package/src/loopback-guard.ts +74 -0
  101. package/src/markdown.ts +117 -0
  102. package/src/plan-edits.ts +120 -0
  103. package/src/proactive.ts +22 -13
  104. package/src/receipt-send.ts +89 -0
  105. package/src/serve.ts +23 -1
  106. package/src/session-guard.ts +541 -0
  107. package/src/task.ts +8 -26
  108. package/src/waste.ts +42 -0
  109. package/src/zone.ts +95 -0
package/README.md CHANGED
@@ -88,13 +88,15 @@ trazum bill
88
88
  | `trazum baseline [dir]` | what the prompts cost now, recorded to a file you commit |
89
89
  | `trazum profile <log\|dir>` | where the money actually went — reads a usage log (or a directory of rotated ones, `.gz` included), not a prompt. `--against` compares to the previous log; `--what-if <model>` prices these exact calls at another rate card; `--label`/`--since`/`--until` drill down; `--max-usd`/`--max-day-usd`/`--max-growth-usd`/`--max-cache-loss-usd` gate the spend; `--json`/`--csv-out`/`--markdown-out` for pipelines and CI |
90
90
  | `trazum route <log.jsonl>` | is the cheaper model good enough? — measured, and it asks before spending |
91
- | `trazum plan <log\|dir>` | the findings as a ranked plan: what to do first, route+batch combined never summed, projections and money already spent totalled apart, every assumption named. `-o` saves it dated for a later verify; `--min-usd` names what it drops |
91
+ | `trazum plan <log\|dir>` | the findings as a ranked plan: what to do first, route+batch combined never summed, projections and money already spent totalled apart, every assumption named. `-o` saves it dated for a later verify; `--min-usd` names what it drops; `--edits` adds the safe rules' edit to each prompt file the config maps a label to, by hash |
92
92
  | `trazum verify <plan.json> --against <log>` | did the plan's savings arrive? Three outcomes, never two — arrived, did not, cannot be told — with the world's movement named beside each verdict. `--gate` fails CI on broken promises |
93
93
  | `trazum history <dir>` | the long run: series from stored `--json` reports, the climbs and decays no pairwise comparison finds, and plans nobody is executing. Shapes named, nothing forecast |
94
94
  | `trazum connect <provider>` | your bill read from the provider's usage API — no export by hand. The credential is borrowed from the environment and never stored; a connected report is restricted on purpose and names the findings a sum cannot support |
95
95
  | `trazum store` | what the local store holds and what a prune would take. Re-pulls converge instead of doubling; records it cannot tell apart are kept as two and named; pruning refuses without a retention policy and says what went |
96
96
  | `trazum weekly` | the week written down: the bill for seven days, what moved against the seven before, and the three ranked changes, each a projection that says so beside what was measured. A file, or one line on the desktop with `--notify`; every figure is checked against the bills before it is written |
97
97
  | `trazum proactive [status\|on\|off]` | what speaks first, and whether it is on: the status line and its Stop hook, a scheduled `watch`, the MCP server. Offers each one, says which files and which lines, writes only after a yes, and removes exactly what it added. Sends nothing anywhere |
98
+ | `trazum session-guard [status\|install\|uninstall]` | a Claude Code hook that warns once and then stops a session at two dollar figures you set, in API-equivalent cost. No default for either figure or for what to do when the cost cannot be told. Installs and removes only its own lines, and sends nothing anywhere |
99
+ | `trazum waste <transcript.jsonl>` | what a coding-agent session paid for twice, priced from its own counts at the dated catalogue: a file read again, MCP servers loaded and never called, a CLAUDE.md carried every turn. A cost the transcript does not record is named and not priced. Recommends and edits no file; reads counts and paths only |
98
100
  | `trazum watch` | the spend gates evaluated as the money moves, not three weeks later. Measured crossings only, a day half-measured is not-yet-judgeable rather than passed, a restart neither re-alerts nor calls a blown budget clean. `--sessions` watches what `bill` reads, no store; `--notify` tells the person at the machine |
99
101
  | `trazum serve` | a loopback endpoint answering what a call will cost and whether there is budget, in milliseconds. The measured half and the estimated half stay apart, and the verdict says which it rests on |
100
102
  | `trazum doctor [dir]` | the whole workspace: what nothing is watching, and what fixing would be worth |
@@ -107,6 +109,7 @@ trazum bill
107
109
  | `trazum from-otel <file>` | what the LLM calls in my OpenTelemetry export cost — the GenAI spans any exporter already emits, counts only |
108
110
  | `trazum switch <log> --to <model>` | should we move this traffic, and when does moving pay — measured saving, declared migration cost, break-even as division on the past |
109
111
  | `trazum ownrate` | what my self-hosted model costs per million tokens — your GPU rate over your measured throughput, derived rather than guessed |
112
+ | `trazum model-pricing <settings>` | price at the contracted rates we already gave Claude Code in `modelPricing` — written as an overlay for `--pricing` |
110
113
  | `trazum where [file]` | which prompts hide in my source files, and which model they call |
111
114
  | `trazum models` · `trazum rules` | prices; what each rule does |
112
115
 
@@ -60,6 +60,49 @@ session="$(field session_id)"
60
60
  model="$(field model.display_name '?')"
61
61
  cache="$cache_dir/${session:-unknown}.txt"
62
62
 
63
+ # The plan's own limits, as Claude Code hands them to the status line in
64
+ # `rate_limits`: how much of the five-hour and the seven-day window is used and
65
+ # when each resets, and a spend limit where a gateway sets one. Only a window
66
+ # Claude Code sent, with a percentage and a reset still ahead, is shown: there
67
+ # is no table of plan limits here and no counter worked out from tokens. On an
68
+ # API key, and before a session's first response, Claude Code sends none, and
69
+ # the line shows no plan figure at all.
70
+ # The program is JavaScript in single quotes on purpose: its ${...} are
71
+ # template literals, and the shell must leave them alone.
72
+ # shellcheck disable=SC2016
73
+ limits() { printf '%s' "$json" | node -e '
74
+ let raw = "";
75
+ process.stdin.on("data", (c) => { raw += c; });
76
+ process.stdin.on("end", () => {
77
+ let r;
78
+ try { r = JSON.parse(raw).rate_limits; } catch { r = undefined; }
79
+ if (r === null || typeof r !== "object") return;
80
+ const now = Date.now() / 1000;
81
+ const live = (w) => w !== null && typeof w === "object" && Number.isFinite(w.used_percentage) && Number.isFinite(w.resets_at) && w.resets_at > now;
82
+ const pad = (n) => String(n).padStart(2, "0");
83
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
84
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
85
+ const clock = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
86
+ const at = (s, how) => {
87
+ const d = new Date(s * 1000);
88
+ if (how === "time") return clock(d);
89
+ if (how === "day") return `${days[d.getDay()]} ${clock(d)}`;
90
+ return `${months[d.getMonth()]} ${d.getDate()}`;
91
+ };
92
+ // Down, never up: a window at 99.6% is not shown as used up.
93
+ const used = (w) => `${Math.floor(w.used_percentage)}%`;
94
+ const parts = [];
95
+ if (live(r.five_hour)) parts.push(`5h ${used(r.five_hour)}, resets ${at(r.five_hour.resets_at, "time")}`);
96
+ if (live(r.seven_day)) parts.push(`7d ${used(r.seven_day)}, resets ${at(r.seven_day.resets_at, "day")}`);
97
+ const s = r.spend_limit;
98
+ if (live(s)) {
99
+ const per = { daily: "/day", weekly: "/week", monthly: "/month" }[s.period] ?? "";
100
+ const of = Number.isFinite(s.limit_usd) ? ` of $${s.limit_usd}${per}` : "";
101
+ parts.push(`spend ${used(s)}${of}, resets ${at(s.resets_at, "date")}`);
102
+ }
103
+ process.stdout.write(parts.join(" · "));
104
+ });'; }
105
+
63
106
  if [ "${1-}" != "--refresh" ]; then
64
107
  # The status line. Reads, never computes. A missing cache is the normal
65
108
  # state of the first turn and of an install without the hook, so it is not
@@ -71,6 +114,8 @@ if [ "${1-}" != "--refresh" ]; then
71
114
  else
72
115
  printf '%s $%s (Claude Code)' "$model" "$(field cost.total_cost_usd 0)"
73
116
  fi
117
+ plan="$(limits)"
118
+ [ -n "$plan" ] && printf ' | %s' "$plan"
74
119
  exit 0
75
120
  fi
76
121
 
@@ -0,0 +1,173 @@
1
+ import type { ModelPricing, PricingCatalogue } from '@trazum/core';
2
+ /**
3
+ * What a pull request does to each prompt's cost against its base branch
4
+ * (#785): `trazum check <target> --base <ref>`.
5
+ *
6
+ * The base side is read out of the clone the job already has, with
7
+ * `git show`, through `git.ts`. Nothing is fetched and nothing is sent: a
8
+ * base commit the checkout does not hold is reported as missing, never
9
+ * replaced by the working tree, which would compare the head with itself
10
+ * and report every pull request as free.
11
+ *
12
+ * Every figure is **input tokens at the model's input price**: what the
13
+ * prompt itself costs per call. Output is left out on purpose, because a
14
+ * prompt edit does not set how much the model writes back, and a figure
15
+ * that included a typed output size would carry a number nobody measured.
16
+ *
17
+ * A month needs a number of calls, and that number is a statement about
18
+ * traffic. It comes from `volumes` in `trazum.config.json`, keyed by the
19
+ * label `labels` maps to the prompt file, and from nowhere else. A prompt
20
+ * with no stated volume is priced per call, and the report says so: a
21
+ * month at an invented volume is the figure this product exists not to
22
+ * print.
23
+ */
24
+ /** One prompt, on both sides of the comparison. `null` where it is absent. */
25
+ export interface PromptPair {
26
+ /** How the report names it: a path, or `path#name` for a marked prompt. */
27
+ id: string;
28
+ /** The file it lives in, as the head's walk names it. */
29
+ file: string;
30
+ /** True for a prompt marked inside a source file. */
31
+ embedded: boolean;
32
+ base: string | null;
33
+ head: string | null;
34
+ }
35
+ /** One side of one prompt, priced. */
36
+ export interface PricedSide {
37
+ tokens: number;
38
+ /** The input price this side was billed at, per million tokens. */
39
+ inputPerMTok: number;
40
+ perCallUsd: number;
41
+ /** `null` when nobody stated a volume for this prompt. */
42
+ monthlyUsd: number | null;
43
+ }
44
+ export interface BaseCostRow {
45
+ id: string;
46
+ base: PricedSide | null;
47
+ head: PricedSide | null;
48
+ /** Calls a month from `volumes`, or `null`: then the row is per call only. */
49
+ callsPerMonth: number | null;
50
+ /** The labels whose volumes were added up for this prompt. */
51
+ labels: string[];
52
+ perCallChangeUsd: number;
53
+ monthlyChangeUsd: number | null;
54
+ }
55
+ /** The price every figure was computed at, and where it came from. */
56
+ export interface BaseCostPrice {
57
+ model: string;
58
+ displayName: string;
59
+ /** Who sells it, as the catalogue records it; `null` for an overlay's model with none. */
60
+ provider: string | null;
61
+ /** True when a local pricing overlay supplied this model's price. */
62
+ overlaid: boolean;
63
+ /**
64
+ * The day this price was read: the provider's review date in the bundled
65
+ * catalogue, or the overlay's own date. Never today's date and never a
66
+ * date this module made up: `reviewedForModels` is the one place it comes
67
+ * from.
68
+ */
69
+ readOn: string;
70
+ /** When a promotional price applied, the last day it does. */
71
+ promoUntil: string | null;
72
+ }
73
+ export interface BaseCostGate {
74
+ /** The most the monthly cost may grow, from `--max-monthly-increase-usd`. */
75
+ maxIncreaseUsd: number;
76
+ breached: boolean;
77
+ }
78
+ export type BaseCostReport = {
79
+ status: 'compared';
80
+ /** What the caller passed, and the commit it named. */
81
+ ref: string;
82
+ sha: string;
83
+ price: BaseCostPrice;
84
+ /** Whether the model came from `usage.model` or is Trazum's default. */
85
+ modelFrom: 'config' | 'default';
86
+ /** Prompts whose text differs, added or removed, in id order. */
87
+ rows: BaseCostRow[];
88
+ /** Prompts identical on both sides: counted, not listed. */
89
+ unchanged: number;
90
+ /** Over the rows with a stated volume; `null` when no row has one. */
91
+ totals: {
92
+ baseUsd: number;
93
+ headUsd: number;
94
+ changeUsd: number;
95
+ } | null;
96
+ /** Changed rows with no stated volume, priced per call only. */
97
+ perCallOnly: number;
98
+ gate: BaseCostGate | null;
99
+ } | {
100
+ status: 'unavailable';
101
+ ref: string;
102
+ /** No git, not a repository, or a commit this checkout does not have. */
103
+ why: 'no-git' | 'not-a-repository' | 'no-commit';
104
+ /** A gate that was asked for and could not judge anything. */
105
+ gate: {
106
+ maxIncreaseUsd: number;
107
+ } | null;
108
+ };
109
+ /** Whether a gate asked for in this report fails the run. */
110
+ export declare function baseGateFails(report: BaseCostReport): boolean;
111
+ /**
112
+ * Reads both sides of every prompt under `target`.
113
+ *
114
+ * The head is the disk, walked the way `check` walks it. The base is the
115
+ * commit, listed with `git ls-tree` and read with `git show`, and kept to
116
+ * the files the walk would have kept (`walkIncludes`), so a file the walk
117
+ * skips is not reported as deleted. `listed` is `--files-from`'s list, which
118
+ * replaces the walk on both sides.
119
+ */
120
+ export declare function readBothSides(options: {
121
+ ref: string;
122
+ target: string;
123
+ kind: 'file' | 'directory' | 'list';
124
+ listed?: readonly string[];
125
+ extensions: readonly string[];
126
+ ignore: readonly string[];
127
+ cwd?: string;
128
+ readHead?: (path: string) => Promise<string>;
129
+ }): Promise<{
130
+ status: 'read';
131
+ sha: string;
132
+ pairs: PromptPair[];
133
+ } | {
134
+ status: 'unavailable';
135
+ why: 'no-git' | 'not-a-repository' | 'no-commit';
136
+ }>;
137
+ /**
138
+ * The calls a month stated for a prompt file, from `volumes` through `labels`.
139
+ *
140
+ * Every label mapping to the file is a workload sending it, so their
141
+ * volumes add. When one of them states none, the month is not known and
142
+ * the answer is `null`: a sum missing a workload would be an understated
143
+ * month printed as a whole one. A prompt marked inside a source file gets
144
+ * none, because a label maps a file and a file holding several prompts
145
+ * does not say how often each is sent.
146
+ */
147
+ export declare function volumeFor(pair: Pick<PromptPair, 'file' | 'embedded'>, labels: Readonly<Record<string, string>>, volumes: Readonly<Record<string, number>>, cwd?: string): {
148
+ calls: number;
149
+ labels: string[];
150
+ } | null;
151
+ /**
152
+ * Prices every changed prompt on both sides, at one model and one price list.
153
+ *
154
+ * Both sides are priced at today's prices, from the same catalogue, so a
155
+ * provider repricing between the base and the head cannot appear as a
156
+ * change the pull request made.
157
+ */
158
+ export declare function priceAgainstBase(input: {
159
+ ref: string;
160
+ sha: string;
161
+ pairs: readonly PromptPair[];
162
+ count: (text: string) => Promise<number>;
163
+ model: ModelPricing;
164
+ modelFrom: 'config' | 'default';
165
+ pricing: PricingCatalogue;
166
+ volumeOf: (pair: PromptPair) => {
167
+ calls: number;
168
+ labels: string[];
169
+ } | null;
170
+ maxIncreaseUsd: number | null;
171
+ on?: Date;
172
+ }): Promise<BaseCostReport>;
173
+ //# sourceMappingURL=base-cost.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-cost.d.ts","sourceRoot":"","sources":["../src/base-cost.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAKnE;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,8EAA8E;AAC9E,MAAM,WAAW,UAAU;IACzB,2EAA2E;IAC3E,EAAE,EAAE,MAAM,CAAC;IACX,yDAAyD;IACzD,IAAI,EAAE,MAAM,CAAC;IACb,qDAAqD;IACrD,QAAQ,EA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E_EXTENSIONS, effectivePricing, extractPrompts, hasMarker, matchGlob, promptId, reviewedForModels, } from '@trazum/core';
4
+ import { walkIncludes, walkPrompts } from '@trazum/core/node';
5
+ import { commitOf, contentAt, filesAt, gitAvailable, pathInRepository, repositoryRoot } from './git.js';
6
+ /** Whether a gate asked for in this report fails the run. */
7
+ export function baseGateFails(report) {
8
+ if (report.gate === null)
9
+ return false;
10
+ // A gate that could not read the base is not a pass: it judged nothing.
11
+ if (report.status === 'unavailable')
12
+ return true;
13
+ return report.gate.breached;
14
+ }
15
+ /** The prompts one file holds: itself, or each one marked inside it. */
16
+ function promptsIn(file, text) {
17
+ const isSource = SOURCE_EXTENSIONS.some((ext) => file.toLowerCase().endsWith(ext));
18
+ if (!isSource)
19
+ return [{ id: file, text, embedded: false }];
20
+ if (!hasMarker(text))
21
+ return [];
22
+ return extractPrompts(text).prompts.map((prompt) => ({
23
+ id: promptId(file, prompt),
24
+ text: prompt.text,
25
+ embedded: true,
26
+ }));
27
+ }
28
+ const toPosix = (path) => path.split(sep).join('/');
29
+ /** `a/b` joined for display, the way `check` keys a path under its root. */
30
+ function joinShown(root, rel) {
31
+ const trimmed = root.replace(/[\\/]+$/, '').replace(/\\/g, '/');
32
+ if (trimmed === '' || trimmed === '.')
33
+ return rel;
34
+ return `${trimmed}/${rel}`;
35
+ }
36
+ /**
37
+ * Reads both sides of every prompt under `target`.
38
+ *
39
+ * The head is the disk, walked the way `check` walks it. The base is the
40
+ * commit, listed with `git ls-tree` and read with `git show`, and kept to
41
+ * the files the walk would have kept (`walkIncludes`), so a file the walk
42
+ * skips is not reported as deleted. `listed` is `--files-from`'s list, which
43
+ * replaces the walk on both sides.
44
+ */
45
+ export async function readBothSides(options) {
46
+ const cwd = options.cwd ?? process.cwd();
47
+ const readHead = options.readHead ?? ((path) => readFile(resolve(cwd, path), 'utf8'));
48
+ if (!gitAvailable(cwd))
49
+ return { status: 'unavailable', why: 'no-git' };
50
+ const root = repositoryRoot(cwd);
51
+ if (root === null)
52
+ return { status: 'unavailable', why: 'not-a-repository' };
53
+ let sha;
54
+ try {
55
+ sha = commitOf(options.ref, root);
56
+ }
57
+ catch {
58
+ return { status: 'unavailable', why: 'no-git' };
59
+ }
60
+ if (sha === null)
61
+ return { status: 'unavailable', why: 'no-commit' };
62
+ /** A path as the report shows it, relative to the working directory, to its repository path. */
63
+ const repoPathOf = (shown) => {
64
+ const absolute = resolve(cwd, shown);
65
+ if (absolute === resolve(root))
66
+ return '';
67
+ return pathInRepository(root, absolute);
68
+ };
69
+ // Every file to look at, as the report shows it, mapped to its path in the repository.
70
+ const files = new Map();
71
+ const walkOptions = { extensions: options.extensions, ignore: options.ignore };
72
+ if (options.kind === 'file') {
73
+ const repoPath = repoPathOf(options.target);
74
+ if (repoPath !== null && repoPath !== '')
75
+ files.set(toPosix(options.target), repoPath);
76
+ }
77
+ else if (options.kind === 'list') {
78
+ // The list's own rule, as `check --files-from` applies it: a prompt
79
+ // extension and no ignore pattern. Kept whether or not the file is still
80
+ // on disk, because a deletion is half of what a base comparison is for.
81
+ const extensions = options.extensions.map((ext) => ext.toLowerCase());
82
+ for (const raw of options.listed ?? []) {
83
+ const rel = raw.replace(/^\.\//, '');
84
+ if (!extensions.some((ext) => rel.toLowerCase().endsWith(ext)))
85
+ continue;
86
+ if (options.ignore.some((pattern) => matchGlob(pattern, rel) || matchGlob(pattern, `${rel}/`)))
87
+ continue;
88
+ const repoPath = repoPathOf(rel);
89
+ if (repoPath !== null && repoPath !== '')
90
+ files.set(rel, repoPath);
91
+ }
92
+ }
93
+ else {
94
+ const walked = await walkPrompts(resolve(cwd, options.target), walkOptions);
95
+ for (const rel of walked.files) {
96
+ const shown = joinShown(options.target, rel);
97
+ const repoPath = repoPathOf(shown);
98
+ if (repoPath !== null)
99
+ files.set(shown, repoPath);
100
+ }
101
+ const rootPath = repoPathOf(options.target);
102
+ if (rootPath !== null) {
103
+ for (const repoPath of filesAt(sha, rootPath, root) ?? []) {
104
+ const rel = rootPath === '' ? repoPath : repoPath.slice(rootPath.length + 1);
105
+ if (!walkIncludes(rel, walkOptions))
106
+ continue;
107
+ const shown = joinShown(options.target, rel);
108
+ if (!files.has(shown))
109
+ files.set(shown, repoPath);
110
+ }
111
+ }
112
+ }
113
+ const pairs = new Map();
114
+ for (const [shown, repoPath] of [...files.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
115
+ // The base is read from the commit, and only from the commit.
116
+ const atBase = (filesAt(sha, repoPath, root) ?? []).includes(repoPath) ? contentAt(sha, repoPath, root) : null;
117
+ const atHead = await readHead(shown).catch(() => null);
118
+ for (const prompt of atBase === null ? [] : promptsIn(shown, atBase)) {
119
+ pairs.set(prompt.id, { id: prompt.id, file: shown, embedded: prompt.embedded, base: prompt.text, head: null });
120
+ }
121
+ for (const prompt of atHead === null ? [] : promptsIn(shown, atHead)) {
122
+ const existing = pairs.get(prompt.id);
123
+ if (existing !== undefined)
124
+ existing.head = prompt.text;
125
+ else
126
+ pairs.set(prompt.id, { id: prompt.id, file: shown, embedded: prompt.embedded, base: null, head: prompt.text });
127
+ }
128
+ }
129
+ return { status: 'read', sha, pairs: [...pairs.values()] };
130
+ }
131
+ /**
132
+ * The calls a month stated for a prompt file, from `volumes` through `labels`.
133
+ *
134
+ * Every label mapping to the file is a workload sending it, so their
135
+ * volumes add. When one of them states none, the month is not known and
136
+ * the answer is `null`: a sum missing a workload would be an understated
137
+ * month printed as a whole one. A prompt marked inside a source file gets
138
+ * none, because a label maps a file and a file holding several prompts
139
+ * does not say how often each is sent.
140
+ */
141
+ export function volumeFor(pair, labels, volumes, cwd = process.cwd()) {
142
+ if (pair.embedded)
143
+ return null;
144
+ const target = resolve(cwd, pair.file);
145
+ const sending = Object.keys(labels)
146
+ .filter((label) => resolve(cwd, labels[label]) === target)
147
+ .sort();
148
+ if (sending.length === 0)
149
+ return null;
150
+ let calls = 0;
151
+ for (const label of sending) {
152
+ const stated = volumes[label];
153
+ if (stated === undefined)
154
+ return null;
155
+ calls += stated;
156
+ }
157
+ return { calls, labels: sending };
158
+ }
159
+ /**
160
+ * Prices every changed prompt on both sides, at one model and one price list.
161
+ *
162
+ * Both sides are priced at today's prices, from the same catalogue, so a
163
+ * provider repricing between the base and the head cannot appear as a
164
+ * change the pull request made.
165
+ */
166
+ export async function priceAgainstBase(input) {
167
+ const on = input.on ?? new Date();
168
+ const model = input.model;
169
+ let promoApplied = false;
170
+ const side = async (text, calls) => {
171
+ if (text === null)
172
+ return null;
173
+ const tokens = await input.count(text);
174
+ const rates = effectivePricing(model, on, { inputTokens: tokens });
175
+ promoApplied ||= rates.promoApplied;
176
+ const perCallUsd = (tokens * rates.inputPerMTok) / 1_000_000;
177
+ return {
178
+ tokens,
179
+ inputPerMTok: rates.inputPerMTok,
180
+ perCallUsd,
181
+ monthlyUsd: calls === null ? null : perCallUsd * calls,
182
+ };
183
+ };
184
+ const rows = [];
185
+ let unchanged = 0;
186
+ for (const pair of [...input.pairs].sort((a, b) => a.id.localeCompare(b.id))) {
187
+ if (pair.base === pair.head) {
188
+ if (pair.base !== null)
189
+ unchanged++;
190
+ continue;
191
+ }
192
+ const volume = input.volumeOf(pair);
193
+ const calls = volume === null ? null : volume.calls;
194
+ const base = await side(pair.base, calls);
195
+ const head = await side(pair.head, calls);
196
+ const perCallChangeUsd = (head?.perCallUsd ?? 0) - (base?.perCallUsd ?? 0);
197
+ rows.push({
198
+ id: pair.id,
199
+ base,
200
+ head,
201
+ callsPerMonth: calls,
202
+ labels: volume?.labels ?? [],
203
+ perCallChangeUsd,
204
+ monthlyChangeUsd: calls === null ? null : perCallChangeUsd * calls,
205
+ });
206
+ }
207
+ const monthly = rows.filter((row) => row.callsPerMonth !== null);
208
+ const totals = monthly.length === 0
209
+ ? null
210
+ : {
211
+ baseUsd: monthly.reduce((sum, row) => sum + (row.base?.monthlyUsd ?? 0), 0),
212
+ headUsd: monthly.reduce((sum, row) => sum + (row.head?.monthlyUsd ?? 0), 0),
213
+ changeUsd: monthly.reduce((sum, row) => sum + (row.monthlyChangeUsd ?? 0), 0),
214
+ };
215
+ const overlaid = input.pricing.lastReviewed !== PRICING_LAST_REVIEWED ||
216
+ input.pricing.overriddenModels.includes(model.id) ||
217
+ input.pricing.addedModels.includes(model.id);
218
+ return {
219
+ status: 'compared',
220
+ ref: input.ref,
221
+ sha: input.sha,
222
+ price: {
223
+ model: model.id,
224
+ displayName: model.displayName,
225
+ provider: model.provider ?? null,
226
+ overlaid,
227
+ readOn: reviewedForModels([model.id], input.pricing),
228
+ promoUntil: promoApplied ? (model.promo?.until ?? null) : null,
229
+ },
230
+ modelFrom: input.modelFrom,
231
+ rows,
232
+ unchanged,
233
+ totals,
234
+ perCallOnly: rows.length - monthly.length,
235
+ gate: input.maxIncreaseUsd === null
236
+ ? null
237
+ : {
238
+ maxIncreaseUsd: input.maxIncreaseUsd,
239
+ // A floating-point hair over the limit is not over it.
240
+ breached: (totals?.changeUsd ?? 0) - input.maxIncreaseUsd > 1e-9,
241
+ },
242
+ };
243
+ }
244
+ //# sourceMappingURL=base-cost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-cost.js","sourceRoot":"","sources":["../src/base-cost.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,SAAS,EACT,SAAS,EACT,QAAQ,EACR,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAgHxG,6DAA6D;AAC7D,MAAM,UAAU,aAAa,CAAC,MAAsB;IAClD,IAAI,MAAM,CAA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N,WAAW,EAAE,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM;QACzC,IAAI,EACF,KAAK,CAAC,cAAc,KAAK,IAAI;YAC3B,CAAC,CAAC,IAAI;YACN,CAAC,CAAC;gBACE,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,uDAAuD;gBACvD,QAAQ,EAAE,CAAC,MAAM,EAAE,SAAS,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,cAAc,GAAG,IAAI;aACjE;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,118 @@
1
+ import type { PricingCatalogue } from '@trazum/core';
2
+ import type { CommitTimes } from './git.js';
3
+ /**
4
+ * `trazum bill --git-range`: what was spent in this repository's sessions
5
+ * between the first and the last commit of a range (#777).
6
+ *
7
+ * It is a narrower claim than "what the change cost", and the narrowing is the
8
+ * point. The transcripts say when each call was made and which session made it.
9
+ * They do not say which commit the work was for, and nothing here asks them to.
10
+ * What is measured is **everything recorded in this repository's project during
11
+ * the span**: a morning spent on something else in the same repository is in it,
12
+ * and work for the change done on another machine is not.
13
+ *
14
+ * **How "this repository's project" is told, without reading a branch or a path
15
+ * out of a transcript.** Claude Code keeps one folder per project and names it
16
+ * by the project's absolute path with every character that is not a letter or a
17
+ * digit written as `-`. That encoding cannot be undone (see `projectLabelFor`
18
+ * in `index.ts`), but it can be *done*: git says where this repository's root
19
+ * is, the same encoding is applied to that path here, and the folder is this
20
+ * repository's when the two names are equal. Nothing is decoded and nothing in
21
+ * a transcript is read for it: the label every record already carries came from
22
+ * the name of the folder the file was found in, and the root comes from git.
23
+ * A session started in a subdirectory, or in a worktree of the repository, sits
24
+ * in a folder of another name and is not matched; that is a miss named in the
25
+ * documentation, not a guess.
26
+ *
27
+ * **Sessions that cross an edge are not added in.** A session is inside when its
28
+ * first and last call both fall in the window, outside when neither does, and
29
+ * straddling when it began before the first commit or went on after the last.
30
+ * The figure is the sessions inside. Each straddling session is named, with the
31
+ * part of it inside the window and the part outside, and none of it is added to
32
+ * the figure, because half a session says nothing about which half the change
33
+ * needed. The reader adds what they judge to belong.
34
+ */
35
+ /** The span of a range of commits: the earliest time any of them was written to the latest it was committed. */
36
+ export interface RangeWindow {
37
+ fromMs: number;
38
+ toMs: number;
39
+ commits: number;
40
+ }
41
+ /**
42
+ * The span from the earliest author or commit time to the latest.
43
+ *
44
+ * Both times, because they differ exactly when it matters: a commit rebased
45
+ * onto `main` yesterday was written last week, and the work happened last week.
46
+ * `null` for an empty range, which has no span.
47
+ */
48
+ export declare function windowOf(times: readonly CommitTimes[]): RangeWindow | null;
49
+ /**
50
+ * The name Claude Code gives a project folder for a repository at `root`, less
51
+ * the leading dashes the label shows without (see `projectLabelFor`). It is an
52
+ * encoding of a path that git supplied; it is never decoded back.
53
+ */
54
+ export declare function projectLabelOfRoot(root: string): string;
55
+ /** One session that began before the window or went on after it, with what each side cost. */
56
+ export interface StraddlingSession {
57
+ session: string;
58
+ firstMs: number;
59
+ lastMs: number;
60
+ insideUsd: number;
61
+ insideCalls: number;
62
+ outsideUsd: number;
63
+ outsideCalls: number;
64
+ }
65
+ export interface RangeBill {
66
+ window: RangeWindow;
67
+ /** Records of this project's folder, dated or not: none means nothing was matched at all. */
68
+ projectRecords: number;
69
+ /** Sessions whose every call is inside the window: the figure. */
70
+ inside: {
71
+ usd: number;
72
+ calls: number;
73
+ sessions: number;
74
+ unpricedCalls: number;
75
+ };
76
+ straddling: StraddlingSession[];
77
+ /** Calls of sessions that were wholly before or after the window, not counted. */
78
+ outsideCalls: number;
79
+ /** What was read and could not be placed in this project or in this window. */
80
+ leftOut: {
81
+ otherProjects: number;
82
+ otherSources: number;
83
+ undated: number;
84
+ };
85
+ }
86
+ /**
87
+ * Splits the records of one project against the window and prices each part.
88
+ *
89
+ * `claudeCodeLines` are the usage-log records of the Claude Code transcripts,
90
+ * each carrying the label of its project folder. A record whose label is not
91
+ * `project` is another project's and is counted out, not read further.
92
+ * `otherSources` is how many records came from anywhere else (Codex, Gemini
93
+ * CLI, a log): they carry no project folder this can match, so they are named
94
+ * as left out and never guessed at.
95
+ */
96
+ export declare function billRange(input: {
97
+ claudeCodeLines: readonly string[];
98
+ otherSources: number;
99
+ project: string;
100
+ window: RangeWindow;
101
+ catalogue: PricingCatalogue;
102
+ }): RangeBill;
103
+ /**
104
+ * The recorded figure divided by each delivery count (#825): the arithmetic and
105
+ * nothing else. `null` where the count is zero, so a figure is never divided by
106
+ * nothing and never printed as $0. It is an average over the span: it says
107
+ * nothing about what any one commit, pull request or day was worth or cost.
108
+ */
109
+ export declare function perDelivery(usd: number, delivery: {
110
+ commits: number;
111
+ pullRequests: number;
112
+ days: number;
113
+ }): {
114
+ perCommit: number | null;
115
+ perPullRequest: number | null;
116
+ perDay: number | null;
117
+ };
118
+ //# sourceMappingURL=bill-range.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bill-range.d.ts","sourceRoot":"","sources":["../src/bill-range.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,gHAAgH;AAChH,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,WAAW,GAAG,IAAI,CAI1E;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIvD;AAED,8FAA8F;AAC9F,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,W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