context-doctor 0.32.0 → 0.33.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 +85 -695
- package/dist/autoclear.js +4 -1
- package/dist/autopilot.d.ts +20 -0
- package/dist/autopilot.js +69 -6
- package/dist/ci.js +9 -1
- package/dist/cli.js +355 -245
- package/dist/clihelp.d.ts +24 -0
- package/dist/clihelp.js +116 -0
- package/dist/compactquality.d.ts +1 -1
- package/dist/compactquality.js +3 -2
- package/dist/compactwindow.d.ts +29 -5
- package/dist/compactwindow.js +50 -18
- package/dist/diff.js +24 -2
- package/dist/doctor.d.ts +3 -2
- package/dist/doctor.js +77 -27
- package/dist/install.d.ts +25 -0
- package/dist/install.js +237 -29
- package/dist/invocation.d.ts +18 -0
- package/dist/invocation.js +49 -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 +1 -1
- package/dist/proxy.js +1 -1
- package/dist/savings.d.ts +3 -0
- package/dist/savings.js +9 -3
- 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
|
@@ -48,7 +48,7 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
48
48
|
googleUpstream?: string;
|
|
49
49
|
}
|
|
50
50
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
51
|
-
export declare const PROXY_VERSION = "0.
|
|
51
|
+
export declare const PROXY_VERSION = "0.33.0";
|
|
52
52
|
/**
|
|
53
53
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
54
54
|
* the prefix is absent or the token differs. The comparison is constant time
|
package/dist/proxy.js
CHANGED
|
@@ -21,7 +21,7 @@ import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
|
|
|
21
21
|
import { recordLedger } from "./ledger.js";
|
|
22
22
|
import { minCacheableTokens } from "./cacheplan.js";
|
|
23
23
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
24
|
-
export const PROXY_VERSION = "0.
|
|
24
|
+
export const PROXY_VERSION = "0.33.0";
|
|
25
25
|
/** Connection-level headers that must not be forwarded. */
|
|
26
26
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
27
27
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
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;
|
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;
|
|
@@ -227,9 +229,11 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress) {
|
|
|
227
229
|
// (author's 133 days: 11.4% of weighted tokens, 12.7% of dollars); tokens
|
|
228
230
|
// only when nothing could be priced.
|
|
229
231
|
const savedPct = billedUsd > 0 ? savedUsd / billedUsd : billedW > 0 ? sum("savedWeighted") / billedW : 0;
|
|
232
|
+
onProgress?.(targets.length, targets.length);
|
|
230
233
|
return {
|
|
231
234
|
days,
|
|
232
235
|
sessions: sessions.sort((a, b) => b.savedUsd - a.savedUsd),
|
|
236
|
+
transcripts: targets.length,
|
|
233
237
|
billedUsd,
|
|
234
238
|
savedUsd,
|
|
235
239
|
savedTokens: sum("savedTokens"),
|
|
@@ -249,14 +253,15 @@ export function renderSavings(r, autopilotOn = false, cw) {
|
|
|
249
253
|
if (r.sessions.length === 0) {
|
|
250
254
|
lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
|
|
251
255
|
lines.push("Use Claude Code for a while, then run this again: `context-doctor savings`.");
|
|
252
|
-
return lines.join("\n");
|
|
256
|
+
return withInvocation(lines.join("\n"));
|
|
253
257
|
}
|
|
254
258
|
const n = r.sessions.length;
|
|
255
259
|
const allDesktop = r.unreachableSessions === n;
|
|
256
260
|
const pct = (x) => (r.billedUsd > 0 ? ` (${Math.round((x / r.billedUsd) * 100)}%)` : "");
|
|
257
261
|
// Kept within 80 columns: this is most people's first screen of the tool.
|
|
258
262
|
lines.push("What context-doctor finds in your Claude Code sessions");
|
|
259
|
-
|
|
263
|
+
// The same count, said the same way, as compact-window's.
|
|
264
|
+
lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, at list prices`);
|
|
260
265
|
lines.push("─".repeat(60));
|
|
261
266
|
lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
|
|
262
267
|
lines.push("");
|
|
@@ -294,7 +299,8 @@ export function renderSavings(r, autopilotOn = false, cw) {
|
|
|
294
299
|
lines.push("Replayed request by request through the shipped code and priced as the");
|
|
295
300
|
lines.push("prompt cache bills. On a subscription the same tokens come out of your");
|
|
296
301
|
lines.push("usage limit instead. Share yours: context-doctor savings --share");
|
|
297
|
-
|
|
302
|
+
// Hints as the user can type them: `npx context-doctor …` after an npx run.
|
|
303
|
+
return withInvocation(lines.join("\n"));
|
|
298
304
|
}
|
|
299
305
|
/**
|
|
300
306
|
* `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;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction,
|
|
3
|
+
"version": "0.33.0",
|
|
4
|
+
"description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
7
7
|
"ai-agents",
|
|
@@ -25,8 +25,6 @@
|
|
|
25
25
|
"gemini",
|
|
26
26
|
"gemini-cli",
|
|
27
27
|
"gpt",
|
|
28
|
-
"langchain",
|
|
29
|
-
"llamaindex",
|
|
30
28
|
"llm",
|
|
31
29
|
"llm-cost",
|
|
32
30
|
"llm-tools",
|
|
@@ -62,6 +60,7 @@
|
|
|
62
60
|
"dist",
|
|
63
61
|
"!dist/test",
|
|
64
62
|
"!dist/mcp.bundle.js",
|
|
63
|
+
"!dist/mcpclient.d.ts",
|
|
65
64
|
"skills",
|
|
66
65
|
"README.md",
|
|
67
66
|
"LICENSE"
|
|
@@ -77,11 +76,9 @@
|
|
|
77
76
|
"build:mcpb": "npm run build && node scripts/build-mcpb.mjs",
|
|
78
77
|
"version": "node scripts/sync-versions.mjs"
|
|
79
78
|
},
|
|
80
|
-
"dependencies": {
|
|
81
|
-
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
82
|
-
"zod": "^3.23.0"
|
|
83
|
-
},
|
|
84
79
|
"devDependencies": {
|
|
80
|
+
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
81
|
+
"zod": "^3.23.0",
|
|
85
82
|
"@types/node": "^22.0.0",
|
|
86
83
|
"esbuild": "^0.25.12",
|
|
87
84
|
"typescript": "^5.5.0"
|
|
@@ -20,18 +20,18 @@ You have two jobs when this skill triggers: (1) keep **this session's** context
|
|
|
20
20
|
|
|
21
21
|
Proactively (do not wait to be asked):
|
|
22
22
|
- Summarize large tool outputs right after consuming them.
|
|
23
|
-
-
|
|
23
|
+
- Once, when the session first passes roughly 30 turns or contains several large pastes, offer: "This conversation is getting heavy — want me to compact the older history into a summary so responses stay fast and cheap?"
|
|
24
24
|
- When asked to summarize/compact, produce a dense factual summary (decisions made, current state, open items, key identifiers) — not a narrative.
|
|
25
25
|
|
|
26
26
|
## Using the context-doctor tools
|
|
27
27
|
|
|
28
28
|
If the `context-doctor` MCP tools are available:
|
|
29
|
-
- `profile_context` — pass a conversation JSON (OpenAI or Anthropic format) or raw text; returns a token breakdown, largest messages, findings with estimated savings.
|
|
29
|
+
- `profile_context` — pass a conversation JSON (OpenAI or Anthropic format) or raw text; returns a token breakdown, largest messages, findings with estimated savings. In a chat app, where you cannot export the conversation, pass a `sketch` instead: the turn count plus the large, repeated or image blocks, one size hint each (~120 tokens to write).
|
|
30
30
|
- `optimize_context` — applies deterministic fixes (dedupe, trim stale tool results, strip base64; opt-in `trim-tool-calls` for big inline file writes and `prune-history`). When the result contains pruned-turn source material and asks for a summary, **you write that summary** (≤150 tokens, dense, factual) and place it where the stub indicates — this is how summarization works without any API key.
|
|
31
31
|
- `pack_context` — before reading a large document, log or folder to answer a question (not to edit it), pass `paths` and the `query`: it returns only the best-matching chunks within `max_tokens` (default 4000), each with an id and line range, plus the next-best ids. No query = an outline to pick from with `ids`.
|
|
32
32
|
- `context_best_practices` — provider-specific checklist to share with the user.
|
|
33
33
|
|
|
34
|
-
If the tools are not connected, the CLI does the same: `npx context-doctor analyze <file> --model <model>` and `npx context-doctor optimize <file>`, and `npx context-doctor pack <files> --query "<question>"` for big documents.
|
|
34
|
+
If the tools are not connected, the CLI does the same: `npx context-doctor analyze <file> --model <model>` and `npx context-doctor optimize <file>`, and `npx context-doctor pack <files> --query "<question>"` for big documents. `npx context-doctor session` profiles the user's latest Claude Code session from its transcript, with the API's own token counts, cache economics and subagent costs (`--list` to pick another). For the user's own API apps: `npx context-doctor proxy --autopilot`, then point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at it; it clears stale tool output only when the prompt cache is cold, so it never costs more.
|
|
35
35
|
|
|
36
36
|
## When the user pastes a conversation or asks about their token usage
|
|
37
37
|
|