context-doctor 0.33.0 → 0.35.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 +13 -10
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- package/dist/autopilot.d.ts +0 -6
- package/dist/autopilot.js +37 -2
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +30 -10
- package/dist/cacheplan.js +157 -32
- package/dist/cli.js +68 -19
- 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 +2 -0
- package/dist/compactquality.js +21 -3
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +133 -10
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +58 -8
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +148 -45
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +56 -53
- package/dist/modelswitch.d.ts +76 -0
- package/dist/modelswitch.js +184 -0
- package/dist/optimize.js +40 -6
- package/dist/pack.d.ts +32 -3
- package/dist/pack.js +176 -24
- package/dist/parse.d.ts +3 -1
- package/dist/parse.js +123 -3
- package/dist/pricing.js +8 -0
- package/dist/profile.js +60 -17
- package/dist/proxy.d.ts +22 -1
- package/dist/proxy.js +89 -12
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +15 -2
- package/dist/savings.js +9 -11
- package/dist/session.js +19 -3
- package/dist/sketch.d.ts +2 -0
- package/dist/sketch.js +10 -1
- package/dist/tokens.js +20 -9
- package/dist/wrap.js +27 -5
- package/package.json +1 -1
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cost of a model switch, said before it happens.
|
|
3
|
+
*
|
|
4
|
+
* Each model has its own prompt cache. Switching models mid-session (/model,
|
|
5
|
+
* the picker, Option+P, an SDK's set_model) sends the whole context to the new
|
|
6
|
+
* model, which writes all of it to its cache at 1.25x input (2x at the 1-hour
|
|
7
|
+
* TTL), where the next request on the old model would have read it at
|
|
8
|
+
* 5-10%. On a 600k-token session that is dollars per switch; `cache-misses`
|
|
9
|
+
* finds them in the transcripts after the fact (8 of the 390 misses on the
|
|
10
|
+
* author's history).
|
|
11
|
+
*
|
|
12
|
+
* Claude Code 2.1.251 and later run PreModelSwitch hooks before a switch
|
|
13
|
+
* (verified in the 2.1.295 and 2.1.299 binaries and the hooks docs). Input:
|
|
14
|
+
* session_id, transcript_path, cwd, hook_event_name, from_model, to_model,
|
|
15
|
+
* requested_model, source ("command", "picker" or "sdk"), context_tokens,
|
|
16
|
+
* prompt_cache_warm, cache_ttl ("5m" or "1h"), estimated_cache_write_usd and
|
|
17
|
+
* pricing. A `systemMessage` in the output is shown to the user whether the
|
|
18
|
+
* switch goes ahead or not; `permissionDecision` deny/ask, `decision: "block"`
|
|
19
|
+
* or exit code 2 would stop it, and so does a hook that times out or crashes.
|
|
20
|
+
* This hook only ever answers with a systemMessage and exit 0: it informs,
|
|
21
|
+
* it never blocks, and it does no more than read the transcript's tail.
|
|
22
|
+
*
|
|
23
|
+
* Installing it has a trap, measured: Claude Code before 2.1.251 validates
|
|
24
|
+
* ~/.claude/settings.json's hooks against the events it knows, and a file
|
|
25
|
+
* with an unknown event is skipped ENTIRELY ("Files with errors are skipped
|
|
26
|
+
* entirely, not just the invalid settings"): with a PreModelSwitch entry,
|
|
27
|
+
* 2.1.62 ran none of the user's settings, hooks included. A plugin's inline
|
|
28
|
+
* hooks fail the same way, while a plugin's separate hooks/hooks.json is
|
|
29
|
+
* dropped alone. So `install` writes the hook only when every Claude Code it
|
|
30
|
+
* can find on the machine is 2.1.251 or later, and the plugin carries it in a
|
|
31
|
+
* file of its own.
|
|
32
|
+
*/
|
|
33
|
+
/** The first Claude Code that runs PreModelSwitch hooks (hooks docs). */
|
|
34
|
+
export declare const PRE_MODEL_SWITCH_SINCE = "2.1.251";
|
|
35
|
+
export interface ModelSwitchInput {
|
|
36
|
+
transcript_path?: string;
|
|
37
|
+
from_model?: unknown;
|
|
38
|
+
to_model?: unknown;
|
|
39
|
+
context_tokens?: unknown;
|
|
40
|
+
prompt_cache_warm?: unknown;
|
|
41
|
+
cache_ttl?: unknown;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* What switching costs, in one or two lines for the user, or undefined when
|
|
45
|
+
* there is nothing worth saying: the cache is already cold (staying would
|
|
46
|
+
* re-write it too), no real switch, or a small context.
|
|
47
|
+
*/
|
|
48
|
+
export declare function modelSwitchMessage(input: ModelSwitchInput): string | undefined;
|
|
49
|
+
export interface ClaudeCodeInstall {
|
|
50
|
+
path: string;
|
|
51
|
+
version: string;
|
|
52
|
+
/** Where it was found: a CLI on PATH or a known install location, or the desktop app's bundled Claude Code. */
|
|
53
|
+
source: "cli" | "desktop app";
|
|
54
|
+
}
|
|
55
|
+
/** Compare dotted versions numerically: -1, 0 or 1. */
|
|
56
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
57
|
+
/**
|
|
58
|
+
* Every Claude Code this machine has that reads ~/.claude/settings.json: the
|
|
59
|
+
* CLIs on PATH and in the usual install places, and the newest Claude Code
|
|
60
|
+
* the desktop app has downloaded (the app runs the newest).
|
|
61
|
+
*/
|
|
62
|
+
export declare function claudeCodeInstalls(opts?: {
|
|
63
|
+
home?: string;
|
|
64
|
+
pathEnv?: string;
|
|
65
|
+
runVersion?: boolean;
|
|
66
|
+
}): ClaudeCodeInstall[];
|
|
67
|
+
export interface ModelSwitchReadiness {
|
|
68
|
+
/** Safe to put a PreModelSwitch hook in ~/.claude/settings.json. */
|
|
69
|
+
ok: boolean;
|
|
70
|
+
/** Claude Code versions found that predate the event (and would skip the whole file). */
|
|
71
|
+
old: ClaudeCodeInstall[];
|
|
72
|
+
installs: ClaudeCodeInstall[];
|
|
73
|
+
}
|
|
74
|
+
export declare function modelSwitchReadiness(installs?: ClaudeCodeInstall[]): ModelSwitchReadiness;
|
|
75
|
+
/** "Claude Code 2.1.62 (/opt/homebrew/bin/claude)" for messages. */
|
|
76
|
+
export declare function describeInstalls(list: ClaudeCodeInstall[]): string;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cost of a model switch, said before it happens.
|
|
3
|
+
*
|
|
4
|
+
* Each model has its own prompt cache. Switching models mid-session (/model,
|
|
5
|
+
* the picker, Option+P, an SDK's set_model) sends the whole context to the new
|
|
6
|
+
* model, which writes all of it to its cache at 1.25x input (2x at the 1-hour
|
|
7
|
+
* TTL), where the next request on the old model would have read it at
|
|
8
|
+
* 5-10%. On a 600k-token session that is dollars per switch; `cache-misses`
|
|
9
|
+
* finds them in the transcripts after the fact (8 of the 390 misses on the
|
|
10
|
+
* author's history).
|
|
11
|
+
*
|
|
12
|
+
* Claude Code 2.1.251 and later run PreModelSwitch hooks before a switch
|
|
13
|
+
* (verified in the 2.1.295 and 2.1.299 binaries and the hooks docs). Input:
|
|
14
|
+
* session_id, transcript_path, cwd, hook_event_name, from_model, to_model,
|
|
15
|
+
* requested_model, source ("command", "picker" or "sdk"), context_tokens,
|
|
16
|
+
* prompt_cache_warm, cache_ttl ("5m" or "1h"), estimated_cache_write_usd and
|
|
17
|
+
* pricing. A `systemMessage` in the output is shown to the user whether the
|
|
18
|
+
* switch goes ahead or not; `permissionDecision` deny/ask, `decision: "block"`
|
|
19
|
+
* or exit code 2 would stop it, and so does a hook that times out or crashes.
|
|
20
|
+
* This hook only ever answers with a systemMessage and exit 0: it informs,
|
|
21
|
+
* it never blocks, and it does no more than read the transcript's tail.
|
|
22
|
+
*
|
|
23
|
+
* Installing it has a trap, measured: Claude Code before 2.1.251 validates
|
|
24
|
+
* ~/.claude/settings.json's hooks against the events it knows, and a file
|
|
25
|
+
* with an unknown event is skipped ENTIRELY ("Files with errors are skipped
|
|
26
|
+
* entirely, not just the invalid settings"): with a PreModelSwitch entry,
|
|
27
|
+
* 2.1.62 ran none of the user's settings, hooks included. A plugin's inline
|
|
28
|
+
* hooks fail the same way, while a plugin's separate hooks/hooks.json is
|
|
29
|
+
* dropped alone. So `install` writes the hook only when every Claude Code it
|
|
30
|
+
* can find on the machine is 2.1.251 or later, and the plugin carries it in a
|
|
31
|
+
* file of its own.
|
|
32
|
+
*/
|
|
33
|
+
import { spawnSync } from "node:child_process";
|
|
34
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
35
|
+
import { homedir } from "node:os";
|
|
36
|
+
import { delimiter, dirname, join } from "node:path";
|
|
37
|
+
import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, pricingFor } from "./pricing.js";
|
|
38
|
+
import { formatTokens } from "./tokens.js";
|
|
39
|
+
import { tailUsage } from "./statusline.js";
|
|
40
|
+
/** The first Claude Code that runs PreModelSwitch hooks (hooks docs). */
|
|
41
|
+
export const PRE_MODEL_SWITCH_SINCE = "2.1.251";
|
|
42
|
+
/** Below this context a switch costs pennies: nothing worth interrupting for. */
|
|
43
|
+
const MIN_CONTEXT = 20_000;
|
|
44
|
+
/** Strip Claude Code's context-size tag: "claude-opus-5-5[1m]" is priced as claude-opus-5-5. */
|
|
45
|
+
const bare = (model) => model.replace(/\[\d+m\]$/i, "");
|
|
46
|
+
/**
|
|
47
|
+
* What switching costs, in one or two lines for the user, or undefined when
|
|
48
|
+
* there is nothing worth saying: the cache is already cold (staying would
|
|
49
|
+
* re-write it too), no real switch, or a small context.
|
|
50
|
+
*/
|
|
51
|
+
export function modelSwitchMessage(input) {
|
|
52
|
+
const to = typeof input.to_model === "string" && input.to_model ? input.to_model : undefined;
|
|
53
|
+
const from = typeof input.from_model === "string" && input.from_model ? input.from_model : undefined;
|
|
54
|
+
if (!to || (from && bare(from) === bare(to)))
|
|
55
|
+
return undefined;
|
|
56
|
+
if (input.prompt_cache_warm === false)
|
|
57
|
+
return undefined;
|
|
58
|
+
// The transcript's last reply measured the context as the API billed it;
|
|
59
|
+
// Claude Code's own estimate stands in before the first reply.
|
|
60
|
+
const live = input.transcript_path ? tailUsage(input.transcript_path) : undefined;
|
|
61
|
+
const tokens = live?.tokens ?? (typeof input.context_tokens === "number" && Number.isFinite(input.context_tokens) ? input.context_tokens : 0);
|
|
62
|
+
if (tokens < MIN_CONTEXT)
|
|
63
|
+
return undefined;
|
|
64
|
+
const oneHour = input.cache_ttl === "1h";
|
|
65
|
+
const writeMult = oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M;
|
|
66
|
+
const toPrice = pricingFor(bare(to));
|
|
67
|
+
const fromPrice = from ? pricingFor(bare(from)) : undefined;
|
|
68
|
+
const size = `~${formatTokens(tokens)}-token`;
|
|
69
|
+
if (!toPrice) {
|
|
70
|
+
return `context-doctor: switching to ${to} writes this session's ${size} context into its own cache once (no known price for ${to}); the next request on ${from ?? "the current model"} would read it from cache instead.`;
|
|
71
|
+
}
|
|
72
|
+
const writeUsd = (tokens / 1e6) * toPrice.inputPerM * writeMult;
|
|
73
|
+
const stay = fromPrice ? `, where the next request on ${from} would read it for ${formatUsd((tokens / 1e6) * fromPrice.cacheReadPerM)}` : "";
|
|
74
|
+
return (`context-doctor: switching to ${to} re-writes this session's ${size} context into its cache: ` +
|
|
75
|
+
`about ${formatUsd(writeUsd)} once at the ${oneHour ? "1-hour" : "5-minute"} cache-write rate${stay}. ` +
|
|
76
|
+
`Switching back later costs the same again; /compact first makes it cheaper.`);
|
|
77
|
+
}
|
|
78
|
+
/** Compare dotted versions numerically: -1, 0 or 1. */
|
|
79
|
+
export function compareVersions(a, b) {
|
|
80
|
+
const pa = a.split(".").map((x) => parseInt(x, 10) || 0);
|
|
81
|
+
const pb = b.split(".").map((x) => parseInt(x, 10) || 0);
|
|
82
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
83
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
84
|
+
if (d !== 0)
|
|
85
|
+
return d < 0 ? -1 : 1;
|
|
86
|
+
}
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
|
89
|
+
const VERSION = /(\d+\.\d+\.\d+)/;
|
|
90
|
+
/** A CLI binary's version: from its install path when it carries one, else its package.json, else `--version`. */
|
|
91
|
+
function cliVersion(bin, run) {
|
|
92
|
+
let real = bin;
|
|
93
|
+
try {
|
|
94
|
+
real = realpathSync(bin);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
/* keep the given path */
|
|
98
|
+
}
|
|
99
|
+
// Homebrew's cask (…/Caskroom/claude-code/2.1.62/claude) and the native
|
|
100
|
+
// installer (~/.local/share/claude/versions/2.1.299) keep the version in the path.
|
|
101
|
+
const inPath = /(?:claude-code|claude[\\/]versions)[\\/](\d+\.\d+\.\d+)/.exec(real);
|
|
102
|
+
if (inPath)
|
|
103
|
+
return inPath[1];
|
|
104
|
+
// An npm global install: …/node_modules/@anthropic-ai/claude-code/cli.js.
|
|
105
|
+
for (let dir = dirname(real), i = 0; i < 3; i++, dir = dirname(dir)) {
|
|
106
|
+
const pkg = join(dir, "package.json");
|
|
107
|
+
if (!existsSync(pkg))
|
|
108
|
+
continue;
|
|
109
|
+
try {
|
|
110
|
+
const p = JSON.parse(readFileSync(pkg, "utf8"));
|
|
111
|
+
if (p.name === "@anthropic-ai/claude-code" && typeof p.version === "string")
|
|
112
|
+
return p.version;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
/* not it */
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!run)
|
|
119
|
+
return undefined;
|
|
120
|
+
try {
|
|
121
|
+
const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 10_000, env: { ...process.env, CLAUDECODE: "" }, shell: process.platform === "win32" });
|
|
122
|
+
return VERSION.exec(String(r.stdout ?? ""))?.[1];
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Every Claude Code this machine has that reads ~/.claude/settings.json: the
|
|
130
|
+
* CLIs on PATH and in the usual install places, and the newest Claude Code
|
|
131
|
+
* the desktop app has downloaded (the app runs the newest).
|
|
132
|
+
*/
|
|
133
|
+
export function claudeCodeInstalls(opts = {}) {
|
|
134
|
+
const home = opts.home ?? homedir();
|
|
135
|
+
const out = [];
|
|
136
|
+
const seen = new Set();
|
|
137
|
+
const names = process.platform === "win32" ? ["claude.exe", "claude.cmd", "claude"] : ["claude"];
|
|
138
|
+
const candidates = [
|
|
139
|
+
...(opts.pathEnv ?? process.env.PATH ?? "").split(delimiter).filter(Boolean).flatMap((d) => names.map((n) => join(d, n))),
|
|
140
|
+
join(home, ".local", "bin", "claude"),
|
|
141
|
+
join(home, ".claude", "local", "claude"),
|
|
142
|
+
"/opt/homebrew/bin/claude",
|
|
143
|
+
"/usr/local/bin/claude",
|
|
144
|
+
];
|
|
145
|
+
for (const bin of candidates) {
|
|
146
|
+
let real;
|
|
147
|
+
try {
|
|
148
|
+
if (!statSync(bin).isFile())
|
|
149
|
+
continue;
|
|
150
|
+
real = realpathSync(bin);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (seen.has(real))
|
|
156
|
+
continue;
|
|
157
|
+
seen.add(real);
|
|
158
|
+
const version = cliVersion(bin, opts.runVersion !== false);
|
|
159
|
+
if (version)
|
|
160
|
+
out.push({ path: bin, version, source: "cli" });
|
|
161
|
+
}
|
|
162
|
+
// The desktop app keeps each Claude Code it downloads; it runs the newest.
|
|
163
|
+
for (const root of [join(home, "Library", "Application Support", "Claude", "claude-code"), join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude", "claude-code")]) {
|
|
164
|
+
let versions;
|
|
165
|
+
try {
|
|
166
|
+
versions = readdirSync(root).filter((v) => /^\d+\.\d+\.\d+$/.test(v));
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const newest = versions.sort(compareVersions).pop();
|
|
172
|
+
if (newest)
|
|
173
|
+
out.push({ path: join(root, newest), version: newest, source: "desktop app" });
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
export function modelSwitchReadiness(installs = claudeCodeInstalls()) {
|
|
178
|
+
const old = installs.filter((i) => compareVersions(i.version, PRE_MODEL_SWITCH_SINCE) < 0);
|
|
179
|
+
return { ok: installs.length > 0 && old.length === 0, old, installs };
|
|
180
|
+
}
|
|
181
|
+
/** "Claude Code 2.1.62 (/opt/homebrew/bin/claude)" for messages. */
|
|
182
|
+
export function describeInstalls(list) {
|
|
183
|
+
return list.map((i) => `Claude Code ${i.version} (${i.source === "desktop app" ? "desktop app" : i.path.replace(homedir(), "~")})`).join(", ");
|
|
184
|
+
}
|
package/dist/optimize.js
CHANGED
|
@@ -119,8 +119,10 @@ function hash(text) {
|
|
|
119
119
|
function textOf(content) {
|
|
120
120
|
if (typeof content === "string")
|
|
121
121
|
return content;
|
|
122
|
+
if (content == null)
|
|
123
|
+
return "";
|
|
122
124
|
if (!Array.isArray(content))
|
|
123
|
-
return JSON.stringify(content
|
|
125
|
+
return JSON.stringify(content);
|
|
124
126
|
return content
|
|
125
127
|
.map((b) => {
|
|
126
128
|
if (typeof b === "string")
|
|
@@ -266,6 +268,11 @@ export function optimizeConversation(input, options = {}) {
|
|
|
266
268
|
}
|
|
267
269
|
const messages = Array.isArray(data) ? data : data?.messages;
|
|
268
270
|
if (!Array.isArray(messages)) {
|
|
271
|
+
if (Array.isArray(data?.contents) || typeof data?.input === "string" || Array.isArray(data?.input)) {
|
|
272
|
+
// Profiled by analyze/profile_context; rewriting is for message arrays.
|
|
273
|
+
throw new Error(`optimize rewrites a \`messages\` array (Anthropic or OpenAI chat); this is ${Array.isArray(data?.contents) ? "a Gemini `contents`" : "an OpenAI Responses `input`"} request. ` +
|
|
274
|
+
"Profile it with analyze (or profile_context); the autopilot proxy slims these requests live.");
|
|
275
|
+
}
|
|
269
276
|
throw new Error("No `messages` array found in input");
|
|
270
277
|
}
|
|
271
278
|
// Null / non-object entries occur in truncated and hand-edited files; every
|
|
@@ -284,7 +291,29 @@ export function optimizeConversation(input, options = {}) {
|
|
|
284
291
|
(!Array.isArray(data) && typeof data?.model === "string" ? data.model : undefined) ??
|
|
285
292
|
(looksAnthropic ? "claude" : undefined);
|
|
286
293
|
const tok = (text) => estimateTokens(text, model);
|
|
287
|
-
|
|
294
|
+
// Everything the request carries, not just message content: OpenAI keeps a
|
|
295
|
+
// call's arguments in `tool_calls`, outside `content`. Left out, trimming
|
|
296
|
+
// them counted as saving nothing, so the proxy (which forwards a rewrite
|
|
297
|
+
// only when it saves) dropped the trimmed body and sent the original.
|
|
298
|
+
// The system prompt and tool definitions never change here; they count on
|
|
299
|
+
// both sides so the totals are the request's, not a subset's.
|
|
300
|
+
const fixed = Array.isArray(data)
|
|
301
|
+
? 0
|
|
302
|
+
: (data?.system != null ? tok(typeof data.system === "string" ? data.system : textOf(data.system)) : 0) +
|
|
303
|
+
(data?.tools != null ? tok(JSON.stringify(data.tools)) : 0);
|
|
304
|
+
const messageTokens = (m) => {
|
|
305
|
+
let n = tok(textOf(m.content));
|
|
306
|
+
for (const tc of Array.isArray(m.tool_calls) ? m.tool_calls : []) {
|
|
307
|
+
const fn = tc?.function;
|
|
308
|
+
if (!fn)
|
|
309
|
+
continue;
|
|
310
|
+
n += tok(`${fn.name ?? ""} ${typeof fn.arguments === "string" ? fn.arguments : JSON.stringify(fn.arguments ?? {})}`);
|
|
311
|
+
}
|
|
312
|
+
if (m.function_call)
|
|
313
|
+
n += tok(`${m.function_call.name ?? ""} ${m.function_call.arguments ?? ""}`);
|
|
314
|
+
return n;
|
|
315
|
+
};
|
|
316
|
+
const tokensBefore = fixed + messages.reduce((s, m) => s + messageTokens(m), 0);
|
|
288
317
|
const applied = [];
|
|
289
318
|
// -- strip-base64: replace inline blobs with a placeholder --------------------
|
|
290
319
|
if (opts.strategies.includes("strip-base64")) {
|
|
@@ -455,8 +484,13 @@ export function optimizeConversation(input, options = {}) {
|
|
|
455
484
|
let lead = 0;
|
|
456
485
|
while (lead < messages.length && (messages[lead]?.role === "system" || messages[lead]?.role === "developer"))
|
|
457
486
|
lead++;
|
|
458
|
-
|
|
459
|
-
|
|
487
|
+
// The kept tail is at least the last exchange: with keepRecent 0 or 1 the
|
|
488
|
+
// tail was too short to keep and prune-history silently did nothing, while
|
|
489
|
+
// the option promised "0 = none" left untouched. The live question is never
|
|
490
|
+
// pruned away; everything before the last two messages can be.
|
|
491
|
+
const keepTail = Math.max(2, opts.keepRecent);
|
|
492
|
+
if (opts.strategies.includes("prune-history") && messages.length - lead > keepTail * 2) {
|
|
493
|
+
let keepFrom = messages.length - keepTail;
|
|
460
494
|
// Never let the kept tail START with a tool result: its matching tool_use
|
|
461
495
|
// would be pruned away and both the Anthropic and OpenAI APIs reject
|
|
462
496
|
// conversations with orphaned tool results. Advance past any leading tool
|
|
@@ -472,7 +506,7 @@ export function optimizeConversation(input, options = {}) {
|
|
|
472
506
|
// 1,011-message session, which pruned to 7 messages with one orphan.
|
|
473
507
|
dropOrphanedToolResults(messages.slice(keepFrom));
|
|
474
508
|
const pruned = messages.slice(lead, keepFrom);
|
|
475
|
-
const prunedTokens = pruned.reduce((s, m) => s +
|
|
509
|
+
const prunedTokens = pruned.reduce((s, m) => s + messageTokens(m), 0);
|
|
476
510
|
// Digest: first ~200 chars of each pruned turn — enough for a host LLM to
|
|
477
511
|
// write a faithful summary, small enough not to defeat the pruning.
|
|
478
512
|
prunedDigest = pruned
|
|
@@ -492,6 +526,6 @@ export function optimizeConversation(input, options = {}) {
|
|
|
492
526
|
});
|
|
493
527
|
}
|
|
494
528
|
}
|
|
495
|
-
const tokensAfter = messages.reduce((s, m) => s +
|
|
529
|
+
const tokensAfter = fixed + messages.reduce((s, m) => s + messageTokens(m), 0);
|
|
496
530
|
return { conversation: data, tokensBefore, tokensAfter, applied, prunedDigest };
|
|
497
531
|
}
|
package/dist/pack.d.ts
CHANGED
|
@@ -57,6 +57,17 @@ export interface PackResult {
|
|
|
57
57
|
chunks: Chunk[];
|
|
58
58
|
/** Ids asked for that do not exist. */
|
|
59
59
|
missingIds: string[];
|
|
60
|
+
/**
|
|
61
|
+
* Chunks that were asked for by id, or matched the query, but did not fit
|
|
62
|
+
* what was left of the budget, in priority order. With nothing selected,
|
|
63
|
+
* this is the difference between "nothing matched" and "the budget is too
|
|
64
|
+
* small for what matched".
|
|
65
|
+
*/
|
|
66
|
+
unfit: Array<{
|
|
67
|
+
id: string;
|
|
68
|
+
tokens: number;
|
|
69
|
+
requested: boolean;
|
|
70
|
+
}>;
|
|
60
71
|
/** What semantic ranking did, or why it was off (packContextSemantic only). */
|
|
61
72
|
semanticNote?: string;
|
|
62
73
|
sources: Array<{
|
|
@@ -94,18 +105,36 @@ export declare const PACK_LIMITS: {
|
|
|
94
105
|
fileBytes: number;
|
|
95
106
|
totalBytes: number;
|
|
96
107
|
};
|
|
108
|
+
/** Why `path` looks like a secrets file, or undefined when it does not. */
|
|
109
|
+
export declare function secretFileReason(path: string): string | undefined;
|
|
110
|
+
export interface ReadSourcesOptions {
|
|
111
|
+
/** Names are shown relative to this (default: the working directory). */
|
|
112
|
+
cwd?: string;
|
|
113
|
+
/**
|
|
114
|
+
* Pack secrets files (.env, .npmrc, private keys, …) and paths in credential
|
|
115
|
+
* folders (~/.ssh, ~/.aws, …) too. CLI `--include-secrets` only; the MCP
|
|
116
|
+
* tool has no way to set it.
|
|
117
|
+
*/
|
|
118
|
+
includeSecrets?: boolean;
|
|
119
|
+
/** How the caller can opt in, appended to a "secret, skipped" note. */
|
|
120
|
+
secretsHint?: string;
|
|
121
|
+
}
|
|
97
122
|
/**
|
|
98
123
|
* Read files and directories (recursively, skipping build and dependency
|
|
99
|
-
* folders, binaries, and anything past the size
|
|
100
|
-
* `skipped` says what was left out and why, so nothing
|
|
124
|
+
* folders, hidden entries, binaries, secrets files, and anything past the size
|
|
125
|
+
* limits) into sources. `skipped` says what was left out and why, so nothing
|
|
126
|
+
* vanishes silently.
|
|
101
127
|
*
|
|
102
128
|
* A path named here is read even through a symlink; a symlink met inside a
|
|
103
129
|
* folder is not followed, as git does not follow one either. A link out of
|
|
104
130
|
* the folder would pack files nobody named (a tracked link to /etc/hosts, or
|
|
105
131
|
* to a secret beside the repo), a link to a parent loops, and what a link
|
|
106
132
|
* inside points at is read under its own name (or left out by .gitignore).
|
|
133
|
+
*
|
|
134
|
+
* An unreadable entry (permission denied, a device, /dev/fd) is reported as
|
|
135
|
+
* skipped, never thrown: one locked file must not lose the rest of a folder.
|
|
107
136
|
*/
|
|
108
|
-
export declare function readSources(paths: string[],
|
|
137
|
+
export declare function readSources(paths: string[], cwdOrOptions?: string | ReadSourcesOptions): {
|
|
109
138
|
sources: PackSource[];
|
|
110
139
|
skipped: string[];
|
|
111
140
|
};
|