context-doctor 0.45.0 → 0.47.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 +8 -3
- package/dist/ab.js +3 -2
- package/dist/autopilot.js +9 -5
- package/dist/blob.js +66 -12
- package/dist/budget.d.ts +10 -1
- package/dist/budget.js +37 -8
- package/dist/cachemisses.js +5 -3
- package/dist/cacheplan.js +2 -2
- package/dist/cachettl.js +2 -1
- package/dist/ci.js +2 -1
- package/dist/claudeplugin.d.ts +97 -0
- package/dist/claudeplugin.js +142 -0
- package/dist/cli.js +126 -39
- package/dist/coldresume.d.ts +6 -0
- package/dist/coldresume.js +7 -6
- package/dist/compactcost.d.ts +74 -0
- package/dist/compactcost.js +115 -0
- package/dist/compactwindow.js +5 -4
- package/dist/cursor.js +2 -0
- package/dist/doctor.js +106 -17
- package/dist/extract.js +4 -3
- package/dist/fanout.d.ts +15 -0
- package/dist/fanout.js +31 -10
- package/dist/firstfix.d.ts +43 -0
- package/dist/firstfix.js +80 -0
- package/dist/fix.d.ts +46 -2
- package/dist/fix.js +109 -20
- package/dist/hook.js +6 -2
- package/dist/httpguard.d.ts +13 -0
- package/dist/httpguard.js +22 -0
- package/dist/install.d.ts +21 -9
- package/dist/install.js +211 -40
- package/dist/limits.d.ts +5 -0
- package/dist/limits.js +26 -2
- package/dist/mcp.js +63 -62
- package/dist/missledger.js +5 -3
- package/dist/mod/api.d.ts +135 -0
- package/dist/mod/api.js +12 -0
- package/dist/mod/logic.d.ts +158 -0
- package/dist/mod/logic.js +244 -0
- package/dist/mod/register.d.ts +60 -0
- package/dist/mod/register.js +251 -0
- package/dist/modelids.d.ts +24 -0
- package/dist/modelids.js +65 -0
- package/dist/modelswitch.js +8 -4
- package/dist/modmeasure.d.ts +121 -0
- package/dist/modmeasure.js +310 -0
- package/dist/orgrates.d.ts +93 -0
- package/dist/orgrates.js +214 -0
- package/dist/overhead.js +11 -8
- package/dist/pack.d.ts +13 -0
- package/dist/pack.js +68 -3
- package/dist/preferences.js +2 -1
- package/dist/pricing.d.ts +26 -0
- package/dist/pricing.js +61 -7
- package/dist/progresssummaries.d.ts +148 -0
- package/dist/progresssummaries.js +248 -0
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +11 -1
- package/dist/savings.js +8 -6
- package/dist/sessionprice.d.ts +22 -0
- package/dist/sessionprice.js +46 -14
- package/dist/spend.d.ts +46 -3
- package/dist/spend.js +86 -10
- package/dist/statusline.js +2 -2
- package/dist/subagentmodel.d.ts +12 -0
- package/dist/subagentmodel.js +17 -4
- package/dist/subagentpay.d.ts +15 -1
- package/dist/subagentpay.js +58 -25
- package/dist/subagents.js +4 -0
- package/dist/toolcwd.d.ts +14 -0
- package/dist/toolcwd.js +17 -0
- package/package.json +1 -1
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor mod measure`: what the plugin's mod hands over after each
|
|
3
|
+
* turn, kept the way the status line keeps it.
|
|
4
|
+
*
|
|
5
|
+
* The status line never runs in the Desktop app's Code tab or the VS Code
|
|
6
|
+
* extension, so there the limit ledger stayed empty and Claude Code's own
|
|
7
|
+
* cost was never compared with ours (ROADMAP K2). A mod runs there: after
|
|
8
|
+
* each main-thread turn Claude Code raises `session.measure` with the
|
|
9
|
+
* rate-limit windows (`kind`, `percentUsed`, `resetsAt` as ISO 8601) and the
|
|
10
|
+
* session's cost (`cost.usd`, as /cost totals it). The mod has no file
|
|
11
|
+
* access of its own worth trusting with our formats, so it runs this command
|
|
12
|
+
* with that reading on stdin, and this:
|
|
13
|
+
*
|
|
14
|
+
* - appends the windows to the limits ledger in the status line's own
|
|
15
|
+
* format and with its rules (recordLimits: changes only, at most once a
|
|
16
|
+
* minute, never a lower figure of the same window from a parallel
|
|
17
|
+
* session), so `context-doctor limits` reads Desktop's readings too;
|
|
18
|
+
* - appends Claude Code's cost beside our own price of the same session
|
|
19
|
+
* (sessionTotal: the transcript and its subagents, as the every-prompt
|
|
20
|
+
* hook prices it) to a small capped ledger, for `doctor`'s comparison;
|
|
21
|
+
* - prints what the band needs, as JSON: the cache clock read from the
|
|
22
|
+
* transcript's tail (coldresume.ts), the re-write's price, the price.
|
|
23
|
+
*
|
|
24
|
+
* Silent like the status line: anything unreadable prints `{}` and exits 0.
|
|
25
|
+
* Off: CONTEXT_DOCTOR_NO_LIMITS_LOG=1 (the limits), CONTEXT_DOCTOR_NO_COST_LOG=1
|
|
26
|
+
* (the cost ledger).
|
|
27
|
+
*/
|
|
28
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
|
|
29
|
+
import { dirname, join } from "node:path";
|
|
30
|
+
import { statePath } from "./ledger.js";
|
|
31
|
+
import { recordLimits } from "./limits.js";
|
|
32
|
+
import { claudeProjectDir } from "./session.js";
|
|
33
|
+
import { claudeDir } from "./claudedir.js";
|
|
34
|
+
import { saveIfWorthIt, sessionPriceThresholds, sessionTotal } from "./sessionprice.js";
|
|
35
|
+
import { AFTER_COMPACT_TOKENS, autoCompactsAt, COLD_MARGIN_MS, COLD_MIN_TOKENS, detectColdResume } from "./coldresume.js";
|
|
36
|
+
import { rateCard, ratesAt } from "./pricing.js";
|
|
37
|
+
/**
|
|
38
|
+
* The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
|
|
39
|
+
* resets_at } }`, resets in epoch seconds: the one shape recordLimits reads.
|
|
40
|
+
* A gateway's `spend_limit` has no place in the ledger and is left out.
|
|
41
|
+
*/
|
|
42
|
+
export function statusLineRateLimits(list) {
|
|
43
|
+
if (!Array.isArray(list))
|
|
44
|
+
return undefined;
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const w of list) {
|
|
47
|
+
if (!w || typeof w !== "object")
|
|
48
|
+
continue;
|
|
49
|
+
const { kind, percentUsed, resetsAt } = w;
|
|
50
|
+
if ((kind !== "five_hour" && kind !== "seven_day") || typeof percentUsed !== "number" || !Number.isFinite(percentUsed))
|
|
51
|
+
continue;
|
|
52
|
+
const reset = typeof resetsAt === "string" ? Date.parse(resetsAt) : NaN;
|
|
53
|
+
out[kind] = { used_percentage: percentUsed, ...(Number.isFinite(reset) && reset > 0 ? { resets_at: Math.round(reset / 1000) } : {}) };
|
|
54
|
+
}
|
|
55
|
+
return Object.keys(out).length ? out : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** A Claude Code session's transcript: in its folder's project, else wherever a project holds the id (a session that moved folders). */
|
|
58
|
+
export function findTranscript(sessionId, cwd, home) {
|
|
59
|
+
if (!sessionId || !/^[\w.-]{1,100}$/.test(sessionId))
|
|
60
|
+
return undefined;
|
|
61
|
+
const name = `${sessionId}.jsonl`;
|
|
62
|
+
if (cwd) {
|
|
63
|
+
const p = join(claudeProjectDir(cwd, home), name);
|
|
64
|
+
if (existsSync(p))
|
|
65
|
+
return p;
|
|
66
|
+
}
|
|
67
|
+
const root = join(claudeDir(home), "projects");
|
|
68
|
+
let dirs = [];
|
|
69
|
+
try {
|
|
70
|
+
dirs = readdirSync(root);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
for (const d of dirs) {
|
|
76
|
+
const p = join(root, d, name);
|
|
77
|
+
if (existsSync(p))
|
|
78
|
+
return p;
|
|
79
|
+
}
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
export function costLogPath() {
|
|
83
|
+
return join(dirname(statePath()), ".context-doctor-session-cost.jsonl");
|
|
84
|
+
}
|
|
85
|
+
/** Past this size the ledger keeps its newest COST_KEEP_BYTES: one ~130-byte line a turn holds months of sessions. */
|
|
86
|
+
const COST_ROTATE_AT = 512 * 1024;
|
|
87
|
+
const COST_KEEP_BYTES = 384 * 1024;
|
|
88
|
+
/** A session's figure is written again only once it moved this much. */
|
|
89
|
+
const MIN_MOVE_USD = 0.005;
|
|
90
|
+
function tail(path, bytes) {
|
|
91
|
+
const size = statSync(path).size;
|
|
92
|
+
const n = Math.min(size, bytes);
|
|
93
|
+
const fd = openSync(path, "r");
|
|
94
|
+
try {
|
|
95
|
+
const buf = Buffer.alloc(n);
|
|
96
|
+
readSync(fd, buf, 0, n, size - n);
|
|
97
|
+
return buf.toString("utf8");
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function parseCostLine(line) {
|
|
104
|
+
let e;
|
|
105
|
+
try {
|
|
106
|
+
e = JSON.parse(line);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
if (!e || typeof e !== "object" || typeof e.ts !== "number" || !Number.isFinite(e.ts) || typeof e.sid !== "string")
|
|
112
|
+
return undefined;
|
|
113
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
|
|
114
|
+
return {
|
|
115
|
+
ts: e.ts,
|
|
116
|
+
sid: e.sid,
|
|
117
|
+
...(num(e.cc) !== undefined ? { cc: num(e.cc) } : {}),
|
|
118
|
+
...(num(e.cd) !== undefined ? { cd: num(e.cd) } : {}),
|
|
119
|
+
...(typeof e.model === "string" ? { model: e.model.slice(0, 100) } : {}),
|
|
120
|
+
...(num(e.unpriced) ? { unpriced: num(e.unpriced) } : {}),
|
|
121
|
+
...(num(e.est) ? { est: num(e.est) } : {}),
|
|
122
|
+
...(typeof e.ev === "string" ? { ev: e.ev.slice(0, 20) } : {}),
|
|
123
|
+
...(num(e.tokens) !== undefined ? { tokens: num(e.tokens) } : {}),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function append(path, line) {
|
|
127
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
128
|
+
if (existsSync(path) && statSync(path).size > COST_ROTATE_AT) {
|
|
129
|
+
const text = tail(path, COST_KEEP_BYTES);
|
|
130
|
+
writeFileSync(path, text.slice(text.indexOf("\n") + 1));
|
|
131
|
+
}
|
|
132
|
+
appendFileSync(path, JSON.stringify(line) + "\n");
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Append a session's two figures, unless neither moved since its last line
|
|
136
|
+
* (a second measure of the same turn, a parallel window of the same session).
|
|
137
|
+
* Never throws. True when a line was written.
|
|
138
|
+
*/
|
|
139
|
+
export function recordSessionCost(line, path = costLogPath()) {
|
|
140
|
+
if (line.cc === undefined && line.cd === undefined)
|
|
141
|
+
return false;
|
|
142
|
+
try {
|
|
143
|
+
if (existsSync(path)) {
|
|
144
|
+
let last;
|
|
145
|
+
for (const l of tail(path, 32 * 1024).split("\n")) {
|
|
146
|
+
const p = parseCostLine(l);
|
|
147
|
+
if (p && !p.ev && p.sid === line.sid)
|
|
148
|
+
last = p;
|
|
149
|
+
}
|
|
150
|
+
const same = (a, b) => (a === undefined && b === undefined) || (a !== undefined && b !== undefined && Math.abs(a - b) < MIN_MOVE_USD);
|
|
151
|
+
if (last && same(last.cc, line.cc) && same(last.cd, line.cd))
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
append(path, line);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** A press of one of the mod's buttons that changes nothing on disk (the Compact button), for the follow-through count. */
|
|
162
|
+
export function recordModEvent(sid, ev, tokens, now = Date.now(), path = costLogPath()) {
|
|
163
|
+
if (!/^[\w.-]{1,100}$/.test(sid) || !/^[a-z-]{1,20}$/.test(ev))
|
|
164
|
+
return false;
|
|
165
|
+
try {
|
|
166
|
+
append(path, { ts: now, sid, ev, ...(tokens !== undefined && Number.isFinite(tokens) ? { tokens } : {}) });
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Every line of the ledger since `since`. */
|
|
174
|
+
export function readCostLines(since = 0, path = costLogPath()) {
|
|
175
|
+
let text;
|
|
176
|
+
try {
|
|
177
|
+
text = readFileSync(path, "utf8");
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
return text.split("\n").map(parseCostLine).filter((l) => !!l && l.ts >= since);
|
|
183
|
+
}
|
|
184
|
+
/** Below this, Claude Code's figure is too small for a percentage to mean anything. */
|
|
185
|
+
const MIN_COMPARE_USD = 0.5;
|
|
186
|
+
/** The target: within this of Claude Code's figure wherever every model is priced (ROADMAP K2). */
|
|
187
|
+
export const COST_GAP_TARGET = 0.02;
|
|
188
|
+
/** Each session's last pair, where both figures are there and Claude Code's is worth comparing. */
|
|
189
|
+
export function costGaps(lines) {
|
|
190
|
+
const last = new Map();
|
|
191
|
+
for (const l of lines)
|
|
192
|
+
if (!l.ev && l.cc !== undefined && l.cd !== undefined)
|
|
193
|
+
last.set(l.sid, l);
|
|
194
|
+
return [...last.values()]
|
|
195
|
+
.filter((l) => l.cc >= MIN_COMPARE_USD)
|
|
196
|
+
.map((l) => ({ sid: l.sid, ts: l.ts, cc: l.cc, cd: l.cd, gap: (l.cd - l.cc) / l.cc, ...(l.model ? { model: l.model } : {}), ...(l.unpriced ? { unpriced: l.unpriced } : {}) }));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* What a gap can come from, by its sign. Ours below Claude Code's: requests
|
|
200
|
+
* the transcript keeps no usage for, which Claude Code's ledger holds as
|
|
201
|
+
* billed and context-doctor estimates (a compaction's own request:
|
|
202
|
+
* compactcost.ts) or leaves out (subagent progress summaries:
|
|
203
|
+
* progresssummaries.ts), a model with no price, rates from MDM or server-managed
|
|
204
|
+
* settings.
|
|
205
|
+
* Ours above: a price in context-doctor's table, or contracted rates it
|
|
206
|
+
* does not read.
|
|
207
|
+
*/
|
|
208
|
+
const UNDER = "Claude Code's figure holds as billed what the transcript keeps no usage for and context-doctor only estimates (a compaction's own request: its thinking, its instruction) or leaves out (a background subagent's progress summaries in a terminal session, which context-doctor spend estimates beside its total); a model with no price, or contracted rates set by an MDM profile or server-managed settings (context-doctor reads modelPricing from the managed settings files only), show up here too";
|
|
209
|
+
const OVER = "A price in context-doctor's table that is off, or contracted rates set by an MDM profile or server-managed settings (context-doctor reads modelPricing from the managed settings files only), show up here";
|
|
210
|
+
const pct = (x) => `${x >= 0 ? "+" : ""}${(x * 100).toFixed(Math.abs(x) < 0.1 ? 1 : 0)}%`;
|
|
211
|
+
/**
|
|
212
|
+
* `doctor`'s line: how close our session price is to Claude Code's own cost,
|
|
213
|
+
* on the sessions the mod measured in the last `days`. Undefined when it
|
|
214
|
+
* measured none (no mod, or no session above $0.50 yet).
|
|
215
|
+
*/
|
|
216
|
+
export function costCheck(days = 30, now = Date.now(), path = costLogPath()) {
|
|
217
|
+
const gaps = costGaps(readCostLines(now - days * 86_400_000, path));
|
|
218
|
+
if (!gaps.length)
|
|
219
|
+
return undefined;
|
|
220
|
+
const label = "Session price vs Claude Code";
|
|
221
|
+
const within = gaps.filter((g) => Math.abs(g.gap) <= COST_GAP_TARGET).length;
|
|
222
|
+
const worst = [...gaps].sort((a, b) => Math.abs(b.gap) - Math.abs(a.gap))[0];
|
|
223
|
+
const n = gaps.length;
|
|
224
|
+
const head = `${within} of ${n} session${n === 1 ? "" : "s"} the mod measured in the last ${days} days within ${COST_GAP_TARGET * 100}% of Claude Code's own cost`;
|
|
225
|
+
if (within === n)
|
|
226
|
+
return { label, status: "ok", detail: `${head} (largest gap ${pct(worst.gap)})` };
|
|
227
|
+
const why = worst.unpriced ? `, ${worst.unpriced} request${worst.unpriced === 1 ? "" : "s"} with no list price` : "";
|
|
228
|
+
return { label, status: "warn", detail: `${head}; the largest gap is ${pct(worst.gap)} ($${worst.cd.toFixed(2)} against $${worst.cc.toFixed(2)}${worst.model ? `, on ${worst.model}` : ""}${why}). ${worst.gap < 0 ? UNDER : OVER}` };
|
|
229
|
+
}
|
|
230
|
+
// -- The measure itself ---------------------------------------------------------------
|
|
231
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
|
|
232
|
+
/**
|
|
233
|
+
* Keep what the mod measured and work out the band's inputs. Never throws;
|
|
234
|
+
* what it cannot read is left out of the answer.
|
|
235
|
+
*/
|
|
236
|
+
export function modMeasure(input, now = Date.now(), env = process.env) {
|
|
237
|
+
const out = { at: now, coldMinTokens: COLD_MIN_TOKENS, thresholds: sessionPriceThresholds(env) };
|
|
238
|
+
try {
|
|
239
|
+
if (env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1")
|
|
240
|
+
recordLimits(statusLineRateLimits(input?.rateLimits), now);
|
|
241
|
+
}
|
|
242
|
+
catch { /* the rest still runs */ }
|
|
243
|
+
const ccUsd = num(input?.cost?.usd);
|
|
244
|
+
if (ccUsd !== undefined)
|
|
245
|
+
out.ccUsd = ccUsd;
|
|
246
|
+
const sid = typeof input?.sessionId === "string" ? input.sessionId : undefined;
|
|
247
|
+
const transcript = findTranscript(sid, typeof input?.cwd === "string" ? input.cwd : undefined);
|
|
248
|
+
if (!sid || !transcript)
|
|
249
|
+
return out;
|
|
250
|
+
try {
|
|
251
|
+
const t = sessionTotal({ sessionId: sid, transcript }, now);
|
|
252
|
+
saveIfWorthIt(t);
|
|
253
|
+
out.usd = t.usd;
|
|
254
|
+
if (env.CONTEXT_DOCTOR_NO_COST_LOG !== "1") {
|
|
255
|
+
recordSessionCost({ ts: now, sid, ...(ccUsd !== undefined ? { cc: round(ccUsd) } : {}), cd: round(t.usd), ...(typeof input.model === "string" ? { model: input.model.slice(0, 100) } : {}), ...(t.unpriced ? { unpriced: t.unpriced } : {}), ...(t.estimatedUsd >= 0.005 ? { est: round(t.estimatedUsd) } : {}) });
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch { /* no price: the band does without it */ }
|
|
259
|
+
try {
|
|
260
|
+
// Every return counts here (no idle or size gate): the band decides when it shows.
|
|
261
|
+
const c = detectColdResume(transcript, now, 0, 0);
|
|
262
|
+
if (c) {
|
|
263
|
+
out.tokens = c.tokens;
|
|
264
|
+
if (c.model)
|
|
265
|
+
out.model = c.model;
|
|
266
|
+
out.lastReplyAt = c.lastReplyAt;
|
|
267
|
+
if (c.ttlMs !== undefined)
|
|
268
|
+
out.ttlMs = c.ttlMs;
|
|
269
|
+
out.coldMarginMs = COLD_MARGIN_MS;
|
|
270
|
+
if (c.resumeUsd !== undefined)
|
|
271
|
+
out.rewriteUsd = c.resumeUsd;
|
|
272
|
+
if (c.perMessageUsd !== undefined)
|
|
273
|
+
out.perMessageUsd = c.perMessageUsd;
|
|
274
|
+
const card = rateCard(c.model, undefined, now);
|
|
275
|
+
if (card)
|
|
276
|
+
out.afterCompactPerMessageUsd = (Math.min(c.tokens, AFTER_COMPACT_TOKENS) * ratesAt(card, AFTER_COMPACT_TOKENS).cacheReadPerM) / 1e6;
|
|
277
|
+
const auto = autoCompactsAt(c.model);
|
|
278
|
+
if (auto !== undefined)
|
|
279
|
+
out.autoCompactAt = auto;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
catch { /* no clock: the band shows the price alone */ }
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
const round = (n) => Math.round(n * 10_000) / 10_000;
|
|
286
|
+
async function readStdin() {
|
|
287
|
+
const chunks = [];
|
|
288
|
+
for await (const chunk of process.stdin)
|
|
289
|
+
chunks.push(chunk);
|
|
290
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* The CLI side: `mod measure` keeps the reading and prints the band's
|
|
294
|
+
* figures; `mod event` records a press (`{ sessionId, ev, tokens }`). Both
|
|
295
|
+
* print JSON and exit 0 whatever happens, as the status line does.
|
|
296
|
+
*/
|
|
297
|
+
export async function runMod(sub) {
|
|
298
|
+
let out = {};
|
|
299
|
+
try {
|
|
300
|
+
const input = JSON.parse((await readStdin()) || "{}");
|
|
301
|
+
if (sub === "measure")
|
|
302
|
+
out = modMeasure(input);
|
|
303
|
+
else
|
|
304
|
+
out = { ok: recordModEvent(String(input?.sessionId ?? ""), String(input?.ev ?? ""), num(input?.tokens)) };
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
/* silent by design: the mod shows what it had */
|
|
308
|
+
}
|
|
309
|
+
process.stdout.write(JSON.stringify(out) + "\n");
|
|
310
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An organization's contracted rates: Claude Code's `modelPricing` setting,
|
|
3
|
+
* which it reads from managed (policy) settings only and applies to every
|
|
4
|
+
* spend figure it reports (/cost, the status line, `total_cost_usd`).
|
|
5
|
+
* Where it is set, context-doctor prices Claude requests at the same rates,
|
|
6
|
+
* so its dollars match Claude Code's and the organization's bill.
|
|
7
|
+
*
|
|
8
|
+
* Read from the 2.1.321 binary and the settings reference
|
|
9
|
+
* (code.claude.com/docs/en/settings-reference#modelpricing, read 2026-11-10):
|
|
10
|
+
* - `multiplier`: a number greater than 0 and at most 10, applied to every
|
|
11
|
+
* cost Claude Code computes, a row's included. Anything else is ignored.
|
|
12
|
+
* - `overrides`: model id to `{ input, output, cacheRead, cacheWrite }`, USD
|
|
13
|
+
* per million tokens, all four required, each 0 to 10000; a row missing
|
|
14
|
+
* one is ignored. `cacheWrite` prices 5-minute and 1-hour writes alike. A
|
|
15
|
+
* row is charged as written: no fast-mode or US-only surcharge, no
|
|
16
|
+
* long-prompt tier. Web searches keep their list fee.
|
|
17
|
+
* - A key that spells a Claude model (`claude-sonnet-4-6`, its Bedrock or
|
|
18
|
+
* Vertex id) covers every dated and provider spelling of that model; any
|
|
19
|
+
* other key (a gateway alias) only its exact id, which wins over a
|
|
20
|
+
* model's row.
|
|
21
|
+
* - Managed sources only: user, project and local settings never set it.
|
|
22
|
+
* Here, the managed settings files (effective.ts managedSettingsPaths:
|
|
23
|
+
* managed-settings.json, then managed-settings.d/*.json in alphabetical
|
|
24
|
+
* order, nested blocks merged key by key). MDM profiles and
|
|
25
|
+
* server-managed settings are not read.
|
|
26
|
+
*/
|
|
27
|
+
import type { ModelPricing } from "./pricing.js";
|
|
28
|
+
export interface OrgRates {
|
|
29
|
+
/** Scales every Claude cost, a row's included (1 when unset). */
|
|
30
|
+
multiplier: number;
|
|
31
|
+
/** Rows by their exact key, lowercased. */
|
|
32
|
+
exact: Map<string, ModelPricing>;
|
|
33
|
+
/** Rows keyed by a Claude model, by that model's canonical id. */
|
|
34
|
+
models: Map<string, ModelPricing>;
|
|
35
|
+
/** The files that set it. */
|
|
36
|
+
sources: string[];
|
|
37
|
+
/** Fingerprint of the rates in force: cached dollars priced under other rates are stale. */
|
|
38
|
+
key: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* One Claude model, however a provider spells it: "claude-sonnet-4-6" for
|
|
42
|
+
* claude-sonnet-4-6-20260101, claude-sonnet-4-6[1m],
|
|
43
|
+
* us.anthropic.claude-sonnet-4-6-v1:0 and claude-sonnet-4-6@20260101.
|
|
44
|
+
* Undefined for an id that is not a Claude model's.
|
|
45
|
+
*/
|
|
46
|
+
export declare function canonicalClaude(id: string): string | undefined;
|
|
47
|
+
/** `modelPricing` from merged managed settings, as Claude Code keeps it; undefined when it changes nothing. */
|
|
48
|
+
export declare function parseOrgRates(value: unknown, sources?: string[]): OrgRates | undefined;
|
|
49
|
+
/** The merged `modelPricing` of the managed settings files, and which files set it. */
|
|
50
|
+
export declare function readOrgRates(env?: NodeJS.ProcessEnv): OrgRates | undefined;
|
|
51
|
+
/** The merged `modelPricing` of `paths`, in order (the base file, then the drop-ins). */
|
|
52
|
+
export declare function readOrgRatesFrom(paths: string[]): OrgRates | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* The organization's rates in force, read once per process (and again when
|
|
55
|
+
* the variables that move the managed files change). The hook's cost: a
|
|
56
|
+
* stat of the managed folder and its drop-in folder, once.
|
|
57
|
+
*/
|
|
58
|
+
export declare function orgRates(env?: NodeJS.ProcessEnv): OrgRates | undefined;
|
|
59
|
+
/** Forget what orgRates read (tests that rewrite a managed file in place). */
|
|
60
|
+
export declare function resetOrgRates(): void;
|
|
61
|
+
/** The row that prices `model`: its exact key first, then its Claude model's. */
|
|
62
|
+
export declare function orgRowFor(rates: OrgRates, model: string): ModelPricing | undefined;
|
|
63
|
+
/** Whether the organization's rates reach `model`: a row of its own, or a Claude model under the multiplier. */
|
|
64
|
+
export declare function orgApplies(rates: OrgRates | undefined, model: string | undefined): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* How a report's dollars were priced, for its heading: "at list prices", or
|
|
67
|
+
* "at your organization's rates" where managed settings set `modelPricing`
|
|
68
|
+
* (Claude models at those rates, any other provider's at list).
|
|
69
|
+
*/
|
|
70
|
+
export declare function priceBasis(plural?: boolean, env?: NodeJS.ProcessEnv): string;
|
|
71
|
+
/**
|
|
72
|
+
* The line a report adds where the organization's rates are in force:
|
|
73
|
+
* which files set them and what they are. Undefined at list prices.
|
|
74
|
+
*/
|
|
75
|
+
export declare function orgRatesLine(env?: NodeJS.ProcessEnv): string | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* The managed sources Claude Code reads before the managed settings files,
|
|
78
|
+
* found on this machine. Read from the 2.1.321 binary: the policy origin is
|
|
79
|
+
* server-managed settings when present, else an MDM profile (a macOS
|
|
80
|
+
* managed-preferences plist, the Windows HKLM policy key), else the files,
|
|
81
|
+
* and by default only the first source found counts ("first-wins"): with
|
|
82
|
+
* either of the others present, Claude Code prices at their modelPricing,
|
|
83
|
+
* or at list, never at the files'. context-doctor reads neither (the
|
|
84
|
+
* server-managed copy, `remote-settings.json` in Claude Code's folder, is an
|
|
85
|
+
* undocumented, signed cache); this only says that one is there. The
|
|
86
|
+
* Windows key is not looked up (it needs reg.exe).
|
|
87
|
+
*/
|
|
88
|
+
export declare function managedSourcesAhead(env?: NodeJS.ProcessEnv, home?: string, prefs?: string): string[];
|
|
89
|
+
/**
|
|
90
|
+
* The line a report adds when Claude Code may take its rates from a source
|
|
91
|
+
* context-doctor does not read: undefined when none is on this machine.
|
|
92
|
+
*/
|
|
93
|
+
export declare function managedSourcesLine(env?: NodeJS.ProcessEnv, home?: string, prefs?: string): string | undefined;
|
package/dist/orgrates.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An organization's contracted rates: Claude Code's `modelPricing` setting,
|
|
3
|
+
* which it reads from managed (policy) settings only and applies to every
|
|
4
|
+
* spend figure it reports (/cost, the status line, `total_cost_usd`).
|
|
5
|
+
* Where it is set, context-doctor prices Claude requests at the same rates,
|
|
6
|
+
* so its dollars match Claude Code's and the organization's bill.
|
|
7
|
+
*
|
|
8
|
+
* Read from the 2.1.321 binary and the settings reference
|
|
9
|
+
* (code.claude.com/docs/en/settings-reference#modelpricing, read 2026-11-10):
|
|
10
|
+
* - `multiplier`: a number greater than 0 and at most 10, applied to every
|
|
11
|
+
* cost Claude Code computes, a row's included. Anything else is ignored.
|
|
12
|
+
* - `overrides`: model id to `{ input, output, cacheRead, cacheWrite }`, USD
|
|
13
|
+
* per million tokens, all four required, each 0 to 10000; a row missing
|
|
14
|
+
* one is ignored. `cacheWrite` prices 5-minute and 1-hour writes alike. A
|
|
15
|
+
* row is charged as written: no fast-mode or US-only surcharge, no
|
|
16
|
+
* long-prompt tier. Web searches keep their list fee.
|
|
17
|
+
* - A key that spells a Claude model (`claude-sonnet-4-6`, its Bedrock or
|
|
18
|
+
* Vertex id) covers every dated and provider spelling of that model; any
|
|
19
|
+
* other key (a gateway alias) only its exact id, which wins over a
|
|
20
|
+
* model's row.
|
|
21
|
+
* - Managed sources only: user, project and local settings never set it.
|
|
22
|
+
* Here, the managed settings files (effective.ts managedSettingsPaths:
|
|
23
|
+
* managed-settings.json, then managed-settings.d/*.json in alphabetical
|
|
24
|
+
* order, nested blocks merged key by key). MDM profiles and
|
|
25
|
+
* server-managed settings are not read.
|
|
26
|
+
*/
|
|
27
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
28
|
+
import { userInfo } from "node:os";
|
|
29
|
+
import { basename, join } from "node:path";
|
|
30
|
+
import { claudeDir } from "./claudedir.js";
|
|
31
|
+
import { managedSettingsPaths } from "./effective.js";
|
|
32
|
+
const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
33
|
+
/** Nested blocks merged key by key, the later value winning (Claude Code's rule for managed-settings.d). */
|
|
34
|
+
function merge(a, b) {
|
|
35
|
+
const out = { ...a };
|
|
36
|
+
for (const [k, v] of Object.entries(b)) {
|
|
37
|
+
if (k === "__proto__" || k === "constructor")
|
|
38
|
+
continue;
|
|
39
|
+
out[k] = isObject(v) && isObject(out[k]) ? merge(out[k], v) : v;
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One Claude model, however a provider spells it: "claude-sonnet-4-6" for
|
|
45
|
+
* claude-sonnet-4-6-20260101, claude-sonnet-4-6[1m],
|
|
46
|
+
* us.anthropic.claude-sonnet-4-6-v1:0 and claude-sonnet-4-6@20260101.
|
|
47
|
+
* Undefined for an id that is not a Claude model's.
|
|
48
|
+
*/
|
|
49
|
+
export function canonicalClaude(id) {
|
|
50
|
+
let m = id.trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
51
|
+
m = m.replace(/^(?:[a-z]{2,6}\.)?anthropic\./, "").replace(/-v\d+(?::\d+)?$/, "").replace(/(?:@|-)\d{8}$/, "");
|
|
52
|
+
return /^claude-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(m) ? m : undefined;
|
|
53
|
+
}
|
|
54
|
+
/** A row as Claude Code accepts it, or undefined (all four rates, each 0 to 10000). */
|
|
55
|
+
function rowOf(v) {
|
|
56
|
+
if (!isObject(v))
|
|
57
|
+
return undefined;
|
|
58
|
+
const r = [v.input, v.output, v.cacheRead, v.cacheWrite];
|
|
59
|
+
if (!r.every((x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x <= 10_000))
|
|
60
|
+
return undefined;
|
|
61
|
+
const [inputPerM, outputPerM, cacheReadPerM, cacheWritePerM] = r;
|
|
62
|
+
return { inputPerM, outputPerM, cacheReadPerM, cacheWritePerM };
|
|
63
|
+
}
|
|
64
|
+
/** `modelPricing` from merged managed settings, as Claude Code keeps it; undefined when it changes nothing. */
|
|
65
|
+
export function parseOrgRates(value, sources = []) {
|
|
66
|
+
if (!isObject(value))
|
|
67
|
+
return undefined;
|
|
68
|
+
const mult = value.multiplier;
|
|
69
|
+
const multiplier = typeof mult === "number" && Number.isFinite(mult) && mult > 0 && mult <= 10 ? mult : 1;
|
|
70
|
+
const exact = new Map();
|
|
71
|
+
const models = new Map();
|
|
72
|
+
if (isObject(value.overrides)) {
|
|
73
|
+
for (const [k, v] of Object.entries(value.overrides)) {
|
|
74
|
+
const row = rowOf(v);
|
|
75
|
+
const key = k.trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
76
|
+
// The first row of a key, or of a model, is the one used (Claude Code warns of the later one).
|
|
77
|
+
if (!row || !key || exact.has(key))
|
|
78
|
+
continue;
|
|
79
|
+
exact.set(key, row);
|
|
80
|
+
const model = canonicalClaude(key);
|
|
81
|
+
if (model && !models.has(model))
|
|
82
|
+
models.set(model, row);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (exact.size === 0 && multiplier === 1)
|
|
86
|
+
return undefined;
|
|
87
|
+
const key = JSON.stringify([multiplier, [...exact].map(([k, r]) => [k, r.inputPerM, r.outputPerM, r.cacheReadPerM, r.cacheWritePerM])]);
|
|
88
|
+
return { multiplier, exact, models, sources, key };
|
|
89
|
+
}
|
|
90
|
+
/** The merged `modelPricing` of the managed settings files, and which files set it. */
|
|
91
|
+
export function readOrgRates(env = process.env) {
|
|
92
|
+
return readOrgRatesFrom(managedSettingsPaths(env));
|
|
93
|
+
}
|
|
94
|
+
/** The merged `modelPricing` of `paths`, in order (the base file, then the drop-ins). */
|
|
95
|
+
export function readOrgRatesFrom(paths) {
|
|
96
|
+
let merged = {};
|
|
97
|
+
const sources = [];
|
|
98
|
+
for (const path of paths) {
|
|
99
|
+
if (basename(path).startsWith("."))
|
|
100
|
+
continue; // Claude Code skips hidden drop-ins
|
|
101
|
+
let data;
|
|
102
|
+
try {
|
|
103
|
+
data = JSON.parse(readFileSync(path, "utf8").replace(/^/, ""));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
continue; /* absent or unreadable */
|
|
107
|
+
}
|
|
108
|
+
if (!isObject(data) || data.modelPricing === undefined)
|
|
109
|
+
continue;
|
|
110
|
+
sources.push(path);
|
|
111
|
+
merged = merge(merged, { modelPricing: data.modelPricing });
|
|
112
|
+
}
|
|
113
|
+
return parseOrgRates(merged.modelPricing, sources);
|
|
114
|
+
}
|
|
115
|
+
let cache;
|
|
116
|
+
/**
|
|
117
|
+
* The organization's rates in force, read once per process (and again when
|
|
118
|
+
* the variables that move the managed files change). The hook's cost: a
|
|
119
|
+
* stat of the managed folder and its drop-in folder, once.
|
|
120
|
+
*/
|
|
121
|
+
export function orgRates(env = process.env) {
|
|
122
|
+
const k = `${env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS ?? ""}\u0000${env.CLAUDE_CODE_MANAGED_SETTINGS_PATH ?? ""}`;
|
|
123
|
+
if (cache?.env !== k)
|
|
124
|
+
cache = { env: k, rates: readOrgRates(env) };
|
|
125
|
+
return cache.rates;
|
|
126
|
+
}
|
|
127
|
+
/** Forget what orgRates read (tests that rewrite a managed file in place). */
|
|
128
|
+
export function resetOrgRates() {
|
|
129
|
+
cache = undefined;
|
|
130
|
+
}
|
|
131
|
+
/** The row that prices `model`: its exact key first, then its Claude model's. */
|
|
132
|
+
export function orgRowFor(rates, model) {
|
|
133
|
+
const exact = rates.exact.get(model.trim().toLowerCase().replace(/\[1m\]$/, ""));
|
|
134
|
+
if (exact)
|
|
135
|
+
return exact;
|
|
136
|
+
const canon = canonicalClaude(model);
|
|
137
|
+
return canon ? rates.models.get(canon) : undefined;
|
|
138
|
+
}
|
|
139
|
+
/** Whether the organization's rates reach `model`: a row of its own, or a Claude model under the multiplier. */
|
|
140
|
+
export function orgApplies(rates, model) {
|
|
141
|
+
if (!rates || !model)
|
|
142
|
+
return false;
|
|
143
|
+
return orgRowFor(rates, model) !== undefined || (rates.multiplier !== 1 && /claude/i.test(model));
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* How a report's dollars were priced, for its heading: "at list prices", or
|
|
147
|
+
* "at your organization's rates" where managed settings set `modelPricing`
|
|
148
|
+
* (Claude models at those rates, any other provider's at list).
|
|
149
|
+
*/
|
|
150
|
+
export function priceBasis(plural = true, env = process.env) {
|
|
151
|
+
return orgRates(env) ? "at your organization's rates" : plural ? "at list prices" : "at list price";
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* The line a report adds where the organization's rates are in force:
|
|
155
|
+
* which files set them and what they are. Undefined at list prices.
|
|
156
|
+
*/
|
|
157
|
+
export function orgRatesLine(env = process.env) {
|
|
158
|
+
const r = orgRates(env);
|
|
159
|
+
if (!r)
|
|
160
|
+
return undefined;
|
|
161
|
+
const keys = [...r.exact.keys()];
|
|
162
|
+
const parts = [
|
|
163
|
+
...(r.multiplier !== 1 ? [`multiplier ${r.multiplier}`] : []),
|
|
164
|
+
...(keys.length ? [`${keys.length === 1 ? "a row" : `${keys.length} rows`} for ${keys.slice(0, 3).join(", ")}${keys.length > 3 ? " and others" : ""}`] : []),
|
|
165
|
+
];
|
|
166
|
+
return `Claude requests priced at your organization's rates (Claude Code's managed modelPricing: ${parts.join("; ")}; in ${r.sources.map((s) => basename(s)).join(", ")}), as Claude Code's own cost figures are; other providers at list prices.`;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The managed sources Claude Code reads before the managed settings files,
|
|
170
|
+
* found on this machine. Read from the 2.1.321 binary: the policy origin is
|
|
171
|
+
* server-managed settings when present, else an MDM profile (a macOS
|
|
172
|
+
* managed-preferences plist, the Windows HKLM policy key), else the files,
|
|
173
|
+
* and by default only the first source found counts ("first-wins"): with
|
|
174
|
+
* either of the others present, Claude Code prices at their modelPricing,
|
|
175
|
+
* or at list, never at the files'. context-doctor reads neither (the
|
|
176
|
+
* server-managed copy, `remote-settings.json` in Claude Code's folder, is an
|
|
177
|
+
* undocumented, signed cache); this only says that one is there. The
|
|
178
|
+
* Windows key is not looked up (it needs reg.exe).
|
|
179
|
+
*/
|
|
180
|
+
export function managedSourcesAhead(env = process.env, home, prefs = "/Library/Managed Preferences") {
|
|
181
|
+
if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
|
|
182
|
+
return [];
|
|
183
|
+
const out = [];
|
|
184
|
+
try {
|
|
185
|
+
const remote = join(claudeDir(home, env), "remote-settings.json");
|
|
186
|
+
if (existsSync(remote))
|
|
187
|
+
out.push(`server-managed settings (Claude Code's copy: ${remote})`);
|
|
188
|
+
}
|
|
189
|
+
catch { /* no config folder */ }
|
|
190
|
+
if (process.platform === "darwin") {
|
|
191
|
+
let user = "";
|
|
192
|
+
try {
|
|
193
|
+
user = userInfo().username;
|
|
194
|
+
}
|
|
195
|
+
catch { /* none */ }
|
|
196
|
+
for (const p of [...(user ? [join(prefs, user, "com.anthropic.claudecode.plist")] : []), join(prefs, "com.anthropic.claudecode.plist")]) {
|
|
197
|
+
if (existsSync(p)) {
|
|
198
|
+
out.push(`an MDM profile (${p})`);
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The line a report adds when Claude Code may take its rates from a source
|
|
207
|
+
* context-doctor does not read: undefined when none is on this machine.
|
|
208
|
+
*/
|
|
209
|
+
export function managedSourcesLine(env = process.env, home, prefs) {
|
|
210
|
+
const ahead = managedSourcesAhead(env, home, prefs);
|
|
211
|
+
if (!ahead.length)
|
|
212
|
+
return undefined;
|
|
213
|
+
return `Claude Code takes its managed settings from ${ahead.join(" and ")} before the managed settings files, and only from the first it finds: its own cost figures may use contracted rates (modelPricing) set there, which context-doctor does not read; these reports price ${orgRates(env) ? "at the files' rates" : "at list rates"}.`;
|
|
214
|
+
}
|