@aispendbook/cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +207 -2
- package/dist/bin.js +23 -0
- package/dist/cache-audit.js +162 -0
- package/dist/cli.js +402 -0
- package/dist/compare.js +238 -0
- package/dist/config.js +87 -0
- package/dist/mcp.js +155 -0
- package/dist/node-impl.js +69 -0
- package/dist/prices.json +1743 -0
- package/dist/pricing.js +170 -0
- package/dist/range.js +45 -0
- package/dist/report.js +112 -0
- package/dist/savings.js +83 -0
- package/dist/skill/SKILL.md +76 -0
- package/dist/skill/reference.md +47 -0
- package/dist/sources/claude-code.js +106 -0
- package/dist/sources/claude-prefix.js +111 -0
- package/dist/sources/codex.js +165 -0
- package/dist/sources/gemini.js +141 -0
- package/dist/sources/util.js +53 -0
- package/dist/sync.js +174 -0
- package/dist/types.js +2 -0
- package/package.json +43 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AI Spendbook
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,208 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aispendbook/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`aispendbook` reads the local logs of your AI coding tools and reports token usage and its
|
|
4
|
+
API-equivalent cost. It compares your sessions before and after a change (such as installing the
|
|
5
|
+
AI Spendbook savings skill), audits prompt caching, can upload the counts to AI Spendbook, and can
|
|
6
|
+
run as a local MCP server so Claude Code can answer "what did my Claude Code usage cost this week?".
|
|
7
|
+
|
|
8
|
+
Node.js 18.3 or later. No runtime dependencies.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npx -y @aispendbook/cli report
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## What it reads
|
|
15
|
+
|
|
16
|
+
| Tool | Where | Notes |
|
|
17
|
+
| --- | --- | --- |
|
|
18
|
+
| Claude Code | `~/.claude/projects/**/*.jsonl` and `~/.config/claude/projects` (or each directory in `CLAUDE_CONFIG_DIR`, comma-separated) | Claude Code writes a response once per content block and copies messages into subagent and resumed transcripts. Records are counted once per message id and request id. `<synthetic>` messages are skipped. |
|
|
19
|
+
| OpenAI Codex CLI | `~/.codex/sessions/**/rollout-*.jsonl` and `~/.codex/archived_sessions` (or `CODEX_HOME`) | Uses per-response `token_usage_record` lines when a file has them, otherwise `token_count` events, skipping a repeated cumulative total. Compressed `.jsonl.zst` archives need Node.js 22.15 or later; on older versions they are skipped and the report says how many. |
|
|
20
|
+
| Gemini CLI | `~/.gemini/tmp/<project>/chats/` (or `GEMINI_CLI_HOME/.gemini/tmp`) | Reads the JSON Lines chat files and the older single-JSON chat files. `tokens.input` includes cached tokens; tool-use prompt tokens are added to input and thinking tokens to output. |
|
|
21
|
+
|
|
22
|
+
Bad lines and unknown shapes are skipped and counted, never fatal. Log files are opened read-only and
|
|
23
|
+
only these fields are extracted: model, timestamps, token counts, session, message and response ids,
|
|
24
|
+
and the working directory (for the project name). Prompts, code, tool calls and responses are never
|
|
25
|
+
extracted, printed or uploaded.
|
|
26
|
+
|
|
27
|
+
The project is the last folder of the working directory. A worktree that a tool keeps inside the
|
|
28
|
+
project (`<project>/.claude/worktrees/<name>`) counts as that project.
|
|
29
|
+
|
|
30
|
+
## report
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
aispendbook report [--since 7d|YYYY-MM-DD] [--until YYYY-MM-DD] [--by day|project|model|tool]
|
|
34
|
+
[--source claude-code|codex|gemini] [--json]
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Local only: `report` makes no network calls. `--since 7d` (the default) means today and the 6 days
|
|
38
|
+
before, in local time. `--until` names the last day included. `--source` may repeat or take a comma
|
|
39
|
+
list. Columns: requests, uncached input, cache write, cache read, output and total tokens, and cost.
|
|
40
|
+
`--json` prints the same data with cost in integer USD micros.
|
|
41
|
+
|
|
42
|
+
## sync
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
export AISPENDBOOK_INGESTION_KEY=afk_...
|
|
46
|
+
aispendbook sync [--api https://www.aispendbook.com] [--since 30d|YYYY-MM-DD]
|
|
47
|
+
[--source ...] [--project-names hashed|plain] [--dry-run]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Uploads to `POST {api}/api/v1/ingest/batch` with `Authorization: Bearer <ingestion key>`, in batches
|
|
51
|
+
of up to 500 events. A 429 response is retried after its `Retry-After`; server errors are retried with
|
|
52
|
+
backoff, up to 5 times. The command prints how many events were written, how many were already there
|
|
53
|
+
and how many were rejected. `--dry-run` prints the event count and a sample of what would be sent,
|
|
54
|
+
and needs no key.
|
|
55
|
+
|
|
56
|
+
Without `--since`, a sync starts one day before the last successful one (kept in
|
|
57
|
+
`~/.aispendbook/sync-state.json`, or `AISPENDBOOK_HOME`), and the first sync looks back 30 days.
|
|
58
|
+
Event ids are derived from each request's own id, so re-sending the same requests is deduplicated by
|
|
59
|
+
the server: the state file only saves work.
|
|
60
|
+
|
|
61
|
+
### What is uploaded
|
|
62
|
+
|
|
63
|
+
One event per model request, and nothing else:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"event_id": "cc_<40 hex: sha256 of tool and message id>",
|
|
68
|
+
"occurred_at": "2026-11-20T12:00:00.000Z",
|
|
69
|
+
"provider": "anthropic",
|
|
70
|
+
"model": "claude-opus-5-5",
|
|
71
|
+
"input_tokens": 10,
|
|
72
|
+
"output_tokens": 20,
|
|
73
|
+
"cache_read_tokens": 30,
|
|
74
|
+
"cache_write_tokens": 40,
|
|
75
|
+
"cache_write_1h_tokens": 15,
|
|
76
|
+
"feature": "claude-code",
|
|
77
|
+
"project_id": "p_<24 hex: sha256 of the project name>",
|
|
78
|
+
"session_id": "s_<24 hex: sha256 of the session id>",
|
|
79
|
+
"sdk": { "name": "aispendbook-cli", "version": "0.1.0" }
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`input_tokens` is uncached input. `cache_write_1h_tokens` is the part of `cache_write_tokens` written
|
|
84
|
+
with a 1-hour lifetime. `feature` is `claude-code`, `codex` or `gemini`, and event ids start with
|
|
85
|
+
`cc_`, `cx_` or `gm_`.
|
|
86
|
+
|
|
87
|
+
Not uploaded: prompts, responses, code, file paths, tool calls, the working directory, request ids
|
|
88
|
+
and readable message or session ids. Project names are hashed unless you pass
|
|
89
|
+
`--project-names plain`. The hash is a pseudonym, not encryption: anyone who guesses a project name
|
|
90
|
+
can compute its hash.
|
|
91
|
+
|
|
92
|
+
## report --compare
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
aispendbook report --compare # split at the savings skill install
|
|
96
|
+
aispendbook report --compare --marker v2-prompts # or at a marker you set
|
|
97
|
+
aispendbook report --compare --split 2026-11-01 [--window 30]
|
|
98
|
+
aispendbook report --compare --before 2026-10-01..2026-10-31 --after 2026-11-01..2026-11-30
|
|
99
|
+
[--min-sessions 20] [--source ...] [--json] [--sync [--key afk_...] [--api URL] [--label TEXT]]
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Local only unless `--sync`. The split point is the skill install time recorded by `skill install`,
|
|
103
|
+
a marker, or `--split` (a day or an ISO time), with `--window` days on each side (default 30; the
|
|
104
|
+
after side ends now, or when the skill was uninstalled). `--before` and `--after` compare two date
|
|
105
|
+
ranges instead.
|
|
106
|
+
|
|
107
|
+
How it is measured:
|
|
108
|
+
|
|
109
|
+
- A session is one tool session id. It belongs to the period its first request falls in, and all
|
|
110
|
+
of its requests count there. Requests without a session id count in the totals only.
|
|
111
|
+
- Per side: sessions, requests, uncached input, output, cache read and cache write tokens, and
|
|
112
|
+
API-equivalent cost at the dated list prices in `prices.json` (each price page and the date it
|
|
113
|
+
was read are printed).
|
|
114
|
+
- Cost per session, per request and per 1,000 output tokens, each with the median and the 25th to
|
|
115
|
+
75th percentiles (linear interpolation), next to requests per session and minutes per session.
|
|
116
|
+
Sessions with a model that has no list price are left out of the per-session cost figures.
|
|
117
|
+
- Below `--min-sessions` sessions on either side (default 20) the verdict is "not enough data" and
|
|
118
|
+
no difference is shown.
|
|
119
|
+
- Otherwise the result is an **observed difference**, never a saving: the tasks in the two periods
|
|
120
|
+
differ. Caveats say when median session length differs by more than 25%, when the after median
|
|
121
|
+
lies inside the before period's 25th to 75th percentiles, and when list prices changed.
|
|
122
|
+
|
|
123
|
+
`--sync` sends the summary, numbers only (no projects, models, prompts or ids), to
|
|
124
|
+
`POST {api}/api/v1/savings-comparisons/ingest` with an ingestion key. It shows on the Usage page.
|
|
125
|
+
|
|
126
|
+
## cache-audit
|
|
127
|
+
|
|
128
|
+
```sh
|
|
129
|
+
aispendbook cache-audit [--since 30d|YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Claude Code only, local only. Each transcript line is hashed (SHA-256) together with the hash of
|
|
133
|
+
the line before it, in memory, so a request's prefix hash names every message sent before it. For
|
|
134
|
+
each request, the nearest earlier request on the same chain sent a prompt that this request repeats
|
|
135
|
+
verbatim. Of those repeated tokens, the log shows how many were read from cache, billed at the full
|
|
136
|
+
input price or written to the cache again; they are split by the time since the earlier request
|
|
137
|
+
(within 5 minutes, within an hour, longer). Model changes and prompts under the model's minimum
|
|
138
|
+
cacheable length are not counted.
|
|
139
|
+
|
|
140
|
+
The estimated saving prices those tokens at the model's dated list prices as cache reads, less the
|
|
141
|
+
cache write premium once per token: within 5 minutes after a 5-minute write, within an hour after a
|
|
142
|
+
1-hour write (not when the earlier request already wrote a 1-hour cache). Longer gaps save nothing.
|
|
143
|
+
It assumes the system prompt and tools did not change between the two requests; the log does not
|
|
144
|
+
record them. Cache rules: https://platform.claude.com/docs/en/build-with-claude/prompt-caching (read
|
|
145
|
+
2026-12-01). Codex CLI and Gemini CLI are not audited.
|
|
146
|
+
|
|
147
|
+
## skill and marker
|
|
148
|
+
|
|
149
|
+
```sh
|
|
150
|
+
aispendbook skill install [--dir PATH] # copies the savings skill to ~/.claude/skills/aispendbook-savings
|
|
151
|
+
aispendbook skill uninstall | status
|
|
152
|
+
aispendbook marker add NAME [--at YYYY-MM-DD|ISO time] | marker list | marker remove NAME
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`skill install` records the first install time in `~/.aispendbook/savings.json` (or
|
|
156
|
+
`AISPENDBOOK_HOME`); a reinstall keeps it. `skill uninstall` removes only a folder named
|
|
157
|
+
`aispendbook-savings` and records the removal time. Markers are named points in time to compare
|
|
158
|
+
around, like git tags. Nothing is uploaded.
|
|
159
|
+
|
|
160
|
+
## mcp
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
claude mcp add aispendbook -- npx -y @aispendbook/cli mcp
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Runs a local MCP server over stdio (newline-delimited JSON-RPC 2.0, protocol version 2025-11-25)
|
|
167
|
+
with one read-only tool, `my_local_ai_usage`. Arguments: `since`, `until`, `by` and `source`, as for
|
|
168
|
+
`report`. It returns a text summary and the table as `structuredContent`. Nothing is uploaded, and
|
|
169
|
+
nothing but protocol messages is written to stdout.
|
|
170
|
+
|
|
171
|
+
## Price basis
|
|
172
|
+
|
|
173
|
+
Cost is an **API-equivalent estimate at public list prices**, not a bill. It answers "what would
|
|
174
|
+
these tokens cost on the pay-as-you-go API?". Subscriptions with a flat fee, such as Claude Pro or
|
|
175
|
+
Max or ChatGPT plans that include Codex, are not billed per token, so the number is not what you paid.
|
|
176
|
+
|
|
177
|
+
Prices ship with the package (`prices.json`, exported from the AI Spendbook pricing catalog with
|
|
178
|
+
`scripts/export_cli_prices.py`, each row citing its source page and observation date). They are in
|
|
179
|
+
integer micros per million tokens, used by effective date, with cache reads, 5-minute and 1-hour
|
|
180
|
+
cache writes and the long-context tier applied per request. A model without a list price is listed
|
|
181
|
+
as unpriced and left out of the cost, never guessed. Modes without their own list price (for
|
|
182
|
+
example a fast mode) are priced at the standard rate and counted in the report's note.
|
|
183
|
+
|
|
184
|
+
## Configuration
|
|
185
|
+
|
|
186
|
+
| Setting | Flag | Environment | Default |
|
|
187
|
+
| --- | --- | --- | --- |
|
|
188
|
+
| Ingestion key | `--key` | `AISPENDBOOK_INGESTION_KEY` | none |
|
|
189
|
+
| API base URL | `--api` | `AISPENDBOOK_API` | `https://www.aispendbook.com` |
|
|
190
|
+
| State directory (sync state, skill install time, markers) | | `AISPENDBOOK_HOME` | `~/.aispendbook` |
|
|
191
|
+
| Skills directory | `--dir` | | `~/.claude/skills` |
|
|
192
|
+
| Sessions per side for a comparison | `--min-sessions` | | 20 |
|
|
193
|
+
| Days on each side of a split | `--window` | | 30 |
|
|
194
|
+
| Claude Code config directories | | `CLAUDE_CONFIG_DIR` | `~/.claude`, `~/.config/claude` |
|
|
195
|
+
| Codex home | | `CODEX_HOME` | `~/.codex` |
|
|
196
|
+
| Gemini CLI home | | `GEMINI_CLI_HOME` | your home directory |
|
|
197
|
+
|
|
198
|
+
All defaults live in `src/config.ts`.
|
|
199
|
+
|
|
200
|
+
## Development
|
|
201
|
+
|
|
202
|
+
```sh
|
|
203
|
+
npm run build # tsc to dist/, copies prices.json and ../savings-skill/skill
|
|
204
|
+
npm run typecheck
|
|
205
|
+
npm test # vitest, against synthetic logs in test/fixtures
|
|
206
|
+
# refresh prices (from services/api):
|
|
207
|
+
uv run python ../../scripts/export_cli_prices.py
|
|
208
|
+
```
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { packageVersion, runCli } from "./cli.js";
|
|
5
|
+
import { fetchHttp, NodeFileSystem, processOutput, realSleeper, systemClock } from "./node-impl.js";
|
|
6
|
+
import { CatalogPriceBook, loadPriceFile } from "./pricing.js";
|
|
7
|
+
import { HttpComparisonPoster, HttpUploader } from "./sync.js";
|
|
8
|
+
const code = await runCli(process.argv.slice(2), {
|
|
9
|
+
env: process.env,
|
|
10
|
+
home: homedir(),
|
|
11
|
+
fs: new NodeFileSystem(),
|
|
12
|
+
clock: systemClock,
|
|
13
|
+
uploader: new HttpUploader(fetchHttp, realSleeper, systemClock),
|
|
14
|
+
poster: new HttpComparisonPoster(fetchHttp),
|
|
15
|
+
// The build copies packages/savings-skill/skill next to this file.
|
|
16
|
+
skillSourceDir: fileURLToPath(new URL("./skill/", import.meta.url)),
|
|
17
|
+
prices: new CatalogPriceBook(loadPriceFile()),
|
|
18
|
+
output: processOutput,
|
|
19
|
+
stdin: process.stdin,
|
|
20
|
+
stdout: process.stdout,
|
|
21
|
+
version: packageVersion(),
|
|
22
|
+
});
|
|
23
|
+
process.exitCode = code;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache audit over Claude Code prompt chains (sources/claude-prefix.ts).
|
|
3
|
+
*
|
|
4
|
+
* For a request whose previous request on the chain is known, that previous request's whole prompt
|
|
5
|
+
* (uncached input + cache read + cache write tokens) was sent again verbatim: the repeated prefix.
|
|
6
|
+
* Of those repeated tokens, the log shows how many were read from the cache; the rest were either
|
|
7
|
+
* billed at the full input price or written to the cache again. Measured, per request:
|
|
8
|
+
* read = min(cache read, repeated)
|
|
9
|
+
* full price = min(repeated - read, uncached input)
|
|
10
|
+
* rewritten = min(repeated - read - full price, cache write)
|
|
11
|
+
* Requests where the model changed (caches are per model) or the repeated prefix is shorter than the
|
|
12
|
+
* model's minimum cacheable length are not counted as cacheable.
|
|
13
|
+
*
|
|
14
|
+
* The estimated saving (labelled as an estimate) prices those tokens at the request's dated list
|
|
15
|
+
* prices: a full-price token repeated within 5 minutes could have been a cache read after a 5-minute
|
|
16
|
+
* write, and one within an hour after a 1-hour write; a token re-written after a 5-minute cache
|
|
17
|
+
* expired, but within an hour, could have been a read after a 1-hour write. The extra cost of the
|
|
18
|
+
* write is subtracted once per token, which is conservative when a prefix is read many times. Gaps
|
|
19
|
+
* over an hour are past any cache lifetime and saved nothing, and so is a re-write within the hour
|
|
20
|
+
* when the earlier request already wrote a 1-hour cache (the cause was not the lifetime).
|
|
21
|
+
*/
|
|
22
|
+
import { CACHE_FACTS } from "./config.js";
|
|
23
|
+
import { divRoundHalfEven, formatUsd, MICROS_PER_MTOK } from "./pricing.js";
|
|
24
|
+
export const AUDIT_BASIS = "Token counts are measured from your local Claude Code logs. The saving is an estimate at dated public " +
|
|
25
|
+
"list prices: it assumes the system prompt and tools were unchanged between the two requests (the log " +
|
|
26
|
+
"does not record them) and charges the cache write premium once per token.";
|
|
27
|
+
const buckets = () => ({ within5m: 0, within1h: 0, over1h: 0 });
|
|
28
|
+
function emptyRow(key) {
|
|
29
|
+
return {
|
|
30
|
+
key, requests: 0, withPrevious: 0, repeatedTokens: 0, readTokens: 0, fullPriceTokens: buckets(),
|
|
31
|
+
rewrittenTokens: buckets(), notCacheable: 0, estimatedSavingMicros: 0, unpricedRequests: 0,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function minCacheableTokens(modelId) {
|
|
35
|
+
let best = "";
|
|
36
|
+
for (const k of Object.keys(CACHE_FACTS.minTokens))
|
|
37
|
+
if (modelId.startsWith(k) && k.length > best.length)
|
|
38
|
+
best = k;
|
|
39
|
+
return best ? CACHE_FACTS.minTokens[best] : CACHE_FACTS.defaultMinTokens;
|
|
40
|
+
}
|
|
41
|
+
const prompt = (l) => l.inputTokens + l.cacheReadTokens + l.cacheWriteTokens;
|
|
42
|
+
function bucketOf(gapMs) {
|
|
43
|
+
if (gapMs <= CACHE_FACTS.ttl5mMs)
|
|
44
|
+
return "within5m";
|
|
45
|
+
return gapMs <= CACHE_FACTS.ttl1hMs ? "within1h" : "over1h";
|
|
46
|
+
}
|
|
47
|
+
/** Saving in micros (x 1M) for tokens at per-MTok rates; never below zero. */
|
|
48
|
+
function savingUnits(tokens, perTokenGain) {
|
|
49
|
+
return perTokenGain > 0 && tokens > 0 ? BigInt(tokens) * BigInt(perTokenGain) : 0n;
|
|
50
|
+
}
|
|
51
|
+
/** Per-MTok gain of caching a repeated token. `oneHourUsed`: the earlier request already wrote a
|
|
52
|
+
* 1-hour cache, so a longer lifetime would not have changed anything within the hour. */
|
|
53
|
+
function gains(sheet, bucket, oneHourUsed) {
|
|
54
|
+
const read = sheet.cache_read_per_mtok;
|
|
55
|
+
const w5 = sheet.cache_write_5m_per_mtok;
|
|
56
|
+
const w1 = sheet.cache_write_1h_per_mtok;
|
|
57
|
+
const inp = sheet.input_per_mtok;
|
|
58
|
+
if (read === null)
|
|
59
|
+
return { fullPrice: 0, rewrite: 0 };
|
|
60
|
+
if (bucket === "within5m")
|
|
61
|
+
return { fullPrice: w5 === null ? 0 : inp - read - (w5 - inp), rewrite: 0 };
|
|
62
|
+
if (bucket === "within1h" && !oneHourUsed) {
|
|
63
|
+
return {
|
|
64
|
+
fullPrice: w1 === null ? 0 : inp - read - (w1 - inp),
|
|
65
|
+
rewrite: w1 === null || w5 === null ? 0 : w5 - read - (w1 - w5),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return { fullPrice: 0, rewrite: 0 };
|
|
69
|
+
}
|
|
70
|
+
export function auditCaching(links, prices, range) {
|
|
71
|
+
const byKey = new Map(links.map((l) => [l.key, l]));
|
|
72
|
+
const rows = new Map();
|
|
73
|
+
const totals = emptyRow("total");
|
|
74
|
+
const sources = new Map();
|
|
75
|
+
const units = new Map();
|
|
76
|
+
const prefixUse = new Map();
|
|
77
|
+
for (const l of links) {
|
|
78
|
+
if (l.prefixHash)
|
|
79
|
+
prefixUse.set(l.prefixHash, (prefixUse.get(l.prefixHash) ?? 0) + 1);
|
|
80
|
+
const row = rows.get(l.model) ?? emptyRow(l.model);
|
|
81
|
+
rows.set(l.model, row);
|
|
82
|
+
const both = [row, totals];
|
|
83
|
+
for (const r of both)
|
|
84
|
+
r.requests++;
|
|
85
|
+
const prev = l.previous ? byKey.get(l.previous) : undefined;
|
|
86
|
+
if (!prev)
|
|
87
|
+
continue;
|
|
88
|
+
for (const r of both)
|
|
89
|
+
r.withPrevious++;
|
|
90
|
+
const sheet = prices.sheet("anthropic", l.model, l.at.toISOString().slice(0, 10));
|
|
91
|
+
const repeated = prompt(prev);
|
|
92
|
+
const modelId = sheet?.model_id ?? l.model;
|
|
93
|
+
if (prev.model !== l.model || repeated < minCacheableTokens(modelId)) {
|
|
94
|
+
for (const r of both)
|
|
95
|
+
r.notCacheable++;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const read = Math.min(l.cacheReadTokens, repeated);
|
|
99
|
+
const full = Math.min(repeated - read, l.inputTokens);
|
|
100
|
+
const rewritten = Math.min(repeated - read - full, l.cacheWriteTokens);
|
|
101
|
+
const bucket = bucketOf(l.at.getTime() - prev.at.getTime());
|
|
102
|
+
let u = 0n;
|
|
103
|
+
if (sheet) {
|
|
104
|
+
const g = gains(sheet, bucket, prev.cacheWrite1hTokens > 0);
|
|
105
|
+
u = savingUnits(full, g.fullPrice) + savingUnits(rewritten, g.rewrite);
|
|
106
|
+
if (full || rewritten)
|
|
107
|
+
sources.set(`${sheet.source_url}\u0000${sheet.observed_at}`, { url: sheet.source_url, observedAt: sheet.observed_at });
|
|
108
|
+
}
|
|
109
|
+
for (const r of both) {
|
|
110
|
+
r.repeatedTokens += repeated;
|
|
111
|
+
r.readTokens += read;
|
|
112
|
+
r.fullPriceTokens[bucket] += full;
|
|
113
|
+
r.rewrittenTokens[bucket] += rewritten;
|
|
114
|
+
if (!sheet && (full || rewritten))
|
|
115
|
+
r.unpricedRequests++;
|
|
116
|
+
units.set(r, (units.get(r) ?? 0n) + u);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const [r, u] of units)
|
|
120
|
+
r.estimatedSavingMicros = Number(divRoundHalfEven(u, MICROS_PER_MTOK));
|
|
121
|
+
return {
|
|
122
|
+
basis: AUDIT_BASIS, since: range.since, until: range.until,
|
|
123
|
+
rows: [...rows.values()].sort((a, b) => b.estimatedSavingMicros - a.estimatedSavingMicros || b.requests - a.requests),
|
|
124
|
+
totals, sharedPrefixes: [...prefixUse.values()].filter((v) => v > 1).length,
|
|
125
|
+
priceSources: [...sources.values()],
|
|
126
|
+
cacheFacts: { url: CACHE_FACTS.sourceUrl, observedAt: CACHE_FACTS.observedAt },
|
|
127
|
+
notes: [],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const n = (v) => v.toLocaleString("en-US");
|
|
131
|
+
const sum = (b) => b.within5m + b.within1h + b.over1h;
|
|
132
|
+
export function formatAudit(a) {
|
|
133
|
+
const t = a.totals;
|
|
134
|
+
const head = ["model", "requests", "repeated tokens", "read from cache", "full price", "re-written", "est. saving"];
|
|
135
|
+
const line = (r) => [
|
|
136
|
+
r.key, n(r.requests), n(r.repeatedTokens), n(r.readTokens), n(sum(r.fullPriceTokens)), n(sum(r.rewrittenTokens)),
|
|
137
|
+
formatUsd(r.estimatedSavingMicros) + (r.unpricedRequests ? " *" : ""),
|
|
138
|
+
];
|
|
139
|
+
const body = [head, ...a.rows.map(line), line(t)];
|
|
140
|
+
const widths = head.map((_, i) => Math.max(...body.map((c) => c[i].length)));
|
|
141
|
+
const fmt = (c) => c.map((x, i) => (i === 0 ? x.padEnd(widths[i]) : x.padStart(widths[i]))).join(" ");
|
|
142
|
+
const rule = widths.map((w) => "-".repeat(w)).join(" ");
|
|
143
|
+
const share = t.repeatedTokens ? ((t.readTokens / t.repeatedTokens) * 100).toFixed(1) : "0.0";
|
|
144
|
+
const out = [
|
|
145
|
+
`Claude Code prompt cache audit, ${a.since} to ${a.until ?? "now"}`,
|
|
146
|
+
"",
|
|
147
|
+
fmt(head), rule, ...a.rows.map((r) => fmt(line(r))), rule, fmt(line(t)),
|
|
148
|
+
"",
|
|
149
|
+
`Measured: ${n(t.withPrevious)} of ${n(t.requests)} requests repeated an earlier request's prompt; ${n(t.repeatedTokens)} repeated tokens, ${share}% read from the cache.`,
|
|
150
|
+
`Billed at full input price: ${n(t.fullPriceTokens.within5m)} within 5 minutes of the earlier request, ${n(t.fullPriceTokens.within1h)} within an hour, ${n(t.fullPriceTokens.over1h)} after more than an hour.`,
|
|
151
|
+
`Written to the cache again: ${n(t.rewrittenTokens.within5m)} within 5 minutes, ${n(t.rewrittenTokens.within1h)} within an hour, ${n(t.rewrittenTokens.over1h)} after more than an hour.`,
|
|
152
|
+
`${n(t.notCacheable)} request(s) not counted: the model changed or the repeated prompt was under the model's minimum cacheable length. ${n(a.sharedPrefixes)} prefix(es) were the start of more than one request.`,
|
|
153
|
+
`Estimated saving (estimate, not measured): ${formatUsd(t.estimatedSavingMicros)} at list prices.`,
|
|
154
|
+
"Prices: " + (a.priceSources.map((s) => `${s.url} (read ${s.observedAt})`).join("; ") || "none needed"),
|
|
155
|
+
`Cache rules: ${a.cacheFacts.url} (read ${a.cacheFacts.observedAt}).`,
|
|
156
|
+
a.basis,
|
|
157
|
+
];
|
|
158
|
+
if (t.unpricedRequests)
|
|
159
|
+
out.push(`* ${n(t.unpricedRequests)} request(s) with a model that has no list price have no saving estimate.`);
|
|
160
|
+
out.push(...a.notes);
|
|
161
|
+
return out.join("\n");
|
|
162
|
+
}
|