context-doctor 0.37.0 → 0.38.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 +10 -4
- package/dist/autoclear.d.ts +11 -4
- package/dist/autoclear.js +52 -6
- package/dist/autopilot.d.ts +24 -0
- package/dist/autopilot.js +108 -0
- package/dist/cachemisses.d.ts +104 -2
- package/dist/cachemisses.js +199 -11
- package/dist/cli.js +123 -12
- package/dist/compactwindow.d.ts +1 -1
- package/dist/compactwindow.js +6 -1
- package/dist/doctor.js +58 -1
- package/dist/fanout.d.ts +131 -0
- package/dist/fanout.js +317 -0
- package/dist/handoff.js +10 -0
- package/dist/hook.js +15 -0
- package/dist/install.js +17 -5
- package/dist/lens.d.ts +56 -0
- package/dist/lens.js +213 -0
- package/dist/limits.d.ts +229 -0
- package/dist/limits.js +869 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +64 -57
- package/dist/mcpschema.d.ts +25 -1
- package/dist/mcpschema.js +78 -25
- package/dist/overhead.js +7 -6
- package/dist/precompact.js +8 -7
- package/dist/pricing.d.ts +29 -2
- package/dist/pricing.js +46 -8
- package/dist/proxy.d.ts +5 -3
- package/dist/proxy.js +12 -7
- package/dist/prune.d.ts +116 -0
- package/dist/prune.js +428 -0
- package/dist/recall.d.ts +104 -0
- package/dist/recall.js +393 -0
- package/dist/savings.d.ts +1 -1
- package/dist/savings.js +11 -1
- package/dist/session.js +6 -13
- package/dist/statusline.d.ts +6 -0
- package/dist/statusline.js +9 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +1 -1
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +1 -0
package/dist/install.js
CHANGED
|
@@ -12,6 +12,7 @@ import { delimiter, dirname, join, sep } from "node:path";
|
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { selfCommand, withInvocation } from "./invocation.js";
|
|
14
14
|
import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
|
|
15
|
+
import { FANOUT_MATCHER } from "./fanout.js";
|
|
15
16
|
import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
|
|
16
17
|
function claudeDesktopConfigPath() {
|
|
17
18
|
switch (platform()) {
|
|
@@ -137,7 +138,7 @@ export function claudeInstalledCopies(home = homedir()) {
|
|
|
137
138
|
catch { /* unreadable: not ours to judge here */ }
|
|
138
139
|
try {
|
|
139
140
|
const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
|
|
140
|
-
if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
|
|
141
|
+
if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch", "PreToolUse"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
|
|
141
142
|
found.push("hooks in ~/.claude/settings.json");
|
|
142
143
|
}
|
|
143
144
|
catch { /* unreadable */ }
|
|
@@ -313,6 +314,10 @@ function installHook() {
|
|
|
313
314
|
if (path) {
|
|
314
315
|
installHookInto(settings, join(homedir(), ".claude"), "PreCompact");
|
|
315
316
|
installHookInto(settings, join(homedir(), ".claude"), "SessionStart");
|
|
317
|
+
// Before a subagent starts: its price. PreToolUse is in every Claude Code
|
|
318
|
+
// with hooks (2.1.62's event list has it), so no version guard is needed,
|
|
319
|
+
// and a timeout never blocks the call. "Task" is the tool's name before 2.1.63.
|
|
320
|
+
installHookInto(settings, join(homedir(), ".claude"), "PreToolUse", { matcher: FANOUT_MATCHER, timeout: 10 });
|
|
316
321
|
}
|
|
317
322
|
return path;
|
|
318
323
|
}
|
|
@@ -322,25 +327,29 @@ function installHook() {
|
|
|
322
327
|
* ({hooks:{UserPromptSubmit:[{hooks:[{type:"command",command}]}]}}), so one
|
|
323
328
|
* writer serves both; only the path differs.
|
|
324
329
|
*/
|
|
325
|
-
function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit") {
|
|
330
|
+
function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit", opts = {}) {
|
|
326
331
|
if (!existsSync(gateDir))
|
|
327
332
|
return null; // that app is not on this machine
|
|
328
333
|
const settings = readJson(settingsPath);
|
|
329
334
|
settings.hooks = settings.hooks ?? {};
|
|
330
335
|
const entries = settings.hooks[event] ?? [];
|
|
331
336
|
const want = hookCommand();
|
|
337
|
+
const entry = () => ({
|
|
338
|
+
...(opts.matcher ? { matcher: opts.matcher } : {}),
|
|
339
|
+
hooks: [{ type: "command", command: want, ...(opts.timeout ? { timeout: opts.timeout } : {}) }],
|
|
340
|
+
});
|
|
332
341
|
// Re-running install must REPAIR a stale entry, not skip it. Earlier versions
|
|
333
342
|
// wrote a version-pinned node binary; if we only checked "is it present?" an
|
|
334
343
|
// upgrade would leave that broken command in place forever.
|
|
335
344
|
const ours = entries.filter(isOurHookEntry);
|
|
336
345
|
const current = ours[0]?.hooks?.[0]?.command;
|
|
337
346
|
if (ours.length === 0) {
|
|
338
|
-
entries.push(
|
|
347
|
+
entries.push(entry());
|
|
339
348
|
}
|
|
340
|
-
else if (current !== want) {
|
|
349
|
+
else if (current !== want || (ours[0]?.matcher ?? undefined) !== opts.matcher) {
|
|
341
350
|
// Replace every entry of ours with exactly one correct entry.
|
|
342
351
|
const others = entries.filter((e) => !isOurHookEntry(e));
|
|
343
|
-
others.push(
|
|
352
|
+
others.push(entry());
|
|
344
353
|
settings.hooks[event] = others;
|
|
345
354
|
writeJsonWithBackup(settingsPath, settings);
|
|
346
355
|
return settingsPath;
|
|
@@ -359,6 +368,7 @@ function uninstallHook(attempt) {
|
|
|
359
368
|
attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
|
|
360
369
|
attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
|
|
361
370
|
attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
|
|
371
|
+
attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
|
|
362
372
|
attempt("Codex every-prompt hook", () => uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook"));
|
|
363
373
|
attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
|
|
364
374
|
attempt("Cursor hooks", () => uninstallCursorHook());
|
|
@@ -1188,6 +1198,8 @@ const OUR_CLAUDE_FILES = [
|
|
|
1188
1198
|
".context-doctor-autopilot-paused",
|
|
1189
1199
|
".context-doctor-proxy.log",
|
|
1190
1200
|
".context-doctor-proxy-restart",
|
|
1201
|
+
".context-doctor-limits.jsonl",
|
|
1202
|
+
".context-doctor-subagent-costs.json",
|
|
1191
1203
|
];
|
|
1192
1204
|
export async function runUninstall() {
|
|
1193
1205
|
changes = 0;
|
package/dist/lens.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Two costs the other reports do not show: the output side of the bill, and
|
|
3
|
+
* polling.
|
|
4
|
+
*
|
|
5
|
+
* - Output and reasoning: what share of a session's (or a period's) cost is
|
|
6
|
+
* output tokens, and of those the reasoning (Claude's
|
|
7
|
+
* `output_tokens_details.thinking_tokens`, Codex's
|
|
8
|
+
* `reasoning_output_tokens`), per model. Only shown: whether shorter output
|
|
9
|
+
* keeps quality is a question for `context-doctor ab`, so no saving is
|
|
10
|
+
* claimed here.
|
|
11
|
+
* - Polling: a tool call identical to the one before it (same tool, same
|
|
12
|
+
* input), as a wait-and-check loop makes (BashOutput on one shell, Codex's
|
|
13
|
+
* `wait` or `write_stdin` with nothing to write, `sleep 30 && tail log`).
|
|
14
|
+
* Each repeat is a whole request that re-reads the context; it is priced
|
|
15
|
+
* at that request's billed cost.
|
|
16
|
+
*/
|
|
17
|
+
export interface ModelOutput {
|
|
18
|
+
model: string;
|
|
19
|
+
requests: number;
|
|
20
|
+
outputTokens: number;
|
|
21
|
+
/** Reasoning (thinking) tokens within the output, where the usage records them. */
|
|
22
|
+
reasoningTokens: number;
|
|
23
|
+
outputUsd: number;
|
|
24
|
+
totalUsd: number;
|
|
25
|
+
}
|
|
26
|
+
export interface PollStats {
|
|
27
|
+
/** Calls identical to the call before them. */
|
|
28
|
+
repeats: number;
|
|
29
|
+
/** The requests that issued them, at list price. */
|
|
30
|
+
usd: number;
|
|
31
|
+
/** Context those requests re-read. */
|
|
32
|
+
contextTokens: number;
|
|
33
|
+
byTool: Array<{
|
|
34
|
+
tool: string;
|
|
35
|
+
repeats: number;
|
|
36
|
+
usd: number;
|
|
37
|
+
}>;
|
|
38
|
+
}
|
|
39
|
+
export interface Lens {
|
|
40
|
+
sessions: number;
|
|
41
|
+
byModel: ModelOutput[];
|
|
42
|
+
polls: PollStats;
|
|
43
|
+
totalUsd: number;
|
|
44
|
+
}
|
|
45
|
+
/** One session transcript (Claude Code or Codex). */
|
|
46
|
+
export declare function sessionLens(path: string, since?: number): Lens;
|
|
47
|
+
/** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */
|
|
48
|
+
export declare function lensOverSessions(days?: number, opts?: {
|
|
49
|
+
claudeOnly?: boolean;
|
|
50
|
+
paths?: string[];
|
|
51
|
+
now?: number;
|
|
52
|
+
}): Lens;
|
|
53
|
+
/** Lines for `session` and `savings` (within 60 columns), or none when nothing is priced. */
|
|
54
|
+
export declare function renderLens(l: Lens, opts?: {
|
|
55
|
+
heading?: boolean;
|
|
56
|
+
}): string[];
|
package/dist/lens.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Two costs the other reports do not show: the output side of the bill, and
|
|
3
|
+
* polling.
|
|
4
|
+
*
|
|
5
|
+
* - Output and reasoning: what share of a session's (or a period's) cost is
|
|
6
|
+
* output tokens, and of those the reasoning (Claude's
|
|
7
|
+
* `output_tokens_details.thinking_tokens`, Codex's
|
|
8
|
+
* `reasoning_output_tokens`), per model. Only shown: whether shorter output
|
|
9
|
+
* keeps quality is a question for `context-doctor ab`, so no saving is
|
|
10
|
+
* claimed here.
|
|
11
|
+
* - Polling: a tool call identical to the one before it (same tool, same
|
|
12
|
+
* input), as a wait-and-check loop makes (BashOutput on one shell, Codex's
|
|
13
|
+
* `wait` or `write_stdin` with nothing to write, `sleep 30 && tail log`).
|
|
14
|
+
* Each repeat is a whole request that re-reads the context; it is priced
|
|
15
|
+
* at that request's billed cost.
|
|
16
|
+
*/
|
|
17
|
+
import { forEachLine, listSessions, replyCounter } from "./session.js";
|
|
18
|
+
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
19
|
+
import { formatTokens, realModel } from "./tokens.js";
|
|
20
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
21
|
+
class Acc {
|
|
22
|
+
models = new Map();
|
|
23
|
+
polls = new Map();
|
|
24
|
+
pollContext = 0;
|
|
25
|
+
sessions = 0;
|
|
26
|
+
request(model, u, reasoning) {
|
|
27
|
+
const name = model ?? "unknown";
|
|
28
|
+
const m = this.models.get(name) ?? { model: name, requests: 0, outputTokens: 0, reasoningTokens: 0, outputUsd: 0, totalUsd: 0 };
|
|
29
|
+
const price = pricingFor(model);
|
|
30
|
+
const cost = price ? usageCost(u, price) : undefined;
|
|
31
|
+
m.requests++;
|
|
32
|
+
m.outputTokens += num(u.output_tokens);
|
|
33
|
+
m.reasoningTokens += Math.min(num(u.output_tokens), reasoning);
|
|
34
|
+
m.outputUsd += cost?.outputUsd ?? 0;
|
|
35
|
+
m.totalUsd += cost?.totalUsd ?? 0;
|
|
36
|
+
this.models.set(name, m);
|
|
37
|
+
return cost?.totalUsd ?? 0;
|
|
38
|
+
}
|
|
39
|
+
poll(tool, usd, context) {
|
|
40
|
+
const p = this.polls.get(tool) ?? { repeats: 0, usd: 0 };
|
|
41
|
+
p.repeats++;
|
|
42
|
+
p.usd += usd;
|
|
43
|
+
this.polls.set(tool, p);
|
|
44
|
+
this.pollContext += context;
|
|
45
|
+
}
|
|
46
|
+
result() {
|
|
47
|
+
const byModel = [...this.models.values()].filter((m) => m.requests > 0).sort((a, b) => b.totalUsd - a.totalUsd);
|
|
48
|
+
const byTool = [...this.polls.entries()].map(([tool, p]) => ({ tool, ...p })).sort((a, b) => b.usd - a.usd || b.repeats - a.repeats);
|
|
49
|
+
return {
|
|
50
|
+
sessions: this.sessions,
|
|
51
|
+
byModel,
|
|
52
|
+
polls: { repeats: byTool.reduce((n, t) => n + t.repeats, 0), usd: byTool.reduce((n, t) => n + t.usd, 0), contextTokens: this.pollContext, byTool },
|
|
53
|
+
totalUsd: byModel.reduce((n, m) => n + m.totalUsd, 0),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** A call's identity: its tool and its exact input. */
|
|
58
|
+
const callKey = (name, input) => `${name}\u0000${typeof input === "string" ? input : JSON.stringify(input ?? null)}`;
|
|
59
|
+
function scanClaude(path, acc, since, runRows) {
|
|
60
|
+
const sighting = replyCounter(runRows);
|
|
61
|
+
const costOf = new Map();
|
|
62
|
+
let prevCall;
|
|
63
|
+
forEachLine(path, (line) => {
|
|
64
|
+
const prompt = line.includes('"type":"user"') && !line.includes('"tool_result"');
|
|
65
|
+
if (!prompt && !line.includes('"usage"') && !line.includes('"tool_use"'))
|
|
66
|
+
return;
|
|
67
|
+
let e;
|
|
68
|
+
try {
|
|
69
|
+
e = JSON.parse(line);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// A prompt the user typed between two identical calls makes the second a
|
|
75
|
+
// new request, not a poll (the same check, asked for again).
|
|
76
|
+
if (e?.type === "user" && !e.isSidechain && !e.isMeta && !(Array.isArray(e.message?.content) && e.message.content.some((b) => b?.type === "tool_result"))) {
|
|
77
|
+
prevCall = undefined;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (e?.type !== "assistant" || e.isSidechain || !e.message)
|
|
81
|
+
return;
|
|
82
|
+
const m = e.message;
|
|
83
|
+
const at = Date.parse(String(e.timestamp ?? ""));
|
|
84
|
+
const inPeriod = !(Number.isFinite(at) && at < since);
|
|
85
|
+
const id = typeof m.id === "string" ? m.id : undefined;
|
|
86
|
+
if (m.usage && realModel(m.model)) {
|
|
87
|
+
const seen = sighting(e);
|
|
88
|
+
if (seen === "new" && inPeriod) {
|
|
89
|
+
const u = m.usage;
|
|
90
|
+
const usd = acc.request(realModel(m.model), u, num(u.output_tokens_details?.thinking_tokens));
|
|
91
|
+
if (id)
|
|
92
|
+
costOf.set(id, { usd, context: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens) });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(m.content))
|
|
96
|
+
return;
|
|
97
|
+
for (const b of m.content) {
|
|
98
|
+
if (b?.type !== "tool_use" || typeof b.name !== "string")
|
|
99
|
+
continue;
|
|
100
|
+
const key = callKey(b.name, b.input);
|
|
101
|
+
if (key === prevCall && inPeriod) {
|
|
102
|
+
// One reply's cost once, however many identical calls it holds.
|
|
103
|
+
const c = id ? costOf.get(id) : undefined;
|
|
104
|
+
acc.poll(b.name, c?.usd ?? 0, c?.context ?? 0);
|
|
105
|
+
if (id && c)
|
|
106
|
+
costOf.set(id, { usd: 0, context: 0 });
|
|
107
|
+
}
|
|
108
|
+
prevCall = key;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
function scanCodex(path, acc, since) {
|
|
113
|
+
let model;
|
|
114
|
+
let prevCall;
|
|
115
|
+
/** Repeats waiting for the token_count of the response that made them. */
|
|
116
|
+
let pending = [];
|
|
117
|
+
let total = -1;
|
|
118
|
+
forEachLine(path, (line) => {
|
|
119
|
+
let e;
|
|
120
|
+
try {
|
|
121
|
+
e = JSON.parse(line);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const p = e?.payload;
|
|
127
|
+
if (!p || typeof p !== "object")
|
|
128
|
+
return;
|
|
129
|
+
const at = Date.parse(String(e.timestamp ?? ""));
|
|
130
|
+
const inPeriod = !(Number.isFinite(at) && at < since);
|
|
131
|
+
if (e.type === "turn_context" && typeof p.model === "string")
|
|
132
|
+
model = p.model;
|
|
133
|
+
if (e.type === "response_item" && p.type === "message" && p.role === "user")
|
|
134
|
+
prevCall = undefined;
|
|
135
|
+
if (e.type === "response_item" && (p.type === "function_call" || p.type === "custom_tool_call" || p.type === "local_shell_call")) {
|
|
136
|
+
const name = String(p.name ?? (p.type === "local_shell_call" ? "shell" : p.type));
|
|
137
|
+
const key = callKey(name, p.arguments ?? p.input ?? p.action);
|
|
138
|
+
if (key === prevCall && inPeriod)
|
|
139
|
+
pending.push(name);
|
|
140
|
+
prevCall = key;
|
|
141
|
+
}
|
|
142
|
+
if (e.type === "event_msg" && p.type === "token_count") {
|
|
143
|
+
const last = p.info?.last_token_usage;
|
|
144
|
+
const runTotal = num(p.info?.total_token_usage?.total_tokens);
|
|
145
|
+
if (!last || !(num(last.input_tokens) > 0) || (runTotal !== 0 && runTotal === total))
|
|
146
|
+
return;
|
|
147
|
+
total = runTotal;
|
|
148
|
+
if (!inPeriod) {
|
|
149
|
+
pending = [];
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const u = openAIUsage(last);
|
|
153
|
+
const usd = acc.request(model, u, num(last.reasoning_output_tokens));
|
|
154
|
+
pending.forEach((name, i) => acc.poll(name, i === 0 ? usd : 0, i === 0 ? num(last.input_tokens) : 0));
|
|
155
|
+
pending = [];
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** One session transcript (Claude Code or Codex). */
|
|
160
|
+
export function sessionLens(path, since = 0) {
|
|
161
|
+
const acc = new Acc();
|
|
162
|
+
acc.sessions = 1;
|
|
163
|
+
if (/[\\/]\.codex[\\/]/.test(path) || /rollout-[^\\/]*\.jsonl$/.test(path))
|
|
164
|
+
scanCodex(path, acc, since);
|
|
165
|
+
else
|
|
166
|
+
scanClaude(path, acc, since);
|
|
167
|
+
return acc.result();
|
|
168
|
+
}
|
|
169
|
+
/** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */
|
|
170
|
+
export function lensOverSessions(days = 30, opts = {}) {
|
|
171
|
+
const since = (opts.now ?? Date.now()) - days * 86_400_000;
|
|
172
|
+
const files = opts.paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since && (s.path.includes(".claude") || (!opts.claudeOnly && s.project === "codex"))).map((s) => s.path);
|
|
173
|
+
const acc = new Acc();
|
|
174
|
+
const runRows = new Set();
|
|
175
|
+
for (const f of files) {
|
|
176
|
+
try {
|
|
177
|
+
if (/[\\/]\.codex[\\/]/.test(f))
|
|
178
|
+
scanCodex(f, acc, since);
|
|
179
|
+
else
|
|
180
|
+
scanClaude(f, acc, since, runRows);
|
|
181
|
+
acc.sessions++;
|
|
182
|
+
}
|
|
183
|
+
catch { /* skip */ }
|
|
184
|
+
}
|
|
185
|
+
return acc.result();
|
|
186
|
+
}
|
|
187
|
+
const pct = (x) => `${Math.round(x * 100)}%`;
|
|
188
|
+
const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n >= 0.01 ? `$${n.toFixed(2)}` : n > 0 ? "<$0.01" : "$0");
|
|
189
|
+
/** A tool as people say it: an MCP tool by its own name, without the server prefix. */
|
|
190
|
+
const toolName = (t) => /^mcp__.+?__(.+)$/.exec(t)?.[1] ?? t;
|
|
191
|
+
/** Lines for `session` and `savings` (within 60 columns), or none when nothing is priced. */
|
|
192
|
+
export function renderLens(l, opts = {}) {
|
|
193
|
+
const priced = l.byModel.filter((m) => m.totalUsd > 0);
|
|
194
|
+
if (!priced.length)
|
|
195
|
+
return [];
|
|
196
|
+
const out = [];
|
|
197
|
+
if (opts.heading !== false)
|
|
198
|
+
out.push("Output and polling (at list price; shown, not a lever)");
|
|
199
|
+
const all = priced.reduce((a, m) => ({ out: a.out + m.outputUsd, total: a.total + m.totalUsd, tokens: a.tokens + m.outputTokens, reasoning: a.reasoning + m.reasoningTokens }), { out: 0, total: 0, tokens: 0, reasoning: 0 });
|
|
200
|
+
out.push(` Output: ${pct(all.out / all.total)} of ${usd(all.total)}` + (all.reasoning > 0 ? `; reasoning ${pct(all.reasoning / Math.max(1, all.tokens))} of output tokens.` : "."));
|
|
201
|
+
if (priced.length > 1) {
|
|
202
|
+
for (const m of priced.slice(0, 4)) {
|
|
203
|
+
out.push(` ${m.model.slice(0, 20).padEnd(20)} ${pct(m.outputUsd / m.totalUsd).padStart(4)} of ${usd(m.totalUsd).padStart(7)}${m.reasoningTokens > 0 ? `, reasoning ${pct(m.reasoningTokens / Math.max(1, m.outputTokens))}` : ""}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (l.polls.repeats > 0) {
|
|
207
|
+
const top = l.polls.byTool.slice(0, 3).map((t) => `${toolName(t.tool).slice(0, 18)} ${t.repeats}`).join(", ");
|
|
208
|
+
out.push(` ${l.polls.repeats} repeated identical tool call${l.polls.repeats === 1 ? "" : "s"} (polling) re-read`);
|
|
209
|
+
out.push(` ~${formatTokens(l.polls.contextTokens)} tokens: ${usd(l.polls.usd)}. Most: ${top}.`);
|
|
210
|
+
}
|
|
211
|
+
out.push(" Does shorter output keep quality? context-doctor ab");
|
|
212
|
+
return out;
|
|
213
|
+
}
|
package/dist/limits.d.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor limits`: your plan's usage limits, in their own unit.
|
|
3
|
+
*
|
|
4
|
+
* Subscriptions are billed in % of a 5-hour and a weekly window (Claude
|
|
5
|
+
* Pro/Max), or in credits per token (Codex since April 2026), and neither
|
|
6
|
+
* vendor shows where the percentage went. Two local sources say:
|
|
7
|
+
*
|
|
8
|
+
* - Claude Code hands its status line command `rate_limits.five_hour` and
|
|
9
|
+
* `.seven_day`, each `{used_percentage, resets_at}` (documented at
|
|
10
|
+
* code.claude.com/docs/en/statusline; built in 2.1.308 as
|
|
11
|
+
* Math.round(utilization*1000)/10, so 0.1% steps; present only for
|
|
12
|
+
* Pro/Max subscribers, after the first reply). `context-doctor statusline`
|
|
13
|
+
* appends each new reading to a small local log (recordLimits).
|
|
14
|
+
* - Codex records `rate_limits.primary` / `.secondary`
|
|
15
|
+
* `{used_percent, window_minutes, resets_at}` on every token_count event of
|
|
16
|
+
* its rollouts (~/.codex/sessions), next to that request's usage, in
|
|
17
|
+
* whole percent.
|
|
18
|
+
*
|
|
19
|
+
* From the readings: the current %, the pace, and when each window runs out
|
|
20
|
+
* at that pace. And, by fitting each rise in % against the usage recorded on
|
|
21
|
+
* this machine over the same interval, an estimate of what 1M tokens of each
|
|
22
|
+
* kind cost in % of the limit, with the fit's error. Usage elsewhere (claude.ai
|
|
23
|
+
* in a browser, another computer) moves the % without leaving a transcript
|
|
24
|
+
* here; it shows up as error, and rises with no local usage at all are
|
|
25
|
+
* counted apart. When the fit is too thin to trust, the report says so
|
|
26
|
+
* instead of printing a number.
|
|
27
|
+
*/
|
|
28
|
+
/** Claude Code's two windows, as its status line input names them. */
|
|
29
|
+
export declare const CLAUDE_WINDOWS: readonly ["five_hour", "seven_day"];
|
|
30
|
+
/** One reading of one window: how much of it was used at `ts`. */
|
|
31
|
+
export interface LimitReading {
|
|
32
|
+
/** When it was read, ms. */
|
|
33
|
+
ts: number;
|
|
34
|
+
app: "claude" | "codex";
|
|
35
|
+
/** "five_hour", "seven_day", or for Codex "codex:[<plan>:][<limit id>:]<minutes>". */
|
|
36
|
+
window: string;
|
|
37
|
+
/** Percent used, 0-100 (a gateway's spend can pass 100). */
|
|
38
|
+
pct: number;
|
|
39
|
+
/** When the window resets, ms. */
|
|
40
|
+
resetsAt?: number;
|
|
41
|
+
/** The window's length, ms, when known. */
|
|
42
|
+
windowMs?: number;
|
|
43
|
+
/** Codex's plan ("plus", "team", "free"...). */
|
|
44
|
+
plan?: string;
|
|
45
|
+
}
|
|
46
|
+
/** One request's usage, from a transcript on this machine. */
|
|
47
|
+
export interface UsagePoint {
|
|
48
|
+
ts: number;
|
|
49
|
+
app: "claude" | "codex";
|
|
50
|
+
model?: string;
|
|
51
|
+
/** Uncached input, cache reads, cache writes, output: tokens. */
|
|
52
|
+
input: number;
|
|
53
|
+
read: number;
|
|
54
|
+
write: number;
|
|
55
|
+
output: number;
|
|
56
|
+
/** At API list price; 0 when the model has no price on file. */
|
|
57
|
+
usd: number;
|
|
58
|
+
}
|
|
59
|
+
/** Beside the hook state and the ledger: ~/.claude/.context-doctor-limits.jsonl. */
|
|
60
|
+
export declare function limitsLogPath(): string;
|
|
61
|
+
/**
|
|
62
|
+
* Append what changed in Claude Code's `rate_limits` to the log: a window
|
|
63
|
+
* whose % or reset time moved since its last line, or that has not been
|
|
64
|
+
* written for 15 minutes. Nothing when there are no limits (an API key,
|
|
65
|
+
* Bedrock, Vertex). Never throws: the status line must stay silent. Returns
|
|
66
|
+
* the lines written.
|
|
67
|
+
*/
|
|
68
|
+
export declare function recordLimits(rateLimits: unknown, now?: number, path?: string): number;
|
|
69
|
+
/** Every Claude reading in the log since `since`. */
|
|
70
|
+
export declare function readClaudeReadings(since?: number, path?: string): LimitReading[];
|
|
71
|
+
export declare function codexSessionsRoot(home?: string): string;
|
|
72
|
+
/**
|
|
73
|
+
* Codex readings and usage since `since`. A token_count event repeats the
|
|
74
|
+
* last request's usage when only the limits were refreshed, so a request is
|
|
75
|
+
* counted when the running total moves.
|
|
76
|
+
*/
|
|
77
|
+
export declare function codexLimitData(since: number, root?: string): {
|
|
78
|
+
readings: LimitReading[];
|
|
79
|
+
usage: UsagePoint[];
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Every Claude Code request between `since` and `until`, main threads and
|
|
83
|
+
* subagents alike (both draw on the same limits), each reply once.
|
|
84
|
+
*/
|
|
85
|
+
export declare function claudeUsage(since: number, until?: number, paths?: string[]): UsagePoint[];
|
|
86
|
+
export interface WindowStatus {
|
|
87
|
+
window: string;
|
|
88
|
+
label: string;
|
|
89
|
+
app: "claude" | "codex";
|
|
90
|
+
pct: number;
|
|
91
|
+
/** When the newest reading was taken. */
|
|
92
|
+
at: number;
|
|
93
|
+
resetsAt?: number;
|
|
94
|
+
/** True when the newest reading's window has reset since (its % is stale). */
|
|
95
|
+
resetSince: boolean;
|
|
96
|
+
/** Points per hour over the recent stretch (the last hour of a 5-hour window, the last day otherwise). */
|
|
97
|
+
recentPerHour?: number;
|
|
98
|
+
/** Points per hour since the window began, when its length is known. */
|
|
99
|
+
averagePerHour?: number;
|
|
100
|
+
/** At the recent pace: when it reaches 100%, and whether that is before the reset. */
|
|
101
|
+
runsOutAt?: number;
|
|
102
|
+
beforeReset?: boolean;
|
|
103
|
+
readings: number;
|
|
104
|
+
plan?: string;
|
|
105
|
+
}
|
|
106
|
+
export declare function windowLabel(window: string, windowMs?: number): string;
|
|
107
|
+
/**
|
|
108
|
+
* One window's readings, in time order, without the stale ones: a reading
|
|
109
|
+
* lower than an earlier one of the same period comes from another session
|
|
110
|
+
* (two Claude Code windows, two Codex sessions) still holding an older
|
|
111
|
+
* figure. Within a period usage only grows, so it is dropped, never read as
|
|
112
|
+
* a new period or a fall in the pace. Logs written before 0.38 hold them.
|
|
113
|
+
*/
|
|
114
|
+
export declare function cleanReadings(readings: LimitReading[]): LimitReading[];
|
|
115
|
+
/** 0.1 when any reading has a fraction (Claude), else 1 (Codex's whole percents). */
|
|
116
|
+
export declare function resolutionOf(readings: LimitReading[]): number;
|
|
117
|
+
export declare function windowStatus(readings: LimitReading[], now?: number): WindowStatus | undefined;
|
|
118
|
+
/** A stretch of one window's period in which the % rose by `dpct`, with the usage recorded in it. */
|
|
119
|
+
export interface Segment {
|
|
120
|
+
from: number;
|
|
121
|
+
to: number;
|
|
122
|
+
dpct: number;
|
|
123
|
+
/** Millions of tokens: uncached input, cache read, cache write, output. */
|
|
124
|
+
x: [number, number, number, number];
|
|
125
|
+
usd: number;
|
|
126
|
+
requests: number;
|
|
127
|
+
}
|
|
128
|
+
export declare const TOKEN_TYPES: readonly ["input", "cache read", "cache write", "output"];
|
|
129
|
+
/**
|
|
130
|
+
* Cut each period into stretches of at least `stretchMs` (half an hour on
|
|
131
|
+
* Claude's 0.1% steps, three hours on Codex's whole percents) and sum the
|
|
132
|
+
* usage that falls inside each. Cut by time, not by rise: stretches then
|
|
133
|
+
* differ in how much was used, which is what the fit learns from, and a
|
|
134
|
+
* quiet stretch says as much as a busy one. A rise with no local usage at
|
|
135
|
+
* all is usage elsewhere: counted, kept out of the fit; a quiet stretch with
|
|
136
|
+
* no rise is left out.
|
|
137
|
+
*/
|
|
138
|
+
export declare function segmentsOf(readings: LimitReading[], usage: UsagePoint[], stretchMs?: number): {
|
|
139
|
+
segments: Segment[];
|
|
140
|
+
elsewhere: number;
|
|
141
|
+
elsewherePct: number;
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* Non-negative least squares through the origin, exactly, by trying every
|
|
145
|
+
* subset of columns (four token types: sixteen subsets) and keeping the best
|
|
146
|
+
* fit whose coefficients are all non-negative. Columns with almost no data
|
|
147
|
+
* are left out and reported as such.
|
|
148
|
+
*/
|
|
149
|
+
export declare function nnls(rows: number[][], y: number[], usable: number[]): number[];
|
|
150
|
+
export interface FitQuality {
|
|
151
|
+
/** 1 - SSE / total sum of squares around the mean: share of the variation explained (shown, not a gate). */
|
|
152
|
+
r2: number;
|
|
153
|
+
/** Cross-validated prediction error, in points of the limit per stretch. */
|
|
154
|
+
looRmse: number;
|
|
155
|
+
/** looRmse relative to the mean rise per stretch. */
|
|
156
|
+
relError: number;
|
|
157
|
+
/** Price fit only: the coefficient's standard error relative to the coefficient. */
|
|
158
|
+
relSe?: number;
|
|
159
|
+
}
|
|
160
|
+
export interface LimitFit {
|
|
161
|
+
window: string;
|
|
162
|
+
label: string;
|
|
163
|
+
app: "claude" | "codex";
|
|
164
|
+
segments: number;
|
|
165
|
+
/** Points the window rose over the fitted segments. */
|
|
166
|
+
totalPct: number;
|
|
167
|
+
/** Rises with no usage on this machine (usage elsewhere), left out. */
|
|
168
|
+
elsewhere: number;
|
|
169
|
+
elsewherePct: number;
|
|
170
|
+
resolution: number;
|
|
171
|
+
/** Requests and list-price dollars the segments hold. */
|
|
172
|
+
requests: number;
|
|
173
|
+
usd: number;
|
|
174
|
+
/** % of the limit per 1M tokens of each type; undefined for a type with too little data. */
|
|
175
|
+
perMillion?: Partial<Record<(typeof TOKEN_TYPES)[number], number>>;
|
|
176
|
+
byType?: FitQuality;
|
|
177
|
+
/** % of the limit per list-price dollar, and how well that alone explains the rises. */
|
|
178
|
+
pctPerUsd?: number;
|
|
179
|
+
byPrice?: FitQuality;
|
|
180
|
+
/** The model most of the dollars went to, which the per-1M figures from price are for. */
|
|
181
|
+
mainModel?: string;
|
|
182
|
+
/** Stretches left out of the price fit for rising far beyond their usage (use elsewhere at the same time), and the excess points. */
|
|
183
|
+
outliers?: number;
|
|
184
|
+
outlierPct?: number;
|
|
185
|
+
/** With an intercept, the slope's standard error relative to it: large when the rises do not follow the usage. */
|
|
186
|
+
slopeRelSe?: number;
|
|
187
|
+
/** Good enough to put savings in % of this limit. */
|
|
188
|
+
usable: boolean;
|
|
189
|
+
/** Why not, in words, when it is not. */
|
|
190
|
+
why?: string;
|
|
191
|
+
}
|
|
192
|
+
export declare function fitWindow(readings: LimitReading[], usage: UsagePoint[], stretchMs?: number): LimitFit | undefined;
|
|
193
|
+
export interface LimitsReport {
|
|
194
|
+
days: number;
|
|
195
|
+
now: number;
|
|
196
|
+
/** Where the Claude readings are logged, and how many there are. */
|
|
197
|
+
claudeLog: string;
|
|
198
|
+
claudeReadings: number;
|
|
199
|
+
codexReadings: number;
|
|
200
|
+
windows: WindowStatus[];
|
|
201
|
+
fits: LimitFit[];
|
|
202
|
+
}
|
|
203
|
+
export interface LimitsOptions {
|
|
204
|
+
now?: number;
|
|
205
|
+
logPath?: string;
|
|
206
|
+
codexRoot?: string;
|
|
207
|
+
/** Claude Code transcripts to read usage from (default: every one touched in the period). */
|
|
208
|
+
claudePaths?: string[];
|
|
209
|
+
/** Leave Codex out (savings and the other Claude Code reports). */
|
|
210
|
+
claudeOnly?: boolean;
|
|
211
|
+
}
|
|
212
|
+
export declare function limitsReport(days?: number, opts?: LimitsOptions): LimitsReport;
|
|
213
|
+
/** The Claude fit to quote savings in: the weekly window first (savings are weekly), then the 5-hour one. */
|
|
214
|
+
export declare function claudeLimitFit(r: LimitsReport): LimitFit | undefined;
|
|
215
|
+
/**
|
|
216
|
+
* A dollar saving over `days`, in the limit's own unit: for the weekly
|
|
217
|
+
* limit, points of it a week ("≈ 4.1% of your weekly limit a week (±0.4)");
|
|
218
|
+
* for the 5-hour window, how many whole windows the saving amounts to. The
|
|
219
|
+
* ± is the rate's own standard error: a saving sums many stretches, so the
|
|
220
|
+
* per-stretch miss averages out and the rate's error is what remains.
|
|
221
|
+
*/
|
|
222
|
+
export declare function inLimit(fit: LimitFit, usd: number, days: number): string | undefined;
|
|
223
|
+
/**
|
|
224
|
+
* Lines for the Claude Code reports: each lever's saving in the limit, when
|
|
225
|
+
* a fit is good enough; nothing otherwise (never a number the fit cannot
|
|
226
|
+
* carry). Kept within 60 columns, as `savings` is.
|
|
227
|
+
*/
|
|
228
|
+
export declare function limitSavingsLines(fit: LimitFit | undefined, items: Array<[label: string, usd: number]>, days: number): string[];
|
|
229
|
+
export declare function renderLimits(r: LimitsReport): string;
|