context-doctor 0.35.1 → 0.37.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 +21 -14
- package/dist/ab.d.ts +188 -0
- package/dist/ab.js +857 -0
- package/dist/abtasks.d.ts +49 -0
- package/dist/abtasks.js +287 -0
- package/dist/cli.js +83 -8
- package/dist/compact.d.ts +36 -0
- package/dist/compact.js +144 -0
- package/dist/copilot.d.ts +63 -0
- package/dist/copilot.js +96 -0
- package/dist/doctor.js +114 -1
- package/dist/extract.d.ts +23 -0
- package/dist/extract.js +121 -4
- package/dist/fileparams.d.ts +61 -0
- package/dist/fileparams.js +308 -0
- package/dist/handoff.d.ts +143 -0
- package/dist/handoff.js +529 -0
- package/dist/hook.d.ts +1 -1
- package/dist/hook.js +25 -3
- package/dist/httpguard.d.ts +56 -0
- package/dist/httpguard.js +141 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +16 -0
- package/dist/install.js +176 -3
- package/dist/ledger.d.ts +6 -1
- package/dist/ledger.js +45 -7
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +72 -56
- package/dist/pack.d.ts +20 -0
- package/dist/pack.js +29 -1
- package/dist/preferences.d.ts +3 -1
- package/dist/preferences.js +8 -6
- package/dist/pricing.d.ts +7 -0
- package/dist/pricing.js +29 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/rules.d.ts +19 -0
- package/dist/rules.js +34 -0
- package/dist/sketch.d.ts +5 -1
- package/dist/sketch.js +23 -7
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +2 -0
package/dist/pack.d.ts
CHANGED
|
@@ -118,6 +118,15 @@ export interface ReadSourcesOptions {
|
|
|
118
118
|
includeSecrets?: boolean;
|
|
119
119
|
/** How the caller can opt in, appended to a "secret, skipped" note. */
|
|
120
120
|
secretsHint?: string;
|
|
121
|
+
/**
|
|
122
|
+
* Internal (readSourcesAsync): instead of extracting a PDF or office file
|
|
123
|
+
* on the spot, reserve its slot and list it here for asynchronous
|
|
124
|
+
* extraction under a time budget.
|
|
125
|
+
*/
|
|
126
|
+
defer?: Array<{
|
|
127
|
+
slot: number;
|
|
128
|
+
path: string;
|
|
129
|
+
}>;
|
|
121
130
|
}
|
|
122
131
|
/**
|
|
123
132
|
* Read files and directories (recursively, skipping build and dependency
|
|
@@ -138,3 +147,14 @@ export declare function readSources(paths: string[], cwdOrOptions?: string | Rea
|
|
|
138
147
|
sources: PackSource[];
|
|
139
148
|
skipped: string[];
|
|
140
149
|
};
|
|
150
|
+
/**
|
|
151
|
+
* readSources for a server: the same walk, with PDFs and office documents
|
|
152
|
+
* extracted asynchronously and all of them within one time budget, so a slow
|
|
153
|
+
* or hostile document neither blocks the event loop nor holds the call.
|
|
154
|
+
*/
|
|
155
|
+
export declare function readSourcesAsync(paths: string[], options?: Omit<ReadSourcesOptions, "defer"> & {
|
|
156
|
+
budgetMs?: number;
|
|
157
|
+
}): Promise<{
|
|
158
|
+
sources: PackSource[];
|
|
159
|
+
skipped: string[];
|
|
160
|
+
}>;
|
package/dist/pack.js
CHANGED
|
@@ -18,7 +18,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSyn
|
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { estimateTokens, formatTokens } from "./tokens.js";
|
|
21
|
-
import { EXTRACTABLE, extractText } from "./extract.js";
|
|
21
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync } from "./extract.js";
|
|
22
22
|
const DEFAULT_BUDGET = 4000;
|
|
23
23
|
const DEFAULT_CHUNK_TOKENS = 400;
|
|
24
24
|
/** Claude's tokenizer produces the most tokens per char; a budget in its terms never overruns another's. */
|
|
@@ -590,6 +590,13 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
590
590
|
const rel = relative(cwd, p);
|
|
591
591
|
const name = rel && !rel.startsWith("..") ? rel : p;
|
|
592
592
|
if (EXTRACTABLE.has(extname(p).toLowerCase())) {
|
|
593
|
+
if (options.defer) {
|
|
594
|
+
bytes += st.size;
|
|
595
|
+
seen.add(real);
|
|
596
|
+
sources.push({ name, text: "" });
|
|
597
|
+
options.defer.push({ slot: sources.length - 1, path: p });
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
593
600
|
const got = extractText(p);
|
|
594
601
|
if ("error" in got)
|
|
595
602
|
skipped.push(`${p}: ${got.error}`);
|
|
@@ -631,3 +638,24 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
631
638
|
}
|
|
632
639
|
return { sources, skipped };
|
|
633
640
|
}
|
|
641
|
+
/**
|
|
642
|
+
* readSources for a server: the same walk, with PDFs and office documents
|
|
643
|
+
* extracted asynchronously and all of them within one time budget, so a slow
|
|
644
|
+
* or hostile document neither blocks the event loop nor holds the call.
|
|
645
|
+
*/
|
|
646
|
+
export async function readSourcesAsync(paths, options = {}) {
|
|
647
|
+
const defer = [];
|
|
648
|
+
const { sources, skipped } = readSources(paths, { ...options, defer });
|
|
649
|
+
const deadline = Date.now() + (options.budgetMs ?? EXTRACT_BUDGET_MS);
|
|
650
|
+
const failed = new Set();
|
|
651
|
+
for (const d of defer) {
|
|
652
|
+
const got = await extractTextAsync(d.path, deadline);
|
|
653
|
+
if ("error" in got) {
|
|
654
|
+
skipped.push(`${d.path}: ${got.error}`);
|
|
655
|
+
failed.add(d.slot);
|
|
656
|
+
}
|
|
657
|
+
else
|
|
658
|
+
sources[d.slot].text = got.text;
|
|
659
|
+
}
|
|
660
|
+
return { sources: sources.filter((_, i) => !failed.has(i)), skipped };
|
|
661
|
+
}
|
package/dist/preferences.d.ts
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
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 (~190 Claude tokens, ~125 GPT): it rides in every conversation.
|
|
8
|
+
* The handoff is the one real cut a chat app allows: its history cannot be
|
|
9
|
+
* edited, so a long chat continues in a new one from a short brief.
|
|
8
10
|
*/
|
|
9
11
|
export declare const CHAT_PREFERENCES: string;
|
|
10
12
|
/** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
|
package/dist/preferences.js
CHANGED
|
@@ -4,15 +4,17 @@
|
|
|
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 (~190 Claude tokens, ~125 GPT): it rides in every conversation.
|
|
8
|
+
* The handoff is the one real cut a chat app allows: its history cannot be
|
|
9
|
+
* edited, so a long chat continues in a new one from a short brief.
|
|
8
10
|
*/
|
|
9
11
|
import { spawnSync } from "node:child_process";
|
|
10
12
|
export const CHAT_PREFERENCES = [
|
|
11
|
-
"Context hygiene:
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
13
|
+
"Context hygiene: summarize anything long I paste into the points you will use; refer to it by name, never re-quote it,",
|
|
14
|
+
"never inline base64. When I ask about tokens, limits, cost or speed, and once past ~30 turns: if profile_context exists,",
|
|
15
|
+
"call it with a sketch and act on its top finding. When a chat grows long, offer a handoff once (its history cannot",
|
|
16
|
+
"be trimmed): a 400-token brief of goal, decisions, state and open items, plus what must stay exact, saved with",
|
|
17
|
+
"save_handoff if it exists, to start a new chat.",
|
|
16
18
|
].join(" ");
|
|
17
19
|
/** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
|
|
18
20
|
export const PREFERENCE_TARGETS = [
|
package/dist/pricing.d.ts
CHANGED
|
@@ -19,6 +19,13 @@ export interface ModelPricing {
|
|
|
19
19
|
export declare const CACHE_WRITE_5M = 1.25;
|
|
20
20
|
export declare const CACHE_WRITE_1H = 2;
|
|
21
21
|
export declare function pricingFor(model?: string): ModelPricing | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* A Claude model's price from a row for its own version, not a family
|
|
24
|
+
* fallback: what a command that caps spending needs (`ab --budget`). An id
|
|
25
|
+
* the table only knows by family (a new release, a typo like
|
|
26
|
+
* claude-opus-9) gets undefined.
|
|
27
|
+
*/
|
|
28
|
+
export declare function exactClaudePricingFor(model?: string): ModelPricing | undefined;
|
|
22
29
|
export declare function inputCostUsd(tokens: number, pricing: ModelPricing): number;
|
|
23
30
|
/** `usage` as the API returns it and Claude Code records it on each reply. */
|
|
24
31
|
export interface RecordedUsage {
|
package/dist/pricing.js
CHANGED
|
@@ -23,6 +23,8 @@ function claude(families, major, minor) {
|
|
|
23
23
|
? new RegExp(`claude-(?:${families})-${major}(?![.\\d]|-\\d{1,2}(?!\\d))`, "i")
|
|
24
24
|
: new RegExp(`claude-(?:${families})-${major}[-.]${minor}(?!\\d)`, "i");
|
|
25
25
|
}
|
|
26
|
+
/** The Claude family fallbacks: a price for ids the table does not know by version yet. */
|
|
27
|
+
const CLAUDE_FAMILY = [/claude.*fable|claude.*mythos/i, /claude.*opus/i, /claude.*sonnet/i, /claude.*haiku/i];
|
|
26
28
|
const PRICING = [
|
|
27
29
|
// Specific Claude versions first: the family rows below are only a
|
|
28
30
|
// fallback for ids this table does not know yet.
|
|
@@ -45,11 +47,17 @@ const PRICING = [
|
|
|
45
47
|
[claude("haiku", 4, 5), rate(1, 5, 0.1)],
|
|
46
48
|
[/claude-3-5-haiku/i, rate(0.8, 4, 0.08)],
|
|
47
49
|
[/claude-3-haiku/i, rate(0.25, 1.25, 0.03)],
|
|
48
|
-
// Sonnet 4.6, 4.5, 4 and the 3.x Sonnets are all $3 / $15 / $0.30
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
[
|
|
52
|
-
[
|
|
50
|
+
// Sonnet 4.6, 4.5, 4 and the 3.x Sonnets are all $3 / $15 / $0.30, the
|
|
51
|
+
// family row's price; rows of their own so a spending cap can tell a known
|
|
52
|
+
// version from a guess (exactClaudePricingFor).
|
|
53
|
+
[claude("sonnet", 4, 6), rate(3, 15, 0.3)],
|
|
54
|
+
[claude("sonnet", 4, 5), rate(3, 15, 0.3)],
|
|
55
|
+
[claude("sonnet", 4), rate(3, 15, 0.3)],
|
|
56
|
+
[/claude-3-[57]-sonnet/i, rate(3, 15, 0.3)],
|
|
57
|
+
[CLAUDE_FAMILY[0], rate(10, 50, 1)],
|
|
58
|
+
[CLAUDE_FAMILY[1], rate(5, 25, 0.5)],
|
|
59
|
+
[CLAUDE_FAMILY[2], rate(3, 15, 0.3)],
|
|
60
|
+
[CLAUDE_FAMILY[3], rate(1, 5, 0.1)],
|
|
53
61
|
[/gpt-5.*(mini|nano)/i, { inputPerM: 0.25, outputPerM: 2, cacheReadPerM: 0.025 }],
|
|
54
62
|
[/gpt-5/i, { inputPerM: 1.25, outputPerM: 10, cacheReadPerM: 0.125 }],
|
|
55
63
|
[/gpt-4o-mini/i, { inputPerM: 0.15, outputPerM: 0.6, cacheReadPerM: 0.075 }],
|
|
@@ -76,6 +84,22 @@ export function pricingFor(model) {
|
|
|
76
84
|
}
|
|
77
85
|
return undefined;
|
|
78
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* A Claude model's price from a row for its own version, not a family
|
|
89
|
+
* fallback: what a command that caps spending needs (`ab --budget`). An id
|
|
90
|
+
* the table only knows by family (a new release, a typo like
|
|
91
|
+
* claude-opus-9) gets undefined.
|
|
92
|
+
*/
|
|
93
|
+
export function exactClaudePricingFor(model) {
|
|
94
|
+
if (!model || !/claude/i.test(model))
|
|
95
|
+
return undefined;
|
|
96
|
+
for (const [pattern, pricing] of PRICING) {
|
|
97
|
+
if (!pattern.test(model))
|
|
98
|
+
continue;
|
|
99
|
+
return CLAUDE_FAMILY.includes(pattern) ? undefined : pricing;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
79
103
|
export function inputCostUsd(tokens, pricing) {
|
|
80
104
|
return (tokens / 1_000_000) * pricing.inputPerM;
|
|
81
105
|
}
|
package/dist/proxy.d.ts
CHANGED
|
@@ -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.37.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
|
package/dist/proxy.js
CHANGED
|
@@ -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.37.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"]);
|
package/dist/rules.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standing context rules: the one text every surface without a hook of
|
|
3
|
+
* its own gets. The MCP server sends it as its `instructions` (Claude
|
|
4
|
+
* Desktop, Cursor, ChatGPT and any MCP client that passes them on), and the
|
|
5
|
+
* GitHub Copilot sessionStart hook adds it as context, since the Copilot CLI
|
|
6
|
+
* includes only some MCP servers' instructions unless started with
|
|
7
|
+
* --allow-all-mcp-server-instructions. Kept in a module of its own so both
|
|
8
|
+
* read the same words and neither pulls in the other's dependencies.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* The standing rules every chat gets. ChatGPT's MCP guide says to keep the
|
|
12
|
+
* most important details in the first 512 characters, so rules 1-4 (when to
|
|
13
|
+
* measure, the handoff, and the two habits) end exactly at character 512: a
|
|
14
|
+
* client that keeps only that much gets whole rules, none cut mid-sentence
|
|
15
|
+
* (mcp-http.test.ts pins the boundary). The two that need a particular tool
|
|
16
|
+
* come after. Rule 2 is the only real cut a chat app allows: its history
|
|
17
|
+
* cannot be edited, so a long chat moves to a new one (save_handoff).
|
|
18
|
+
*/
|
|
19
|
+
export declare const SERVER_INSTRUCTIONS = "Context hygiene rules (always on):\n1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a `sketch`. Act on its top finding. Do not estimate token counts yourself.\n2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.\n3. Summarize any paste or tool result over ~2k tokens into the points you need.\n4. Refer to earlier content by name; never re-quote it or inline base64.\n5. For a big file you won't edit, call pack_context with the question; don't read it whole.\n6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.";
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standing context rules: the one text every surface without a hook of
|
|
3
|
+
* its own gets. The MCP server sends it as its `instructions` (Claude
|
|
4
|
+
* Desktop, Cursor, ChatGPT and any MCP client that passes them on), and the
|
|
5
|
+
* GitHub Copilot sessionStart hook adds it as context, since the Copilot CLI
|
|
6
|
+
* includes only some MCP servers' instructions unless started with
|
|
7
|
+
* --allow-all-mcp-server-instructions. Kept in a module of its own so both
|
|
8
|
+
* read the same words and neither pulls in the other's dependencies.
|
|
9
|
+
*/
|
|
10
|
+
// Kept deliberately terse: these ride in EVERY conversation's context, and a
|
|
11
|
+
// context-saving tool must not itself be context overhead (~250 Claude tokens).
|
|
12
|
+
//
|
|
13
|
+
// Written as conditions and actions, not offers. On Claude Desktop this string
|
|
14
|
+
// is the only channel that reaches the model without the user asking — MCP has
|
|
15
|
+
// no hook and no data path there — so "offer to run" leaves it to a model that
|
|
16
|
+
// will usually not, while "when X, call Y before answering" is followed. The
|
|
17
|
+
// thresholds keep it from firing on every turn, which would cost more context
|
|
18
|
+
// than it saves.
|
|
19
|
+
/**
|
|
20
|
+
* The standing rules every chat gets. ChatGPT's MCP guide says to keep the
|
|
21
|
+
* most important details in the first 512 characters, so rules 1-4 (when to
|
|
22
|
+
* measure, the handoff, and the two habits) end exactly at character 512: a
|
|
23
|
+
* client that keeps only that much gets whole rules, none cut mid-sentence
|
|
24
|
+
* (mcp-http.test.ts pins the boundary). The two that need a particular tool
|
|
25
|
+
* come after. Rule 2 is the only real cut a chat app allows: its history
|
|
26
|
+
* cannot be edited, so a long chat moves to a new one (save_handoff).
|
|
27
|
+
*/
|
|
28
|
+
export const SERVER_INSTRUCTIONS = `Context hygiene rules (always on):
|
|
29
|
+
1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a \`sketch\`. Act on its top finding. Do not estimate token counts yourself.
|
|
30
|
+
2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
|
|
31
|
+
3. Summarize any paste or tool result over ~2k tokens into the points you need.
|
|
32
|
+
4. Refer to earlier content by name; never re-quote it or inline base64.
|
|
33
|
+
5. For a big file you won't edit, call pack_context with the question; don't read it whole.
|
|
34
|
+
6. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.`;
|
package/dist/sketch.d.ts
CHANGED
|
@@ -61,5 +61,9 @@ export declare function exchangeTokens(model?: string): number;
|
|
|
61
61
|
export declare const MAX_LABEL_CHARS = 60;
|
|
62
62
|
export declare function profileSketch(sketch: ConversationSketch): SketchProfile;
|
|
63
63
|
export declare function renderSketchProfile(p: SketchProfile): string;
|
|
64
|
-
/** Profile a sketch
|
|
64
|
+
/** Profile a sketch and log it to the ledger like a hook check (unless `record` is false: the HTTP server). */
|
|
65
|
+
export declare function runSketchProfile(sketch: ConversationSketch, { record }?: {
|
|
66
|
+
record?: boolean;
|
|
67
|
+
}): SketchProfile;
|
|
68
|
+
/** Profile a sketch, log it, and render. */
|
|
65
69
|
export declare function runSketch(sketch: ConversationSketch): string;
|
package/dist/sketch.js
CHANGED
|
@@ -43,7 +43,10 @@ const DEFAULT_CHARS = {
|
|
|
43
43
|
const IMAGE_TOKENS = 1500;
|
|
44
44
|
const LARGE_BLOCK_TOKENS = 2000;
|
|
45
45
|
const LONG_HISTORY_TURNS = 30;
|
|
46
|
-
|
|
46
|
+
// The handoff brief's target size (save_handoff, the `handoff` prompt).
|
|
47
|
+
const HANDOFF_SUMMARY_TOKENS = 400;
|
|
48
|
+
// Below this, a new chat is not worth the user's trouble.
|
|
49
|
+
const HANDOFF_WORTH_TOKENS = 10_000;
|
|
47
50
|
const RECENT_TURNS_KEPT = 6;
|
|
48
51
|
/** Code, tool output and base64 tokenize at the code ratio; pastes and text at the prose ratio. */
|
|
49
52
|
function ratioFor(kind, model) {
|
|
@@ -137,7 +140,7 @@ export function profileSketch(sketch) {
|
|
|
137
140
|
severity: totalTokens > 100_000 ? "high" : "warn",
|
|
138
141
|
estSavings: Math.max(0, totalTokens - afterHandoff),
|
|
139
142
|
message: `${turns} turns: every new message re-reads ~${formatTokens(totalTokens)}.`,
|
|
140
|
-
action: `Offer a handoff: write a ≤${HANDOFF_SUMMARY_TOKENS}-token
|
|
143
|
+
action: `Offer a handoff once: with the user's agreement, write a ≤${HANDOFF_SUMMARY_TOKENS}-token brief (goal, decisions, current state, open items, key identifiers) and call save_handoff, or the user picks the \`handoff\` prompt. A new chat re-reads ~${formatTokens(afterHandoff)} of conversation instead, plus the app's own system prompt, which every chat carries.`,
|
|
141
144
|
});
|
|
142
145
|
}
|
|
143
146
|
const contextWindow = contextWindowFor(sketch.model);
|
|
@@ -182,21 +185,34 @@ export function renderSketchProfile(p) {
|
|
|
182
185
|
return lines.join("\n");
|
|
183
186
|
}
|
|
184
187
|
lines.push("");
|
|
185
|
-
|
|
188
|
+
// A chat app's history cannot be edited: summarizing a block stops it being
|
|
189
|
+
// quoted again, but the block is still re-read on every turn. Saying
|
|
190
|
+
// "recoverable" without that sent models to promise savings that never came.
|
|
191
|
+
lines.push(`Findings (recoverable ~${formatTokens(p.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`);
|
|
186
192
|
p.findings.forEach((f, i) => {
|
|
187
193
|
const save = f.estSavings > 0 ? ` [~${formatTokens(f.estSavings)}]` : "";
|
|
188
194
|
lines.push(`${i + 1}. ${f.severity.toUpperCase()}${save} ${f.message}`);
|
|
189
195
|
lines.push(` → ${f.action}`);
|
|
190
196
|
});
|
|
191
197
|
lines.push("");
|
|
192
|
-
lines.push("Act on #1 in your reply (do it, do not just suggest it)
|
|
198
|
+
lines.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat.");
|
|
199
|
+
const handoffOffered = p.findings.some((f) => f.id === "long_history");
|
|
200
|
+
if (!handoffOffered && p.totalEstSavings >= HANDOFF_WORTH_TOKENS) {
|
|
201
|
+
lines.push(`To recover the ~${formatTokens(p.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a ≤${HANDOFF_SUMMARY_TOKENS}-token brief plus the blocks that must stay exact); a new chat starts from that.`);
|
|
202
|
+
}
|
|
193
203
|
return lines.join("\n");
|
|
194
204
|
}
|
|
195
|
-
/** Profile a sketch
|
|
196
|
-
export function
|
|
205
|
+
/** Profile a sketch and log it to the ledger like a hook check (unless `record` is false: the HTTP server). */
|
|
206
|
+
export function runSketchProfile(sketch, { record = true } = {}) {
|
|
197
207
|
const profile = profileSketch(sketch);
|
|
208
|
+
if (!record)
|
|
209
|
+
return profile;
|
|
198
210
|
// No session id: each sketch describes a different chat, and a shared id made
|
|
199
211
|
// the dashboard read "big sketch, then a smaller one" as tokens saved.
|
|
200
212
|
recordLedger({ ev: "check", src: "mcp", tok: profile.totalTokens, warn: profile.findings.some((f) => f.severity !== "info"), model: sketch.model });
|
|
201
|
-
return
|
|
213
|
+
return profile;
|
|
214
|
+
}
|
|
215
|
+
/** Profile a sketch, log it, and render. */
|
|
216
|
+
export function runSketch(sketch) {
|
|
217
|
+
return renderSketchProfile(runSketchProfile(sketch));
|
|
202
218
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
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",
|
|
@@ -22,11 +22,13 @@ 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
|
+
- In a chat app (claude.ai, Claude Desktop, ChatGPT) the history cannot be edited: a summary stops further re-quoting, but the old turns are still re-read on every turn. The real cut is a new chat, so offer a **handoff** once instead: a ≤400-token brief (goal, decisions, current state, open items, key identifiers) plus only the blocks that must stay exact, saved with `save_handoff` when it is available, for the user to start a new chat from.
|
|
25
26
|
|
|
26
27
|
## Using the context-doctor tools
|
|
27
28
|
|
|
28
29
|
If the `context-doctor` MCP tools are available:
|
|
29
30
|
- `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).
|
|
31
|
+
- `save_handoff` — stores the handoff brief you wrote and the exact blocks, masks secret-looking strings, and returns the per-turn saving and how to continue (attach `handoff://latest` in a new chat, or paste it). Call it only when the user agrees.
|
|
30
32
|
- `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
33
|
- `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
34
|
- `context_best_practices` — provider-specific checklist to share with the user.
|