context-doctor 0.45.0 → 0.46.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 +4 -2
- package/dist/budget.d.ts +4 -1
- package/dist/budget.js +11 -5
- package/dist/cachemisses.js +5 -3
- package/dist/cacheplan.js +2 -2
- package/dist/cachettl.js +2 -1
- package/dist/cli.js +17 -3
- package/dist/coldresume.d.ts +6 -0
- package/dist/coldresume.js +7 -6
- package/dist/compactwindow.js +5 -4
- package/dist/doctor.js +17 -0
- package/dist/fanout.js +1 -1
- package/dist/fix.js +14 -10
- package/dist/hook.js +6 -2
- package/dist/mcp.js +61 -61
- package/dist/mod/api.d.ts +129 -0
- package/dist/mod/api.js +12 -0
- package/dist/mod/logic.d.ts +146 -0
- package/dist/mod/logic.js +222 -0
- package/dist/mod/register.d.ts +58 -0
- package/dist/mod/register.js +237 -0
- package/dist/modelids.d.ts +23 -0
- package/dist/modelids.js +49 -0
- package/dist/modmeasure.d.ts +121 -0
- package/dist/modmeasure.js +298 -0
- package/dist/orgrates.d.ts +75 -0
- package/dist/orgrates.js +165 -0
- package/dist/overhead.js +11 -8
- package/dist/pack.js +30 -1
- package/dist/pricing.d.ts +18 -0
- package/dist/pricing.js +45 -7
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -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 +12 -3
- package/dist/spend.js +39 -7
- package/dist/statusline.js +2 -2
- package/dist/subagentpay.d.ts +7 -1
- package/dist/subagentpay.js +51 -25
- package/dist/subagents.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,298 @@
|
|
|
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
|
+
const pct = (x) => `${x >= 0 ? "+" : ""}${(x * 100).toFixed(Math.abs(x) < 0.1 ? 1 : 0)}%`;
|
|
199
|
+
/**
|
|
200
|
+
* `doctor`'s line: how close our session price is to Claude Code's own cost,
|
|
201
|
+
* on the sessions the mod measured in the last `days`. Undefined when it
|
|
202
|
+
* measured none (no mod, or no session above $0.50 yet).
|
|
203
|
+
*/
|
|
204
|
+
export function costCheck(days = 30, now = Date.now(), path = costLogPath()) {
|
|
205
|
+
const gaps = costGaps(readCostLines(now - days * 86_400_000, path));
|
|
206
|
+
if (!gaps.length)
|
|
207
|
+
return undefined;
|
|
208
|
+
const label = "Session price vs Claude Code";
|
|
209
|
+
const within = gaps.filter((g) => Math.abs(g.gap) <= COST_GAP_TARGET).length;
|
|
210
|
+
const worst = [...gaps].sort((a, b) => Math.abs(b.gap) - Math.abs(a.gap))[0];
|
|
211
|
+
const n = gaps.length;
|
|
212
|
+
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`;
|
|
213
|
+
if (within === n)
|
|
214
|
+
return { label, status: "ok", detail: `${head} (largest gap ${pct(worst.gap)})` };
|
|
215
|
+
const why = worst.unpriced ? `, ${worst.unpriced} request${worst.unpriced === 1 ? "" : "s"} with no list price` : "";
|
|
216
|
+
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}). A price missing from context-doctor's table, or contracted rates Claude Code applies (modelPricing), show up here` };
|
|
217
|
+
}
|
|
218
|
+
// -- The measure itself ---------------------------------------------------------------
|
|
219
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
|
|
220
|
+
/**
|
|
221
|
+
* Keep what the mod measured and work out the band's inputs. Never throws;
|
|
222
|
+
* what it cannot read is left out of the answer.
|
|
223
|
+
*/
|
|
224
|
+
export function modMeasure(input, now = Date.now(), env = process.env) {
|
|
225
|
+
const out = { at: now, coldMinTokens: COLD_MIN_TOKENS, thresholds: sessionPriceThresholds(env) };
|
|
226
|
+
try {
|
|
227
|
+
if (env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1")
|
|
228
|
+
recordLimits(statusLineRateLimits(input?.rateLimits), now);
|
|
229
|
+
}
|
|
230
|
+
catch { /* the rest still runs */ }
|
|
231
|
+
const ccUsd = num(input?.cost?.usd);
|
|
232
|
+
if (ccUsd !== undefined)
|
|
233
|
+
out.ccUsd = ccUsd;
|
|
234
|
+
const sid = typeof input?.sessionId === "string" ? input.sessionId : undefined;
|
|
235
|
+
const transcript = findTranscript(sid, typeof input?.cwd === "string" ? input.cwd : undefined);
|
|
236
|
+
if (!sid || !transcript)
|
|
237
|
+
return out;
|
|
238
|
+
try {
|
|
239
|
+
const t = sessionTotal({ sessionId: sid, transcript }, now);
|
|
240
|
+
saveIfWorthIt(t);
|
|
241
|
+
out.usd = t.usd;
|
|
242
|
+
if (env.CONTEXT_DOCTOR_NO_COST_LOG !== "1") {
|
|
243
|
+
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) } : {}) });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch { /* no price: the band does without it */ }
|
|
247
|
+
try {
|
|
248
|
+
// Every return counts here (no idle or size gate): the band decides when it shows.
|
|
249
|
+
const c = detectColdResume(transcript, now, 0, 0);
|
|
250
|
+
if (c) {
|
|
251
|
+
out.tokens = c.tokens;
|
|
252
|
+
if (c.model)
|
|
253
|
+
out.model = c.model;
|
|
254
|
+
out.lastReplyAt = c.lastReplyAt;
|
|
255
|
+
if (c.ttlMs !== undefined)
|
|
256
|
+
out.ttlMs = c.ttlMs;
|
|
257
|
+
out.coldMarginMs = COLD_MARGIN_MS;
|
|
258
|
+
if (c.resumeUsd !== undefined)
|
|
259
|
+
out.rewriteUsd = c.resumeUsd;
|
|
260
|
+
if (c.perMessageUsd !== undefined)
|
|
261
|
+
out.perMessageUsd = c.perMessageUsd;
|
|
262
|
+
const card = rateCard(c.model, undefined, now);
|
|
263
|
+
if (card)
|
|
264
|
+
out.afterCompactPerMessageUsd = (Math.min(c.tokens, AFTER_COMPACT_TOKENS) * ratesAt(card, AFTER_COMPACT_TOKENS).cacheReadPerM) / 1e6;
|
|
265
|
+
const auto = autoCompactsAt(c.model);
|
|
266
|
+
if (auto !== undefined)
|
|
267
|
+
out.autoCompactAt = auto;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
catch { /* no clock: the band shows the price alone */ }
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
const round = (n) => Math.round(n * 10_000) / 10_000;
|
|
274
|
+
async function readStdin() {
|
|
275
|
+
const chunks = [];
|
|
276
|
+
for await (const chunk of process.stdin)
|
|
277
|
+
chunks.push(chunk);
|
|
278
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The CLI side: `mod measure` keeps the reading and prints the band's
|
|
282
|
+
* figures; `mod event` records a press (`{ sessionId, ev, tokens }`). Both
|
|
283
|
+
* print JSON and exit 0 whatever happens, as the status line does.
|
|
284
|
+
*/
|
|
285
|
+
export async function runMod(sub) {
|
|
286
|
+
let out = {};
|
|
287
|
+
try {
|
|
288
|
+
const input = JSON.parse((await readStdin()) || "{}");
|
|
289
|
+
if (sub === "measure")
|
|
290
|
+
out = modMeasure(input);
|
|
291
|
+
else
|
|
292
|
+
out = { ok: recordModEvent(String(input?.sessionId ?? ""), String(input?.ev ?? ""), num(input?.tokens)) };
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
/* silent by design: the mod shows what it had */
|
|
296
|
+
}
|
|
297
|
+
process.stdout.write(JSON.stringify(out) + "\n");
|
|
298
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
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;
|
package/dist/orgrates.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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 { readFileSync } from "node:fs";
|
|
28
|
+
import { basename } from "node:path";
|
|
29
|
+
import { managedSettingsPaths } from "./effective.js";
|
|
30
|
+
const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
31
|
+
/** Nested blocks merged key by key, the later value winning (Claude Code's rule for managed-settings.d). */
|
|
32
|
+
function merge(a, b) {
|
|
33
|
+
const out = { ...a };
|
|
34
|
+
for (const [k, v] of Object.entries(b)) {
|
|
35
|
+
if (k === "__proto__" || k === "constructor")
|
|
36
|
+
continue;
|
|
37
|
+
out[k] = isObject(v) && isObject(out[k]) ? merge(out[k], v) : v;
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One Claude model, however a provider spells it: "claude-sonnet-4-6" for
|
|
43
|
+
* claude-sonnet-4-6-20260101, claude-sonnet-4-6[1m],
|
|
44
|
+
* us.anthropic.claude-sonnet-4-6-v1:0 and claude-sonnet-4-6@20260101.
|
|
45
|
+
* Undefined for an id that is not a Claude model's.
|
|
46
|
+
*/
|
|
47
|
+
export function canonicalClaude(id) {
|
|
48
|
+
let m = id.trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
49
|
+
m = m.replace(/^(?:[a-z]{2,6}\.)?anthropic\./, "").replace(/-v\d+(?::\d+)?$/, "").replace(/(?:@|-)\d{8}$/, "");
|
|
50
|
+
return /^claude-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(m) ? m : undefined;
|
|
51
|
+
}
|
|
52
|
+
/** A row as Claude Code accepts it, or undefined (all four rates, each 0 to 10000). */
|
|
53
|
+
function rowOf(v) {
|
|
54
|
+
if (!isObject(v))
|
|
55
|
+
return undefined;
|
|
56
|
+
const r = [v.input, v.output, v.cacheRead, v.cacheWrite];
|
|
57
|
+
if (!r.every((x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x <= 10_000))
|
|
58
|
+
return undefined;
|
|
59
|
+
const [inputPerM, outputPerM, cacheReadPerM, cacheWritePerM] = r;
|
|
60
|
+
return { inputPerM, outputPerM, cacheReadPerM, cacheWritePerM };
|
|
61
|
+
}
|
|
62
|
+
/** `modelPricing` from merged managed settings, as Claude Code keeps it; undefined when it changes nothing. */
|
|
63
|
+
export function parseOrgRates(value, sources = []) {
|
|
64
|
+
if (!isObject(value))
|
|
65
|
+
return undefined;
|
|
66
|
+
const mult = value.multiplier;
|
|
67
|
+
const multiplier = typeof mult === "number" && Number.isFinite(mult) && mult > 0 && mult <= 10 ? mult : 1;
|
|
68
|
+
const exact = new Map();
|
|
69
|
+
const models = new Map();
|
|
70
|
+
if (isObject(value.overrides)) {
|
|
71
|
+
for (const [k, v] of Object.entries(value.overrides)) {
|
|
72
|
+
const row = rowOf(v);
|
|
73
|
+
const key = k.trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
74
|
+
// The first row of a key, or of a model, is the one used (Claude Code warns of the later one).
|
|
75
|
+
if (!row || !key || exact.has(key))
|
|
76
|
+
continue;
|
|
77
|
+
exact.set(key, row);
|
|
78
|
+
const model = canonicalClaude(key);
|
|
79
|
+
if (model && !models.has(model))
|
|
80
|
+
models.set(model, row);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (exact.size === 0 && multiplier === 1)
|
|
84
|
+
return undefined;
|
|
85
|
+
const key = JSON.stringify([multiplier, [...exact].map(([k, r]) => [k, r.inputPerM, r.outputPerM, r.cacheReadPerM, r.cacheWritePerM])]);
|
|
86
|
+
return { multiplier, exact, models, sources, key };
|
|
87
|
+
}
|
|
88
|
+
/** The merged `modelPricing` of the managed settings files, and which files set it. */
|
|
89
|
+
export function readOrgRates(env = process.env) {
|
|
90
|
+
return readOrgRatesFrom(managedSettingsPaths(env));
|
|
91
|
+
}
|
|
92
|
+
/** The merged `modelPricing` of `paths`, in order (the base file, then the drop-ins). */
|
|
93
|
+
export function readOrgRatesFrom(paths) {
|
|
94
|
+
let merged = {};
|
|
95
|
+
const sources = [];
|
|
96
|
+
for (const path of paths) {
|
|
97
|
+
if (basename(path).startsWith("."))
|
|
98
|
+
continue; // Claude Code skips hidden drop-ins
|
|
99
|
+
let data;
|
|
100
|
+
try {
|
|
101
|
+
data = JSON.parse(readFileSync(path, "utf8").replace(/^/, ""));
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
continue; /* absent or unreadable */
|
|
105
|
+
}
|
|
106
|
+
if (!isObject(data) || data.modelPricing === undefined)
|
|
107
|
+
continue;
|
|
108
|
+
sources.push(path);
|
|
109
|
+
merged = merge(merged, { modelPricing: data.modelPricing });
|
|
110
|
+
}
|
|
111
|
+
return parseOrgRates(merged.modelPricing, sources);
|
|
112
|
+
}
|
|
113
|
+
let cache;
|
|
114
|
+
/**
|
|
115
|
+
* The organization's rates in force, read once per process (and again when
|
|
116
|
+
* the variables that move the managed files change). The hook's cost: a
|
|
117
|
+
* stat of the managed folder and its drop-in folder, once.
|
|
118
|
+
*/
|
|
119
|
+
export function orgRates(env = process.env) {
|
|
120
|
+
const k = `${env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS ?? ""}\u0000${env.CLAUDE_CODE_MANAGED_SETTINGS_PATH ?? ""}`;
|
|
121
|
+
if (cache?.env !== k)
|
|
122
|
+
cache = { env: k, rates: readOrgRates(env) };
|
|
123
|
+
return cache.rates;
|
|
124
|
+
}
|
|
125
|
+
/** Forget what orgRates read (tests that rewrite a managed file in place). */
|
|
126
|
+
export function resetOrgRates() {
|
|
127
|
+
cache = undefined;
|
|
128
|
+
}
|
|
129
|
+
/** The row that prices `model`: its exact key first, then its Claude model's. */
|
|
130
|
+
export function orgRowFor(rates, model) {
|
|
131
|
+
const exact = rates.exact.get(model.trim().toLowerCase().replace(/\[1m\]$/, ""));
|
|
132
|
+
if (exact)
|
|
133
|
+
return exact;
|
|
134
|
+
const canon = canonicalClaude(model);
|
|
135
|
+
return canon ? rates.models.get(canon) : undefined;
|
|
136
|
+
}
|
|
137
|
+
/** Whether the organization's rates reach `model`: a row of its own, or a Claude model under the multiplier. */
|
|
138
|
+
export function orgApplies(rates, model) {
|
|
139
|
+
if (!rates || !model)
|
|
140
|
+
return false;
|
|
141
|
+
return orgRowFor(rates, model) !== undefined || (rates.multiplier !== 1 && /claude/i.test(model));
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* How a report's dollars were priced, for its heading: "at list prices", or
|
|
145
|
+
* "at your organization's rates" where managed settings set `modelPricing`
|
|
146
|
+
* (Claude models at those rates, any other provider's at list).
|
|
147
|
+
*/
|
|
148
|
+
export function priceBasis(plural = true, env = process.env) {
|
|
149
|
+
return orgRates(env) ? "at your organization's rates" : plural ? "at list prices" : "at list price";
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The line a report adds where the organization's rates are in force:
|
|
153
|
+
* which files set them and what they are. Undefined at list prices.
|
|
154
|
+
*/
|
|
155
|
+
export function orgRatesLine(env = process.env) {
|
|
156
|
+
const r = orgRates(env);
|
|
157
|
+
if (!r)
|
|
158
|
+
return undefined;
|
|
159
|
+
const keys = [...r.exact.keys()];
|
|
160
|
+
const parts = [
|
|
161
|
+
...(r.multiplier !== 1 ? [`multiplier ${r.multiplier}`] : []),
|
|
162
|
+
...(keys.length ? [`${keys.length === 1 ? "a row" : `${keys.length} rows`} for ${keys.slice(0, 3).join(", ")}${keys.length > 3 ? " and others" : ""}`] : []),
|
|
163
|
+
];
|
|
164
|
+
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.`;
|
|
165
|
+
}
|
package/dist/overhead.js
CHANGED
|
@@ -20,7 +20,8 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
|
20
20
|
import { codexDir } from "./codexdir.js";
|
|
21
21
|
import { forEachLine, listSessions, replyCounter, textOf } from "./session.js";
|
|
22
22
|
import { estimateTokens, formatTokens, providerFor, realModel, tokensForLength } from "./tokens.js";
|
|
23
|
-
import { cacheWriteSplit, formatUsd,
|
|
23
|
+
import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier as ttlWriteMultiplier, writePerM } from "./pricing.js";
|
|
24
|
+
import { priceBasis } from "./orgrates.js";
|
|
24
25
|
import { isGeminiChat, readGeminiMessages } from "./gemini.js";
|
|
25
26
|
import { claudeMcpConfigs, mcpUsage, measureServer, otherServerUses, serverUses } from "./mcpschema.js";
|
|
26
27
|
import { claudeDir } from "./claudedir.js";
|
|
@@ -183,7 +184,7 @@ function claudeUsage(path, runRows) {
|
|
|
183
184
|
const w = cacheWriteSplit(u);
|
|
184
185
|
out.writes5m += w.fiveMinute;
|
|
185
186
|
out.writes1h += w.oneHour;
|
|
186
|
-
out.reqs.push({ at, model: realModel(e.message.model) });
|
|
187
|
+
out.reqs.push({ at, model: realModel(e.message.model), prompt, billing: { speed: u.speed, inference_geo: u.inference_geo } });
|
|
187
188
|
});
|
|
188
189
|
return out;
|
|
189
190
|
}
|
|
@@ -275,7 +276,7 @@ function aggregate(agent, sessions, since, days) {
|
|
|
275
276
|
const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
|
|
276
277
|
if (cold)
|
|
277
278
|
coldStarts++;
|
|
278
|
-
starts.push({ cold, model: r.model });
|
|
279
|
+
starts.push({ cold, model: r.model, at: r.at, prompt: r.prompt, billing: r.billing });
|
|
279
280
|
if (r.model)
|
|
280
281
|
models.set(r.model, (models.get(r.model) ?? 0) + 1);
|
|
281
282
|
}
|
|
@@ -291,11 +292,13 @@ function aggregate(agent, sessions, since, days) {
|
|
|
291
292
|
// at its own model's price: one month can mix a $4 and a $10 model.
|
|
292
293
|
let usdPerK = 0, priced = 0;
|
|
293
294
|
for (const r of starts) {
|
|
294
|
-
|
|
295
|
-
|
|
295
|
+
// At the rates that request billed (rateCard: its prompt's tier, fast mode, US-only, the day).
|
|
296
|
+
const card = rateCard(r.model ?? model, r.billing, r.at);
|
|
297
|
+
if (!card)
|
|
296
298
|
continue;
|
|
299
|
+
const price = ratesAt(card, r.prompt ?? 0);
|
|
297
300
|
priced++;
|
|
298
|
-
usdPerK += (1000 * (r.cold ? writeMultiplier(r.model ?? model, writes5m, writes1h)
|
|
301
|
+
usdPerK += (1000 * (r.cold ? writePerM(price, writeMultiplier(r.model ?? model, writes5m, writes1h)) : price.cacheReadPerM)) / 1e6;
|
|
299
302
|
}
|
|
300
303
|
const usdPerKPerMonth = priced > 0 ? usdPerK * (30 / days) : undefined;
|
|
301
304
|
return {
|
|
@@ -470,7 +473,7 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
470
473
|
if (b) {
|
|
471
474
|
out.push(`Claude Code, last ${b.days} days: ${sessionCount(b)} start at a median ~${formatTokens(b.median)} tokens (p90 ~${formatTokens(b.p90)}) before the first message.`, `Memory files loaded here are ~${formatTokens(claudeTokens)} of that; the rest is Claude Code's system prompt, tools, skills and MCP schemas.`);
|
|
472
475
|
if (b.usdPerKPerMonth !== undefined) {
|
|
473
|
-
out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model}
|
|
476
|
+
out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} ${priceBasis().replace(/^at /, "")}) every 1k tokens of it costs ~${formatUsd(b.usdPerKPerMonth)} a month;`, `the whole overhead ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month.`);
|
|
474
477
|
}
|
|
475
478
|
}
|
|
476
479
|
else {
|
|
@@ -480,7 +483,7 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
480
483
|
const tokens = r.files.filter((f) => f.agent === o.agent).reduce((s, f) => s + f.tokens, 0);
|
|
481
484
|
out.push("", `${o.agent}, last ${o.days} days: ${sessionCount(o)} start at a median ~${formatTokens(o.median)} tokens (p90 ~${formatTokens(o.p90)}); ${tokens ? `memory files loaded here ~${formatTokens(tokens)} of it` : "no memory files of its own here"}.` +
|
|
482
485
|
(o.usdPerKPerMonth !== undefined
|
|
483
|
-
? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model}
|
|
486
|
+
? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} ${priceBasis().replace(/^at /, "")}).`
|
|
484
487
|
: ""));
|
|
485
488
|
}
|
|
486
489
|
out.push(...renderMcp(r));
|
package/dist/pack.js
CHANGED
|
@@ -460,6 +460,8 @@ function agentConfigFiles() {
|
|
|
460
460
|
const home = homedir();
|
|
461
461
|
const files = [
|
|
462
462
|
claudeJsonPath(), join(home, ".claude.json"),
|
|
463
|
+
// Claude Code's copies of it: <config dir>/backups/.claude.json.backup.<ms> (2.1.321), and the older <file>.backup.
|
|
464
|
+
`${claudeJsonPath()}.backup`, join(home, ".claude.json.backup"), join(claudeDir(), "backups"), join(home, ".claude", "backups"),
|
|
463
465
|
...[claudeDir(), join(home, ".claude")].flatMap((d) => [join(d, "settings.json"), join(d, "settings.local.json")]),
|
|
464
466
|
join(home, ".cursor", "mcp.json"),
|
|
465
467
|
join(codexDir(), "config.toml"), join(home, ".codex", "config.toml"),
|
|
@@ -471,9 +473,35 @@ function agentConfigFiles() {
|
|
|
471
473
|
join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json"),
|
|
472
474
|
join(home, ".config", "Claude", "claude_desktop_config.json"),
|
|
473
475
|
join(process.env.COPILOT_HOME || join(home, ".copilot"), "mcp-config.json"), join(home, ".copilot", "mcp-config.json"),
|
|
476
|
+
// Claude Desktop's extensions keep their settings, API keys among them, in a folder of their own.
|
|
477
|
+
...appDataDirs().map((d) => join(d, "Claude", "Claude Extensions Settings")),
|
|
478
|
+
// VS Code's user MCP servers (stable and Insiders; a profile's own are vsCodeProfileDirs').
|
|
479
|
+
...vsCodeUserDirs().map((d) => join(d, "mcp.json")),
|
|
480
|
+
// Windsurf, and Zed, whose MCP servers ("context_servers") are in its settings.
|
|
481
|
+
join(home, ".codeium", "windsurf", "mcp_config.json"),
|
|
482
|
+
// (%APPDATA%\Zed on Windows, whose disks ignore case: inSensitiveDir.)
|
|
483
|
+
...appDataDirs().map((d) => join(d, "zed", "settings.json")),
|
|
474
484
|
];
|
|
475
485
|
return [...new Set([...files, ...files.map(realOf)])];
|
|
476
486
|
}
|
|
487
|
+
/** Where apps keep their settings: macOS's Application Support, Windows' %APPDATA%, Linux's XDG config folder (every one, whatever the OS). */
|
|
488
|
+
function appDataDirs() {
|
|
489
|
+
const home = homedir();
|
|
490
|
+
return [...new Set([
|
|
491
|
+
join(home, "Library", "Application Support"),
|
|
492
|
+
process.env.APPDATA || join(home, "AppData", "Roaming"),
|
|
493
|
+
process.env.XDG_CONFIG_HOME || join(home, ".config"), join(home, ".config"),
|
|
494
|
+
])];
|
|
495
|
+
}
|
|
496
|
+
/** VS Code's user folders, stable and Insiders. */
|
|
497
|
+
function vsCodeUserDirs() {
|
|
498
|
+
return appDataDirs().flatMap((d) => ["Code", "Code - Insiders"].map((app) => join(d, app, "User")));
|
|
499
|
+
}
|
|
500
|
+
/** The folders that hold VS Code's profiles, each with an mcp.json of its own (User/profiles/<id>/mcp.json). */
|
|
501
|
+
function vsCodeProfileDirs() {
|
|
502
|
+
const dirs = vsCodeUserDirs().map((d) => join(d, "profiles"));
|
|
503
|
+
return [...new Set([...dirs, ...dirs.map(realOf)])];
|
|
504
|
+
}
|
|
477
505
|
/**
|
|
478
506
|
* A path's real spelling: links resolved and, where the system can say,
|
|
479
507
|
* the case on disk and Windows' long names (`realpathSync.native`), so
|
|
@@ -536,6 +564,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
536
564
|
const secretsHint = options.secretsHint ?? "";
|
|
537
565
|
const denied = includeSecrets ? [] : sensitiveDirs();
|
|
538
566
|
const deniedConfigs = includeSecrets ? [] : agentConfigFiles();
|
|
567
|
+
const deniedProfiles = includeSecrets ? [] : vsCodeProfileDirs();
|
|
539
568
|
const sources = [];
|
|
540
569
|
const skipped = [];
|
|
541
570
|
let bytes = 0;
|
|
@@ -583,7 +612,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
583
612
|
skipped.push(`${p}: refused, ${dir} holds credentials${secretsHint}`);
|
|
584
613
|
return;
|
|
585
614
|
}
|
|
586
|
-
const config = inSensitiveDir(real, deniedConfigs);
|
|
615
|
+
const config = inSensitiveDir(real, deniedConfigs) ?? (basename(real).toLowerCase() === "mcp.json" ? inSensitiveDir(real, deniedProfiles) : undefined);
|
|
587
616
|
if (config) {
|
|
588
617
|
skipped.push(`${p}: refused, ${config} can hold API keys (an MCP server's env)${secretsHint}`);
|
|
589
618
|
return;
|