context-doctor 0.47.0 → 0.49.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 +17 -14
- package/dist/ab.d.ts +51 -3
- package/dist/ab.js +68 -26
- package/dist/abclaude.d.ts +167 -0
- package/dist/abclaude.js +511 -0
- package/dist/abstore.d.ts +46 -0
- package/dist/abstore.js +58 -0
- package/dist/budget.d.ts +5 -2
- package/dist/budget.js +21 -7
- package/dist/cache.js +3 -3
- package/dist/cachemisses.d.ts +3 -0
- package/dist/cachemisses.js +8 -0
- package/dist/cachettl.js +6 -2
- package/dist/ccost.d.ts +160 -0
- package/dist/ccost.js +304 -0
- package/dist/cli.js +154 -32
- package/dist/cline.d.ts +41 -0
- package/dist/cline.js +174 -0
- package/dist/coldresume.d.ts +11 -0
- package/dist/coldresume.js +3 -3
- package/dist/coldreturns.d.ts +145 -0
- package/dist/coldreturns.js +282 -0
- package/dist/compactcost.d.ts +10 -4
- package/dist/compactcost.js +12 -7
- package/dist/compactwindow.js +2 -2
- package/dist/copilotusage.d.ts +78 -0
- package/dist/copilotusage.js +193 -0
- package/dist/doctor.d.ts +6 -0
- package/dist/doctor.js +17 -4
- package/dist/fix.d.ts +35 -4
- package/dist/fix.js +55 -8
- package/dist/install.js +2 -0
- package/dist/limits.d.ts +222 -14
- package/dist/limits.js +684 -33
- package/dist/mcp.d.ts +4 -0
- package/dist/mcp.js +142 -98
- package/dist/mcpclient.js +73 -42
- package/dist/mcpdefer.d.ts +47 -0
- package/dist/mcpdefer.js +91 -0
- package/dist/mod/api.d.ts +72 -2
- package/dist/mod/api.js +5 -1
- package/dist/mod/logic.d.ts +281 -0
- package/dist/mod/logic.js +336 -0
- package/dist/mod/register.d.ts +35 -2
- package/dist/mod/register.js +283 -6
- package/dist/modelids.d.ts +58 -0
- package/dist/modelids.js +133 -1
- package/dist/modmeasure.d.ts +6 -4
- package/dist/modmeasure.js +8 -4
- package/dist/opencode.d.ts +57 -0
- package/dist/opencode.js +234 -0
- package/dist/orgrates.d.ts +7 -0
- package/dist/orgrates.js +19 -0
- package/dist/overhead.d.ts +3 -0
- package/dist/overhead.js +5 -1
- package/dist/pricing.d.ts +59 -2
- package/dist/pricing.js +139 -12
- package/dist/proxy.d.ts +8 -1
- package/dist/proxy.js +13 -1
- package/dist/savings.d.ts +5 -1
- package/dist/savings.js +11 -5
- package/dist/scan.d.ts +3 -1
- package/dist/scan.js +8 -1
- package/dist/sessionprice.d.ts +5 -0
- package/dist/sessionprice.js +5 -1
- package/dist/spend.d.ts +86 -3
- package/dist/spend.js +240 -23
- package/dist/spendplace.d.ts +40 -0
- package/dist/spendplace.js +93 -0
- package/dist/spendteam.d.ts +160 -0
- package/dist/spendteam.js +286 -0
- package/dist/starts.d.ts +106 -0
- package/dist/starts.js +406 -0
- package/dist/statusline.d.ts +2 -2
- package/dist/statusline.js +2 -2
- package/dist/subagentmodel.js +9 -7
- package/dist/subagentpay.d.ts +31 -2
- package/dist/subagentpay.js +232 -68
- package/dist/subagents.js +3 -3
- package/dist/tasks.js +3 -2
- package/dist/tooloutput.js +5 -5
- package/dist/usagepane.d.ts +77 -0
- package/dist/usagepane.js +287 -0
- package/package.json +6 -3
package/dist/pricing.js
CHANGED
|
@@ -145,12 +145,15 @@ const PRICING = [
|
|
|
145
145
|
// Fast mode (priority processing; Codex records only its thread's
|
|
146
146
|
// `service_tier`, not each request's) and the 10% regional uplift.
|
|
147
147
|
[openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
|
|
148
|
+
// GPT-6 Astra for Law's price is promotional "at least through December
|
|
149
|
+
// 31, 2026" (read 2026-11-14): no end date to record yet.
|
|
148
150
|
[openai("gpt-6-astra-law"), rate(10, 50, 1)],
|
|
149
151
|
[openai("gpt-6.1-sol"), ...openaiLong(2, 10, 0.1)],
|
|
150
152
|
[openai("gpt-6.1-terra"), ...openaiLong(1, 5, 0.05)],
|
|
151
153
|
[openai("gpt-6-sol"), ...openaiLong(2, 10, 0.2)],
|
|
152
154
|
[openai("gpt-6-luna"), ...openaiLong(0.1, 0.5, 0.01)],
|
|
153
|
-
|
|
155
|
+
// gpt-6-cyber's long-context row ($40 / $150 / $4, read 2026-11-14) is 2x / 1.5x.
|
|
156
|
+
[openai("gpt-6-cyber"), ...openaiLong(20, 100, 2)],
|
|
154
157
|
[openai("gpt-6-rosalind"), ...openaiLong(15, 75, 1.5)],
|
|
155
158
|
[openai("gpt-rosalind-research"), rate(5, 25, 0.5)],
|
|
156
159
|
[openai("gpt-rosalind-discovery"), rate(5, 25, 0.5)],
|
|
@@ -165,6 +168,8 @@ const PRICING = [
|
|
|
165
168
|
[openai("gpt-5.5"), ...openaiLong(5, 30, 0.5)],
|
|
166
169
|
[openai("gpt-5.5-pro"), ...openaiLong(30, 180, 30)],
|
|
167
170
|
[openai("gpt-5.5-cyber"), rate(12.5, 75, 1.25)],
|
|
171
|
+
// The page names it gpt-5.5-cyber-preview now (read 2026-11-14), at the same price.
|
|
172
|
+
[openai("gpt-5.5-cyber-preview"), rate(12.5, 75, 1.25)],
|
|
168
173
|
[openai("gpt-5.4"), ...openaiLong(2.5, 15, 0.25)],
|
|
169
174
|
[openai("gpt-5.4-mini"), rate(0.75, 4.5, 0.075)],
|
|
170
175
|
[openai("gpt-5.4-nano"), rate(0.2, 1.25, 0.02)],
|
|
@@ -184,6 +189,8 @@ const PRICING = [
|
|
|
184
189
|
[openai("o3"), rate(2, 8, 0.5)],
|
|
185
190
|
[openai("o3-pro"), rate(20, 80, 20)],
|
|
186
191
|
[openai("chat-latest"), rate(5, 30, 0.5)],
|
|
192
|
+
// Specialized models, Search (read 2026-11-14); its web search fee is per call, not modelled.
|
|
193
|
+
[openai("gpt-5-search-api"), rate(1.25, 10, 0.125)],
|
|
187
194
|
// Fallbacks for OpenAI ids not on the page (gpt-5-codex, gpt-5.1-codex-max,
|
|
188
195
|
// gpt-4.1-nano, gpt-4-turbo, o1, o3-mini...): older approximate prices.
|
|
189
196
|
[/gpt-5.*(mini|nano)/i, rate(0.25, 2, 0.025), FALLBACK],
|
|
@@ -195,8 +202,13 @@ const PRICING = [
|
|
|
195
202
|
// Google: ai.google.dev/gemini-api/docs/pricing (paid tier, Standard, text),
|
|
196
203
|
// read 2026-11-06; the dates and the Pro tiers read again 2026-11-08.
|
|
197
204
|
// Gemini 4 Argon's $2 / $10 / $0.10 hold "through November 30, 2026";
|
|
198
|
-
// "starting December 1, 2026" it is $4 / $20 / $0.20.
|
|
205
|
+
// "starting December 1, 2026" it is $4 / $20 / $0.20. Read again
|
|
206
|
+
// 2026-11-14: unchanged; Gemini 4 Carbon is new at the same prices and
|
|
207
|
+
// dates, Gemini 4 Hydrogen new at $1.50 / $7.50 / $0.075 with no date.
|
|
208
|
+
// Neither has a long-prompt tier (one 1M-token context).
|
|
209
|
+
[gemini("gemini-4-carbon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
|
|
199
210
|
[gemini("gemini-4-argon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
|
|
211
|
+
[gemini("gemini-4-hydrogen"), rate(1.5, 7.5, 0.075)],
|
|
200
212
|
// 3.6 and 3.8 Flash double "starting January 1, 2027" ($1.50 / $7.50 / $0.15).
|
|
201
213
|
[gemini("gemini-3.8-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
|
|
202
214
|
[gemini("gemini-3.6-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
|
|
@@ -221,16 +233,19 @@ const PRICING = [
|
|
|
221
233
|
[/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
|
|
222
234
|
];
|
|
223
235
|
let tableKey;
|
|
236
|
+
/** Bumped when what a request costs changes beyond the table: 2, the iterations its top-level usage leaves out (billedCost); 3, a compaction's context read from the cache however long the idle (compactcost.ts). */
|
|
237
|
+
const BILLING_RULES = 3;
|
|
224
238
|
/**
|
|
225
239
|
* A fingerprint of this table and its billing constants. Dollars a ledger
|
|
226
240
|
* keeps per request (the budget's, a session's price) were priced by the
|
|
227
241
|
* table of the context-doctor that read them: under another table (an
|
|
228
242
|
* upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
|
|
229
|
-
* and read again, not carried to the period's end.
|
|
243
|
+
* and read again, not carried to the period's end. So are those priced by
|
|
244
|
+
* rules that changed what a request costs (BILLING_RULES).
|
|
230
245
|
*/
|
|
231
246
|
export function priceTableKey() {
|
|
232
247
|
tableKey ??= createHash("sha1")
|
|
233
|
-
.update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD]))
|
|
248
|
+
.update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD, BILLING_RULES]))
|
|
234
249
|
.digest("hex")
|
|
235
250
|
.slice(0, 12);
|
|
236
251
|
return tableKey;
|
|
@@ -447,17 +462,129 @@ export function addModifiers(a, b) {
|
|
|
447
462
|
*/
|
|
448
463
|
export function priceChange(model) {
|
|
449
464
|
const b = row(model)?.[2];
|
|
450
|
-
return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}) } : undefined;
|
|
465
|
+
return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}), ...(b.routes ? { routes: b.routes } : {}) } : undefined;
|
|
451
466
|
}
|
|
452
|
-
/** "
|
|
467
|
+
/** "ended" for a row whose price stops with no price published after it (a promotion), "changed" otherwise: what a report's short label says. */
|
|
468
|
+
export function priceEndWord(model) {
|
|
469
|
+
const c = priceChange(model);
|
|
470
|
+
return c && !c.then && !c.routes ? "ended" : "changed";
|
|
471
|
+
}
|
|
472
|
+
/** "$4 in / $20 out per M": a price as the notes quote it. */
|
|
473
|
+
const perMText = (p) => `$${+p.inputPerM.toFixed(4)} in / $${+p.outputPerM.toFixed(4)} out per M`;
|
|
474
|
+
/**
|
|
475
|
+
* What a request priced past its row's date (rateCard's `changedOn`) was
|
|
476
|
+
* priced at, in words: the price the page said would follow, the model it
|
|
477
|
+
* is billed as from then, or, when the page named nothing (gpt-5.6-sol's
|
|
478
|
+
* promotion), the price that ended. Never silent about which.
|
|
479
|
+
*/
|
|
480
|
+
function priceUsedText(model, on) {
|
|
481
|
+
const b = row(model)?.[2];
|
|
482
|
+
if (b?.routes && b.changes !== undefined && b.changes < on) {
|
|
483
|
+
// Billed as another model whose own price changed later: that model's change is the one in force.
|
|
484
|
+
return `${model} is billed as ${b.routes} from ${b.changes}; ${priceUsedText(b.routes, on)}`;
|
|
485
|
+
}
|
|
486
|
+
if (b?.routes)
|
|
487
|
+
return `${model}'s price ended on ${on}: from then it is billed as ${b.routes}, priced at ${b.routes}'s rates`;
|
|
488
|
+
if (b?.then)
|
|
489
|
+
return `${model}'s price changed on ${on}: priced at the price the page said would follow (${perMText(b.then)})`;
|
|
490
|
+
const was = pricingFor(model);
|
|
491
|
+
return `${model}'s price ended on ${on} and no later price is published: priced at the one that ended${was ? ` (${perMText(was)})` : ""}`;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Said for the models priced past their row's date: which price ended,
|
|
495
|
+
* when, and the price each request was priced at instead, an estimate
|
|
496
|
+
* either way (a scheduled price can be called off, a promotion extended).
|
|
497
|
+
*/
|
|
453
498
|
export function priceChangedText(models) {
|
|
454
|
-
const
|
|
455
|
-
for (const [m, on] of models)
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
499
|
+
const seen = new Map();
|
|
500
|
+
for (const [m, on] of models)
|
|
501
|
+
if (!seen.has(`${m}\u0000${on}`))
|
|
502
|
+
seen.set(`${m}\u0000${on}`, priceUsedText(m, on));
|
|
503
|
+
const parts = [...seen.values()];
|
|
504
|
+
const open = [...seen.keys()].some((k) => { const [m] = k.split("\u0000"); const b = row(m)?.[2]; return !b?.then && !b?.routes; });
|
|
505
|
+
return `${parts.slice(0, 3).join("; ")}${parts.length > 3 ? `; and ${parts.length - 3} more` : ""}; an estimate${open ? "; a newer context-doctor may know the price that followed" : ""}`;
|
|
506
|
+
}
|
|
507
|
+
const promptOf = (u) => count(u?.input_tokens) + count(u?.cache_read_input_tokens) + count(u?.cache_creation_input_tokens);
|
|
508
|
+
/**
|
|
509
|
+
* The iterations of a request billed beyond its top-level usage. The API
|
|
510
|
+
* itemizes one request's inner calls in `usage.iterations`, each with its
|
|
511
|
+
* own tokens (and `model` where it differs), and its top-level usage counts
|
|
512
|
+
* only some of them:
|
|
513
|
+
* - the advisor tool: top-level usage is the sum of the executor's
|
|
514
|
+
* iterations ("message"); each `advisor_message` is billed on top, at the
|
|
515
|
+
* advisor model's rates (Anthropic, "Advisor tool", Usage and billing);
|
|
516
|
+
* - server-side fallbacks: top-level usage is the attempt that produced the
|
|
517
|
+
* message, the last; each earlier attempt (the declined model's, its own
|
|
518
|
+
* `model`) is billed on top (refusals and fallback: "usage.iterations is
|
|
519
|
+
* the per-attempt source of truth"). On the author's machine 34 replies
|
|
520
|
+
* carry one: claude-fable-5 declined after reading 294k tokens, and
|
|
521
|
+
* claude-opus-4-8 answered.
|
|
522
|
+
* Which is which is checked on the tokens, never assumed from the types:
|
|
523
|
+
* the iterations other than the advisor's must add up to the top-level
|
|
524
|
+
* prompt (input, cache reads and writes), or the last of them must equal
|
|
525
|
+
* it. A shape that is neither has only its advisor iterations added (never
|
|
526
|
+
* in the top-level, whatever the rest), so nothing is counted twice.
|
|
527
|
+
* Empty for the common request, one iteration that is the request itself.
|
|
528
|
+
*/
|
|
529
|
+
export function extraIterations(usage) {
|
|
530
|
+
const its = usage?.iterations;
|
|
531
|
+
if (!Array.isArray(its) || its.length < 2)
|
|
532
|
+
return [];
|
|
533
|
+
const list = its.filter((t) => !!t && typeof t === "object" && !Array.isArray(t));
|
|
534
|
+
const extra = (t) => ({
|
|
535
|
+
type: typeof t.type === "string" ? t.type : "message",
|
|
536
|
+
...(typeof t.model === "string" && t.model ? { model: t.model } : {}),
|
|
537
|
+
usage: {
|
|
538
|
+
input_tokens: count(t.input_tokens), cache_read_input_tokens: count(t.cache_read_input_tokens), cache_creation_input_tokens: count(t.cache_creation_input_tokens), output_tokens: count(t.output_tokens),
|
|
539
|
+
...(t.cache_creation && typeof t.cache_creation === "object" ? { cache_creation: t.cache_creation } : {}),
|
|
540
|
+
// The request's own modifiers: where it ran (US-only) and its speed hold for every call in it.
|
|
541
|
+
...(usage?.inference_geo === "us" ? { inference_geo: "us" } : {}),
|
|
542
|
+
...(usage?.speed === "fast" ? { speed: "fast" } : {}),
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
const advisor = list.filter((t) => t.type === "advisor_message");
|
|
546
|
+
const rest = list.filter((t) => t.type !== "advisor_message");
|
|
547
|
+
const top = promptOf(usage);
|
|
548
|
+
if (rest.length <= 1 || rest.reduce((n, t) => n + promptOf(t), 0) === top)
|
|
549
|
+
return advisor.map(extra);
|
|
550
|
+
if (promptOf(rest[rest.length - 1]) === top)
|
|
551
|
+
return [...rest.slice(0, -1), ...advisor].map(extra);
|
|
552
|
+
return advisor.map(extra);
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* What a request cost with the iterations its top-level usage leaves out
|
|
556
|
+
* (extraIterations), each priced by requestCost at its own model and the
|
|
557
|
+
* request's time: the parts and modifiers added up, `rates` the request's
|
|
558
|
+
* own. `extra` is what those iterations added; absent when none. Undefined
|
|
559
|
+
* when the request's own model has no price.
|
|
560
|
+
*/
|
|
561
|
+
export function billedCost(model, usage, at = Date.now()) {
|
|
562
|
+
const c = requestCost(model, usage, at);
|
|
563
|
+
const extras = extraIterations(usage);
|
|
564
|
+
if (!c || !extras.length)
|
|
565
|
+
return c;
|
|
566
|
+
const out = { ...c, modifiers: { ...c.modifiers }, extra: { usd: 0, iterations: 0, unpriced: 0 } };
|
|
567
|
+
for (const x of extras) {
|
|
568
|
+
const e = requestCost(x.model ?? model, x.usage, at);
|
|
569
|
+
if (!e) {
|
|
570
|
+
out.extra.unpriced++;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
out.inputUsd += e.inputUsd;
|
|
574
|
+
out.writeUsd += e.writeUsd;
|
|
575
|
+
out.readUsd += e.readUsd;
|
|
576
|
+
out.outputUsd += e.outputUsd;
|
|
577
|
+
out.promptUsd += e.promptUsd;
|
|
578
|
+
out.totalUsd += e.totalUsd;
|
|
579
|
+
addModifiers(out.modifiers, e.modifiers);
|
|
580
|
+
out.extra.usd += e.totalUsd;
|
|
581
|
+
out.extra.iterations++;
|
|
582
|
+
if (e.estimated)
|
|
583
|
+
out.estimated = true;
|
|
584
|
+
if (e.changedOn && !out.changedOn)
|
|
585
|
+
out.changedOn = e.changedOn;
|
|
459
586
|
}
|
|
460
|
-
return
|
|
587
|
+
return out;
|
|
461
588
|
}
|
|
462
589
|
/**
|
|
463
590
|
* OpenAI usage, in any of its shapes, as RecordedUsage: Responses
|
package/dist/proxy.d.ts
CHANGED
|
@@ -72,11 +72,18 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
72
72
|
* than taking the proxy (and every agent behind it) down.
|
|
73
73
|
*/
|
|
74
74
|
maxBodyBytes?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Where the plan's rate-limit readings from Anthropic's replies go (the
|
|
77
|
+
* `anthropic-ratelimit-unified-5h-*` / `-7d-*` headers a claude.ai sign-in
|
|
78
|
+
* gets): the limits ledger `context-doctor limits` reads, by default.
|
|
79
|
+
* CONTEXT_DOCTOR_NO_LIMITS_LOG=1 keeps none.
|
|
80
|
+
*/
|
|
81
|
+
limitsLogPath?: string;
|
|
75
82
|
}
|
|
76
83
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
77
84
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
78
85
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
79
|
-
export declare const PROXY_VERSION = "0.
|
|
86
|
+
export declare const PROXY_VERSION = "0.49.0";
|
|
80
87
|
/**
|
|
81
88
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
82
89
|
* the prefix is absent or the token differs. The comparison is constant time
|
package/dist/proxy.js
CHANGED
|
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
|
|
|
25
25
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
26
26
|
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
27
27
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
28
|
-
export const PROXY_VERSION = "0.
|
|
28
|
+
export const PROXY_VERSION = "0.49.0";
|
|
29
29
|
/** Connection-level headers that must not be forwarded. */
|
|
30
30
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
31
31
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -566,6 +566,18 @@ export function startProxy(opts = {}) {
|
|
|
566
566
|
upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
|
|
567
567
|
}
|
|
568
568
|
}
|
|
569
|
+
// The plan's windows, as Claude Code reads them from the same headers:
|
|
570
|
+
// into the limits ledger, after the reply is on its way (recordLimits
|
|
571
|
+
// writes only a change, at most once a minute, and never throws).
|
|
572
|
+
if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && (upstream.headers.has("anthropic-ratelimit-unified-7d-utilization") || upstream.headers.has("anthropic-ratelimit-unified-5h-utilization"))) {
|
|
573
|
+
const got = upstream.headers;
|
|
574
|
+
// Loaded on first use: limits.ts reads transcripts and imports this module's version.
|
|
575
|
+
void import("./limits.js").then((m) => {
|
|
576
|
+
const rl = m.rateLimitsFromHeaders((n) => got.get(n));
|
|
577
|
+
if (rl)
|
|
578
|
+
m.recordLimits(rl, Date.now(), opts.limitsLogPath, "proxy");
|
|
579
|
+
}).catch(() => undefined);
|
|
580
|
+
}
|
|
569
581
|
console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
|
|
570
582
|
(stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
|
|
571
583
|
res.statusCode = upstream.status;
|
package/dist/savings.d.ts
CHANGED
|
@@ -90,7 +90,11 @@ export interface CompactWindowLine {
|
|
|
90
90
|
nowPerWeek: number;
|
|
91
91
|
isCurrent: boolean;
|
|
92
92
|
}
|
|
93
|
-
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[]
|
|
93
|
+
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[], keepWarm?: {
|
|
94
|
+
hours: number;
|
|
95
|
+
netUsd: number;
|
|
96
|
+
pingUsd: number;
|
|
97
|
+
}): string;
|
|
94
98
|
/**
|
|
95
99
|
* `savings --share`: a few lines people can paste or screenshot. Totals only:
|
|
96
100
|
* no project names, paths or session ids, so sharing it leaks nothing.
|
package/dist/savings.js
CHANGED
|
@@ -16,7 +16,7 @@ import { AutoClearer } from "./autoclear.js";
|
|
|
16
16
|
import { coldResumeEvents } from "./coldresume.js";
|
|
17
17
|
import { listSessions, isClaudeSession } from "./session.js";
|
|
18
18
|
import { rowsOf } from "./scan.js";
|
|
19
|
-
import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt,
|
|
19
|
+
import { billedCost, CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
|
|
20
20
|
import { priceBasis } from "./orgrates.js";
|
|
21
21
|
import { estimateTokens, formatTokens, realModel } from "./tokens.js";
|
|
22
22
|
import { withInvocation } from "./invocation.js";
|
|
@@ -143,7 +143,8 @@ function replayExtractor(id, options, makeClearer, replay) {
|
|
|
143
143
|
k: "r", now, cold,
|
|
144
144
|
bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
|
|
145
145
|
// No time of its own (now is 0 then): priced as of now, as requestCost prices one.
|
|
146
|
-
|
|
146
|
+
// With the iterations its usage leaves out (billedCost): an advisor's call, a declined attempt.
|
|
147
|
+
usd: billedCost(pm, u, now || undefined)?.promptUsd ?? 0,
|
|
147
148
|
raw: fresh + read + write,
|
|
148
149
|
};
|
|
149
150
|
// Only what is set: a record read back from the cache must equal this one.
|
|
@@ -197,8 +198,8 @@ function replayExtractor(id, options, makeClearer, replay) {
|
|
|
197
198
|
load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
|
|
198
199
|
};
|
|
199
200
|
}
|
|
200
|
-
const REPLAY = replayExtractor("replay.
|
|
201
|
-
const BILL = replayExtractor("bill.
|
|
201
|
+
const REPLAY = replayExtractor("replay.5", {}, undefined, true);
|
|
202
|
+
const BILL = replayExtractor("bill.5", {}, undefined, false);
|
|
202
203
|
/** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
|
|
203
204
|
export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
|
|
204
205
|
/**
|
|
@@ -353,7 +354,7 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress, repl
|
|
|
353
354
|
}
|
|
354
355
|
const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
|
|
355
356
|
const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
356
|
-
export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines) {
|
|
357
|
+
export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines, keepWarm) {
|
|
357
358
|
const lines = [];
|
|
358
359
|
if (r.sessions.length === 0) {
|
|
359
360
|
lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
|
|
@@ -375,6 +376,11 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
|
|
|
375
376
|
lines.push(" expired. Running /compact then, net of the compaction itself, would");
|
|
376
377
|
lines.push(" have saved this. The every-prompt hook points these moments out, in");
|
|
377
378
|
lines.push(" every Claude Code surface, the desktop app included.");
|
|
379
|
+
if (keepWarm && keepWarm.netUsd >= 1) {
|
|
380
|
+
// Not a third column to add up: it replaces the re-write compaction cannot avoid.
|
|
381
|
+
lines.push(` Or keep the cache warm while away, up to ${keepWarm.hours} h: ${usd(keepWarm.netUsd)} net of`);
|
|
382
|
+
lines.push(` ${usd(keepWarm.pingUsd)} in pings (/context-doctor-keep-warm; each gap: cache-misses).`);
|
|
383
|
+
}
|
|
378
384
|
lines.push("");
|
|
379
385
|
if (allDesktop) {
|
|
380
386
|
lines.push(`2. Autopilot ${"n/a".padStart(9)}`);
|
package/dist/scan.d.ts
CHANGED
|
@@ -109,4 +109,6 @@ export declare function pick(o: any, keys: readonly string[]): any;
|
|
|
109
109
|
* records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
|
|
110
110
|
* would grow every record for nothing.
|
|
111
111
|
*/
|
|
112
|
-
export declare const slimUsage: (u: any
|
|
112
|
+
export declare const slimUsage: (u: any, opts?: {
|
|
113
|
+
iterations?: boolean;
|
|
114
|
+
}) => unknown;
|
package/dist/scan.js
CHANGED
|
@@ -43,6 +43,7 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
43
43
|
import { homedir } from "node:os";
|
|
44
44
|
import { isAbsolute, join } from "node:path";
|
|
45
45
|
import { PROXY_VERSION } from "./proxy.js";
|
|
46
|
+
import { extraIterations } from "./pricing.js";
|
|
46
47
|
/** Bumped when the entry layout below changes. */
|
|
47
48
|
const SCHEMA = 1;
|
|
48
49
|
const DAY = 86_400_000;
|
|
@@ -507,7 +508,7 @@ const USAGE_KEYS = ["input_tokens", "cache_creation_input_tokens", "cache_read_i
|
|
|
507
508
|
* records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
|
|
508
509
|
* would grow every record for nothing.
|
|
509
510
|
*/
|
|
510
|
-
export const slimUsage = (u) => {
|
|
511
|
+
export const slimUsage = (u, opts = {}) => {
|
|
511
512
|
const out = pick(u, USAGE_KEYS);
|
|
512
513
|
if (!out || typeof out !== "object" || Array.isArray(out))
|
|
513
514
|
return out;
|
|
@@ -518,5 +519,11 @@ export const slimUsage = (u) => {
|
|
|
518
519
|
const searches = u.server_tool_use?.web_search_requests;
|
|
519
520
|
if (typeof searches === "number" && searches > 0)
|
|
520
521
|
out.server_tool_use = { web_search_requests: searches };
|
|
522
|
+
// The request's iterations, only where some bill beyond its top-level usage (an advisor's, a
|
|
523
|
+
// declined attempt's: extraIterations); every request has one, the request itself, kept for nothing.
|
|
524
|
+
if (opts.iterations && extraIterations(u).length)
|
|
525
|
+
out.iterations = u.iterations.map((t) => pick(t, ITERATION_KEYS));
|
|
521
526
|
return out;
|
|
522
527
|
};
|
|
528
|
+
/** What an iteration is priced from (extraIterations). */
|
|
529
|
+
const ITERATION_KEYS = ["type", "model", "input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens", "cache_creation"];
|
package/dist/sessionprice.d.ts
CHANGED
|
@@ -84,6 +84,11 @@ export interface SessionTotal {
|
|
|
84
84
|
estimatedUsd: number;
|
|
85
85
|
/** Bytes read to bring the entries up to date. */
|
|
86
86
|
read: number;
|
|
87
|
+
/** Each file's own dollars and requests (the main transcript, each subagent's), as counted in `usd`: the usage pane's per-subagent cost. */
|
|
88
|
+
byFile: Record<string, {
|
|
89
|
+
usd: number;
|
|
90
|
+
requests: number;
|
|
91
|
+
}>;
|
|
87
92
|
/** Keeps the entries, so the next look reads only what was appended. */
|
|
88
93
|
save: () => void;
|
|
89
94
|
}
|
package/dist/sessionprice.js
CHANGED
|
@@ -202,10 +202,12 @@ export function sessionTotal(input, now = Date.now()) {
|
|
|
202
202
|
// Each reply once: a fork's copy shares its key with the reply it copied.
|
|
203
203
|
const seen = new Set();
|
|
204
204
|
let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
|
|
205
|
+
const byFile = {};
|
|
205
206
|
for (const [file, whose] of files) {
|
|
206
207
|
const e = kept[file];
|
|
207
208
|
if (!e)
|
|
208
209
|
continue;
|
|
210
|
+
const mine = (byFile[file] = { usd: 0, requests: 0 });
|
|
209
211
|
const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
|
|
210
212
|
e.k.forEach((key, i) => {
|
|
211
213
|
if (key) {
|
|
@@ -214,6 +216,8 @@ export function sessionTotal(input, now = Date.now()) {
|
|
|
214
216
|
seen.add(key);
|
|
215
217
|
}
|
|
216
218
|
usd += e.d[i];
|
|
219
|
+
mine.usd += e.d[i];
|
|
220
|
+
mine.requests++;
|
|
217
221
|
if (whose === "sub")
|
|
218
222
|
subagentUsd += e.d[i];
|
|
219
223
|
if (whose === "workflow")
|
|
@@ -240,7 +244,7 @@ export function sessionTotal(input, now = Date.now()) {
|
|
|
240
244
|
}
|
|
241
245
|
catch { /* read again next time */ }
|
|
242
246
|
};
|
|
243
|
-
return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save };
|
|
247
|
+
return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, byFile, save };
|
|
244
248
|
}
|
|
245
249
|
/** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
|
|
246
250
|
export function saveIfWorthIt(t) {
|
package/dist/spend.d.ts
CHANGED
|
@@ -41,8 +41,15 @@
|
|
|
41
41
|
*/
|
|
42
42
|
import { type ProgressOptions } from "./progresssummaries.js";
|
|
43
43
|
import { type Modifiers } from "./pricing.js";
|
|
44
|
+
import { type SessionGap } from "./ccost.js";
|
|
45
|
+
/**
|
|
46
|
+
* What spend's dollars are: each request as it was billed (its tier, fast mode,
|
|
47
|
+
* US-only, web searches) at list rates, or at the organization's rates.
|
|
48
|
+
* "At list prices" was true before those were priced; it no longer is.
|
|
49
|
+
*/
|
|
50
|
+
export declare const spendBasis: () => string;
|
|
44
51
|
import { type Extractor } from "./scan.js";
|
|
45
|
-
export type Tool = "claude" | "codex" | "gemini" | "cursor";
|
|
52
|
+
export type Tool = "claude" | "codex" | "gemini" | "cursor" | "copilot" | "opencode" | "cline";
|
|
46
53
|
export declare const TOOLS: Tool[];
|
|
47
54
|
export declare const TOOL_NAME: Record<Tool, string>;
|
|
48
55
|
/** One request (a Cursor reply), priced. */
|
|
@@ -78,6 +85,23 @@ export interface SpendItem {
|
|
|
78
85
|
key?: string;
|
|
79
86
|
/** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
|
|
80
87
|
compaction?: boolean;
|
|
88
|
+
/** Copilot CLI: the AI credits it used (one is $0.01), as Copilot recorded them; not in `usd`. */
|
|
89
|
+
credits?: number;
|
|
90
|
+
/** Copilot CLI: the premium requests it counted (its multiplier); not in `usd`. */
|
|
91
|
+
premium?: number;
|
|
92
|
+
/** The folder it ran in, and its git root and branch where the tool recorded them (spendplace.ts). Read for `--by repo` and `--by branch` only; never exported. */
|
|
93
|
+
cwd?: string;
|
|
94
|
+
root?: string;
|
|
95
|
+
branch?: string;
|
|
96
|
+
/** Its repository's name (spendplace.ts repoName), set when the report groups by repository or branch. */
|
|
97
|
+
repo?: string;
|
|
98
|
+
/**
|
|
99
|
+
* Claude Code: an iteration of a request that its top-level usage leaves
|
|
100
|
+
* out, billed on top at its own model (pricing.ts extraIterations): its
|
|
101
|
+
* type, "advisor_message" (the advisor tool's call) or the attempt a
|
|
102
|
+
* fallback replaced ("message"). Not a request of its own: not in the counts.
|
|
103
|
+
*/
|
|
104
|
+
iteration?: string;
|
|
81
105
|
}
|
|
82
106
|
/**
|
|
83
107
|
* A project folder's name (its path with "-" for separators, as Claude Code
|
|
@@ -95,7 +119,7 @@ export declare const anyModifier: (m: Modifiers | undefined) => m is Modifiers;
|
|
|
95
119
|
* Claude Code's requests between `since` and `until`, main threads and
|
|
96
120
|
* subagents, over `tops` (default: every transcript written since `since`).
|
|
97
121
|
*/
|
|
98
|
-
export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
|
|
122
|
+
export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void, place?: boolean): SpendItem[];
|
|
99
123
|
/**
|
|
100
124
|
* What `spend` takes from a Codex rollout: its folder, its own id and the
|
|
101
125
|
* thread that spawned it (the first session_meta), each model change, and
|
|
@@ -150,6 +174,16 @@ export declare function geminiFileSpend(file: string, since: number, until?: num
|
|
|
150
174
|
export declare function geminiFiles(since: number, home?: string): string[];
|
|
151
175
|
export declare function geminiSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
152
176
|
export declare function cursorSpend(since: number, until?: number): SpendItem[];
|
|
177
|
+
/**
|
|
178
|
+
* Copilot CLI's model calls (copilotusage.ts), each priced at its model's
|
|
179
|
+
* list price where the table has one, else counted. What Copilot bills is
|
|
180
|
+
* its AI credits and premium requests, kept beside the price, not in it.
|
|
181
|
+
*/
|
|
182
|
+
export declare function copilotSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
183
|
+
/** OpenCode's model calls (opencode.ts), each at its model's list price. Throws SqliteUnavailableError when its database cannot be read here. */
|
|
184
|
+
export declare function opencodeSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
185
|
+
/** Cline's requests (cline.ts), each at its model's list price; one with no model is counted, not priced. */
|
|
186
|
+
export declare function clineSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
153
187
|
export interface ToolSpend {
|
|
154
188
|
tool: Tool;
|
|
155
189
|
name: string;
|
|
@@ -168,6 +202,9 @@ export interface ToolSpend {
|
|
|
168
202
|
workflowRuns?: number;
|
|
169
203
|
/** Cursor: priced without a cache split, an upper bound. */
|
|
170
204
|
estimate?: boolean;
|
|
205
|
+
/** Copilot CLI: the AI credits and premium requests it recorded, beside `usd` (which is the tokens at list price). */
|
|
206
|
+
credits?: number;
|
|
207
|
+
premium?: number;
|
|
171
208
|
/** Requests whose model has no list price, counted but not in `usd`. */
|
|
172
209
|
unpriced: number;
|
|
173
210
|
unpricedTokens: number;
|
|
@@ -194,6 +231,15 @@ export interface SpendReport {
|
|
|
194
231
|
projects: Array<SpendRow & {
|
|
195
232
|
project: string;
|
|
196
233
|
}>;
|
|
234
|
+
/** By repository (`--by repo` or `--by branch`): a folder's git repository, else the project. Absent otherwise. */
|
|
235
|
+
repos?: Array<SpendRow & {
|
|
236
|
+
repo: string;
|
|
237
|
+
}>;
|
|
238
|
+
/** By repository and branch (`--by branch`); a request whose tool records no branch has none. Absent otherwise. */
|
|
239
|
+
branches?: Array<SpendRow & {
|
|
240
|
+
repo: string;
|
|
241
|
+
branch?: string;
|
|
242
|
+
}>;
|
|
197
243
|
models: Array<SpendRow & {
|
|
198
244
|
model: string;
|
|
199
245
|
}>;
|
|
@@ -223,6 +269,21 @@ export interface SpendReport {
|
|
|
223
269
|
requests: number;
|
|
224
270
|
usd: number;
|
|
225
271
|
};
|
|
272
|
+
/** Claude Code: iterations billed beyond their request's top-level usage (the advisor's calls, attempts a fallback replaced), by type: inside `usd`; absent when none. */
|
|
273
|
+
iterations?: Record<string, {
|
|
274
|
+
calls: number;
|
|
275
|
+
usd: number;
|
|
276
|
+
models: string[];
|
|
277
|
+
}>;
|
|
278
|
+
/**
|
|
279
|
+
* Claude Code's own figure (its `cost-state` records) beside ours, per
|
|
280
|
+
* session wholly in the window that has one (ccost.ts); absent when none.
|
|
281
|
+
*/
|
|
282
|
+
claudeCode?: {
|
|
283
|
+
ccUsd: number;
|
|
284
|
+
ourUsd: number;
|
|
285
|
+
sessions: SessionGap[];
|
|
286
|
+
};
|
|
226
287
|
/**
|
|
227
288
|
* Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
|
|
228
289
|
* `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
|
|
@@ -259,6 +320,8 @@ export declare function localDay(ts: number): string;
|
|
|
259
320
|
export declare function summarizeSpend(items: SpendItem[], days: number, since: number, until: number, skipped?: SpendReport["skipped"]): SpendReport;
|
|
260
321
|
export interface SpendOptions {
|
|
261
322
|
home?: string;
|
|
323
|
+
/** Group by repository, or by repository and branch, besides project: reads where each request ran (spendplace.ts). */
|
|
324
|
+
by?: "project" | "repo" | "branch";
|
|
262
325
|
/** Claude Code transcripts to read instead of every one written in the window (tests). */
|
|
263
326
|
claudePaths?: string[];
|
|
264
327
|
onProgress?: (done: number, total: number) => void;
|
|
@@ -277,12 +340,32 @@ export interface SpendOptions {
|
|
|
277
340
|
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
278
341
|
*/
|
|
279
342
|
export declare const MAX_SPEND_DAYS = 3650;
|
|
343
|
+
/**
|
|
344
|
+
* One Claude Code session's comparison with Claude Code's own figure (ccost.ts):
|
|
345
|
+
* its transcript and its subagents', to its last `cost-state`. Undefined when
|
|
346
|
+
* it has none, or cannot be read.
|
|
347
|
+
*/
|
|
348
|
+
export declare function claudeCodeSession(top: string): SessionGap | undefined;
|
|
349
|
+
/**
|
|
350
|
+
* A session's requests priced past the day their model's price ended or
|
|
351
|
+
* changed, said as `spend` says it: which price, and the one used instead.
|
|
352
|
+
* Undefined when none (or the transcript cannot be read).
|
|
353
|
+
*/
|
|
354
|
+
export declare function sessionPriceEnded(top: string): string | undefined;
|
|
355
|
+
/** Every request of the last `days` days, every tool on this machine, and what could not be read. */
|
|
356
|
+
export declare function collectSpend(days?: number, opts?: SpendOptions): {
|
|
357
|
+
items: SpendItem[];
|
|
358
|
+
days: number;
|
|
359
|
+
since: number;
|
|
360
|
+
until: number;
|
|
361
|
+
skipped: SpendReport["skipped"];
|
|
362
|
+
};
|
|
280
363
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
281
364
|
export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
|
|
282
365
|
export declare const usd: (n: number) => string;
|
|
283
366
|
/** "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. */
|
|
284
367
|
export declare function modifiersText(m: Modifiers): string;
|
|
285
|
-
/** The full report, kept within 80 columns. `top`: rows per list. */
|
|
368
|
+
/** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
|
|
286
369
|
export declare function renderSpend(r: SpendReport, top?: number): string;
|
|
287
370
|
/**
|
|
288
371
|
* `spend --share`: totals only. No project names, paths or session ids, so
|