context-doctor 0.44.0 → 0.45.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 +2 -1
- package/dist/budget.d.ts +11 -1
- package/dist/budget.js +39 -23
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +1 -1
- package/dist/cachettl.js +6 -4
- package/dist/ci.js +18 -2
- package/dist/cli.js +10 -3
- package/dist/codexcompact.js +14 -7
- package/dist/coldresume.js +16 -8
- package/dist/compactwindow.js +12 -7
- package/dist/doctor.js +9 -2
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +14 -5
- package/dist/limits.js +26 -17
- package/dist/mcp.js +58 -58
- package/dist/mcpschema.js +5 -3
- package/dist/pack.js +66 -22
- package/dist/pricing.d.ts +105 -6
- package/dist/pricing.js +197 -61
- package/dist/proxy.d.ts +12 -1
- package/dist/proxy.js +13 -1
- package/dist/prune.js +55 -3
- package/dist/savings.js +15 -8
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +3 -2
- package/dist/sessionprice.js +16 -8
- package/dist/spend.d.ts +52 -9
- package/dist/spend.js +219 -25
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +17 -8
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +31 -24
- package/dist/subagents.js +11 -10
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.js +14 -5
- package/package.json +1 -1
package/dist/sessionprice.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
* (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
|
|
7
7
|
* So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
|
|
8
8
|
* CLI's BeforeAgent) the hook adds up what this session has cost, subagents
|
|
9
|
-
* included (they bill to it
|
|
9
|
+
* included (they bill to it: Claude Code's, and the agents a Codex thread
|
|
10
|
+
* spawned, codexSpawnedRollouts), and when it passes $25, $100 and $500 says so
|
|
10
11
|
* to the user once: the cost so far, what each message of the main
|
|
11
12
|
* conversation now costs at the model's cache-read rate (or, after an idle
|
|
12
13
|
* that expired the cache, the re-write this message pays), and that
|
|
@@ -37,12 +38,12 @@ import { createHash } from "node:crypto";
|
|
|
37
38
|
import { basename, dirname, join } from "node:path";
|
|
38
39
|
import { statePath } from "./ledger.js";
|
|
39
40
|
import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
|
|
40
|
-
import { codexFileSpend, geminiFileSpend } from "./spend.js";
|
|
41
|
+
import { codexFileSpend, codexSpawnedRollouts, geminiFileSpend } from "./spend.js";
|
|
41
42
|
import { isGeminiChat } from "./gemini.js";
|
|
42
43
|
import { subagentFiles } from "./subagents.js";
|
|
43
44
|
import { tailUsage } from "./statusline.js";
|
|
44
45
|
import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
|
|
45
|
-
import { formatUsd,
|
|
46
|
+
import { formatUsd, rateCard, ratesAt } from "./pricing.js";
|
|
46
47
|
import { formatTokens } from "./tokens.js";
|
|
47
48
|
/** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
|
|
48
49
|
export const SESSION_PRICE_THRESHOLDS = [25, 100, 500];
|
|
@@ -134,6 +135,10 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
|
|
|
134
135
|
if (app === "claude")
|
|
135
136
|
for (const f of subagentFiles(input.transcript))
|
|
136
137
|
files.push([f.file, f.run ? "workflow" : "sub"]);
|
|
138
|
+
// A Codex thread's spawned agents: their rollouts name it as their parent (a forked one's copy of its history counts once, by key).
|
|
139
|
+
if (app === "codex")
|
|
140
|
+
for (const f of codexSpawnedRollouts(input.transcript, now))
|
|
141
|
+
files.push([f, "sub"]);
|
|
137
142
|
let saved = {};
|
|
138
143
|
try {
|
|
139
144
|
const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
|
|
@@ -218,18 +223,21 @@ function perMessage(app, input, now) {
|
|
|
218
223
|
const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
|
|
219
224
|
const last = items[items.length - 1];
|
|
220
225
|
const model = last?.model ?? input.model;
|
|
221
|
-
const
|
|
222
|
-
|
|
226
|
+
const tokens = last ? last.input + last.read + last.write : 0;
|
|
227
|
+
// At the rate the next request bills: its prompt's tier (a long prompt's on OpenAI and Gemini Pro).
|
|
228
|
+
const card = rateCard(model, undefined, now);
|
|
229
|
+
if (!last || !card)
|
|
223
230
|
return {};
|
|
224
|
-
|
|
225
|
-
return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
|
|
231
|
+
return { tokens, model, readUsd: (tokens * ratesAt(card, tokens).cacheReadPerM) / 1e6 };
|
|
226
232
|
}
|
|
227
233
|
// Undefined right after a compaction: the new size is not known yet.
|
|
228
234
|
const live = tailUsage(input.transcript);
|
|
229
235
|
if (!live)
|
|
230
236
|
return {};
|
|
231
237
|
const model = live.model ?? input.model;
|
|
232
|
-
|
|
238
|
+
// As the next request bills: fast mode and US-only as the last one recorded, the tier of its prompt.
|
|
239
|
+
const card = rateCard(model, live.billing, now);
|
|
240
|
+
const p = card && ratesAt(card, live.tokens);
|
|
233
241
|
// Claude Code compacts this very prompt itself: the figure is about to be wrong.
|
|
234
242
|
if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
|
|
235
243
|
return {};
|
package/dist/spend.d.ts
CHANGED
|
@@ -21,7 +21,10 @@
|
|
|
21
21
|
* and an upper bound. Replies on Auto ("default") have no list price and
|
|
22
22
|
* are counted, not priced.
|
|
23
23
|
*
|
|
24
|
-
* Priced at pricing.ts's list prices
|
|
24
|
+
* Priced at pricing.ts's list prices with what each request recorded that
|
|
25
|
+
* changes its bill (requestCost: fast mode, US-only inference, a long
|
|
26
|
+
* prompt's tier, web searches, a price past its end date), as every report
|
|
27
|
+
* here is; the report says what the modifiers added.
|
|
25
28
|
* Claude Code, Codex and Gemini CLI are read through the shared scan
|
|
26
29
|
* (scan.ts), so a second run reads only what was appended since; Cursor's
|
|
27
30
|
* replies are kept per chat until the chat changes.
|
|
@@ -31,6 +34,7 @@
|
|
|
31
34
|
* sessions with 10+ requests. `spend` counts every request, its output and
|
|
32
35
|
* subagents too; on the requests both count, the dollars are the same.
|
|
33
36
|
*/
|
|
37
|
+
import { type Modifiers } from "./pricing.js";
|
|
34
38
|
import { type Extractor } from "./scan.js";
|
|
35
39
|
export type Tool = "claude" | "codex" | "gemini" | "cursor";
|
|
36
40
|
export declare const TOOLS: Tool[];
|
|
@@ -54,9 +58,13 @@ export interface SpendItem {
|
|
|
54
58
|
readUsd: number;
|
|
55
59
|
outputUsd: number;
|
|
56
60
|
priced: boolean;
|
|
57
|
-
/** Priced by its family's row, not one of its own (a new release, an id the table does not list)
|
|
61
|
+
/** Priced by its family's row, not one of its own (a new release, an id the table does not list), or past `changedOn`: an estimate. */
|
|
58
62
|
estimated?: boolean;
|
|
59
|
-
/**
|
|
63
|
+
/** Its model's price in the table changed on this day ("YYYY-MM-DD"), before the request: priced at what the page said would follow, an estimate. */
|
|
64
|
+
changedOn?: string;
|
|
65
|
+
/** What fast mode, US-only, a long prompt's tier and web searches added to its list price, inside `usd`; absent when nothing. */
|
|
66
|
+
modifiers?: Modifiers;
|
|
67
|
+
/** Run by a subagent: Claude Code's (the Agent tool's), or an agent a Codex thread spawned (its `session` is then the thread's). */
|
|
60
68
|
subagent?: boolean;
|
|
61
69
|
/** Claude Code: run by a workflow agent: its run, "<session>/<run>". */
|
|
62
70
|
workflow?: string;
|
|
@@ -73,22 +81,45 @@ export interface SpendItem {
|
|
|
73
81
|
export declare function projectFromDir(dir: string): string;
|
|
74
82
|
/** A project's name as `savings` shows it: the folder's path with "-" for separators, less the home folder. */
|
|
75
83
|
export declare function projectName(folder: string): string;
|
|
84
|
+
/** Whether a request's modifiers added anything (kept on an item only then). */
|
|
85
|
+
export declare const anyModifier: (m: Modifiers | undefined) => m is Modifiers;
|
|
76
86
|
/**
|
|
77
87
|
* Claude Code's requests between `since` and `until`, main threads and
|
|
78
88
|
* subagents, over `tops` (default: every transcript written since `since`).
|
|
79
89
|
*/
|
|
80
90
|
export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
|
|
81
91
|
/**
|
|
82
|
-
* What `spend` takes from a Codex rollout: its folder,
|
|
83
|
-
*
|
|
92
|
+
* What `spend` takes from a Codex rollout: its folder, its own id and the
|
|
93
|
+
* thread that spawned it (the first session_meta), each model change, and
|
|
94
|
+
* every token_count event's last request and running total.
|
|
84
95
|
*/
|
|
85
|
-
export declare const CODEX_SPEND_ROWS: Extractor<
|
|
96
|
+
export declare const CODEX_SPEND_ROWS: Extractor<{
|
|
97
|
+
m?: 1;
|
|
98
|
+
}>;
|
|
86
99
|
/** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
|
|
87
100
|
export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
|
|
88
101
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
89
102
|
export declare function codexFiles(since: number, home?: string): string[];
|
|
90
|
-
/**
|
|
103
|
+
/** A Codex rollout's own thread id and the thread that spawned it, when one did (spawnedBy). Throws when it cannot be read. */
|
|
104
|
+
export declare function codexRolloutMeta(file: string): {
|
|
105
|
+
id?: string;
|
|
106
|
+
parent?: string;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Every Codex request in the window, once: a forked rollout's copy of its
|
|
110
|
+
* parent's (codexEventKey) counts at the earliest time met. A spawned
|
|
111
|
+
* agent's requests are its session's (the thread at the top of its
|
|
112
|
+
* parents, when its rollout is among the window's), marked `subagent`: they
|
|
113
|
+
* bill to the same work, as a Claude Code subagent's do.
|
|
114
|
+
*/
|
|
91
115
|
export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
116
|
+
/**
|
|
117
|
+
* The rollouts of the agents a Codex thread spawned (and theirs), for the
|
|
118
|
+
* session price: those written since the thread began in its own folder,
|
|
119
|
+
* the day folders from then to `now` (by local and UTC date) and the
|
|
120
|
+
* archive. Only each candidate's first line is read.
|
|
121
|
+
*/
|
|
122
|
+
export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string): string[];
|
|
92
123
|
/**
|
|
93
124
|
* What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
|
|
94
125
|
* id, time, model and token counts. A message without a time of its own
|
|
@@ -113,7 +144,7 @@ export interface ToolSpend {
|
|
|
113
144
|
write: number;
|
|
114
145
|
output: number;
|
|
115
146
|
};
|
|
116
|
-
/**
|
|
147
|
+
/** What its subagents cost, inside `usd`: Claude Code's (the Agent tool's), Codex's spawned agents. */
|
|
117
148
|
subagentUsd?: number;
|
|
118
149
|
/** Claude Code: what its workflow agents cost, inside `usd`, and in how many workflow runs. */
|
|
119
150
|
workflowUsd?: number;
|
|
@@ -153,13 +184,23 @@ export interface SpendReport {
|
|
|
153
184
|
daily: Array<SpendRow & {
|
|
154
185
|
day: string;
|
|
155
186
|
}>;
|
|
156
|
-
/** The bill by what it paid for. */
|
|
187
|
+
/** The bill by what it paid for; web searches (Claude's, per use) only when there were any. */
|
|
157
188
|
parts: {
|
|
158
189
|
inputUsd: number;
|
|
159
190
|
writeUsd: number;
|
|
160
191
|
readUsd: number;
|
|
161
192
|
outputUsd: number;
|
|
193
|
+
webSearchUsd?: number;
|
|
162
194
|
};
|
|
195
|
+
/** What billing modifiers added to the list prices, inside `usd` (fast mode, US-only, long-prompt tiers, web searches); absent when nothing. */
|
|
196
|
+
modifiers?: Modifiers;
|
|
197
|
+
/** Models whose price in the table changed on a day before some of their requests: those are priced at what the page said would follow, an estimate. */
|
|
198
|
+
priceChanged?: Array<{
|
|
199
|
+
model: string;
|
|
200
|
+
on: string;
|
|
201
|
+
requests: number;
|
|
202
|
+
usd: number;
|
|
203
|
+
}>;
|
|
163
204
|
sessions: Array<{
|
|
164
205
|
tool: Tool;
|
|
165
206
|
project: string;
|
|
@@ -196,6 +237,8 @@ export declare const MAX_SPEND_DAYS = 3650;
|
|
|
196
237
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
197
238
|
export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
|
|
198
239
|
export declare const usd: (n: number) => string;
|
|
240
|
+
/** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
|
|
241
|
+
export declare function modifiersText(m: Modifiers): string;
|
|
199
242
|
/** The full report, kept within 80 columns. `top`: rows per list. */
|
|
200
243
|
export declare function renderSpend(r: SpendReport, top?: number): string;
|
|
201
244
|
/**
|
package/dist/spend.js
CHANGED
|
@@ -21,7 +21,10 @@
|
|
|
21
21
|
* and an upper bound. Replies on Auto ("default") have no list price and
|
|
22
22
|
* are counted, not priced.
|
|
23
23
|
*
|
|
24
|
-
* Priced at pricing.ts's list prices
|
|
24
|
+
* Priced at pricing.ts's list prices with what each request recorded that
|
|
25
|
+
* changes its bill (requestCost: fast mode, US-only inference, a long
|
|
26
|
+
* prompt's tier, web searches, a price past its end date), as every report
|
|
27
|
+
* here is; the report says what the modifiers added.
|
|
25
28
|
* Claude Code, Codex and Gemini CLI are read through the shared scan
|
|
26
29
|
* (scan.ts), so a second run reads only what was appended since; Cursor's
|
|
27
30
|
* replies are kept per chat until the chat changes.
|
|
@@ -34,11 +37,11 @@
|
|
|
34
37
|
import { basename, dirname, join } from "node:path";
|
|
35
38
|
import { codexDir } from "./codexdir.js";
|
|
36
39
|
import { homedir } from "node:os";
|
|
37
|
-
import { existsSync, statSync } from "node:fs";
|
|
40
|
+
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
38
41
|
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
39
42
|
import { listGeminiChats, readGeminiMessages } from "./gemini.js";
|
|
40
43
|
import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
|
|
41
|
-
import {
|
|
44
|
+
import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
|
|
42
45
|
import { pick, rowsOf } from "./scan.js";
|
|
43
46
|
import { formatTokens } from "./tokens.js";
|
|
44
47
|
import { withInvocation } from "./invocation.js";
|
|
@@ -63,13 +66,24 @@ export function projectName(folder) {
|
|
|
63
66
|
function claudeProject(top) {
|
|
64
67
|
return projectFromDir(basename(dirname(top)));
|
|
65
68
|
}
|
|
69
|
+
/** Whether a request's modifiers added anything (kept on an item only then). */
|
|
70
|
+
export const anyModifier = (m) => Boolean(m && (m.fastUsd || m.geoUsd || m.longUsd || m.webSearchUsd || m.webSearches));
|
|
71
|
+
/** An estimate's labels, and what the modifiers added, onto an item. */
|
|
72
|
+
function label(item, c) {
|
|
73
|
+
if (c.estimated)
|
|
74
|
+
item.estimated = true;
|
|
75
|
+
if (c.changedOn)
|
|
76
|
+
item.changedOn = c.changedOn;
|
|
77
|
+
if (anyModifier(c.modifiers))
|
|
78
|
+
item.modifiers = c.modifiers;
|
|
79
|
+
return item;
|
|
80
|
+
}
|
|
66
81
|
/** `priceAs`: the id to price it by, when the model's own name is not one the table knows (Cursor's names for Claude). */
|
|
67
82
|
function priced(base, u, priceAs = base.model) {
|
|
68
|
-
const
|
|
69
|
-
if (!
|
|
83
|
+
const c = requestCost(priceAs, u, base.ts);
|
|
84
|
+
if (!c)
|
|
70
85
|
return { ...base, usd: 0, inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0, priced: false };
|
|
71
|
-
|
|
72
|
-
return { ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true, ...(hasKnownPrice(priceAs) ? {} : { estimated: true }) };
|
|
86
|
+
return label({ ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true }, c);
|
|
73
87
|
}
|
|
74
88
|
// ---------------------------------------------------------------------------
|
|
75
89
|
// Claude Code
|
|
@@ -94,16 +108,15 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
|
94
108
|
const project = claudeProject(f.top);
|
|
95
109
|
const session = basename(f.top, ".jsonl");
|
|
96
110
|
for (const r of reqs) {
|
|
97
|
-
const price =
|
|
98
|
-
// claudeFileUsage priced it (writes by TTL); the split is what the drivers show.
|
|
111
|
+
const price = r.rates;
|
|
112
|
+
// claudeFileUsage priced it (requestCost: writes by TTL, its modifiers); the split is what the drivers show.
|
|
99
113
|
const inputUsd = price ? (r.input * price.inputPerM) / 1e6 : 0;
|
|
100
114
|
const readUsd = price ? (r.read * price.cacheReadPerM) / 1e6 : 0;
|
|
101
115
|
const item = {
|
|
102
116
|
tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
|
|
103
|
-
usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd), priced: Boolean(price),
|
|
117
|
+
usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd - r.modifiers.webSearchUsd), priced: Boolean(price),
|
|
104
118
|
};
|
|
105
|
-
|
|
106
|
-
item.estimated = true;
|
|
119
|
+
label(item, r);
|
|
107
120
|
if (r.model)
|
|
108
121
|
item.model = r.model;
|
|
109
122
|
if (f.run)
|
|
@@ -122,13 +135,26 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
|
122
135
|
// Codex
|
|
123
136
|
// ---------------------------------------------------------------------------
|
|
124
137
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
138
|
+
* A spawned Codex agent's rollout names the thread that spawned it in its
|
|
139
|
+
* own (first) session_meta: `parent_thread_id`, also under
|
|
140
|
+
* `source.subagent.thread_spawn` (Codex Desktop 0.146, seen on the author's
|
|
141
|
+
* machine; a forked one starts with a copy of its parent's history, its
|
|
142
|
+
* session_meta rows included, which name no parent of theirs). A thread the
|
|
143
|
+
* user forked names only `forked_from_id`: a session of its own.
|
|
144
|
+
*/
|
|
145
|
+
function spawnedBy(p) {
|
|
146
|
+
const parent = p.parent_thread_id ?? p.source?.subagent?.thread_spawn?.parent_thread_id;
|
|
147
|
+
return typeof parent === "string" && parent ? parent : undefined;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* What `spend` takes from a Codex rollout: its folder, its own id and the
|
|
151
|
+
* thread that spawned it (the first session_meta), each model change, and
|
|
152
|
+
* every token_count event's last request and running total.
|
|
127
153
|
*/
|
|
128
154
|
export const CODEX_SPEND_ROWS = {
|
|
129
|
-
id: "codex-spend.
|
|
130
|
-
init: () =>
|
|
131
|
-
line(line, row, out) {
|
|
155
|
+
id: "codex-spend.3",
|
|
156
|
+
init: () => ({}),
|
|
157
|
+
line(line, row, out, st) {
|
|
132
158
|
if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
|
|
133
159
|
return;
|
|
134
160
|
let e;
|
|
@@ -141,6 +167,12 @@ export const CODEX_SPEND_ROWS = {
|
|
|
141
167
|
const p = e?.payload;
|
|
142
168
|
if (!p || typeof p !== "object")
|
|
143
169
|
return;
|
|
170
|
+
if (e.type === "session_meta" && !st.m) {
|
|
171
|
+
st.m = 1;
|
|
172
|
+
const parent = spawnedBy(p);
|
|
173
|
+
if (typeof p.id === "string")
|
|
174
|
+
out.push({ k: "meta", id: p.id, ...(parent ? { parent } : {}) });
|
|
175
|
+
}
|
|
144
176
|
if (e.type === "session_meta" || e.type === "turn_context") {
|
|
145
177
|
if (typeof p.cwd === "string")
|
|
146
178
|
out.push({ k: "cwd", cwd: p.cwd });
|
|
@@ -164,6 +196,8 @@ export function codexFileSpend(file, since, until = Infinity) {
|
|
|
164
196
|
let model, cwd;
|
|
165
197
|
let total = -1;
|
|
166
198
|
for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
|
|
199
|
+
if (r.k === "meta")
|
|
200
|
+
continue;
|
|
167
201
|
if (r.k === "cwd") {
|
|
168
202
|
cwd = cwd ?? r.cwd;
|
|
169
203
|
continue;
|
|
@@ -190,18 +224,141 @@ export function codexFiles(since, home = homedir()) {
|
|
|
190
224
|
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
191
225
|
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
|
|
192
226
|
}
|
|
193
|
-
/**
|
|
227
|
+
/** A Codex rollout's own thread id and the thread that spawned it, when one did (spawnedBy). Throws when it cannot be read. */
|
|
228
|
+
export function codexRolloutMeta(file) {
|
|
229
|
+
const m = rowsOf(file, CODEX_SPEND_ROWS).find((r) => r?.k === "meta");
|
|
230
|
+
return m ? { id: m.id, ...(m.parent ? { parent: m.parent } : {}) } : {};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Every Codex request in the window, once: a forked rollout's copy of its
|
|
234
|
+
* parent's (codexEventKey) counts at the earliest time met. A spawned
|
|
235
|
+
* agent's requests are its session's (the thread at the top of its
|
|
236
|
+
* parents, when its rollout is among the window's), marked `subagent`: they
|
|
237
|
+
* bill to the same work, as a Claude Code subagent's do.
|
|
238
|
+
*/
|
|
194
239
|
export function codexSpend(since, until = Infinity, home = homedir()) {
|
|
195
240
|
const all = [];
|
|
241
|
+
const files = new Map();
|
|
242
|
+
const byFile = [];
|
|
196
243
|
for (const f of codexFiles(since, home)) {
|
|
197
244
|
try {
|
|
198
|
-
|
|
245
|
+
const items = codexFileSpend(f, since, until);
|
|
246
|
+
const meta = codexRolloutMeta(f);
|
|
247
|
+
if (meta.id && !files.has(meta.id))
|
|
248
|
+
files.set(meta.id, { file: f, ...(meta.parent ? { parent: meta.parent } : {}) });
|
|
249
|
+
byFile.push([f, items]);
|
|
199
250
|
}
|
|
200
251
|
catch { /* unreadable: skipped */ }
|
|
201
252
|
}
|
|
253
|
+
// Each spawned rollout's top known parent: its session.
|
|
254
|
+
const sessionOf = new Map();
|
|
255
|
+
for (const { file, parent } of files.values()) {
|
|
256
|
+
let top;
|
|
257
|
+
for (let p = parent, hops = 0; p && files.has(p) && hops < 32; p = files.get(p).parent, hops++)
|
|
258
|
+
top = p;
|
|
259
|
+
if (top)
|
|
260
|
+
sessionOf.set(file, basename(files.get(top).file, ".jsonl"));
|
|
261
|
+
}
|
|
262
|
+
for (const [f, items] of byFile) {
|
|
263
|
+
const session = sessionOf.get(f);
|
|
264
|
+
for (const it of items)
|
|
265
|
+
all.push(session ? { ...it, session, subagent: true } : it);
|
|
266
|
+
}
|
|
202
267
|
const seen = new Set();
|
|
203
268
|
return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
|
|
204
269
|
}
|
|
270
|
+
/** Rollout names end in the thread's id: rollout-<time>-<id>.jsonl. */
|
|
271
|
+
const rolloutId = (file) => /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(basename(file))?.[1];
|
|
272
|
+
/** The first line's start of a rollout (its own session_meta), as much as `bytes` holds. */
|
|
273
|
+
function rolloutHead(file, bytes = 16 * 1024) {
|
|
274
|
+
const fd = openSync(file, "r");
|
|
275
|
+
try {
|
|
276
|
+
const buf = Buffer.alloc(bytes);
|
|
277
|
+
const n = readSync(fd, buf, 0, bytes, 0);
|
|
278
|
+
const text = buf.subarray(0, n).toString("utf8");
|
|
279
|
+
const nl = text.indexOf("\n");
|
|
280
|
+
return nl >= 0 ? text.slice(0, nl) : text;
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
closeSync(fd);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** The thread a rollout's head says spawned it (spawnedBy), read from its first line without parsing the rest. */
|
|
287
|
+
function headParent(file) {
|
|
288
|
+
const head = rolloutHead(file);
|
|
289
|
+
try {
|
|
290
|
+
const p = JSON.parse(head)?.payload ?? {};
|
|
291
|
+
return { id: typeof p.id === "string" ? p.id : undefined, parent: spawnedBy(p) };
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
// The line goes on past what was read (its instructions): its first fields are enough.
|
|
295
|
+
return { id: /"id":"([^"]+)"/.exec(head)?.[1], parent: /"parent_thread_id":"([^"]+)"/.exec(head)?.[1] };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* The rollouts of the agents a Codex thread spawned (and theirs), for the
|
|
300
|
+
* session price: those written since the thread began in its own folder,
|
|
301
|
+
* the day folders from then to `now` (by local and UTC date) and the
|
|
302
|
+
* archive. Only each candidate's first line is read.
|
|
303
|
+
*/
|
|
304
|
+
export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir()) {
|
|
305
|
+
const id = rolloutId(parent);
|
|
306
|
+
if (!id)
|
|
307
|
+
return [];
|
|
308
|
+
let born;
|
|
309
|
+
try {
|
|
310
|
+
born = statSync(parent).birthtimeMs || statSync(parent).mtimeMs;
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
const m = /rollout-(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/.exec(basename(parent));
|
|
316
|
+
if (m)
|
|
317
|
+
born = Math.min(born, new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime());
|
|
318
|
+
const root = codexSessionsRoot(home);
|
|
319
|
+
const dirs = new Set([dirname(parent), join(codexDir(home), "archived_sessions")]);
|
|
320
|
+
// A long session's days, a day either side; bounded, so a bad clock is not a walk of years.
|
|
321
|
+
for (let t = Math.max(born, now - 90 * DAY) - DAY; t <= now + DAY; t += 3_600_000) {
|
|
322
|
+
const d = new Date(t);
|
|
323
|
+
for (const [y, mo, dd] of [[d.getFullYear(), d.getMonth() + 1, d.getDate()], [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]])
|
|
324
|
+
dirs.add(join(root, String(y), String(mo).padStart(2, "0"), String(dd).padStart(2, "0")));
|
|
325
|
+
}
|
|
326
|
+
const heads = new Map();
|
|
327
|
+
for (const dir of dirs) {
|
|
328
|
+
let names;
|
|
329
|
+
try {
|
|
330
|
+
names = readdirSync(dir);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
for (const n of names) {
|
|
336
|
+
const f = join(dir, n);
|
|
337
|
+
if (!n.startsWith("rollout-") || !n.endsWith(".jsonl") || f === parent || heads.has(f))
|
|
338
|
+
continue;
|
|
339
|
+
try {
|
|
340
|
+
if (statSync(f).mtimeMs < born)
|
|
341
|
+
continue;
|
|
342
|
+
heads.set(f, headParent(f));
|
|
343
|
+
}
|
|
344
|
+
catch { /* vanished */ }
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
// Children, then theirs.
|
|
348
|
+
const mine = new Set([id]);
|
|
349
|
+
const out = [];
|
|
350
|
+
for (let grew = true; grew;) {
|
|
351
|
+
grew = false;
|
|
352
|
+
for (const [f, h] of heads) {
|
|
353
|
+
if (!h.parent || !mine.has(h.parent) || !h.id || mine.has(h.id))
|
|
354
|
+
continue;
|
|
355
|
+
mine.add(h.id);
|
|
356
|
+
out.push(f);
|
|
357
|
+
grew = true;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return out.sort((a, b) => basename(a).localeCompare(basename(b)));
|
|
361
|
+
}
|
|
205
362
|
// ---------------------------------------------------------------------------
|
|
206
363
|
// Gemini CLI
|
|
207
364
|
// ---------------------------------------------------------------------------
|
|
@@ -327,7 +484,17 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
327
484
|
const sessionModels = new Map();
|
|
328
485
|
const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
|
|
329
486
|
const runs = new Set();
|
|
487
|
+
const mods = { ...NO_MODIFIERS };
|
|
488
|
+
const changed = new Map();
|
|
330
489
|
for (const it of items) {
|
|
490
|
+
if (it.modifiers)
|
|
491
|
+
addModifiers(mods, it.modifiers);
|
|
492
|
+
if (it.changedOn) {
|
|
493
|
+
const k = `${it.model}\u0000${it.changedOn}`;
|
|
494
|
+
const c = changed.get(k) ?? changed.set(k, { model: it.model ?? "unknown", on: it.changedOn, requests: 0, usd: 0 }).get(k);
|
|
495
|
+
c.requests++;
|
|
496
|
+
c.usd += it.usd;
|
|
497
|
+
}
|
|
331
498
|
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);
|
|
332
499
|
t.usd += it.usd;
|
|
333
500
|
t.requests++;
|
|
@@ -335,8 +502,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
335
502
|
t.tokens.read += it.read;
|
|
336
503
|
t.tokens.write += it.write;
|
|
337
504
|
t.tokens.output += it.output;
|
|
338
|
-
if (it.subagent
|
|
339
|
-
t.subagentUsd
|
|
505
|
+
if (it.subagent)
|
|
506
|
+
t.subagentUsd = (t.subagentUsd ?? 0) + it.usd;
|
|
340
507
|
if (it.workflow) {
|
|
341
508
|
t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
|
|
342
509
|
runs.add(it.workflow);
|
|
@@ -349,7 +516,7 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
349
516
|
if (!t.unpricedModels.includes(m))
|
|
350
517
|
t.unpricedModels.push(m);
|
|
351
518
|
}
|
|
352
|
-
else if (it.estimated) {
|
|
519
|
+
else if (it.estimated && !it.changedOn) {
|
|
353
520
|
const e = (t.estimated ??= { requests: 0, usd: 0, models: [] });
|
|
354
521
|
e.requests++;
|
|
355
522
|
e.usd += it.usd;
|
|
@@ -386,6 +553,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
386
553
|
const day = localDay(d.getTime());
|
|
387
554
|
days_.push({ day, ...(daily.get(day) ?? { usd: 0, requests: 0, byTool: {} }) });
|
|
388
555
|
}
|
|
556
|
+
if (mods.webSearchUsd > 0)
|
|
557
|
+
parts.webSearchUsd = mods.webSearchUsd;
|
|
389
558
|
return {
|
|
390
559
|
days, since, until,
|
|
391
560
|
usd: items.reduce((n, it) => n + it.usd, 0),
|
|
@@ -395,6 +564,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
395
564
|
models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
|
|
396
565
|
daily: days_,
|
|
397
566
|
parts,
|
|
567
|
+
...(anyModifier(mods) ? { modifiers: mods } : {}),
|
|
568
|
+
...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
|
|
398
569
|
sessions: [...sessions.values()].sort(byUsd),
|
|
399
570
|
skipped,
|
|
400
571
|
};
|
|
@@ -430,6 +601,15 @@ const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}
|
|
|
430
601
|
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
431
602
|
const shortDay = (day) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(8, 10)}`;
|
|
432
603
|
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
|
604
|
+
/** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
|
|
605
|
+
export function modifiersText(m) {
|
|
606
|
+
return [
|
|
607
|
+
m.fastUsd > 0 ? `fast mode +${usd(m.fastUsd)}` : "",
|
|
608
|
+
m.geoUsd > 0 ? `US-only +${usd(m.geoUsd)}` : "",
|
|
609
|
+
m.webSearches > 0 ? `web searches ${usd(m.webSearchUsd)} (${m.webSearches.toLocaleString("en-US")})` : "",
|
|
610
|
+
m.longUsd > 0 ? `long-prompt tier +${usd(m.longUsd)}` : "",
|
|
611
|
+
].filter(Boolean).join(", ");
|
|
612
|
+
}
|
|
433
613
|
/** The full report, kept within 80 columns. `top`: rows per list. */
|
|
434
614
|
export function renderSpend(r, top = 8) {
|
|
435
615
|
const lines = [];
|
|
@@ -463,7 +643,9 @@ export function renderSpend(r, top = 8) {
|
|
|
463
643
|
const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
|
|
464
644
|
// One priced by its family's row reads as the estimate it is.
|
|
465
645
|
const estimatedModels = new Set(r.tools.flatMap((t) => t.estimated?.models ?? []));
|
|
466
|
-
|
|
646
|
+
// One priced past the day its price changed, likewise.
|
|
647
|
+
const changedOn = new Map((r.priceChanged ?? []).map((c) => [c.model, c.on]));
|
|
648
|
+
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"}` } : estimatedModels.has(m.model) ? { tail: "estimate: its family's price" } : changedOn.has(m.model) ? { tail: `estimate: price changed ${changedOn.get(m.model)}` } : {}) })), r.models.length - top);
|
|
467
649
|
// The last two weeks of the window, a bar each, scaled to the busiest.
|
|
468
650
|
const recent = r.daily.slice(-14);
|
|
469
651
|
const peak = Math.max(...recent.map((d) => d.usd), 0);
|
|
@@ -471,10 +653,13 @@ export function renderSpend(r, top = 8) {
|
|
|
471
653
|
for (const d of recent)
|
|
472
654
|
lines.push(` ${shortDay(d.day)} ${usd(d.usd).padStart(9)} ${peak > 0 ? "▮".repeat(Math.round((d.usd / peak) * 30)) : ""}`);
|
|
473
655
|
lines.push("", "Where it goes");
|
|
474
|
-
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
|
|
656
|
+
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
|
|
475
657
|
const partText = parts.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${usd(v)} (${share(v, r.usd)})`);
|
|
476
658
|
for (let i = 0; i < partText.length; i += 2)
|
|
477
659
|
lines.push(` ${partText.slice(i, i + 2).join(", ")}`);
|
|
660
|
+
// What the requests' own billing added to the list rates, already in the parts above.
|
|
661
|
+
if (r.modifiers)
|
|
662
|
+
lines.push(` Of it, billed above list rates: ${modifiersText(r.modifiers)}`);
|
|
478
663
|
const claude = r.tools.find((t) => t.tool === "claude");
|
|
479
664
|
if (claude?.subagentUsd)
|
|
480
665
|
lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
|
|
@@ -500,6 +685,11 @@ export function renderSpend(r, top = 8) {
|
|
|
500
685
|
notes.push(`${n.toLocaleString("en-US")} ${t.name} ${t.tool === "cursor" ? (n === 1 ? "reply" : "replies") : n === 1 ? "request" : "requests"} (${usd(t.estimated.usd)}) priced as ${n === 1 ? "its" : "their"} model's family, an estimate:`);
|
|
501
686
|
notes.push(` no list price of its own for ${t.estimated.models.slice(0, 3).join(", ")}${t.estimated.models.length > 3 ? " and others" : ""}.`);
|
|
502
687
|
}
|
|
688
|
+
if (r.priceChanged) {
|
|
689
|
+
const n = r.priceChanged.reduce((s, c) => s + c.requests, 0);
|
|
690
|
+
notes.push(`${n.toLocaleString("en-US")} ${n === 1 ? "request" : "requests"} (${usd(r.priceChanged.reduce((s, c) => s + c.usd, 0))}) priced past the day ${n === 1 ? "its" : "their"} model's price changed, an estimate:`);
|
|
691
|
+
notes.push(` ${priceChangedText(r.priceChanged.map((c) => [c.model, c.on]))}.`);
|
|
692
|
+
}
|
|
503
693
|
if (r.tools.some((t) => t.estimate))
|
|
504
694
|
notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
|
|
505
695
|
for (const s of r.skipped)
|
|
@@ -531,7 +721,11 @@ export function renderSpendShare(r) {
|
|
|
531
721
|
const estimated = r.tools.reduce((n, t) => n + (t.estimated?.usd ?? 0), 0);
|
|
532
722
|
if (r.tools.some((t) => t.estimated))
|
|
533
723
|
lines.push(`Of it, ${usd(estimated)} is on models priced as their family, an estimate.`);
|
|
534
|
-
|
|
724
|
+
if (r.priceChanged)
|
|
725
|
+
lines.push(`Of it, ${usd(r.priceChanged.reduce((s, c) => s + c.usd, 0))} is on models priced past the day their price changed, an estimate.`);
|
|
726
|
+
if (r.modifiers)
|
|
727
|
+
lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
|
|
728
|
+
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
|
|
535
729
|
const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
|
|
536
730
|
const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
|
|
537
731
|
if (r.models[0] && r.usd > 0)
|
package/dist/statusline.d.ts
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
* prints nothing at all, because a status line that shows an error is worse
|
|
29
29
|
* than one that shows nothing.
|
|
30
30
|
*/
|
|
31
|
+
import { type RecordedUsage } from "./pricing.js";
|
|
31
32
|
/** The parts of Claude Code's status payload this reads. All optional. */
|
|
32
33
|
interface StatusInput {
|
|
33
34
|
session_id?: string;
|
|
@@ -52,6 +53,8 @@ interface StatusInput {
|
|
|
52
53
|
input_tokens?: number;
|
|
53
54
|
cache_read_input_tokens?: number;
|
|
54
55
|
cache_creation_input_tokens?: number;
|
|
56
|
+
speed?: string;
|
|
57
|
+
inference_geo?: string;
|
|
55
58
|
} | null;
|
|
56
59
|
};
|
|
57
60
|
}
|
|
@@ -74,6 +77,8 @@ interface LiveUsage {
|
|
|
74
77
|
tokens: number;
|
|
75
78
|
cacheShare?: number;
|
|
76
79
|
model?: string;
|
|
80
|
+
/** What the last request recorded that changes its price (fast mode, US-only): the next one is billed alike. */
|
|
81
|
+
billing?: Pick<RecordedUsage, "speed" | "inference_geo">;
|
|
77
82
|
}
|
|
78
83
|
/** Newest assistant usage from the END of a transcript, without reading the file. */
|
|
79
84
|
export declare function tailUsage(path: string, tailBytes?: number): LiveUsage | undefined;
|
|
@@ -83,9 +88,12 @@ export declare function tailUsage(path: string, tailBytes?: number): LiveUsage |
|
|
|
83
88
|
* 2x at an hour) where a warm one would read them (0.1x). The extra is the
|
|
84
89
|
* price; tokens alone when the model has no price. Undefined when Claude Code
|
|
85
90
|
* does not say (no `prompt_cache`, caching off, or right after a compaction
|
|
86
|
-
* while the cache is cold).
|
|
91
|
+
* while the cache is cold). Priced as the next request bills (requestCost's
|
|
92
|
+
* rate card): `billing` (fast mode, US-only) as the last request recorded,
|
|
93
|
+
* and the tier of a prompt of `prompt` tokens (the re-cached ones when not
|
|
94
|
+
* given).
|
|
87
95
|
*/
|
|
88
|
-
export declare function cacheClock(pc: PromptCache | null | undefined, model: string | undefined, nowMs?: number): string | undefined;
|
|
96
|
+
export declare function cacheClock(pc: PromptCache | null | undefined, model: string | undefined, nowMs?: number, billing?: LiveUsage["billing"], prompt?: number): string | undefined;
|
|
89
97
|
/**
|
|
90
98
|
* Build the status line, or null when there is nothing trustworthy to show.
|
|
91
99
|
* `budget`: the spend budget's part ("$12/$50 today"), when one is set.
|