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/mcpschema.d.ts
CHANGED
|
@@ -35,12 +35,36 @@ export interface McpServerSize {
|
|
|
35
35
|
error?: string;
|
|
36
36
|
}
|
|
37
37
|
export interface McpUsage {
|
|
38
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Calls per server as a first guess from the tool name alone (up to the
|
|
40
|
+
* first "__"): right for app-provided servers, wrong for a configured name
|
|
41
|
+
* with characters Claude Code turns into "_" ("linear (work)" is
|
|
42
|
+
* mcp__linear__work___…). Configured servers go through serverUses().
|
|
43
|
+
*/
|
|
39
44
|
calls: Map<string, number>;
|
|
45
|
+
/** Uses per full name: tools (mcp__server__tool) and prompts run as /mcp__server__prompt. */
|
|
46
|
+
names: Map<string, number>;
|
|
47
|
+
/** Resource reads and listings (ReadMcpResourceTool and its kin) per `server` input. */
|
|
48
|
+
resources: Map<string, number>;
|
|
40
49
|
sessions: number;
|
|
41
50
|
/** Sessions in which the model used ToolSearch, i.e. MCP definitions were deferred. */
|
|
42
51
|
toolSearchSessions: number;
|
|
43
52
|
}
|
|
53
|
+
/** The MCP resource tools (current names and their pre-rename spellings, as the 2.1.308 binary maps them): their `server` input names the server. */
|
|
54
|
+
export declare const MCP_RESOURCE_TOOLS: RegExp;
|
|
55
|
+
/** A prompt run as a slash command: `<command-name>/mcp__server__prompt</command-name>`. */
|
|
56
|
+
export declare const MCP_PROMPT_COMMAND: RegExp;
|
|
57
|
+
/**
|
|
58
|
+
* Uses of each configured server: every tool or prompt name counted under the
|
|
59
|
+
* LONGEST configured prefix `mcp__<toolPrefixName(name)>__` it starts with (so
|
|
60
|
+
* "linear" does not take "linear (work)"'s calls), plus resource-tool calls
|
|
61
|
+
* whose `server` input is the server's name.
|
|
62
|
+
*/
|
|
63
|
+
export declare function serverUses(configNames: string[], usage: Pick<McpUsage, "names" | "resources">): Map<string, number>;
|
|
64
|
+
/** Names no configured prefix claims: the app's own servers and connectors, by the first-guess parse. */
|
|
65
|
+
export declare function otherServerUses(configNames: string[], usage: Pick<McpUsage, "names">): Map<string, number>;
|
|
66
|
+
/** Count one row's MCP uses into `names` and `resources`: tool calls, resource-tool calls, prompts run as slash commands. */
|
|
67
|
+
export declare function countMcpRow(e: any, names: Map<string, number>, resources: Map<string, number>): void;
|
|
44
68
|
/** Claude Code's spelling of a server name inside tool names. */
|
|
45
69
|
export declare function toolPrefixName(server: string): string;
|
|
46
70
|
/** MCP servers Claude Code starts in `cwd`, with their launch configs. */
|
package/dist/mcpschema.js
CHANGED
|
@@ -23,6 +23,63 @@ import { forEachLine, listSessions } from "./session.js";
|
|
|
23
23
|
import { subagentDir } from "./subagents.js";
|
|
24
24
|
import { estimateTokens } from "./tokens.js";
|
|
25
25
|
const CLAUDE = "claude-opus-5";
|
|
26
|
+
/** The MCP resource tools (current names and their pre-rename spellings, as the 2.1.308 binary maps them): their `server` input names the server. */
|
|
27
|
+
export const MCP_RESOURCE_TOOLS = /^(ListMcpResources|ReadMcpResource|ReadMcpResourceDir)(Tool)?$/;
|
|
28
|
+
/** A prompt run as a slash command: `<command-name>/mcp__server__prompt</command-name>`. */
|
|
29
|
+
export const MCP_PROMPT_COMMAND = /<command-name>\/(mcp__[\w-]+?__[^<\s]+)<\/command-name>/g;
|
|
30
|
+
/**
|
|
31
|
+
* Uses of each configured server: every tool or prompt name counted under the
|
|
32
|
+
* LONGEST configured prefix `mcp__<toolPrefixName(name)>__` it starts with (so
|
|
33
|
+
* "linear" does not take "linear (work)"'s calls), plus resource-tool calls
|
|
34
|
+
* whose `server` input is the server's name.
|
|
35
|
+
*/
|
|
36
|
+
export function serverUses(configNames, usage) {
|
|
37
|
+
const prefixes = configNames.map((name) => ({ name, prefix: `mcp__${toolPrefixName(name)}__` })).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
38
|
+
const out = new Map(configNames.map((n) => [n, 0]));
|
|
39
|
+
for (const [full, n] of usage.names) {
|
|
40
|
+
const hit = prefixes.find((p) => full.startsWith(p.prefix));
|
|
41
|
+
if (hit)
|
|
42
|
+
out.set(hit.name, (out.get(hit.name) ?? 0) + n);
|
|
43
|
+
}
|
|
44
|
+
for (const [server, n] of usage.resources) {
|
|
45
|
+
const hit = configNames.find((c) => c === server) ?? configNames.find((c) => toolPrefixName(c) === toolPrefixName(server));
|
|
46
|
+
if (hit)
|
|
47
|
+
out.set(hit, (out.get(hit) ?? 0) + n);
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/** Names no configured prefix claims: the app's own servers and connectors, by the first-guess parse. */
|
|
52
|
+
export function otherServerUses(configNames, usage) {
|
|
53
|
+
const prefixes = configNames.map((name) => `mcp__${toolPrefixName(name)}__`);
|
|
54
|
+
const out = new Map();
|
|
55
|
+
for (const [full, n] of usage.names) {
|
|
56
|
+
if (prefixes.some((p) => full.startsWith(p)))
|
|
57
|
+
continue;
|
|
58
|
+
const server = /^mcp__(.+?)__./.exec(full)?.[1];
|
|
59
|
+
if (server)
|
|
60
|
+
out.set(server, (out.get(server) ?? 0) + n);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** Count one row's MCP uses into `names` and `resources`: tool calls, resource-tool calls, prompts run as slash commands. */
|
|
65
|
+
export function countMcpRow(e, names, resources) {
|
|
66
|
+
const content = e?.message?.content;
|
|
67
|
+
const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((b) => (typeof b?.text === "string" ? b.text : "")).join("\n") : "";
|
|
68
|
+
if (e?.type === "user" && text.includes("<command-name>/mcp__")) {
|
|
69
|
+
for (const m of text.matchAll(MCP_PROMPT_COMMAND))
|
|
70
|
+
names.set(m[1], (names.get(m[1]) ?? 0) + 1);
|
|
71
|
+
}
|
|
72
|
+
if (!Array.isArray(content))
|
|
73
|
+
return;
|
|
74
|
+
for (const b of content) {
|
|
75
|
+
if (b?.type !== "tool_use" || typeof b.name !== "string")
|
|
76
|
+
continue;
|
|
77
|
+
if (b.name.startsWith("mcp__"))
|
|
78
|
+
names.set(b.name, (names.get(b.name) ?? 0) + 1);
|
|
79
|
+
else if (MCP_RESOURCE_TOOLS.test(b.name) && typeof b.input?.server === "string")
|
|
80
|
+
resources.set(b.input.server, (resources.get(b.input.server) ?? 0) + 1);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
26
83
|
/** Claude Code's spelling of a server name inside tool names. */
|
|
27
84
|
export function toolPrefixName(server) {
|
|
28
85
|
return server.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
@@ -71,14 +128,16 @@ export function claudeMcpConfigs(cwd = process.cwd(), home = homedir()) {
|
|
|
71
128
|
export function mcpUsage(days = 30, paths, onProgress) {
|
|
72
129
|
const since = Date.now() - days * 86_400_000;
|
|
73
130
|
const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
74
|
-
const
|
|
131
|
+
const names = new Map();
|
|
132
|
+
const resources = new Map();
|
|
75
133
|
const counted = new Set();
|
|
76
134
|
let toolSearchSessions = 0;
|
|
77
135
|
for (const [index, path] of files.entries()) {
|
|
78
136
|
onProgress?.(index, files.length);
|
|
79
137
|
let searched = false;
|
|
80
138
|
const scan = (file) => forEachLine(file, (line) => {
|
|
81
|
-
|
|
139
|
+
const tool = line.includes('"tool_use"') && (line.includes('"name":"mcp__') || line.includes('"name":"ToolSearch"') || line.includes('McpResource'));
|
|
140
|
+
if (!tool && !line.includes("<command-name>/mcp__"))
|
|
82
141
|
return;
|
|
83
142
|
let e;
|
|
84
143
|
try {
|
|
@@ -88,31 +147,19 @@ export function mcpUsage(days = 30, paths, onProgress) {
|
|
|
88
147
|
return;
|
|
89
148
|
}
|
|
90
149
|
const content = e?.message?.content;
|
|
91
|
-
if (!Array.isArray(content))
|
|
92
|
-
return;
|
|
93
150
|
// Whether a session defers MCP definitions is a property of the
|
|
94
151
|
// session, so ToolSearch counts whenever it was used; calls are dated.
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
continue;
|
|
105
|
-
const server = /^mcp__(.+?)__./.exec(b.name)?.[1];
|
|
106
|
-
if (!server)
|
|
107
|
-
continue;
|
|
108
|
-
if (typeof b.id === "string" && typeof e.uuid === "string") {
|
|
109
|
-
const key = `${e.uuid}\0${b.id}`;
|
|
110
|
-
if (counted.has(key))
|
|
111
|
-
continue;
|
|
112
|
-
counted.add(key);
|
|
113
|
-
}
|
|
114
|
-
calls.set(server, (calls.get(server) ?? 0) + 1);
|
|
152
|
+
if (Array.isArray(content) && content.some((b) => b?.type === "tool_use" && b.name === "ToolSearch"))
|
|
153
|
+
searched = true;
|
|
154
|
+
if (Date.parse(e?.timestamp) < since)
|
|
155
|
+
return;
|
|
156
|
+
// A fork's copied rows (same uuid) were counted in the parent.
|
|
157
|
+
if (typeof e.uuid === "string") {
|
|
158
|
+
if (counted.has(e.uuid))
|
|
159
|
+
return;
|
|
160
|
+
counted.add(e.uuid);
|
|
115
161
|
}
|
|
162
|
+
countMcpRow(e, names, resources);
|
|
116
163
|
});
|
|
117
164
|
scan(path);
|
|
118
165
|
let agents = [];
|
|
@@ -129,7 +176,13 @@ export function mcpUsage(days = 30, paths, onProgress) {
|
|
|
129
176
|
if (searched)
|
|
130
177
|
toolSearchSessions++;
|
|
131
178
|
}
|
|
132
|
-
|
|
179
|
+
const calls = new Map();
|
|
180
|
+
for (const [full, n] of names) {
|
|
181
|
+
const server = /^mcp__(.+?)__./.exec(full)?.[1];
|
|
182
|
+
if (server)
|
|
183
|
+
calls.set(server, (calls.get(server) ?? 0) + n);
|
|
184
|
+
}
|
|
185
|
+
return { calls, names, resources, sessions: files.length, toolSearchSessions };
|
|
133
186
|
}
|
|
134
187
|
/** Connect to one server the way a client does and size its tool list. */
|
|
135
188
|
export async function measureServer(cfg, timeoutMs = 15_000) {
|
package/dist/overhead.js
CHANGED
|
@@ -21,7 +21,7 @@ import { forEachLine, listSessions, replyCounter } from "./session.js";
|
|
|
21
21
|
import { estimateTokens, formatTokens, providerFor, realModel } from "./tokens.js";
|
|
22
22
|
import { cacheWriteSplit, formatUsd, pricingFor, writeMultiplier as ttlWriteMultiplier } from "./pricing.js";
|
|
23
23
|
import { isGeminiChat, readGeminiMessages } from "./gemini.js";
|
|
24
|
-
import { claudeMcpConfigs, mcpUsage, measureServer,
|
|
24
|
+
import { claudeMcpConfigs, mcpUsage, measureServer, otherServerUses, serverUses } from "./mcpschema.js";
|
|
25
25
|
const TTL_MS = 3_600_000;
|
|
26
26
|
const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
|
|
27
27
|
function readText(path) {
|
|
@@ -439,9 +439,10 @@ export async function measureMcpSizes(r) {
|
|
|
439
439
|
export function mcpFindings(m, baseline) {
|
|
440
440
|
const out = [];
|
|
441
441
|
const deferred = m.usage.sessions > 0 && m.usage.toolSearchSessions / m.usage.sessions >= 0.5;
|
|
442
|
+
const uses = serverUses(m.configs.map((c) => c.name), m.usage);
|
|
442
443
|
for (const c of m.configs) {
|
|
443
444
|
const size = m.sizes?.find((s) => s.name === c.name);
|
|
444
|
-
const calls =
|
|
445
|
+
const calls = uses.get(c.name) ?? 0;
|
|
445
446
|
const tokens = size?.schemaTokens === undefined ? undefined : deferred ? size.nameTokens : size.schemaTokens;
|
|
446
447
|
if (calls > 0 || tokens === undefined || tokens < 200)
|
|
447
448
|
continue;
|
|
@@ -515,17 +516,17 @@ export function mcpDisplayName(server) {
|
|
|
515
516
|
}
|
|
516
517
|
function renderMcp(r) {
|
|
517
518
|
const { configs, usage, sizes } = r.mcp;
|
|
518
|
-
if (configs.length === 0 && usage.
|
|
519
|
+
if (configs.length === 0 && usage.names.size === 0)
|
|
519
520
|
return [];
|
|
520
521
|
const out = ["", "MCP servers", "─".repeat(56)];
|
|
521
522
|
const deferred = usage.sessions > 0 && usage.toolSearchSessions / usage.sessions >= 0.5;
|
|
522
523
|
out.push(deferred
|
|
523
524
|
? `Tool search was used in ${usage.toolSearchSessions} of ${usage.sessions} sessions: Claude Code defers MCP definitions, so a server costs about its tool names until the model looks one up.`
|
|
524
525
|
: `Tool search was used in ${usage.toolSearchSessions} of ${usage.sessions} sessions: MCP definitions mostly load in full, on every request.`);
|
|
525
|
-
const
|
|
526
|
+
const uses = serverUses(configs.map((c) => c.name), usage);
|
|
526
527
|
for (const c of configs) {
|
|
527
528
|
const s = sizes?.find((x) => x.name === c.name);
|
|
528
|
-
const calls =
|
|
529
|
+
const calls = uses.get(c.name) ?? 0;
|
|
529
530
|
const size = !sizes
|
|
530
531
|
? "size: run with --mcp"
|
|
531
532
|
: s?.error
|
|
@@ -533,7 +534,7 @@ function renderMcp(r) {
|
|
|
533
534
|
: `${s.tools} tools, ~${formatTokens(s.schemaTokens)} tokens of definitions (names ~${formatTokens(s.nameTokens)})`;
|
|
534
535
|
out.push(` ${c.name.padEnd(22)} ${c.scope.padEnd(9)} ${String(calls).padStart(6)} calls ${size}`);
|
|
535
536
|
}
|
|
536
|
-
const app = [...
|
|
537
|
+
const app = [...otherServerUses(configs.map((c) => c.name), usage).entries()].sort((a, b) => b[1] - a[1]);
|
|
537
538
|
if (app.length) {
|
|
538
539
|
out.push(` Provided by the app or connectors (not in your config; toggle them in the app):`);
|
|
539
540
|
for (const [n, calls] of app.slice(0, 10))
|
package/dist/precompact.js
CHANGED
|
@@ -107,12 +107,13 @@ export function compactInstructions(f) {
|
|
|
107
107
|
list("Commands still failing at this point (keep the command and the error)", f.failing);
|
|
108
108
|
if (!sections.length)
|
|
109
109
|
return "";
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
|
|
110
|
+
const head = "context-doctor, from this session's transcript: the summary must carry the following, so the work continues without re-reading files, re-asking the user, or repeating a failed approach.";
|
|
111
|
+
const tail = "Keep exact identifiers (paths, function names, commands, versions, IDs, URLs). Leave out raw tool output already acted on; one line on what it showed is enough: the full transcript stays on disk, and the recall tool (or `npx context-doctor recall \"<words>\"`) finds it after compacting.";
|
|
112
|
+
// Over the cap the lists are cut, never the closing line (it says where the rest still is).
|
|
113
|
+
let body = sections.join("\n\n");
|
|
114
|
+
const room = MAX_CHARS - head.length - tail.length - 4;
|
|
115
|
+
if (body.length > room)
|
|
116
|
+
body = body.slice(0, room - 1) + "…";
|
|
117
|
+
const out = [head, body, tail].join("\n\n");
|
|
117
118
|
return out;
|
|
118
119
|
}
|
package/dist/pricing.d.ts
CHANGED
|
@@ -18,6 +18,15 @@ export interface ModelPricing {
|
|
|
18
18
|
/** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
|
|
19
19
|
export declare const CACHE_WRITE_5M = 1.25;
|
|
20
20
|
export declare const CACHE_WRITE_1H = 2;
|
|
21
|
+
/**
|
|
22
|
+
* OpenAI cache writes on GPT-5.6 and later, relative to input: 1.25x for the
|
|
23
|
+
* default 30-minute lifetime (the same rate as Anthropic's 5-minute writes,
|
|
24
|
+
* so they share that slot below) and 2.5x for 12 hours. "Total write rates,
|
|
25
|
+
* not surcharges"; earlier models charge no writes (prompt caching guide,
|
|
26
|
+
* read 2026-10-26).
|
|
27
|
+
*/
|
|
28
|
+
export declare const CACHE_WRITE_OPENAI_30M = 1.25;
|
|
29
|
+
export declare const CACHE_WRITE_OPENAI_12H = 2.5;
|
|
21
30
|
export declare function pricingFor(model?: string): ModelPricing | undefined;
|
|
22
31
|
/**
|
|
23
32
|
* A Claude model's price from a row for its own version, not a family
|
|
@@ -33,10 +42,14 @@ export interface RecordedUsage {
|
|
|
33
42
|
cache_creation_input_tokens?: unknown;
|
|
34
43
|
cache_read_input_tokens?: unknown;
|
|
35
44
|
output_tokens?: unknown;
|
|
36
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* The cache writes split by TTL; absent in older transcripts.
|
|
47
|
+
* `ttl_12h_input_tokens` carries OpenAI's 12-hour writes (see openAIUsage).
|
|
48
|
+
*/
|
|
37
49
|
cache_creation?: {
|
|
38
50
|
ephemeral_5m_input_tokens?: unknown;
|
|
39
51
|
ephemeral_1h_input_tokens?: unknown;
|
|
52
|
+
ttl_12h_input_tokens?: unknown;
|
|
40
53
|
} | null;
|
|
41
54
|
}
|
|
42
55
|
export interface UsageCost {
|
|
@@ -60,6 +73,7 @@ export interface UsageCost {
|
|
|
60
73
|
export declare function cacheWriteSplit(usage: RecordedUsage | undefined | null): {
|
|
61
74
|
fiveMinute: number;
|
|
62
75
|
oneHour: number;
|
|
76
|
+
twelveHour: number;
|
|
63
77
|
};
|
|
64
78
|
/**
|
|
65
79
|
* The write price, relative to input, of a mix of 5-minute and 1-hour
|
|
@@ -68,13 +82,26 @@ export declare function cacheWriteSplit(usage: RecordedUsage | undefined | null)
|
|
|
68
82
|
* that is the TTL its harness would have written at; 1.25x when nothing was
|
|
69
83
|
* written to learn from.
|
|
70
84
|
*/
|
|
71
|
-
export declare function writeMultiplier(fiveMinute: number, oneHour: number): number;
|
|
85
|
+
export declare function writeMultiplier(fiveMinute: number, oneHour: number, twelveHour?: number): number;
|
|
72
86
|
/**
|
|
73
87
|
* What one recorded request cost: uncached input, cache writes priced by
|
|
74
88
|
* TTL, cache reads, output. The one place recorded usage is priced, so every
|
|
75
89
|
* report agrees with the others and with the bill.
|
|
76
90
|
*/
|
|
77
91
|
export declare function usageCost(usage: RecordedUsage | undefined | null, pricing: ModelPricing): UsageCost;
|
|
92
|
+
/**
|
|
93
|
+
* OpenAI usage, in any of its shapes, as RecordedUsage: Responses
|
|
94
|
+
* (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`
|
|
95
|
+
* and its `cache_write_tokens_details.ttl_30m_tokens` / `ttl_12h_tokens`),
|
|
96
|
+
* Chat Completions (`prompt_tokens`, `prompt_tokens_details`,
|
|
97
|
+
* `completion_tokens`) and Codex rollouts (`cached_input_tokens`,
|
|
98
|
+
* `cache_write_input_tokens`). OpenAI's input count holds every input token
|
|
99
|
+
* once, each billed at the uncached, cached or write rate, so the uncached
|
|
100
|
+
* part is what is left after reads AND writes. Writes without a split are
|
|
101
|
+
* 30-minute writes, the default lifetime: Codex rollouts record only the
|
|
102
|
+
* total, so a Codex 12-hour write would be priced at half its 2.5x.
|
|
103
|
+
*/
|
|
104
|
+
export declare function openAIUsage(raw: Record<string, any> | undefined | null): RecordedUsage;
|
|
78
105
|
/**
|
|
79
106
|
* Rough time-to-first-token impact of input size. Prompt processing on major
|
|
80
107
|
* providers runs on the order of tens of thousands of tokens per second;
|
package/dist/pricing.js
CHANGED
|
@@ -10,6 +10,15 @@
|
|
|
10
10
|
/** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
|
|
11
11
|
export const CACHE_WRITE_5M = 1.25;
|
|
12
12
|
export const CACHE_WRITE_1H = 2;
|
|
13
|
+
/**
|
|
14
|
+
* OpenAI cache writes on GPT-5.6 and later, relative to input: 1.25x for the
|
|
15
|
+
* default 30-minute lifetime (the same rate as Anthropic's 5-minute writes,
|
|
16
|
+
* so they share that slot below) and 2.5x for 12 hours. "Total write rates,
|
|
17
|
+
* not surcharges"; earlier models charge no writes (prompt caching guide,
|
|
18
|
+
* read 2026-10-26).
|
|
19
|
+
*/
|
|
20
|
+
export const CACHE_WRITE_OPENAI_30M = 1.25;
|
|
21
|
+
export const CACHE_WRITE_OPENAI_12H = 2.5;
|
|
13
22
|
const rate = (inputPerM, outputPerM, cacheReadPerM) => ({ inputPerM, outputPerM, cacheReadPerM });
|
|
14
23
|
/**
|
|
15
24
|
* One Claude version, whatever wraps the id: a date (-20251101, @20251101),
|
|
@@ -119,10 +128,11 @@ export function cacheWriteSplit(usage) {
|
|
|
119
128
|
const total = count(usage?.cache_creation_input_tokens);
|
|
120
129
|
const split = usage?.cache_creation;
|
|
121
130
|
if (!split || typeof split !== "object")
|
|
122
|
-
return { fiveMinute: total, oneHour: 0 };
|
|
123
|
-
const all = total || count(split.ephemeral_5m_input_tokens) + count(split.ephemeral_1h_input_tokens);
|
|
131
|
+
return { fiveMinute: total, oneHour: 0, twelveHour: 0 };
|
|
132
|
+
const all = total || count(split.ephemeral_5m_input_tokens) + count(split.ephemeral_1h_input_tokens) + count(split.ttl_12h_input_tokens);
|
|
124
133
|
const oneHour = Math.min(all, count(split.ephemeral_1h_input_tokens));
|
|
125
|
-
|
|
134
|
+
const twelveHour = Math.min(all - oneHour, count(split.ttl_12h_input_tokens));
|
|
135
|
+
return { fiveMinute: all - oneHour - twelveHour, oneHour, twelveHour };
|
|
126
136
|
}
|
|
127
137
|
/**
|
|
128
138
|
* The write price, relative to input, of a mix of 5-minute and 1-hour
|
|
@@ -131,9 +141,9 @@ export function cacheWriteSplit(usage) {
|
|
|
131
141
|
* that is the TTL its harness would have written at; 1.25x when nothing was
|
|
132
142
|
* written to learn from.
|
|
133
143
|
*/
|
|
134
|
-
export function writeMultiplier(fiveMinute, oneHour) {
|
|
135
|
-
const total = fiveMinute + oneHour;
|
|
136
|
-
return total > 0 ? (fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H) / total : CACHE_WRITE_5M;
|
|
144
|
+
export function writeMultiplier(fiveMinute, oneHour, twelveHour = 0) {
|
|
145
|
+
const total = fiveMinute + oneHour + twelveHour;
|
|
146
|
+
return total > 0 ? (fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H) / total : CACHE_WRITE_5M;
|
|
137
147
|
}
|
|
138
148
|
/**
|
|
139
149
|
* What one recorded request cost: uncached input, cache writes priced by
|
|
@@ -141,15 +151,43 @@ export function writeMultiplier(fiveMinute, oneHour) {
|
|
|
141
151
|
* report agrees with the others and with the bill.
|
|
142
152
|
*/
|
|
143
153
|
export function usageCost(usage, pricing) {
|
|
144
|
-
const { fiveMinute, oneHour } = cacheWriteSplit(usage);
|
|
154
|
+
const { fiveMinute, oneHour, twelveHour } = cacheWriteSplit(usage);
|
|
145
155
|
const perM = (tokens, usd) => (tokens * usd) / 1_000_000;
|
|
146
156
|
const inputUsd = perM(count(usage?.input_tokens), pricing.inputPerM);
|
|
147
|
-
const writeUsd = perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H, pricing.inputPerM);
|
|
157
|
+
const writeUsd = perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H, pricing.inputPerM);
|
|
148
158
|
const readUsd = perM(count(usage?.cache_read_input_tokens), pricing.cacheReadPerM);
|
|
149
159
|
const outputUsd = perM(count(usage?.output_tokens), pricing.outputPerM);
|
|
150
160
|
const promptUsd = inputUsd + writeUsd + readUsd;
|
|
151
161
|
return { inputUsd, writeUsd, readUsd, outputUsd, promptUsd, totalUsd: promptUsd + outputUsd };
|
|
152
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* OpenAI usage, in any of its shapes, as RecordedUsage: Responses
|
|
165
|
+
* (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`
|
|
166
|
+
* and its `cache_write_tokens_details.ttl_30m_tokens` / `ttl_12h_tokens`),
|
|
167
|
+
* Chat Completions (`prompt_tokens`, `prompt_tokens_details`,
|
|
168
|
+
* `completion_tokens`) and Codex rollouts (`cached_input_tokens`,
|
|
169
|
+
* `cache_write_input_tokens`). OpenAI's input count holds every input token
|
|
170
|
+
* once, each billed at the uncached, cached or write rate, so the uncached
|
|
171
|
+
* part is what is left after reads AND writes. Writes without a split are
|
|
172
|
+
* 30-minute writes, the default lifetime: Codex rollouts record only the
|
|
173
|
+
* total, so a Codex 12-hour write would be priced at half its 2.5x.
|
|
174
|
+
*/
|
|
175
|
+
export function openAIUsage(raw) {
|
|
176
|
+
const u = raw ?? {};
|
|
177
|
+
const details = u.input_tokens_details ?? u.prompt_tokens_details ?? {};
|
|
178
|
+
const input = count(u.input_tokens ?? u.prompt_tokens);
|
|
179
|
+
const cached = count(details.cached_tokens ?? u.cached_input_tokens);
|
|
180
|
+
const writes = count(details.cache_write_tokens ?? u.cache_write_input_tokens);
|
|
181
|
+
const split = details.cache_write_tokens_details ?? {};
|
|
182
|
+
const twelveHour = Math.min(writes, count(split.ttl_12h_tokens));
|
|
183
|
+
return {
|
|
184
|
+
input_tokens: Math.max(0, input - cached - writes),
|
|
185
|
+
cache_read_input_tokens: cached,
|
|
186
|
+
cache_creation_input_tokens: writes,
|
|
187
|
+
cache_creation: { ephemeral_5m_input_tokens: writes - twelveHour, ephemeral_1h_input_tokens: 0, ttl_12h_input_tokens: twelveHour },
|
|
188
|
+
output_tokens: count(u.output_tokens ?? u.completion_tokens),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
153
191
|
/**
|
|
154
192
|
* Rough time-to-first-token impact of input size. Prompt processing on major
|
|
155
193
|
* providers runs on the order of tens of thousands of tokens per second;
|
package/dist/proxy.d.ts
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* in flight (dedupe, trim stale tool results, strip base64) before being
|
|
5
5
|
* forwarded — no code changes in your app, just a base-URL env var:
|
|
6
6
|
*
|
|
7
|
-
* ANTHROPIC_BASE_URL=http://
|
|
8
|
-
* OPENAI_BASE_URL=http://
|
|
7
|
+
* ANTHROPIC_BASE_URL=http://127.0.0.1:8787 (Anthropic SDKs)
|
|
8
|
+
* OPENAI_BASE_URL=http://127.0.0.1:8787/v1 (OpenAI SDKs)
|
|
9
9
|
*
|
|
10
10
|
* API keys pass through untouched in headers — the proxy stores nothing and
|
|
11
11
|
* talks only to the official upstream endpoints (overridable for testing).
|
|
@@ -65,7 +65,7 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
65
65
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
66
66
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
67
67
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
68
|
-
export declare const PROXY_VERSION = "0.
|
|
68
|
+
export declare const PROXY_VERSION = "0.38.0";
|
|
69
69
|
/**
|
|
70
70
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
71
71
|
* the prefix is absent or the token differs. The comparison is constant time
|
|
@@ -111,6 +111,8 @@ export interface ProxyStats {
|
|
|
111
111
|
upstreamCacheWriteTokens: number;
|
|
112
112
|
/** OpenAI's cached_tokens: the part of upstreamInputTokens its responses say was read from cache. */
|
|
113
113
|
openaiCachedTokens: number;
|
|
114
|
+
/** OpenAI's cache_write_tokens (GPT-5.6+): input billed at the write rate (1.25x for 30 minutes, 2.5x for 12 hours). */
|
|
115
|
+
openaiCacheWriteTokens: number;
|
|
114
116
|
/** OpenAI requests sent with a conversation prompt_cache_key the proxy added (cachekey.ts). */
|
|
115
117
|
cacheKeysAdded: number;
|
|
116
118
|
autopilot?: {
|
package/dist/proxy.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* in flight (dedupe, trim stale tool results, strip base64) before being
|
|
5
5
|
* forwarded — no code changes in your app, just a base-URL env var:
|
|
6
6
|
*
|
|
7
|
-
* ANTHROPIC_BASE_URL=http://
|
|
8
|
-
* OPENAI_BASE_URL=http://
|
|
7
|
+
* ANTHROPIC_BASE_URL=http://127.0.0.1:8787 (Anthropic SDKs)
|
|
8
|
+
* OPENAI_BASE_URL=http://127.0.0.1:8787/v1 (OpenAI SDKs)
|
|
9
9
|
*
|
|
10
10
|
* API keys pass through untouched in headers — the proxy stores nothing and
|
|
11
11
|
* talks only to the official upstream endpoints (overridable for testing).
|
|
@@ -24,7 +24,7 @@ import { withPromptCacheKey } from "./cachekey.js";
|
|
|
24
24
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
25
25
|
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
26
26
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
27
|
-
export const PROXY_VERSION = "0.
|
|
27
|
+
export const PROXY_VERSION = "0.38.0";
|
|
28
28
|
/** Connection-level headers that must not be forwarded. */
|
|
29
29
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
30
30
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -205,6 +205,7 @@ export function startProxy(opts = {}) {
|
|
|
205
205
|
upstreamCacheReadTokens: 0,
|
|
206
206
|
upstreamCacheWriteTokens: 0,
|
|
207
207
|
openaiCachedTokens: 0,
|
|
208
|
+
openaiCacheWriteTokens: 0,
|
|
208
209
|
cacheKeysAdded: 0,
|
|
209
210
|
autopilot: opts.autopilot
|
|
210
211
|
? { enabled: true, paused: false, requests: 0, changedRequests: 0, batches: 0, coldBatches: 0, resultsCleared: 0, tokensRemoved: 0, lastReason: "" }
|
|
@@ -325,7 +326,8 @@ export function startProxy(opts = {}) {
|
|
|
325
326
|
try {
|
|
326
327
|
const parsed = JSON.parse(body);
|
|
327
328
|
const urlModel = gemini ? geminiModelFromUrl(url) : undefined;
|
|
328
|
-
|
|
329
|
+
// Claude Code (User-Agent claude-cli/…) keeps a transcript recall can search.
|
|
330
|
+
const r = clearer.apply(parsed, Date.now(), urlModel, account, { recallHint: /^claude-cli\//.test(String(req.headers["user-agent"] ?? "")) });
|
|
329
331
|
ap.requests++;
|
|
330
332
|
ap.lastReason = r.reason;
|
|
331
333
|
if (r.newlyCleared > 0) {
|
|
@@ -580,6 +582,7 @@ export function startProxy(opts = {}) {
|
|
|
580
582
|
stats.upstreamCacheReadTokens += lastNum(/"cache_read_input_tokens"\s*:\s*(\d+)/g);
|
|
581
583
|
stats.upstreamCacheWriteTokens += lastNum(/"cache_creation_input_tokens"\s*:\s*(\d+)/g);
|
|
582
584
|
stats.openaiCachedTokens += lastNum(/"cached_tokens"\s*:\s*(\d+)/g);
|
|
585
|
+
stats.openaiCacheWriteTokens += lastNum(/"cache_write_tokens"\s*:\s*(\d+)/g);
|
|
583
586
|
}
|
|
584
587
|
}
|
|
585
588
|
res.end();
|
|
@@ -691,12 +694,14 @@ export function startProxy(opts = {}) {
|
|
|
691
694
|
// Print the token as <token>, never the value: this log is what people paste into bug reports.
|
|
692
695
|
const prefix = opts.token ? "/t/<token>" : "";
|
|
693
696
|
console.error(`context-doctor proxy listening on http://${host}:${port}`);
|
|
694
|
-
|
|
695
|
-
|
|
697
|
+
// 127.0.0.1, not localhost: on macOS another program can hold the same
|
|
698
|
+
// port on :: or ::1 beside this one, and `localhost` may resolve there.
|
|
699
|
+
console.error(` Anthropic apps/SDKs: export ANTHROPIC_BASE_URL=http://127.0.0.1:${port}${prefix}`);
|
|
700
|
+
console.error(` OpenAI apps/SDKs: export OPENAI_BASE_URL=http://127.0.0.1:${port}${prefix}/v1`);
|
|
696
701
|
console.error(opts.autopilot
|
|
697
702
|
? ` Autopilot: stale re-runnable tool output is cleared only when the prompt cache is cold; savings are logged here.`
|
|
698
703
|
: ` Every request's context is optimized in flight; savings are logged here.`);
|
|
699
|
-
console.error(` Cumulative savings: http://
|
|
704
|
+
console.error(` Cumulative savings: http://127.0.0.1:${port}${prefix}/stats`);
|
|
700
705
|
if (opts.token) {
|
|
701
706
|
console.error(` Token required: every path except /health must start with /t/<token>/.`);
|
|
702
707
|
console.error(` Cursor with your own OpenAI key: expose this port on HTTPS (a tunnel), then Settings > Models > OpenAI API Key >`);
|
package/dist/prune.d.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor overhead prune`: MCP servers and skills a project has not
|
|
3
|
+
* used in N days, switched off for that project only.
|
|
4
|
+
*
|
|
5
|
+
* Every MCP server's tool definitions (or, with tool search, their names)
|
|
6
|
+
* and every skill's name and description ride in each request of every
|
|
7
|
+
* session, used or not ("33k tokens before reading the prompt"). The
|
|
8
|
+
* transcripts say what each project actually calls: MCP tools are
|
|
9
|
+
* `mcp__<server>__<tool>`, skills are the `Skill` tool (`{skill}`) or a
|
|
10
|
+
* typed `/<name>`. The plan lists, per project with enough sessions, the
|
|
11
|
+
* configured servers and installed skills with no use in the period; with
|
|
12
|
+
* `--write` they are switched off for the current folder's project, in its
|
|
13
|
+
* own `.claude/settings.local.json` (a backup kept, each entry recorded so
|
|
14
|
+
* `--undo` takes exactly those out again):
|
|
15
|
+
*
|
|
16
|
+
* - a server from the project's `.mcp.json`: `disabledMcpjsonServers`;
|
|
17
|
+
* - a server from ~/.claude.json (user or local scope): `deniedMcpServers`
|
|
18
|
+
* `{serverName}` (settings-reference: entries from every settings file
|
|
19
|
+
* merge; it shows as blocked in /mcp until the entry is removed);
|
|
20
|
+
* - a personal or project skill: `skillOverrides` `"off"` (Claude Code
|
|
21
|
+
* 2.1.129+; older versions ignore the key).
|
|
22
|
+
*
|
|
23
|
+
* Never touched: anything the app provides (claude.ai connectors, the
|
|
24
|
+
* desktop app's own servers, plugin servers and skills), which no config
|
|
25
|
+
* file here lists, and context-doctor's own server, whose standing rules
|
|
26
|
+
* work without a single call. Verified against the settings reference and
|
|
27
|
+
* the 2.1.308 binary (disabledMcpjsonServers, deniedMcpServers merged from
|
|
28
|
+
* every settings file, skillOverrides).
|
|
29
|
+
*/
|
|
30
|
+
import { type McpServerConfig } from "./mcpschema.js";
|
|
31
|
+
/** A folder as one spelling: /var and /private/var (macOS) or a symlinked checkout are the same project. */
|
|
32
|
+
export declare function canonical(p: string): string;
|
|
33
|
+
/** Fewer sessions than this in the period say too little about what a project uses. */
|
|
34
|
+
export declare const MIN_SESSIONS = 3;
|
|
35
|
+
export interface ProjectUse {
|
|
36
|
+
cwd: string;
|
|
37
|
+
sessions: number;
|
|
38
|
+
/** MCP uses by full name: tools (mcp__server__tool) and prompts run as slash commands. */
|
|
39
|
+
mcpNames: Map<string, number>;
|
|
40
|
+
/** MCP resource-tool uses by their `server` input. */
|
|
41
|
+
mcpResources: Map<string, number>;
|
|
42
|
+
/** Skill uses by name (the part after a plugin's "plugin:" prefix too). */
|
|
43
|
+
skillUses: Map<string, number>;
|
|
44
|
+
}
|
|
45
|
+
/** What each project (by the `cwd` its sessions record) used in the last `days`, subagents included. */
|
|
46
|
+
export declare function projectUsage(days?: number, paths?: string[], now?: number): Map<string, ProjectUse>;
|
|
47
|
+
export interface SkillInfo {
|
|
48
|
+
name: string;
|
|
49
|
+
scope: "personal" | "project";
|
|
50
|
+
/** Tokens of its listing (name and description) in every request. */
|
|
51
|
+
tokens: number;
|
|
52
|
+
}
|
|
53
|
+
/** Skills Claude Code lists in `cwd`: ~/.claude/skills and <cwd>/.claude/skills (not plugins'). */
|
|
54
|
+
export declare function installedSkills(cwd: string, home?: string): SkillInfo[];
|
|
55
|
+
export interface PruneItem {
|
|
56
|
+
kind: "mcp" | "skill";
|
|
57
|
+
name: string;
|
|
58
|
+
scope: McpServerConfig["scope"] | SkillInfo["scope"];
|
|
59
|
+
/** The settings entry that switches it off for this project. */
|
|
60
|
+
entry: "disabledMcpjsonServers" | "deniedMcpServers" | "skillOverrides";
|
|
61
|
+
tokens?: number;
|
|
62
|
+
}
|
|
63
|
+
export interface ProjectPlan {
|
|
64
|
+
cwd: string;
|
|
65
|
+
sessions: number;
|
|
66
|
+
unused: PruneItem[];
|
|
67
|
+
/** Configured or installed, and used: name and uses. */
|
|
68
|
+
used: Array<{
|
|
69
|
+
kind: "mcp" | "skill";
|
|
70
|
+
name: string;
|
|
71
|
+
uses: number;
|
|
72
|
+
}>;
|
|
73
|
+
/** Too few sessions to judge. */
|
|
74
|
+
thin: boolean;
|
|
75
|
+
/** Already switched off here by an earlier prune (or by hand). */
|
|
76
|
+
alreadyOff: string[];
|
|
77
|
+
}
|
|
78
|
+
export interface PrunePlan {
|
|
79
|
+
days: number;
|
|
80
|
+
plans: ProjectPlan[];
|
|
81
|
+
}
|
|
82
|
+
/** The project's own settings file, where prune writes. */
|
|
83
|
+
export declare function localSettingsPath(cwd: string): string;
|
|
84
|
+
export declare function planPrune(days?: number, opts?: {
|
|
85
|
+
home?: string;
|
|
86
|
+
usage?: Map<string, ProjectUse>;
|
|
87
|
+
cwds?: string[];
|
|
88
|
+
minSessions?: number;
|
|
89
|
+
}): PrunePlan;
|
|
90
|
+
/** Where `--write` records what it added, for `--undo`. */
|
|
91
|
+
export declare function pruneRecordPath(): string;
|
|
92
|
+
interface Added {
|
|
93
|
+
disabledMcpjsonServers: string[];
|
|
94
|
+
deniedMcpServers: string[];
|
|
95
|
+
skillOverrides: string[];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Switch the plan's unused servers and skills off in the project's
|
|
99
|
+
* `.claude/settings.local.json`. The file's original is kept once as
|
|
100
|
+
* `.context-doctor.backup`; every entry added is recorded for `--undo`.
|
|
101
|
+
*/
|
|
102
|
+
export declare function applyPrune(plan: ProjectPlan): {
|
|
103
|
+
file: string;
|
|
104
|
+
backup?: string;
|
|
105
|
+
added: Added;
|
|
106
|
+
};
|
|
107
|
+
/** Take out exactly what `--write` added for this project (entries changed since by hand stay). */
|
|
108
|
+
export declare function undoPrune(cwd: string): {
|
|
109
|
+
file: string;
|
|
110
|
+
removed: string[];
|
|
111
|
+
} | undefined;
|
|
112
|
+
export declare function renderPrune(r: PrunePlan, current: string, opts?: {
|
|
113
|
+
usdPerKPerMonth?: number;
|
|
114
|
+
home?: string;
|
|
115
|
+
}): string;
|
|
116
|
+
export {};
|