context-doctor 0.40.0 → 0.42.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/README.md +12 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +102 -0
- package/dist/budget.js +550 -0
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +145 -15
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.d.ts +23 -0
- package/dist/cursor.js +140 -6
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +49 -12
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +23 -2
- package/dist/fix.js +86 -10
- package/dist/hook.js +45 -7
- package/dist/install.js +108 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +53 -6
- package/dist/limits.js +152 -77
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +10 -0
- package/dist/scan.js +23 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +183 -0
- package/dist/spend.js +493 -0
- package/dist/statusline.d.ts +9 -2
- package/dist/statusline.js +20 -4
- package/dist/subagentmodel.d.ts +141 -0
- package/dist/subagentmodel.js +408 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +23 -4
- package/package.json +1 -1
package/dist/spend.js
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor spend`: one bill across every AI coding tool on this
|
|
3
|
+
* machine, at list prices.
|
|
4
|
+
*
|
|
5
|
+
* Each tool keeps its own record of what it sent, and none adds them up:
|
|
6
|
+
*
|
|
7
|
+
* - Claude Code: every reply's `usage` in its transcripts, the main
|
|
8
|
+
* conversation and each subagent's (`<session>/subagents/agent-*.jsonl`),
|
|
9
|
+
* read as `limits` reads them (claudeFileUsage): each reply once, its
|
|
10
|
+
* output settled on its last row, a fork's copy of its parent counted once.
|
|
11
|
+
* - Codex: the `token_count` events of its rollouts (~/.codex/sessions and
|
|
12
|
+
* archived_sessions), a request each time the running total moves, as
|
|
13
|
+
* `limits` counts them; the model from `turn_context`, the folder from
|
|
14
|
+
* `session_meta`.
|
|
15
|
+
* - Gemini CLI: each `gemini` message's `tokens` in ~/.gemini/tmp/<project>/chats,
|
|
16
|
+
* the last copy of a message written twice. A message later rewound was
|
|
17
|
+
* still billed, so it is counted.
|
|
18
|
+
* - Cursor: the `tokenCount` on its agent replies (cursorUsage). It records
|
|
19
|
+
* no cache split, so every input token is priced uncached: an estimate,
|
|
20
|
+
* and an upper bound. Replies on Auto ("default") have no list price and
|
|
21
|
+
* are counted, not priced.
|
|
22
|
+
*
|
|
23
|
+
* Priced at pricing.ts's list prices (usageCost), as every report here is.
|
|
24
|
+
* Claude Code, Codex and Gemini CLI are read through the shared scan
|
|
25
|
+
* (scan.ts), so a second run reads only what was appended since; Cursor's
|
|
26
|
+
* replies are kept per chat until the chat changes.
|
|
27
|
+
*
|
|
28
|
+
* `savings` bills a narrower slice of the same Claude Code requests: the main
|
|
29
|
+
* conversation's input (cache writes and reads included, output not), in
|
|
30
|
+
* sessions with 10+ requests. `spend` counts every request, its output and
|
|
31
|
+
* subagents too; on the requests both count, the dollars are the same.
|
|
32
|
+
*/
|
|
33
|
+
import { basename, dirname, join } from "node:path";
|
|
34
|
+
import { codexDir } from "./codexdir.js";
|
|
35
|
+
import { homedir } from "node:os";
|
|
36
|
+
import { existsSync, statSync } from "node:fs";
|
|
37
|
+
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
38
|
+
import { listGeminiChats, readGeminiMessages } from "./gemini.js";
|
|
39
|
+
import { cursorUsage, SqliteUnavailableError } from "./cursor.js";
|
|
40
|
+
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
41
|
+
import { pick, rowsOf } from "./scan.js";
|
|
42
|
+
import { formatTokens } from "./tokens.js";
|
|
43
|
+
import { withInvocation } from "./invocation.js";
|
|
44
|
+
const DAY = 86_400_000;
|
|
45
|
+
export const TOOLS = ["claude", "codex", "gemini", "cursor"];
|
|
46
|
+
export const TOOL_NAME = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", cursor: "Cursor" };
|
|
47
|
+
/** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
|
|
48
|
+
export function projectName(folder) {
|
|
49
|
+
const dir = folder.replace(/[^A-Za-z0-9]/g, "-");
|
|
50
|
+
return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
|
|
51
|
+
}
|
|
52
|
+
/** A Claude Code transcript's project: its folder under projects/, named as `savings` names it. */
|
|
53
|
+
function claudeProject(top) {
|
|
54
|
+
const dir = basename(dirname(top));
|
|
55
|
+
return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
|
|
56
|
+
}
|
|
57
|
+
function priced(base, u) {
|
|
58
|
+
const price = pricingFor(base.model);
|
|
59
|
+
if (!price)
|
|
60
|
+
return { ...base, usd: 0, inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0, priced: false };
|
|
61
|
+
const c = usageCost(u, price);
|
|
62
|
+
return { ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true };
|
|
63
|
+
}
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// Claude Code
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
/**
|
|
68
|
+
* Claude Code's requests between `since` and `until`, main threads and
|
|
69
|
+
* subagents, over `tops` (default: every transcript written since `since`).
|
|
70
|
+
*/
|
|
71
|
+
export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
72
|
+
const out = [];
|
|
73
|
+
const runRows = new Set();
|
|
74
|
+
const files = claudeUsageFiles(since, tops);
|
|
75
|
+
for (const [i, f] of files.entries()) {
|
|
76
|
+
onProgress?.(i, files.length);
|
|
77
|
+
let reqs;
|
|
78
|
+
try {
|
|
79
|
+
reqs = claudeFileUsage(f.file, since, until, runRows);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
continue; // one unreadable transcript must not sink the report
|
|
83
|
+
}
|
|
84
|
+
const project = claudeProject(f.top);
|
|
85
|
+
const session = basename(f.top, ".jsonl");
|
|
86
|
+
for (const r of reqs) {
|
|
87
|
+
const price = pricingFor(r.model);
|
|
88
|
+
// claudeFileUsage priced it (writes by TTL); the split is what the drivers show.
|
|
89
|
+
const inputUsd = price ? (r.input * price.inputPerM) / 1e6 : 0;
|
|
90
|
+
const readUsd = price ? (r.read * price.cacheReadPerM) / 1e6 : 0;
|
|
91
|
+
const item = {
|
|
92
|
+
tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
|
|
93
|
+
usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd), priced: Boolean(price),
|
|
94
|
+
};
|
|
95
|
+
if (r.model)
|
|
96
|
+
item.model = r.model;
|
|
97
|
+
if (f.subagent || r.sidechain)
|
|
98
|
+
item.subagent = true;
|
|
99
|
+
if (r.uuid)
|
|
100
|
+
item.key = r.uuid;
|
|
101
|
+
out.push(item);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
onProgress?.(files.length, files.length);
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Codex
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
/**
|
|
111
|
+
* What `spend` takes from a Codex rollout: its folder, each model change,
|
|
112
|
+
* and every token_count event's last request and running total.
|
|
113
|
+
*/
|
|
114
|
+
export const CODEX_SPEND_ROWS = {
|
|
115
|
+
id: "codex-spend.2",
|
|
116
|
+
init: () => null,
|
|
117
|
+
line(line, row, out) {
|
|
118
|
+
if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
|
|
119
|
+
return;
|
|
120
|
+
let e;
|
|
121
|
+
try {
|
|
122
|
+
e = row();
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const p = e?.payload;
|
|
128
|
+
if (!p || typeof p !== "object")
|
|
129
|
+
return;
|
|
130
|
+
if (e.type === "session_meta" || e.type === "turn_context") {
|
|
131
|
+
if (typeof p.cwd === "string")
|
|
132
|
+
out.push({ k: "cwd", cwd: p.cwd });
|
|
133
|
+
if (e.type === "turn_context" && typeof p.model === "string")
|
|
134
|
+
out.push({ k: "model", model: p.model });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (e.type !== "event_msg" || p.type !== "token_count")
|
|
138
|
+
return;
|
|
139
|
+
const last = p.info?.last_token_usage;
|
|
140
|
+
if (!last || typeof last !== "object")
|
|
141
|
+
return;
|
|
142
|
+
const total = p.info?.total_token_usage?.total_tokens;
|
|
143
|
+
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, key: codexEventKey(p.info?.total_token_usage, last), u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
147
|
+
/** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
|
|
148
|
+
export function codexFileSpend(file, since, until = Infinity) {
|
|
149
|
+
const out = [];
|
|
150
|
+
let model, cwd;
|
|
151
|
+
let total = -1;
|
|
152
|
+
for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
|
|
153
|
+
if (r.k === "cwd") {
|
|
154
|
+
cwd = cwd ?? r.cwd;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (r.k === "model") {
|
|
158
|
+
model = r.model;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
// A token_count event repeats the last request when only the limits were refreshed.
|
|
162
|
+
const runTotal = num(r.total);
|
|
163
|
+
if (num(r.u?.input_tokens) === 0 || (runTotal !== 0 && runTotal === total))
|
|
164
|
+
continue;
|
|
165
|
+
total = runTotal;
|
|
166
|
+
const ts = Date.parse(r.ts);
|
|
167
|
+
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
168
|
+
continue;
|
|
169
|
+
const u = openAIUsage(r.u);
|
|
170
|
+
out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { model } : {}), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), ...(r.key ? { key: r.key } : {}) }, u));
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
175
|
+
export function codexFiles(since, home = homedir()) {
|
|
176
|
+
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
177
|
+
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
|
|
178
|
+
}
|
|
179
|
+
/** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
|
|
180
|
+
export function codexSpend(since, until = Infinity, home = homedir()) {
|
|
181
|
+
const all = [];
|
|
182
|
+
for (const f of codexFiles(since, home)) {
|
|
183
|
+
try {
|
|
184
|
+
all.push(...codexFileSpend(f, since, until));
|
|
185
|
+
}
|
|
186
|
+
catch { /* unreadable: skipped */ }
|
|
187
|
+
}
|
|
188
|
+
const seen = new Set();
|
|
189
|
+
return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
|
|
190
|
+
}
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
// Gemini CLI
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
/**
|
|
195
|
+
* What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
|
|
196
|
+
* id, time, model and token counts. A message without a time of its own
|
|
197
|
+
* takes the last time met before it.
|
|
198
|
+
*/
|
|
199
|
+
export const GEMINI_SPEND_ROWS = {
|
|
200
|
+
id: "gemini-spend.1",
|
|
201
|
+
init: () => ({ ts: "" }),
|
|
202
|
+
line(line, row, out, st) {
|
|
203
|
+
if (!line.includes('"tokens"') && !line.includes('"timestamp"') && !line.includes('"startTime"'))
|
|
204
|
+
return;
|
|
205
|
+
let r;
|
|
206
|
+
try {
|
|
207
|
+
r = row();
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (!r || typeof r !== "object")
|
|
213
|
+
return;
|
|
214
|
+
const at = typeof r.timestamp === "string" ? r.timestamp : typeof r.startTime === "string" ? r.startTime : "";
|
|
215
|
+
if (at)
|
|
216
|
+
st.ts = at;
|
|
217
|
+
if (r.type !== "gemini" || !r.tokens || typeof r.tokens !== "object")
|
|
218
|
+
return;
|
|
219
|
+
const rec = { ts: st.ts, t: pick(r.tokens, ["input", "output", "cached", "thoughts"]) };
|
|
220
|
+
if (typeof r.id === "string")
|
|
221
|
+
rec.id = r.id;
|
|
222
|
+
if (typeof r.model === "string")
|
|
223
|
+
rec.model = r.model;
|
|
224
|
+
out.push(rec);
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
/** Gemini's counts as recorded usage: `input` includes the cached part; thoughts bill as output. */
|
|
228
|
+
function geminiUsage(t) {
|
|
229
|
+
const input = num(t.input), cached = Math.min(input, num(t.cached));
|
|
230
|
+
return { input_tokens: input - cached, cache_read_input_tokens: cached, cache_creation_input_tokens: 0, output_tokens: num(t.output) + num(t.thoughts) };
|
|
231
|
+
}
|
|
232
|
+
/** The billed messages of one Gemini CLI chat since `since`. Throws when it cannot be read. */
|
|
233
|
+
export function geminiFileSpend(file, since, until = Infinity) {
|
|
234
|
+
// A message written again (its tokens arrive after its text) replaces the earlier copy.
|
|
235
|
+
const byId = new Map();
|
|
236
|
+
let anon = 0;
|
|
237
|
+
if (file.endsWith(".jsonl")) {
|
|
238
|
+
for (const r of rowsOf(file, GEMINI_SPEND_ROWS))
|
|
239
|
+
byId.set(r.id ?? `anon-${anon++}`, r);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
// Older Gemini CLI: one JSON document, small, read whole.
|
|
243
|
+
let last = "";
|
|
244
|
+
for (const m of readGeminiMessages(file)) {
|
|
245
|
+
if (typeof m?.timestamp === "string")
|
|
246
|
+
last = m.timestamp;
|
|
247
|
+
if (m?.type === "gemini" && m.tokens && typeof m.tokens === "object")
|
|
248
|
+
byId.set(typeof m.id === "string" ? m.id : `anon-${anon++}`, { ts: last, t: m.tokens, model: typeof m.model === "string" ? m.model : undefined });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const project = basename(dirname(dirname(file)));
|
|
252
|
+
const out = [];
|
|
253
|
+
let model, mtime;
|
|
254
|
+
for (const r of byId.values()) {
|
|
255
|
+
model = r.model ?? model;
|
|
256
|
+
// No time anywhere before it: the chat's last write.
|
|
257
|
+
const ts = Date.parse(r.ts) || (mtime ??= statSync(file).mtimeMs);
|
|
258
|
+
if (ts < since || ts > until)
|
|
259
|
+
continue;
|
|
260
|
+
const u = geminiUsage(r.t);
|
|
261
|
+
if (num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.output_tokens) === 0)
|
|
262
|
+
continue;
|
|
263
|
+
out.push(priced({ tool: "gemini", ts, project: /^[0-9a-f]{40,}$/.test(project) ? project.slice(0, 8) : project, session: basename(file).replace(/\.jsonl?$/, ""), ...(model ? { model } : {}), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: 0, output: num(u.output_tokens) }, u));
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
export function geminiFiles(since, home = homedir()) {
|
|
268
|
+
return listGeminiChats(home).filter((s) => s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
269
|
+
}
|
|
270
|
+
export function geminiSpend(since, until = Infinity, home = homedir()) {
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const f of geminiFiles(since, home)) {
|
|
273
|
+
try {
|
|
274
|
+
out.push(...geminiFileSpend(f, since, until));
|
|
275
|
+
}
|
|
276
|
+
catch { /* unreadable: skipped */ }
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
// ---------------------------------------------------------------------------
|
|
281
|
+
// Cursor
|
|
282
|
+
// ---------------------------------------------------------------------------
|
|
283
|
+
export function cursorSpend(since, until = Infinity) {
|
|
284
|
+
const out = [];
|
|
285
|
+
for (const r of cursorUsage(since)) {
|
|
286
|
+
if (r.ts > until)
|
|
287
|
+
continue;
|
|
288
|
+
// No cache split: every input token at the uncached rate.
|
|
289
|
+
out.push(priced({ tool: "cursor", ts: r.ts, project: r.folder ? projectName(r.folder) : "(no folder)", session: r.composerId, ...(r.model ? { model: r.model } : {}), input: r.input, read: 0, write: 0, output: r.output }, { input_tokens: r.input, output_tokens: r.output }));
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
/** The local calendar day of `ts`, "YYYY-MM-DD". */
|
|
294
|
+
export function localDay(ts) {
|
|
295
|
+
const d = new Date(ts);
|
|
296
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
297
|
+
}
|
|
298
|
+
function add(map, key, it) {
|
|
299
|
+
const r = map.get(key) ?? map.set(key, { usd: 0, requests: 0, byTool: {} }).get(key);
|
|
300
|
+
r.usd += it.usd;
|
|
301
|
+
r.requests++;
|
|
302
|
+
r.byTool[it.tool] = (r.byTool[it.tool] ?? 0) + it.usd;
|
|
303
|
+
}
|
|
304
|
+
/** Add up priced requests into the report. */
|
|
305
|
+
export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
306
|
+
const tools = new Map();
|
|
307
|
+
const projects = new Map(), models = new Map(), daily = new Map();
|
|
308
|
+
const sessions = new Map();
|
|
309
|
+
const sessionModels = new Map();
|
|
310
|
+
const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
|
|
311
|
+
for (const it of items) {
|
|
312
|
+
const t = tools.get(it.tool) ?? tools.set(it.tool, { tool: it.tool, name: TOOL_NAME[it.tool], usd: 0, requests: 0, tokens: { input: 0, read: 0, write: 0, output: 0 }, unpriced: 0, unpricedTokens: 0, unpricedModels: [], ...(it.tool === "cursor" ? { estimate: true } : {}), ...(it.tool === "claude" ? { subagentUsd: 0 } : {}) }).get(it.tool);
|
|
313
|
+
t.usd += it.usd;
|
|
314
|
+
t.requests++;
|
|
315
|
+
t.tokens.input += it.input;
|
|
316
|
+
t.tokens.read += it.read;
|
|
317
|
+
t.tokens.write += it.write;
|
|
318
|
+
t.tokens.output += it.output;
|
|
319
|
+
if (it.subagent && t.subagentUsd !== undefined)
|
|
320
|
+
t.subagentUsd += it.usd;
|
|
321
|
+
if (!it.priced) {
|
|
322
|
+
t.unpriced++;
|
|
323
|
+
t.unpricedTokens += it.input + it.read + it.write + it.output;
|
|
324
|
+
const m = it.model ?? "unknown";
|
|
325
|
+
if (!t.unpricedModels.includes(m))
|
|
326
|
+
t.unpricedModels.push(m);
|
|
327
|
+
}
|
|
328
|
+
add(projects, it.project, it);
|
|
329
|
+
add(models, it.model ?? "unknown", it);
|
|
330
|
+
add(daily, localDay(it.ts), it);
|
|
331
|
+
parts.inputUsd += it.inputUsd;
|
|
332
|
+
parts.writeUsd += it.writeUsd;
|
|
333
|
+
parts.readUsd += it.readUsd;
|
|
334
|
+
parts.outputUsd += it.outputUsd;
|
|
335
|
+
const sk = `${it.tool}\u0000${it.session}`;
|
|
336
|
+
const s = sessions.get(sk) ?? sessions.set(sk, { tool: it.tool, project: it.project, session: it.session, usd: 0, requests: 0, first: it.ts, last: it.ts }).get(sk);
|
|
337
|
+
s.usd += it.usd;
|
|
338
|
+
s.requests++;
|
|
339
|
+
s.first = Math.min(s.first, it.ts);
|
|
340
|
+
s.last = Math.max(s.last, it.ts);
|
|
341
|
+
if (it.model) {
|
|
342
|
+
const ms = sessionModels.get(sk) ?? sessionModels.set(sk, new Map()).get(sk);
|
|
343
|
+
ms.set(it.model, (ms.get(it.model) ?? 0) + it.usd);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Each session's model: the one it spent most on.
|
|
347
|
+
for (const [sk, ms] of sessionModels)
|
|
348
|
+
sessions.get(sk).model = [...ms].sort((a, b) => b[1] - a[1])[0][0];
|
|
349
|
+
const byUsd = (a, b) => b.usd - a.usd || b.requests - a.requests;
|
|
350
|
+
// Every day of the window, the empty ones too: a day off reads as a day off.
|
|
351
|
+
const days_ = [];
|
|
352
|
+
const s0 = new Date(since);
|
|
353
|
+
for (const d = new Date(s0.getFullYear(), s0.getMonth(), s0.getDate()); d.getTime() <= until; d.setDate(d.getDate() + 1)) {
|
|
354
|
+
const day = localDay(d.getTime());
|
|
355
|
+
days_.push({ day, ...(daily.get(day) ?? { usd: 0, requests: 0, byTool: {} }) });
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
days, since, until,
|
|
359
|
+
usd: items.reduce((n, it) => n + it.usd, 0),
|
|
360
|
+
requests: items.length,
|
|
361
|
+
tools: TOOLS.filter((t) => tools.has(t)).map((t) => tools.get(t)).sort(byUsd),
|
|
362
|
+
projects: [...projects].map(([project, r]) => ({ project, ...r })).sort(byUsd),
|
|
363
|
+
models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
|
|
364
|
+
daily: days_,
|
|
365
|
+
parts,
|
|
366
|
+
sessions: [...sessions.values()].sort(byUsd),
|
|
367
|
+
skipped,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The longest window: ten years, older than any history these tools keep.
|
|
372
|
+
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
373
|
+
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
374
|
+
*/
|
|
375
|
+
export const MAX_SPEND_DAYS = 3650;
|
|
376
|
+
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
377
|
+
export function spendReport(days = 30, opts = {}) {
|
|
378
|
+
days = Math.min(days, MAX_SPEND_DAYS);
|
|
379
|
+
const until = opts.now ?? Date.now();
|
|
380
|
+
const since = until - days * DAY;
|
|
381
|
+
const home = opts.home ?? homedir();
|
|
382
|
+
const items = [...claudeSpend(since, until, opts.claudePaths, opts.onProgress), ...codexSpend(since, until, home), ...geminiSpend(since, until, home)];
|
|
383
|
+
const skipped = [];
|
|
384
|
+
try {
|
|
385
|
+
items.push(...cursorSpend(since, until));
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
if (e instanceof SqliteUnavailableError)
|
|
389
|
+
skipped.push({ tool: "cursor", reason: "reading Cursor's history needs SQLite: Node 22.13+ or the sqlite3 command" });
|
|
390
|
+
}
|
|
391
|
+
return summarizeSpend(items, days, since, until, skipped);
|
|
392
|
+
}
|
|
393
|
+
// ---------------------------------------------------------------------------
|
|
394
|
+
// Rendering
|
|
395
|
+
// ---------------------------------------------------------------------------
|
|
396
|
+
export const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n > 0 && n < 0.005 ? "<$0.01" : `$${n.toFixed(2)}`);
|
|
397
|
+
const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "");
|
|
398
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
399
|
+
const shortDay = (day) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(8, 10)}`;
|
|
400
|
+
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
|
401
|
+
/** The full report, kept within 80 columns. `top`: rows per list. */
|
|
402
|
+
export function renderSpend(r, top = 8) {
|
|
403
|
+
const lines = [];
|
|
404
|
+
if (r.requests === 0) {
|
|
405
|
+
lines.push(`No usage in the last ${r.days} days from Claude Code, Codex, Gemini CLI or Cursor on this machine.`);
|
|
406
|
+
for (const s of r.skipped)
|
|
407
|
+
lines.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
|
|
408
|
+
return lines.join("\n");
|
|
409
|
+
}
|
|
410
|
+
lines.push("What your AI coding cost, across every tool here");
|
|
411
|
+
lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices`);
|
|
412
|
+
lines.push("─".repeat(60));
|
|
413
|
+
for (const t of r.tools) {
|
|
414
|
+
const unit = t.tool === "cursor" ? "replies" : "requests";
|
|
415
|
+
const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
|
|
416
|
+
const note = notes.length ? ` ${notes.join(", ")}` : "";
|
|
417
|
+
lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
|
|
418
|
+
}
|
|
419
|
+
if (r.tools.length > 1)
|
|
420
|
+
lines.push(`${"Total".padEnd(14)}${usd(r.usd).padStart(11)}`);
|
|
421
|
+
const list = (title, rows, more) => {
|
|
422
|
+
lines.push("", title);
|
|
423
|
+
for (const x of rows)
|
|
424
|
+
lines.push(` ${clip(x.name, 34).padEnd(34)}${usd(x.usd).padStart(10)} ${share(x.usd, r.usd).padStart(4)}${x.tail ? ` ${x.tail}` : ""}`);
|
|
425
|
+
if (more > 0)
|
|
426
|
+
lines.push(` … and ${more} more`);
|
|
427
|
+
};
|
|
428
|
+
const toolsOf = (byTool) => (r.tools.length > 1 ? TOOLS.filter((t) => (byTool[t] ?? 0) > 0).map((t) => TOOL_NAME[t]).join(", ") : undefined);
|
|
429
|
+
list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
|
|
430
|
+
// A model with no list price reads "not priced", not a $0.00 that looks free.
|
|
431
|
+
const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
|
|
432
|
+
list("By model", r.models.slice(0, top).map((m) => ({ name: m.model, usd: m.usd, ...(m.usd === 0 && unpricedModels.has(m.model) ? { tail: `not priced, ${m.requests.toLocaleString("en-US")} ${m.requests === 1 ? "request" : "requests"}` } : {}) })), r.models.length - top);
|
|
433
|
+
// The last two weeks of the window, a bar each, scaled to the busiest.
|
|
434
|
+
const recent = r.daily.slice(-14);
|
|
435
|
+
const peak = Math.max(...recent.map((d) => d.usd), 0);
|
|
436
|
+
lines.push("", `By day${r.daily.length > recent.length ? " (last 14; all in --json)" : ""}`);
|
|
437
|
+
for (const d of recent)
|
|
438
|
+
lines.push(` ${shortDay(d.day)} ${usd(d.usd).padStart(9)} ${peak > 0 ? "▮".repeat(Math.round((d.usd / peak) * 30)) : ""}`);
|
|
439
|
+
lines.push("", "Where it goes");
|
|
440
|
+
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
|
|
441
|
+
const partText = parts.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${usd(v)} (${share(v, r.usd)})`);
|
|
442
|
+
for (let i = 0; i < partText.length; i += 2)
|
|
443
|
+
lines.push(` ${partText.slice(i, i + 2).join(", ")}`);
|
|
444
|
+
const claude = r.tools.find((t) => t.tool === "claude");
|
|
445
|
+
if (claude?.subagentUsd)
|
|
446
|
+
lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
|
|
447
|
+
lines.push(" Biggest sessions:");
|
|
448
|
+
for (const s of r.sessions.slice(0, Math.min(top, 5))) {
|
|
449
|
+
const when = shortDay(localDay(s.last));
|
|
450
|
+
lines.push(` ${usd(s.usd).padStart(9)} ${clip(s.project, 26).padEnd(26)} ${clip(s.model ?? "", 18).padEnd(18)} ${when}${r.tools.length > 1 ? ` ${TOOL_NAME[s.tool]}` : ""}`);
|
|
451
|
+
}
|
|
452
|
+
const notes = [];
|
|
453
|
+
for (const t of r.tools) {
|
|
454
|
+
if (t.unpriced === 0)
|
|
455
|
+
continue;
|
|
456
|
+
const auto = t.tool === "cursor" && t.unpricedModels.every((m) => m === "default" || m === "auto");
|
|
457
|
+
notes.push(`${t.unpriced.toLocaleString("en-US")} ${t.name} ${t.tool === "cursor" ? "replies" : "requests"} (${formatTokens(t.unpricedTokens)} tokens) not priced:`);
|
|
458
|
+
notes.push(` ${auto ? "on Auto, which Cursor bills from your plan with no list price" : `no list price for ${t.unpricedModels.slice(0, 3).join(", ")}`}.`);
|
|
459
|
+
}
|
|
460
|
+
if (r.tools.some((t) => t.estimate))
|
|
461
|
+
notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
|
|
462
|
+
for (const s of r.skipped)
|
|
463
|
+
notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
|
|
464
|
+
if (notes.length)
|
|
465
|
+
lines.push("", ...notes);
|
|
466
|
+
lines.push("", "List prices, as an API key bills; on a subscription the same tokens come out");
|
|
467
|
+
lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
|
|
468
|
+
return withInvocation(lines.map((l) => l.trimEnd()).join("\n"));
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* `spend --share`: totals only. No project names, paths or session ids, so
|
|
472
|
+
* sharing it leaks nothing.
|
|
473
|
+
*/
|
|
474
|
+
export function renderSpendShare(r) {
|
|
475
|
+
if (r.requests === 0)
|
|
476
|
+
return "context-doctor found no AI coding usage to measure yet.";
|
|
477
|
+
const tools = r.tools.map((t) => `${t.name} ${t.estimate ? "~" : ""}${usd(t.usd)}${t.estimate ? " (estimate)" : ""}`).join(", ");
|
|
478
|
+
const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
|
|
479
|
+
const claude = r.tools.find((t) => t.tool === "claude");
|
|
480
|
+
if (claude?.subagentUsd)
|
|
481
|
+
lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
|
|
482
|
+
// Requests on a model with no list price are not in the total: said, so the total is not read as all of it.
|
|
483
|
+
const unpriced = r.tools.reduce((n, t) => n + t.unpriced, 0);
|
|
484
|
+
if (unpriced)
|
|
485
|
+
lines.push(`Not in it: ${unpriced.toLocaleString("en-US")} ${unpriced === 1 ? "request" : "requests"} (${formatTokens(r.tools.reduce((n, t) => n + t.unpricedTokens, 0))} tokens) on models with no list price.`);
|
|
486
|
+
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
|
|
487
|
+
const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
|
|
488
|
+
const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
|
|
489
|
+
if (r.models[0] && r.usd > 0)
|
|
490
|
+
lines.push(`Top model ${r.models[0].model} (${share(r.models[0].usd, r.usd)}); the biggest part is ${bigPart} (${share(bigUsd, r.usd)}); busiest day ${usd(busiest.usd)}.`);
|
|
491
|
+
lines.push("Measured locally from my own history with context-doctor: npx context-doctor spend");
|
|
492
|
+
return lines.join("\n");
|
|
493
|
+
}
|
package/dist/statusline.d.ts
CHANGED
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
* (Pro and Max), each new 5-hour and weekly reading is appended to
|
|
19
19
|
* ~/.claude/.context-doctor-limits.jsonl for `context-doctor limits`.
|
|
20
20
|
*
|
|
21
|
+
* With a spend budget set (`context-doctor budget`), the session's cost gives
|
|
22
|
+
* way to the period's across tools, "$12/$50 today", from the same ledger
|
|
23
|
+
* the every-prompt hook keeps (budget.ts).
|
|
24
|
+
*
|
|
21
25
|
* It has to be fast and silent. Fast: the status payload on stdin carries the
|
|
22
26
|
* live context size in recent versions; when it does not, only the tail of the
|
|
23
27
|
* transcript is read (last 256KB, ~1ms on a 20MB file). Silent: any failure
|
|
@@ -82,7 +86,10 @@ export declare function tailUsage(path: string, tailBytes?: number): LiveUsage |
|
|
|
82
86
|
* while the cache is cold).
|
|
83
87
|
*/
|
|
84
88
|
export declare function cacheClock(pc: PromptCache | null | undefined, model: string | undefined, nowMs?: number): string | undefined;
|
|
85
|
-
/**
|
|
86
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Build the status line, or null when there is nothing trustworthy to show.
|
|
91
|
+
* `budget`: the spend budget's part ("$12/$50 today"), when one is set.
|
|
92
|
+
*/
|
|
93
|
+
export declare function renderStatusLine(input: StatusInput, nowMs?: number, budget?: string): string | null;
|
|
87
94
|
export declare function runStatusLine(): Promise<void>;
|
|
88
95
|
export {};
|
package/dist/statusline.js
CHANGED
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
* (Pro and Max), each new 5-hour and weekly reading is appended to
|
|
19
19
|
* ~/.claude/.context-doctor-limits.jsonl for `context-doctor limits`.
|
|
20
20
|
*
|
|
21
|
+
* With a spend budget set (`context-doctor budget`), the session's cost gives
|
|
22
|
+
* way to the period's across tools, "$12/$50 today", from the same ledger
|
|
23
|
+
* the every-prompt hook keeps (budget.ts).
|
|
24
|
+
*
|
|
21
25
|
* It has to be fast and silent. Fast: the status payload on stdin carries the
|
|
22
26
|
* live context size in recent versions; when it does not, only the tail of the
|
|
23
27
|
* transcript is read (last 256KB, ~1ms on a 20MB file). Silent: any failure
|
|
@@ -29,6 +33,7 @@ import { contextWindowFor, formatTokens } from "./tokens.js";
|
|
|
29
33
|
import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, pricingFor } from "./pricing.js";
|
|
30
34
|
import { recordLimits } from "./limits.js";
|
|
31
35
|
import { recordMiss } from "./missledger.js";
|
|
36
|
+
import { budgetStatus } from "./budget.js";
|
|
32
37
|
/** Newest assistant usage from the END of a transcript, without reading the file. */
|
|
33
38
|
export function tailUsage(path, tailBytes = 256 * 1024) {
|
|
34
39
|
try {
|
|
@@ -119,8 +124,11 @@ export function cacheClock(pc, model, nowMs = Date.now()) {
|
|
|
119
124
|
}
|
|
120
125
|
return undefined;
|
|
121
126
|
}
|
|
122
|
-
/**
|
|
123
|
-
|
|
127
|
+
/**
|
|
128
|
+
* Build the status line, or null when there is nothing trustworthy to show.
|
|
129
|
+
* `budget`: the spend budget's part ("$12/$50 today"), when one is set.
|
|
130
|
+
*/
|
|
131
|
+
export function renderStatusLine(input, nowMs = Date.now(), budget) {
|
|
124
132
|
let live;
|
|
125
133
|
const cw = input.context_window;
|
|
126
134
|
// Only current_usage is the context. total_input_tokens is a running total
|
|
@@ -156,7 +164,10 @@ export function renderStatusLine(input, nowMs = Date.now()) {
|
|
|
156
164
|
if (warmth)
|
|
157
165
|
parts.push(warmth);
|
|
158
166
|
// The session's cost is true whatever the context is; show it on its own.
|
|
159
|
-
|
|
167
|
+
// With a budget set, the period's spend across tools takes the session's cost's place: it includes it.
|
|
168
|
+
if (budget)
|
|
169
|
+
parts.push(budget);
|
|
170
|
+
else if (input.cost?.total_cost_usd && input.cost.total_cost_usd > 0)
|
|
160
171
|
parts.push(formatUsd(input.cost.total_cost_usd));
|
|
161
172
|
return parts.length > 0 ? parts.join(" · ") : null;
|
|
162
173
|
}
|
|
@@ -169,7 +180,12 @@ async function readStdin() {
|
|
|
169
180
|
export async function runStatusLine() {
|
|
170
181
|
try {
|
|
171
182
|
const input = JSON.parse(await readStdin());
|
|
172
|
-
|
|
183
|
+
let budget;
|
|
184
|
+
try {
|
|
185
|
+
budget = budgetStatus();
|
|
186
|
+
}
|
|
187
|
+
catch { /* the line goes out without it */ }
|
|
188
|
+
const line = renderStatusLine(input, Date.now(), budget);
|
|
173
189
|
if (line)
|
|
174
190
|
console.log(line);
|
|
175
191
|
// After the line is out: the limit readings `context-doctor limits` fits
|