context-doctor 0.32.0 → 0.34.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 +84 -694
- package/dist/autoclear.js +4 -1
- package/dist/autopilot.d.ts +20 -6
- package/dist/autopilot.js +105 -7
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cacheplan.d.ts +29 -9
- package/dist/cacheplan.js +110 -29
- package/dist/ci.js +9 -1
- package/dist/cli.js +359 -247
- package/dist/clihelp.d.ts +24 -0
- package/dist/clihelp.js +116 -0
- package/dist/codexroute.d.ts +46 -0
- package/dist/codexroute.js +122 -0
- package/dist/coldresume.d.ts +62 -0
- package/dist/coldresume.js +85 -6
- package/dist/compactquality.d.ts +3 -1
- package/dist/compactquality.js +15 -4
- package/dist/compactwindow.d.ts +31 -5
- package/dist/compactwindow.js +80 -25
- package/dist/diff.js +24 -2
- package/dist/doctor.d.ts +8 -2
- package/dist/doctor.js +138 -35
- package/dist/hook.js +23 -4
- package/dist/install.d.ts +35 -0
- package/dist/install.js +280 -48
- package/dist/invocation.d.ts +18 -0
- package/dist/invocation.js +49 -0
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.d.ts +5 -2
- package/dist/mcp.js +93 -299
- package/dist/mcpclient.js +45 -0
- package/dist/mcpschema.d.ts +1 -1
- package/dist/mcpschema.js +11 -8
- package/dist/optimize.d.ts +2 -0
- package/dist/optimize.js +2 -0
- package/dist/overhead.d.ts +12 -1
- package/dist/overhead.js +31 -7
- package/dist/preferences.d.ts +1 -1
- package/dist/preferences.js +5 -5
- package/dist/proxy.d.ts +14 -1
- package/dist/proxy.js +45 -4
- package/dist/savings.d.ts +17 -1
- package/dist/savings.js +12 -13
- package/dist/session.d.ts +15 -0
- package/dist/session.js +43 -0
- package/dist/subagentpay.d.ts +1 -1
- package/dist/subagentpay.js +3 -2
- package/package.json +5 -8
- package/skills/context-doctor/SKILL.md +3 -3
package/dist/mcpschema.d.ts
CHANGED
|
@@ -61,6 +61,6 @@ export declare function claudeMcpConfigs(cwd?: string, home?: string): McpServer
|
|
|
61
61
|
* of them in one 30-day count). Rows without a timestamp count with their
|
|
62
62
|
* file.
|
|
63
63
|
*/
|
|
64
|
-
export declare function mcpUsage(days?: number, paths?: string[]): McpUsage;
|
|
64
|
+
export declare function mcpUsage(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): McpUsage;
|
|
65
65
|
/** Connect to one server the way a client does and size its tool list. */
|
|
66
66
|
export declare function measureServer(cfg: McpServerConfig, timeoutMs?: number): Promise<McpServerSize>;
|
package/dist/mcpschema.js
CHANGED
|
@@ -68,13 +68,14 @@ export function claudeMcpConfigs(cwd = process.cwd(), home = homedir()) {
|
|
|
68
68
|
* of them in one 30-day count). Rows without a timestamp count with their
|
|
69
69
|
* file.
|
|
70
70
|
*/
|
|
71
|
-
export function mcpUsage(days = 30, paths) {
|
|
71
|
+
export function mcpUsage(days = 30, paths, onProgress) {
|
|
72
72
|
const since = Date.now() - days * 86_400_000;
|
|
73
73
|
const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
74
74
|
const calls = new Map();
|
|
75
75
|
const counted = new Set();
|
|
76
76
|
let toolSearchSessions = 0;
|
|
77
|
-
for (const path of files) {
|
|
77
|
+
for (const [index, path] of files.entries()) {
|
|
78
|
+
onProgress?.(index, files.length);
|
|
78
79
|
let searched = false;
|
|
79
80
|
const scan = (file) => forEachLine(file, (line) => {
|
|
80
81
|
if (!line.includes('"tool_use"') || (!line.includes('"name":"mcp__') && !line.includes('"name":"ToolSearch"')))
|
|
@@ -135,16 +136,18 @@ export async function measureServer(cfg, timeoutMs = 15_000) {
|
|
|
135
136
|
if (!cfg.command && !(cfg.url && cfg.type !== "sse")) {
|
|
136
137
|
return { name: cfg.name, error: cfg.type === "sse" ? "SSE server: not measured" : "no command or url" };
|
|
137
138
|
}
|
|
138
|
-
// The SDK
|
|
139
|
-
//
|
|
140
|
-
//
|
|
139
|
+
// The SDK's client comes from dist/mcpclient.js, which the build bundles
|
|
140
|
+
// with the SDK inside: the npm package has no runtime dependencies, and the
|
|
141
|
+
// Claude Code plugin runs dist/ from a git checkout with no node_modules.
|
|
142
|
+
// Should it still fail to load, that is a per-server note, never a crash
|
|
143
|
+
// that loses the whole `overhead --mcp` report.
|
|
141
144
|
let client;
|
|
142
145
|
let transport;
|
|
143
146
|
try {
|
|
144
|
-
const sdk = await import("
|
|
147
|
+
const sdk = await import("./mcpclient.js");
|
|
145
148
|
client = new sdk.Client({ name: "context-doctor-overhead", version: "1" });
|
|
146
149
|
if (cfg.command) {
|
|
147
|
-
const { StdioClientTransport } =
|
|
150
|
+
const { StdioClientTransport } = sdk;
|
|
148
151
|
transport = new StdioClientTransport({
|
|
149
152
|
command: cfg.command,
|
|
150
153
|
args: cfg.args ?? [],
|
|
@@ -153,7 +156,7 @@ export async function measureServer(cfg, timeoutMs = 15_000) {
|
|
|
153
156
|
});
|
|
154
157
|
}
|
|
155
158
|
else {
|
|
156
|
-
const { StreamableHTTPClientTransport } =
|
|
159
|
+
const { StreamableHTTPClientTransport } = sdk;
|
|
157
160
|
transport = new StreamableHTTPClientTransport(new URL(cfg.url));
|
|
158
161
|
}
|
|
159
162
|
}
|
package/dist/optimize.d.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
* so the output is a drop-in replacement for the input conversation.
|
|
8
8
|
*/
|
|
9
9
|
export type StrategyId = "dedupe" | "trim-tool-results" | "trim-tool-calls" | "prune-history" | "strip-base64";
|
|
10
|
+
/** Every strategy id, for validating what a user typed. */
|
|
11
|
+
export declare const STRATEGY_IDS: readonly StrategyId[];
|
|
10
12
|
export interface OptimizeOptions {
|
|
11
13
|
strategies?: StrategyId[];
|
|
12
14
|
/**
|
package/dist/optimize.js
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
10
|
import { charsPerTokenFor, estimateTokens } from "./tokens.js";
|
|
11
11
|
import { hasBase64Blob, stripBase64Blobs } from "./blob.js";
|
|
12
|
+
/** Every strategy id, for validating what a user typed. */
|
|
13
|
+
export const STRATEGY_IDS = ["dedupe", "trim-tool-results", "trim-tool-calls", "strip-base64", "prune-history"];
|
|
12
14
|
const TRIM_BOUNDARY_STEP = 10;
|
|
13
15
|
const DEFAULTS = {
|
|
14
16
|
strategies: ["dedupe", "trim-tool-results", "strip-base64"],
|
package/dist/overhead.d.ts
CHANGED
|
@@ -30,7 +30,10 @@ export interface OverheadFinding {
|
|
|
30
30
|
}
|
|
31
31
|
export interface Baseline {
|
|
32
32
|
agent: Agent;
|
|
33
|
+
/** Sessions with a measurable first request, of any length (not only the 10+ request ones savings replays). */
|
|
33
34
|
sessions: number;
|
|
35
|
+
/** This agent's transcripts written in the period. */
|
|
36
|
+
transcripts: number;
|
|
34
37
|
/** Median tokens of the first request, minus the first user message. */
|
|
35
38
|
median: number;
|
|
36
39
|
p90: number;
|
|
@@ -65,7 +68,7 @@ export declare function findMemoryFiles(cwd?: string, home?: string): MemoryFile
|
|
|
65
68
|
* request and cold-start counts that turn tokens into a monthly bill.
|
|
66
69
|
* Claude Code, Codex and Gemini CLI sessions, newest `days` only.
|
|
67
70
|
*/
|
|
68
|
-
export declare function measureBaselines(days?: number, paths?: string[]): Baseline[];
|
|
71
|
+
export declare function measureBaselines(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): Baseline[];
|
|
69
72
|
/** Claude Code's baseline (the one memory-file prices are quoted against). */
|
|
70
73
|
export declare function measureBaseline(days?: number, paths?: string[]): Baseline | undefined;
|
|
71
74
|
/** What is worth changing in the memory files. */
|
|
@@ -75,9 +78,17 @@ export declare function overheadReport(opts?: {
|
|
|
75
78
|
home?: string;
|
|
76
79
|
days?: number;
|
|
77
80
|
paths?: string[];
|
|
81
|
+
onProgress?: (done: number, total: number, stage: "sessions" | "mcp") => void;
|
|
78
82
|
}): OverheadReport;
|
|
79
83
|
/** Launch each configured server and size its tool definitions, then add the findings they support. */
|
|
80
84
|
export declare function measureMcpSizes(r: OverheadReport): Promise<void>;
|
|
81
85
|
/** Configured servers nobody called: their definitions ride on every request for nothing. */
|
|
82
86
|
export declare function mcpFindings(m: McpSection, baseline?: Baseline): OverheadFinding[];
|
|
83
87
|
export declare function renderOverhead(r: OverheadReport, home?: string): string;
|
|
88
|
+
/**
|
|
89
|
+
* A server name as a person reads it. Connectors added on claude.ai reach
|
|
90
|
+
* Claude Code under their UUID (mcp__1a59c906-04da-521d-…__tool), which
|
|
91
|
+
* named nothing anyone recognised: "claude.ai connector 1a59c906" says
|
|
92
|
+
* where to look. --json keeps the full name.
|
|
93
|
+
*/
|
|
94
|
+
export declare function mcpDisplayName(server: string): string;
|
package/dist/overhead.js
CHANGED
|
@@ -311,6 +311,7 @@ function aggregate(agent, sessions, since, days) {
|
|
|
311
311
|
return {
|
|
312
312
|
agent,
|
|
313
313
|
sessions: firsts.length,
|
|
314
|
+
transcripts: sessions.length,
|
|
314
315
|
median: firsts[Math.floor(firsts.length / 2)],
|
|
315
316
|
p90: firsts[Math.min(firsts.length - 1, Math.floor(firsts.length * 0.9))],
|
|
316
317
|
requests,
|
|
@@ -326,12 +327,13 @@ function aggregate(agent, sessions, since, days) {
|
|
|
326
327
|
* request and cold-start counts that turn tokens into a monthly bill.
|
|
327
328
|
* Claude Code, Codex and Gemini CLI sessions, newest `days` only.
|
|
328
329
|
*/
|
|
329
|
-
export function measureBaselines(days = 30, paths) {
|
|
330
|
+
export function measureBaselines(days = 30, paths, onProgress) {
|
|
330
331
|
const since = Date.now() - days * 86_400_000;
|
|
331
332
|
const files = paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
332
333
|
const byAgent = new Map();
|
|
333
334
|
const runRows = new Set();
|
|
334
|
-
for (const path of files) {
|
|
335
|
+
for (const [index, path] of files.entries()) {
|
|
336
|
+
onProgress?.(index, files.length);
|
|
335
337
|
let u;
|
|
336
338
|
try {
|
|
337
339
|
u = usageOf(path, runRows);
|
|
@@ -420,11 +422,12 @@ export function overheadReport(opts = {}) {
|
|
|
420
422
|
const cwd = opts.cwd ?? process.cwd();
|
|
421
423
|
const home = opts.home ?? homedir();
|
|
422
424
|
const files = findMemoryFiles(cwd, home);
|
|
423
|
-
const
|
|
425
|
+
const tick = (stage) => (opts.onProgress ? (done, total) => opts.onProgress(done, total, stage) : undefined);
|
|
426
|
+
const baselines = measureBaselines(opts.days ?? 30, opts.paths, tick("sessions"));
|
|
424
427
|
const baseline = baselines.find((b) => b.agent === "Claude Code");
|
|
425
428
|
// MCP usage comes from Claude Code transcripts only (the tool-name scheme is theirs).
|
|
426
429
|
const claudePaths = opts.paths?.filter((p) => !isGeminiChat(p) && !/[\\/]\.codex[\\/]/.test(p));
|
|
427
|
-
const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, claudePaths) };
|
|
430
|
+
const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, claudePaths, tick("mcp")) };
|
|
428
431
|
return { cwd, baseline, baselines, files, findings: overheadFindings(files, baselines), mcp };
|
|
429
432
|
}
|
|
430
433
|
/** Launch each configured server and size its tool definitions, then add the findings they support. */
|
|
@@ -458,7 +461,7 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
458
461
|
const b = r.baseline;
|
|
459
462
|
const claudeTokens = r.files.filter((f) => f.agent === "Claude Code").reduce((s, f) => s + f.tokens, 0);
|
|
460
463
|
if (b) {
|
|
461
|
-
out.push(`Claude Code, last ${b.days} days: ${b
|
|
464
|
+
out.push(`Claude Code, last ${b.days} days: ${sessionCount(b)} start at a median ~${formatTokens(b.median)} tokens (p90 ~${formatTokens(b.p90)}) before the first message.`, `Memory files loaded here are ~${formatTokens(claudeTokens)} of that; the rest is Claude Code's system prompt, tools, skills and MCP schemas.`);
|
|
462
465
|
if (b.usdPerKPerMonth !== undefined) {
|
|
463
466
|
out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} list prices) every 1k tokens of it costs ~${formatUsd(b.usdPerKPerMonth)} a month;`, `the whole overhead ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month.`);
|
|
464
467
|
}
|
|
@@ -468,7 +471,7 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
468
471
|
}
|
|
469
472
|
for (const o of r.baselines.filter((x) => x.agent !== "Claude Code")) {
|
|
470
473
|
const tokens = r.files.filter((f) => f.agent === o.agent).reduce((s, f) => s + f.tokens, 0);
|
|
471
|
-
out.push("", `${o.agent}, last ${o.days} days: ${o
|
|
474
|
+
out.push("", `${o.agent}, last ${o.days} days: ${sessionCount(o)} start at a median ~${formatTokens(o.median)} tokens (p90 ~${formatTokens(o.p90)}); ${tokens ? `memory files loaded here ~${formatTokens(tokens)} of it` : "no memory files of its own here"}.` +
|
|
472
475
|
(o.usdPerKPerMonth !== undefined
|
|
473
476
|
? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} list prices).`
|
|
474
477
|
: ""));
|
|
@@ -489,6 +492,27 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
489
492
|
out.push(`${f.severity === "warn" ? "▲" : "ℹ"} ${f.message.replace(home, "~")}`, ` → ${f.suggestion}`);
|
|
490
493
|
return out.join("\n");
|
|
491
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Which sessions the overhead is measured on, said precisely: every session
|
|
497
|
+
* whose first request could be measured, whatever its length. `savings` and
|
|
498
|
+
* `compact-window` replay only sessions with 10+ requests, so their counts
|
|
499
|
+
* are smaller; the transcript total is the same in all three.
|
|
500
|
+
*/
|
|
501
|
+
function sessionCount(b) {
|
|
502
|
+
const total = b.transcripts ?? b.sessions;
|
|
503
|
+
return total > b.sessions
|
|
504
|
+
? `${b.sessions} of ${total} sessions (any length; the rest had no first request to measure)`
|
|
505
|
+
: `${b.sessions} session${b.sessions === 1 ? "" : "s"} (any length)`;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* A server name as a person reads it. Connectors added on claude.ai reach
|
|
509
|
+
* Claude Code under their UUID (mcp__1a59c906-04da-521d-…__tool), which
|
|
510
|
+
* named nothing anyone recognised: "claude.ai connector 1a59c906" says
|
|
511
|
+
* where to look. --json keeps the full name.
|
|
512
|
+
*/
|
|
513
|
+
export function mcpDisplayName(server) {
|
|
514
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(server) ? `claude.ai connector ${server.slice(0, 8)}` : server;
|
|
515
|
+
}
|
|
492
516
|
function renderMcp(r) {
|
|
493
517
|
const { configs, usage, sizes } = r.mcp;
|
|
494
518
|
if (configs.length === 0 && usage.calls.size === 0)
|
|
@@ -513,7 +537,7 @@ function renderMcp(r) {
|
|
|
513
537
|
if (app.length) {
|
|
514
538
|
out.push(` Provided by the app or connectors (not in your config; toggle them in the app):`);
|
|
515
539
|
for (const [n, calls] of app.slice(0, 10))
|
|
516
|
-
out.push(` ${n.padEnd(38)} ${String(calls).padStart(6)} calls`);
|
|
540
|
+
out.push(` ${mcpDisplayName(n).padEnd(38)} ${String(calls).padStart(6)} calls`);
|
|
517
541
|
if (app.length > 10)
|
|
518
542
|
out.push(` … ${app.length - 10} more`);
|
|
519
543
|
}
|
package/dist/preferences.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* "custom instructions" are read on every turn of every chat, which is the
|
|
5
5
|
* closest thing those surfaces have to a UserPromptSubmit hook.
|
|
6
6
|
*
|
|
7
|
-
* Kept short (~
|
|
7
|
+
* Kept short (~185 Claude tokens, ~125 GPT): it rides in every conversation.
|
|
8
8
|
*/
|
|
9
9
|
export declare const CHAT_PREFERENCES: string;
|
|
10
10
|
/** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
|
package/dist/preferences.js
CHANGED
|
@@ -4,15 +4,15 @@
|
|
|
4
4
|
* "custom instructions" are read on every turn of every chat, which is the
|
|
5
5
|
* closest thing those surfaces have to a UserPromptSubmit hook.
|
|
6
6
|
*
|
|
7
|
-
* Kept short (~
|
|
7
|
+
* Kept short (~185 Claude tokens, ~125 GPT): it rides in every conversation.
|
|
8
8
|
*/
|
|
9
9
|
import { spawnSync } from "node:child_process";
|
|
10
10
|
export const CHAT_PREFERENCES = [
|
|
11
|
-
"Context hygiene: when I paste something long, summarize it into the points you will use and work from
|
|
11
|
+
"Context hygiene: when I paste something long, summarize it into the points you will use and work from that;",
|
|
12
12
|
"do not carry it verbatim or re-quote it later, refer to it by name. Never inline base64.",
|
|
13
|
-
"
|
|
14
|
-
"call it with a sketch before answering and act on its top finding; otherwise offer me a 300-token
|
|
15
|
-
"summary (decisions, current state, open items) to start a fresh chat.",
|
|
13
|
+
"Once, when a chat first passes ~30 turns, and whenever I ask about tokens, limits, cost or speed: if a profile_context",
|
|
14
|
+
"tool exists, call it with a sketch before answering and act on its top finding; otherwise offer me a 300-token",
|
|
15
|
+
"handoff summary (decisions, current state, open items) to start a fresh chat.",
|
|
16
16
|
].join(" ");
|
|
17
17
|
/** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
|
|
18
18
|
export const PREFERENCE_TARGETS = [
|
package/dist/proxy.d.ts
CHANGED
|
@@ -46,9 +46,18 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
46
46
|
anthropicUpstream?: string;
|
|
47
47
|
openaiUpstream?: string;
|
|
48
48
|
googleUpstream?: string;
|
|
49
|
+
/** Where Codex signed in with ChatGPT is relayed (testing); see the handler. */
|
|
50
|
+
chatgptUpstream?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Add a conversation prompt_cache_key to OpenAI requests that lack one
|
|
53
|
+
* (cachekey.ts). Default: on toward api.openai.com, off toward any other
|
|
54
|
+
* OpenAI-compatible upstream, which may reject the field;
|
|
55
|
+
* CONTEXT_DOCTOR_CACHE_KEY=0 or 1 overrides.
|
|
56
|
+
*/
|
|
57
|
+
promptCacheKey?: boolean;
|
|
49
58
|
}
|
|
50
59
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
51
|
-
export declare const PROXY_VERSION = "0.
|
|
60
|
+
export declare const PROXY_VERSION = "0.34.0";
|
|
52
61
|
/**
|
|
53
62
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
54
63
|
* the prefix is absent or the token differs. The comparison is constant time
|
|
@@ -92,6 +101,10 @@ export interface ProxyStats {
|
|
|
92
101
|
/** Cache reads/writes reported upstream (Anthropic), so autopilot's effect on the cache is visible. */
|
|
93
102
|
upstreamCacheReadTokens: number;
|
|
94
103
|
upstreamCacheWriteTokens: number;
|
|
104
|
+
/** OpenAI's cached_tokens: the part of upstreamInputTokens its responses say was read from cache. */
|
|
105
|
+
openaiCachedTokens: number;
|
|
106
|
+
/** OpenAI requests sent with a conversation prompt_cache_key the proxy added (cachekey.ts). */
|
|
107
|
+
cacheKeysAdded: number;
|
|
95
108
|
autopilot?: {
|
|
96
109
|
enabled: boolean;
|
|
97
110
|
paused: boolean;
|
package/dist/proxy.js
CHANGED
|
@@ -20,8 +20,9 @@ import { formatTokens, CHARS_PER_TOKEN, providerFor } from "./tokens.js";
|
|
|
20
20
|
import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
|
|
21
21
|
import { recordLedger } from "./ledger.js";
|
|
22
22
|
import { minCacheableTokens } from "./cacheplan.js";
|
|
23
|
+
import { withPromptCacheKey } from "./cachekey.js";
|
|
23
24
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
24
|
-
export const PROXY_VERSION = "0.
|
|
25
|
+
export const PROXY_VERSION = "0.34.0";
|
|
25
26
|
/** Connection-level headers that must not be forwarded. */
|
|
26
27
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
27
28
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -185,6 +186,9 @@ export function startProxy(opts = {}) {
|
|
|
185
186
|
else
|
|
186
187
|
refusing.add(account);
|
|
187
188
|
};
|
|
189
|
+
const openaiBase = opts.openaiUpstream ?? "https://api.openai.com";
|
|
190
|
+
const keyEnv = process.env.CONTEXT_DOCTOR_CACHE_KEY;
|
|
191
|
+
const addCacheKeys = opts.promptCacheKey ?? (keyEnv === "0" ? false : keyEnv === "1" ? true : /^https:\/\/api\.openai\.com\/?$/.test(openaiBase));
|
|
188
192
|
const stats = {
|
|
189
193
|
startedAt: new Date().toISOString(),
|
|
190
194
|
requests: 0,
|
|
@@ -198,6 +202,8 @@ export function startProxy(opts = {}) {
|
|
|
198
202
|
advice: [],
|
|
199
203
|
upstreamCacheReadTokens: 0,
|
|
200
204
|
upstreamCacheWriteTokens: 0,
|
|
205
|
+
openaiCachedTokens: 0,
|
|
206
|
+
cacheKeysAdded: 0,
|
|
201
207
|
autopilot: opts.autopilot
|
|
202
208
|
? { enabled: true, paused: false, requests: 0, changedRequests: 0, batches: 0, coldBatches: 0, resultsCleared: 0, tokensRemoved: 0, lastReason: "" }
|
|
203
209
|
: undefined,
|
|
@@ -248,7 +254,16 @@ export function startProxy(opts = {}) {
|
|
|
248
254
|
res.end(JSON.stringify({ ...stats, estUsdSaved: Number(stats.estUsdSaved.toFixed(4)) }, null, 2));
|
|
249
255
|
return;
|
|
250
256
|
}
|
|
251
|
-
|
|
257
|
+
// Codex signed in with ChatGPT, reading a config.toml whose
|
|
258
|
+
// openai_base_url points here (the ChatGPT app's Codex tab shares
|
|
259
|
+
// ~/.codex with a CLI on an API key): without its address it would
|
|
260
|
+
// talk to ChatGPT's Codex backend, so it is relayed there byte for
|
|
261
|
+
// byte. Its path loses the /v1 the OpenAI routes carry, and no rule
|
|
262
|
+
// below matches it: it is never edited.
|
|
263
|
+
const chatgpt = typeof req.headers["chatgpt-account-id"] === "string" && url.startsWith("/v1/");
|
|
264
|
+
if (chatgpt)
|
|
265
|
+
url = url.slice(3);
|
|
266
|
+
const upstreamBase = chatgpt ? (opts.chatgptUpstream ?? "https://chatgpt.com/backend-api/codex") : upstreamFor(url, opts, req.headers);
|
|
252
267
|
if (!upstreamBase) {
|
|
253
268
|
res.statusCode = 404;
|
|
254
269
|
res.setHeader("content-type", "application/json");
|
|
@@ -372,7 +387,7 @@ export function startProxy(opts = {}) {
|
|
|
372
387
|
? `the last entry in "tools" (tools come before system in the cached prefix)`
|
|
373
388
|
: `the last block of "system"`;
|
|
374
389
|
advise(`~${stablePrefixTokens}+ tokens of stable system/tools on ${requestModel} without cache_control. ` +
|
|
375
|
-
`Add {"cache_control":{"type":"ephemeral"}} to ${where}; everything before it then bills at
|
|
390
|
+
`Add {"cache_control":{"type":"ephemeral"}} to ${where}; everything before it then bills at the cache-read rate (2.5-10% of input) on every call`);
|
|
376
391
|
}
|
|
377
392
|
const fp = fnv1a(stablePrefix);
|
|
378
393
|
const prev = prefixFingerprints.get(requestModel);
|
|
@@ -399,7 +414,8 @@ export function startProxy(opts = {}) {
|
|
|
399
414
|
const stableTokens = Math.round(stableChars / CHARS_PER_TOKEN[providerFor(requestModel)].code);
|
|
400
415
|
if (stableTokens >= minCacheable) {
|
|
401
416
|
advise(`messages #0-#${stable - 1} (~${stableTokens} tokens) were identical to the previous ${requestModel} request and carry no cache_control. ` +
|
|
402
|
-
`
|
|
417
|
+
`Simplest: a top-level "cache_control":{"type":"ephemeral"} (automatic caching marks the last block and moves it forward each turn); ` +
|
|
418
|
+
`or put {"cache_control":{"type":"ephemeral"}} on the last content block of message #${stable - 1}. That run then reads from cache instead of re-billing each turn`);
|
|
403
419
|
}
|
|
404
420
|
}
|
|
405
421
|
}
|
|
@@ -442,6 +458,18 @@ export function startProxy(opts = {}) {
|
|
|
442
458
|
/* not a conversation payload — forward as-is */
|
|
443
459
|
}
|
|
444
460
|
}
|
|
461
|
+
// A stable prompt_cache_key per conversation, where the app sent none
|
|
462
|
+
// and the model routes by it (GPT before 5.6): its requests then land
|
|
463
|
+
// on one cache. Added after autopilot, so its view of the conversation
|
|
464
|
+
// is the app's own.
|
|
465
|
+
if (addCacheKeys && !chatgpt && req.method === "POST" && body && /^\/v1\/(chat\/completions|responses)(\?|$)/.test(url) && upstreamBase === openaiBase) {
|
|
466
|
+
const keyed = withPromptCacheKey(body);
|
|
467
|
+
if (keyed) {
|
|
468
|
+
body = keyed.body;
|
|
469
|
+
stats.cacheKeysAdded++;
|
|
470
|
+
note += `; prompt_cache_key ${keyed.key.slice(0, 11)}…`;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
445
473
|
const headers = {};
|
|
446
474
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
447
475
|
if (!SKIP_REQUEST_HEADERS.has(key.toLowerCase()) && typeof value === "string")
|
|
@@ -515,6 +543,7 @@ export function startProxy(opts = {}) {
|
|
|
515
543
|
v = Number(m[1]); return v; };
|
|
516
544
|
stats.upstreamCacheReadTokens += lastNum(/"cache_read_input_tokens"\s*:\s*(\d+)/g);
|
|
517
545
|
stats.upstreamCacheWriteTokens += lastNum(/"cache_creation_input_tokens"\s*:\s*(\d+)/g);
|
|
546
|
+
stats.openaiCachedTokens += lastNum(/"cached_tokens"\s*:\s*(\d+)/g);
|
|
518
547
|
}
|
|
519
548
|
}
|
|
520
549
|
res.end();
|
|
@@ -578,6 +607,18 @@ export function startProxy(opts = {}) {
|
|
|
578
607
|
};
|
|
579
608
|
liveServers.add(drain);
|
|
580
609
|
installSignalHandlers();
|
|
610
|
+
// A WebSocket upgrade cannot be relayed (or edited) here. Codex tries
|
|
611
|
+
// Responses over WebSocket first and, on anything but 426, retries five
|
|
612
|
+
// times (~15 s) before it falls back to HTTP; 426 Upgrade Required makes it
|
|
613
|
+
// switch to HTTP for the session at once (codex-rs core/src/client.rs).
|
|
614
|
+
// Answered on the raw socket, which is then closed: handled as an ordinary
|
|
615
|
+
// request, the upgrade left the connection in a state where the client's
|
|
616
|
+
// next request on it never got an answer.
|
|
617
|
+
server.on("upgrade", (_req, socket) => {
|
|
618
|
+
const body = JSON.stringify({ error: "context-doctor proxy: WebSocket transport is not supported here; send the request over HTTP" });
|
|
619
|
+
socket.on("error", () => { });
|
|
620
|
+
socket.end(`HTTP/1.1 426 Upgrade Required\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
|
|
621
|
+
});
|
|
581
622
|
server.on("close", () => {
|
|
582
623
|
liveServers.delete(drain);
|
|
583
624
|
checkpoint();
|
package/dist/savings.d.ts
CHANGED
|
@@ -47,7 +47,10 @@ export interface SessionSavings {
|
|
|
47
47
|
export declare function autopilotReaches(entrypoint?: string): boolean;
|
|
48
48
|
export interface SavingsReport {
|
|
49
49
|
days: number;
|
|
50
|
+
/** Sessions with 10+ requests in the period: the ones replayed and counted. */
|
|
50
51
|
sessions: SessionSavings[];
|
|
52
|
+
/** Claude Code transcripts written in the period, replayed or not (the progress line's total). */
|
|
53
|
+
transcripts: number;
|
|
51
54
|
billedUsd: number;
|
|
52
55
|
savedUsd: number;
|
|
53
56
|
savedTokens: number;
|
|
@@ -60,6 +63,19 @@ export interface SavingsReport {
|
|
|
60
63
|
coldResumes: number;
|
|
61
64
|
coldResumeNetUsd: number;
|
|
62
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* One arm of the replay: the history as sent, priced incrementally at each
|
|
68
|
+
* request's own model. Reads are priced as they go; writes are kept at the
|
|
69
|
+
* input price and multiplied by the session's write TTL mix at the end
|
|
70
|
+
* (`usd(writeMult)`), since the mix is only known once the whole transcript
|
|
71
|
+
* has been read.
|
|
72
|
+
*/
|
|
73
|
+
/** What an arm needs from a clearer: autopilot's AutoClearer, or the simulated server-side rule (serverclear.ts). */
|
|
74
|
+
export interface ReplayClearer {
|
|
75
|
+
apply(body: Record<string, unknown>, now: number): {
|
|
76
|
+
firstChanged: number;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
63
79
|
/**
|
|
64
80
|
* Replay one Claude Code transcript. Undefined when it holds too few requests
|
|
65
81
|
* to mean anything. `runRows` is shared by every transcript of one report: a
|
|
@@ -68,7 +84,7 @@ export interface SavingsReport {
|
|
|
68
84
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
69
85
|
* transcript again after the replay has added its rows to `runRows`.
|
|
70
86
|
*/
|
|
71
|
-
export declare function replaySession(path: string, options?: AutoClearOptions, since?: number, runRows?: Set<string>, coldRows?: Set<string
|
|
87
|
+
export declare function replaySession(path: string, options?: AutoClearOptions, since?: number, runRows?: Set<string>, coldRows?: Set<string>, makeClearer?: (model?: string) => ReplayClearer): SessionSavings | undefined;
|
|
72
88
|
export declare function estimateSavings(days?: number, options?: AutoClearOptions, paths?: string[], onProgress?: (done: number, total: number) => void): SavingsReport;
|
|
73
89
|
/** Optional third lever, computed by compactwindow.ts and passed in by the CLI. */
|
|
74
90
|
export interface CompactWindowLine {
|
package/dist/savings.js
CHANGED
|
@@ -17,6 +17,8 @@ import { coldResumeEvents } from "./coldresume.js";
|
|
|
17
17
|
import { forEachLine, listSessions, replyCounter } from "./session.js";
|
|
18
18
|
import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
|
|
19
19
|
import { estimateTokens, formatTokens, realModel } from "./tokens.js";
|
|
20
|
+
import { withInvocation } from "./invocation.js";
|
|
21
|
+
import { sessionsLabel } from "./compactwindow.js";
|
|
20
22
|
/** System prompt and tool schemas: sent on every request, identical in both arms. */
|
|
21
23
|
const FIXED_TOKENS = 54_000;
|
|
22
24
|
const CLAUDE_CODE_TTL_MS = 3_600_000;
|
|
@@ -31,13 +33,6 @@ export function autopilotReaches(entrypoint) {
|
|
|
31
33
|
}
|
|
32
34
|
/** Without a price on file the arms still need relative weights: Claude's usual 10% read rate. */
|
|
33
35
|
const UNPRICED = { inputPerM: 1, outputPerM: 5, cacheReadPerM: 0.1 };
|
|
34
|
-
/**
|
|
35
|
-
* One arm of the replay: the history as sent, priced incrementally at each
|
|
36
|
-
* request's own model. Reads are priced as they go; writes are kept at the
|
|
37
|
-
* input price and multiplied by the session's write TTL mix at the end
|
|
38
|
-
* (`usd(writeMult)`), since the mix is only known once the whole transcript
|
|
39
|
-
* has been read.
|
|
40
|
-
*/
|
|
41
36
|
function arm(model, clearer) {
|
|
42
37
|
const msgs = [];
|
|
43
38
|
const tok = [];
|
|
@@ -88,9 +83,9 @@ function arm(model, clearer) {
|
|
|
88
83
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
89
84
|
* transcript again after the replay has added its rows to `runRows`.
|
|
90
85
|
*/
|
|
91
|
-
export function replaySession(path, options = {}, since = 0, runRows, coldRows) {
|
|
86
|
+
export function replaySession(path, options = {}, since = 0, runRows, coldRows, makeClearer = () => new AutoClearer(options)) {
|
|
92
87
|
let model;
|
|
93
|
-
let base = arm(undefined, null), auto = arm(undefined,
|
|
88
|
+
let base = arm(undefined, null), auto = arm(undefined, makeClearer());
|
|
94
89
|
let baseUsd = 0, autoUsd = 0, baseRaw = 0, autoRaw = 0;
|
|
95
90
|
let entrypoint;
|
|
96
91
|
let billed = 0, billedUsd = 0, billedRaw = 0, requests = 0, lastId, lastTs = null;
|
|
@@ -116,7 +111,7 @@ export function replaySession(path, options = {}, since = 0, runRows, coldRows)
|
|
|
116
111
|
// Compaction replaces the history in both arms alike: start fresh.
|
|
117
112
|
flush();
|
|
118
113
|
base = arm(model, null);
|
|
119
|
-
auto = arm(model,
|
|
114
|
+
auto = arm(model, makeClearer(model));
|
|
120
115
|
return;
|
|
121
116
|
}
|
|
122
117
|
if (e.type === "assistant" && e.message) {
|
|
@@ -227,9 +222,11 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress) {
|
|
|
227
222
|
// (author's 133 days: 11.4% of weighted tokens, 12.7% of dollars); tokens
|
|
228
223
|
// only when nothing could be priced.
|
|
229
224
|
const savedPct = billedUsd > 0 ? savedUsd / billedUsd : billedW > 0 ? sum("savedWeighted") / billedW : 0;
|
|
225
|
+
onProgress?.(targets.length, targets.length);
|
|
230
226
|
return {
|
|
231
227
|
days,
|
|
232
228
|
sessions: sessions.sort((a, b) => b.savedUsd - a.savedUsd),
|
|
229
|
+
transcripts: targets.length,
|
|
233
230
|
billedUsd,
|
|
234
231
|
savedUsd,
|
|
235
232
|
savedTokens: sum("savedTokens"),
|
|
@@ -249,14 +246,15 @@ export function renderSavings(r, autopilotOn = false, cw) {
|
|
|
249
246
|
if (r.sessions.length === 0) {
|
|
250
247
|
lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
|
|
251
248
|
lines.push("Use Claude Code for a while, then run this again: `context-doctor savings`.");
|
|
252
|
-
return lines.join("\n");
|
|
249
|
+
return withInvocation(lines.join("\n"));
|
|
253
250
|
}
|
|
254
251
|
const n = r.sessions.length;
|
|
255
252
|
const allDesktop = r.unreachableSessions === n;
|
|
256
253
|
const pct = (x) => (r.billedUsd > 0 ? ` (${Math.round((x / r.billedUsd) * 100)}%)` : "");
|
|
257
254
|
// Kept within 80 columns: this is most people's first screen of the tool.
|
|
258
255
|
lines.push("What context-doctor finds in your Claude Code sessions");
|
|
259
|
-
|
|
256
|
+
// The same count, said the same way, as compact-window's.
|
|
257
|
+
lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, at list prices`);
|
|
260
258
|
lines.push("─".repeat(60));
|
|
261
259
|
lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
|
|
262
260
|
lines.push("");
|
|
@@ -294,7 +292,8 @@ export function renderSavings(r, autopilotOn = false, cw) {
|
|
|
294
292
|
lines.push("Replayed request by request through the shipped code and priced as the");
|
|
295
293
|
lines.push("prompt cache bills. On a subscription the same tokens come out of your");
|
|
296
294
|
lines.push("usage limit instead. Share yours: context-doctor savings --share");
|
|
297
|
-
|
|
295
|
+
// Hints as the user can type them: `npx context-doctor …` after an npx run.
|
|
296
|
+
return withInvocation(lines.join("\n"));
|
|
298
297
|
}
|
|
299
298
|
/**
|
|
300
299
|
* `savings --share`: a few lines people can paste or screenshot. Totals only:
|
package/dist/session.d.ts
CHANGED
|
@@ -72,6 +72,21 @@ export interface ParsedSession {
|
|
|
72
72
|
}
|
|
73
73
|
/** All session transcripts on this machine, newest first. */
|
|
74
74
|
export declare function listSessions(limit?: number): SessionInfo[];
|
|
75
|
+
/** Claude Code's project folder for a working directory: every non-alphanumeric becomes "-". */
|
|
76
|
+
export declare function claudeProjectDir(cwd: string, home?: string): string;
|
|
77
|
+
/** A session `session` picked by itself, and how, in words. */
|
|
78
|
+
export interface PickedSession {
|
|
79
|
+
path: string;
|
|
80
|
+
how: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The session `session` profiles when no file is given: the one it is
|
|
84
|
+
* running in. Inside Claude Code (a Bash tool call, the plugin's checkup
|
|
85
|
+
* skill) CLAUDE_CODE_SESSION_ID names it; otherwise the newest transcript of
|
|
86
|
+
* this folder's project; otherwise the newest on the machine. "Newest on the
|
|
87
|
+
* machine" alone picked whichever other project had written last.
|
|
88
|
+
*/
|
|
89
|
+
export declare function pickCurrentSession(env?: NodeJS.ProcessEnv, cwd?: string, home?: string): PickedSession | undefined;
|
|
75
90
|
/**
|
|
76
91
|
* Read a JSONL transcript line by line without ever materializing the whole
|
|
77
92
|
* file as one string.
|
package/dist/session.js
CHANGED
|
@@ -85,6 +85,49 @@ export function listSessions(limit = 20) {
|
|
|
85
85
|
sessions.push(...listGeminiChats());
|
|
86
86
|
return sessions.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime()).slice(0, limit);
|
|
87
87
|
}
|
|
88
|
+
/** Claude Code's project folder for a working directory: every non-alphanumeric becomes "-". */
|
|
89
|
+
export function claudeProjectDir(cwd, home = homedir()) {
|
|
90
|
+
return join(home, ".claude", "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The session `session` profiles when no file is given: the one it is
|
|
94
|
+
* running in. Inside Claude Code (a Bash tool call, the plugin's checkup
|
|
95
|
+
* skill) CLAUDE_CODE_SESSION_ID names it; otherwise the newest transcript of
|
|
96
|
+
* this folder's project; otherwise the newest on the machine. "Newest on the
|
|
97
|
+
* machine" alone picked whichever other project had written last.
|
|
98
|
+
*/
|
|
99
|
+
export function pickCurrentSession(env = process.env, cwd = process.cwd(), home = homedir()) {
|
|
100
|
+
const id = env.CLAUDE_CODE_SESSION_ID?.trim();
|
|
101
|
+
const here = claudeProjectDir(cwd, home);
|
|
102
|
+
if (id && /^[\w.-]+$/.test(id)) {
|
|
103
|
+
const root = join(home, ".claude", "projects");
|
|
104
|
+
let dirs = [];
|
|
105
|
+
try {
|
|
106
|
+
dirs = readdirSync(root);
|
|
107
|
+
}
|
|
108
|
+
catch { /* no projects */ }
|
|
109
|
+
const candidates = [here, ...dirs.map((d) => join(root, d))].map((d) => join(d, `${id}.jsonl`));
|
|
110
|
+
const found = candidates.find((p) => existsSync(p));
|
|
111
|
+
if (found)
|
|
112
|
+
return { path: found, how: `the current Claude Code session (CLAUDE_CODE_SESSION_ID ${id})` };
|
|
113
|
+
}
|
|
114
|
+
let newest;
|
|
115
|
+
try {
|
|
116
|
+
for (const f of readdirSync(here)) {
|
|
117
|
+
if (!f.endsWith(".jsonl"))
|
|
118
|
+
continue;
|
|
119
|
+
const p = join(here, f);
|
|
120
|
+
const at = statSync(p).mtimeMs;
|
|
121
|
+
if (!newest || at > newest.at)
|
|
122
|
+
newest = { path: p, at };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch { /* no project folder for this directory */ }
|
|
126
|
+
if (newest)
|
|
127
|
+
return { path: newest.path, how: "the newest Claude Code session in this folder's project" };
|
|
128
|
+
const any = listSessions(1)[0];
|
|
129
|
+
return any ? { path: any.path, how: "the newest session on this machine (none for this folder)" } : undefined;
|
|
130
|
+
}
|
|
88
131
|
/**
|
|
89
132
|
* ChatGPT data export (chatgpt.com → Settings → Data controls → Export):
|
|
90
133
|
* conversations.json is an array of conversations, each holding a `mapping`
|
package/dist/subagentpay.d.ts
CHANGED
|
@@ -45,5 +45,5 @@ export interface PaybackReport {
|
|
|
45
45
|
sessions: number;
|
|
46
46
|
subagents: SubagentPayback[];
|
|
47
47
|
}
|
|
48
|
-
export declare function subagentPayback(days?: number, paths?: string[]): PaybackReport;
|
|
48
|
+
export declare function subagentPayback(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): PaybackReport;
|
|
49
49
|
export declare function renderPayback(r: PaybackReport, top?: number): string;
|
package/dist/subagentpay.js
CHANGED
|
@@ -152,12 +152,13 @@ function scanParent(path, ids) {
|
|
|
152
152
|
});
|
|
153
153
|
return view;
|
|
154
154
|
}
|
|
155
|
-
export function subagentPayback(days = 30, paths) {
|
|
155
|
+
export function subagentPayback(days = 30, paths, onProgress) {
|
|
156
156
|
const since = Date.now() - days * 86_400_000;
|
|
157
157
|
const sessions = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
158
158
|
const out = [];
|
|
159
159
|
let withSubagents = 0;
|
|
160
|
-
for (const parent of sessions) {
|
|
160
|
+
for (const [index, parent] of sessions.entries()) {
|
|
161
|
+
onProgress?.(index, sessions.length);
|
|
161
162
|
const dir = join(parent.replace(/\.jsonl$/, ""), "subagents");
|
|
162
163
|
if (!existsSync(dir))
|
|
163
164
|
continue;
|