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
package/dist/proxy.d.ts
CHANGED
|
@@ -46,9 +46,26 @@ 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;
|
|
58
|
+
/**
|
|
59
|
+
* Largest request body accepted, in bytes (default 100 MB). The body is
|
|
60
|
+
* held in memory to be read as JSON; past this a request gets 413 rather
|
|
61
|
+
* than taking the proxy (and every agent behind it) down.
|
|
62
|
+
*/
|
|
63
|
+
maxBodyBytes?: number;
|
|
49
64
|
}
|
|
65
|
+
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
66
|
+
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
50
67
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
51
|
-
export declare const PROXY_VERSION = "0.
|
|
68
|
+
export declare const PROXY_VERSION = "0.35.0";
|
|
52
69
|
/**
|
|
53
70
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
54
71
|
* the prefix is absent or the token differs. The comparison is constant time
|
|
@@ -92,6 +109,10 @@ export interface ProxyStats {
|
|
|
92
109
|
/** Cache reads/writes reported upstream (Anthropic), so autopilot's effect on the cache is visible. */
|
|
93
110
|
upstreamCacheReadTokens: number;
|
|
94
111
|
upstreamCacheWriteTokens: number;
|
|
112
|
+
/** OpenAI's cached_tokens: the part of upstreamInputTokens its responses say was read from cache. */
|
|
113
|
+
openaiCachedTokens: number;
|
|
114
|
+
/** OpenAI requests sent with a conversation prompt_cache_key the proxy added (cachekey.ts). */
|
|
115
|
+
cacheKeysAdded: number;
|
|
95
116
|
autopilot?: {
|
|
96
117
|
enabled: boolean;
|
|
97
118
|
paused: boolean;
|
package/dist/proxy.js
CHANGED
|
@@ -20,8 +20,11 @@ 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";
|
|
24
|
+
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
25
|
+
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
23
26
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
24
|
-
export const PROXY_VERSION = "0.
|
|
27
|
+
export const PROXY_VERSION = "0.35.0";
|
|
25
28
|
/** Connection-level headers that must not be forwarded. */
|
|
26
29
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
27
30
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -185,6 +188,9 @@ export function startProxy(opts = {}) {
|
|
|
185
188
|
else
|
|
186
189
|
refusing.add(account);
|
|
187
190
|
};
|
|
191
|
+
const openaiBase = opts.openaiUpstream ?? "https://api.openai.com";
|
|
192
|
+
const keyEnv = process.env.CONTEXT_DOCTOR_CACHE_KEY;
|
|
193
|
+
const addCacheKeys = opts.promptCacheKey ?? (keyEnv === "0" ? false : keyEnv === "1" ? true : /^https:\/\/api\.openai\.com\/?$/.test(openaiBase));
|
|
188
194
|
const stats = {
|
|
189
195
|
startedAt: new Date().toISOString(),
|
|
190
196
|
requests: 0,
|
|
@@ -198,6 +204,8 @@ export function startProxy(opts = {}) {
|
|
|
198
204
|
advice: [],
|
|
199
205
|
upstreamCacheReadTokens: 0,
|
|
200
206
|
upstreamCacheWriteTokens: 0,
|
|
207
|
+
openaiCachedTokens: 0,
|
|
208
|
+
cacheKeysAdded: 0,
|
|
201
209
|
autopilot: opts.autopilot
|
|
202
210
|
? { enabled: true, paused: false, requests: 0, changedRequests: 0, batches: 0, coldBatches: 0, resultsCleared: 0, tokensRemoved: 0, lastReason: "" }
|
|
203
211
|
: undefined,
|
|
@@ -248,16 +256,46 @@ export function startProxy(opts = {}) {
|
|
|
248
256
|
res.end(JSON.stringify({ ...stats, estUsdSaved: Number(stats.estUsdSaved.toFixed(4)) }, null, 2));
|
|
249
257
|
return;
|
|
250
258
|
}
|
|
251
|
-
|
|
259
|
+
// Codex signed in with ChatGPT, reading a config.toml whose
|
|
260
|
+
// openai_base_url points here (the ChatGPT app's Codex tab shares
|
|
261
|
+
// ~/.codex with a CLI on an API key): without its address it would
|
|
262
|
+
// talk to ChatGPT's Codex backend, so it is relayed there byte for
|
|
263
|
+
// byte. Its path loses the /v1 the OpenAI routes carry, and no rule
|
|
264
|
+
// below matches it: it is never edited.
|
|
265
|
+
const chatgpt = typeof req.headers["chatgpt-account-id"] === "string" && url.startsWith("/v1/");
|
|
266
|
+
if (chatgpt)
|
|
267
|
+
url = url.slice(3);
|
|
268
|
+
const upstreamBase = chatgpt ? (opts.chatgptUpstream ?? "https://chatgpt.com/backend-api/codex") : upstreamFor(url, opts, req.headers);
|
|
252
269
|
if (!upstreamBase) {
|
|
253
270
|
res.statusCode = 404;
|
|
254
271
|
res.setHeader("content-type", "application/json");
|
|
255
272
|
res.end(JSON.stringify({ error: `context-doctor proxy: unsupported path ${url} (supported: /v1/messages, /v1/chat/completions, /v1/responses)` }));
|
|
256
273
|
return;
|
|
257
274
|
}
|
|
275
|
+
const maxBody = opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
276
|
+
const tooLarge = () => {
|
|
277
|
+
res.statusCode = 413;
|
|
278
|
+
res.setHeader("content-type", "application/json");
|
|
279
|
+
res.setHeader("connection", "close");
|
|
280
|
+
res.end(JSON.stringify({ error: `context-doctor proxy: request body over ${Math.round(maxBody / 1024 / 1024)} MB; not forwarded` }));
|
|
281
|
+
};
|
|
282
|
+
if (Number(req.headers["content-length"] ?? 0) > maxBody) {
|
|
283
|
+
tooLarge();
|
|
284
|
+
req.resume(); // drain, so the client reads the answer instead of a reset
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
258
287
|
const chunks = [];
|
|
259
|
-
|
|
260
|
-
|
|
288
|
+
let received = 0;
|
|
289
|
+
for await (const chunk of req) {
|
|
290
|
+
received += chunk.length;
|
|
291
|
+
// Past the cap, keep reading (and dropping) so the 413 reaches the client.
|
|
292
|
+
if (received <= maxBody)
|
|
293
|
+
chunks.push(chunk);
|
|
294
|
+
}
|
|
295
|
+
if (received > maxBody) {
|
|
296
|
+
tooLarge();
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
261
299
|
// Keep the original bytes: only conversation JSON is ever rewritten, and
|
|
262
300
|
// anything else (a multipart file upload) must reach upstream byte for
|
|
263
301
|
// byte. Decoding everything as UTF-8 corrupted binary bodies.
|
|
@@ -323,7 +361,7 @@ export function startProxy(opts = {}) {
|
|
|
323
361
|
// Refused unedited as well: the earlier clearings are what
|
|
324
362
|
// older thinking is bound to; only this request's new ones
|
|
325
363
|
// never reached the model.
|
|
326
|
-
clearer.forget(originalAccepted ? r.appliedIds : r.newIds);
|
|
364
|
+
clearer.forget(originalAccepted ? r.appliedIds : r.newIds, r.conversation);
|
|
327
365
|
};
|
|
328
366
|
note = `autopilot: ${formatTokens(r.tokensRemoved)} tokens of stale tool output not sent (${r.reason})`;
|
|
329
367
|
}
|
|
@@ -372,7 +410,7 @@ export function startProxy(opts = {}) {
|
|
|
372
410
|
? `the last entry in "tools" (tools come before system in the cached prefix)`
|
|
373
411
|
: `the last block of "system"`;
|
|
374
412
|
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
|
|
413
|
+
`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
414
|
}
|
|
377
415
|
const fp = fnv1a(stablePrefix);
|
|
378
416
|
const prev = prefixFingerprints.get(requestModel);
|
|
@@ -399,7 +437,8 @@ export function startProxy(opts = {}) {
|
|
|
399
437
|
const stableTokens = Math.round(stableChars / CHARS_PER_TOKEN[providerFor(requestModel)].code);
|
|
400
438
|
if (stableTokens >= minCacheable) {
|
|
401
439
|
advise(`messages #0-#${stable - 1} (~${stableTokens} tokens) were identical to the previous ${requestModel} request and carry no cache_control. ` +
|
|
402
|
-
`
|
|
440
|
+
`Simplest: a top-level "cache_control":{"type":"ephemeral"} (automatic caching marks the last block and moves it forward each turn); ` +
|
|
441
|
+
`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
442
|
}
|
|
404
443
|
}
|
|
405
444
|
}
|
|
@@ -442,10 +481,25 @@ export function startProxy(opts = {}) {
|
|
|
442
481
|
/* not a conversation payload — forward as-is */
|
|
443
482
|
}
|
|
444
483
|
}
|
|
445
|
-
|
|
484
|
+
// A stable prompt_cache_key per conversation, where the app sent none
|
|
485
|
+
// and the model routes by it (GPT before 5.6): its requests then land
|
|
486
|
+
// on one cache. Added after autopilot, so its view of the conversation
|
|
487
|
+
// is the app's own.
|
|
488
|
+
if (addCacheKeys && !chatgpt && req.method === "POST" && body && /^\/v1\/(chat\/completions|responses)(\?|$)/.test(url) && upstreamBase === openaiBase) {
|
|
489
|
+
const keyed = withPromptCacheKey(body);
|
|
490
|
+
if (keyed) {
|
|
491
|
+
body = keyed.body;
|
|
492
|
+
stats.cacheKeysAdded++;
|
|
493
|
+
note += `; prompt_cache_key ${keyed.key.slice(0, 11)}…`;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// Repeated request headers arrive as arrays; each value is forwarded.
|
|
497
|
+
const headers = new Headers();
|
|
446
498
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
447
|
-
if (
|
|
448
|
-
|
|
499
|
+
if (SKIP_REQUEST_HEADERS.has(key.toLowerCase()) || value === undefined)
|
|
500
|
+
continue;
|
|
501
|
+
for (const v of Array.isArray(value) ? value : [value])
|
|
502
|
+
headers.append(key, v);
|
|
449
503
|
}
|
|
450
504
|
const upstreamStart = Date.now();
|
|
451
505
|
const send = (payload) => fetch(upstreamBase + url, {
|
|
@@ -479,10 +533,20 @@ export function startProxy(opts = {}) {
|
|
|
479
533
|
console.error(`[context-doctor] ${req.method} ${url} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
|
|
480
534
|
(stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
|
|
481
535
|
res.statusCode = upstream.status;
|
|
536
|
+
// setHeader per value kept only the last of a repeated header: two
|
|
537
|
+
// Set-Cookie lines from upstream reached the client as one. Values are
|
|
538
|
+
// gathered per name and set once, Set-Cookie as its separate lines.
|
|
539
|
+
const outHeaders = new Map();
|
|
482
540
|
upstream.headers.forEach((value, key) => {
|
|
483
|
-
if (
|
|
484
|
-
|
|
541
|
+
if (SKIP_RESPONSE_HEADERS.has(key) || key === "set-cookie")
|
|
542
|
+
return;
|
|
543
|
+
outHeaders.set(key, [...(outHeaders.get(key) ?? []), value]);
|
|
485
544
|
});
|
|
545
|
+
const cookies = typeof upstream.headers.getSetCookie === "function" ? upstream.headers.getSetCookie() : [];
|
|
546
|
+
if (cookies.length > 0 && !SKIP_RESPONSE_HEADERS.has("set-cookie"))
|
|
547
|
+
outHeaders.set("set-cookie", cookies);
|
|
548
|
+
for (const [key, values] of outHeaders)
|
|
549
|
+
res.setHeader(key, values.length === 1 ? values[0] : values);
|
|
486
550
|
if (upstream.body) {
|
|
487
551
|
// Pipe through chunk-by-chunk so SSE streaming works unchanged, while
|
|
488
552
|
// accumulating a bounded copy to read exact usage after the fact.
|
|
@@ -515,6 +579,7 @@ export function startProxy(opts = {}) {
|
|
|
515
579
|
v = Number(m[1]); return v; };
|
|
516
580
|
stats.upstreamCacheReadTokens += lastNum(/"cache_read_input_tokens"\s*:\s*(\d+)/g);
|
|
517
581
|
stats.upstreamCacheWriteTokens += lastNum(/"cache_creation_input_tokens"\s*:\s*(\d+)/g);
|
|
582
|
+
stats.openaiCachedTokens += lastNum(/"cached_tokens"\s*:\s*(\d+)/g);
|
|
518
583
|
}
|
|
519
584
|
}
|
|
520
585
|
res.end();
|
|
@@ -578,6 +643,18 @@ export function startProxy(opts = {}) {
|
|
|
578
643
|
};
|
|
579
644
|
liveServers.add(drain);
|
|
580
645
|
installSignalHandlers();
|
|
646
|
+
// A WebSocket upgrade cannot be relayed (or edited) here. Codex tries
|
|
647
|
+
// Responses over WebSocket first and, on anything but 426, retries five
|
|
648
|
+
// times (~15 s) before it falls back to HTTP; 426 Upgrade Required makes it
|
|
649
|
+
// switch to HTTP for the session at once (codex-rs core/src/client.rs).
|
|
650
|
+
// Answered on the raw socket, which is then closed: handled as an ordinary
|
|
651
|
+
// request, the upgrade left the connection in a state where the client's
|
|
652
|
+
// next request on it never got an answer.
|
|
653
|
+
server.on("upgrade", (_req, socket) => {
|
|
654
|
+
const body = JSON.stringify({ error: "context-doctor proxy: WebSocket transport is not supported here; send the request over HTTP" });
|
|
655
|
+
socket.on("error", () => { });
|
|
656
|
+
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}`);
|
|
657
|
+
});
|
|
581
658
|
server.on("close", () => {
|
|
582
659
|
liveServers.delete(drain);
|
|
583
660
|
checkpoint();
|
package/dist/report.js
CHANGED
|
@@ -41,7 +41,9 @@ export function renderProfile(profile, options = {}) {
|
|
|
41
41
|
// report that does not say so reads as a confident answer to the wrong
|
|
42
42
|
// question. Lead with the warning.
|
|
43
43
|
if (p.parseWarning) {
|
|
44
|
-
|
|
44
|
+
// Say what the numbers below are, when there are any: the raw text,
|
|
45
|
+
// profiled as one message. With nothing profiled, the warning stands alone.
|
|
46
|
+
lines.push(`⚠ ${p.parseWarning}${p.sourceFormat === "text" && p.messageCount > 0 ? " Profiled as raw text below, which is almost certainly not what you want." : ""}`);
|
|
45
47
|
lines.push("");
|
|
46
48
|
}
|
|
47
49
|
lines.push(`Total: ~${formatTokens(p.totalTokens)} tokens across ${p.messageCount} messages (${p.sourceFormat} format)`);
|
|
@@ -111,7 +113,11 @@ export function renderProfile(profile, options = {}) {
|
|
|
111
113
|
for (const [id, held] of heldPerKind) {
|
|
112
114
|
if (held.count === 0)
|
|
113
115
|
continue;
|
|
114
|
-
|
|
116
|
+
// Findings overlap (the same tokens can be a duplicate and an oversized
|
|
117
|
+
// result), so their sum can pass what the context holds. The total
|
|
118
|
+
// recovery below is a union; no subset of findings can claim more.
|
|
119
|
+
const heldSavings = Math.min(held.savings, p.totalEstSavings);
|
|
120
|
+
const more = heldSavings > 0 ? `, up to ~${formatTokens(heldSavings)} more recoverable` : "";
|
|
115
121
|
lines.push(` … and ${held.count} more of the same kind (${id})${more}. Use --json for the full list.`);
|
|
116
122
|
}
|
|
117
123
|
lines.push("");
|
package/dist/savings.d.ts
CHANGED
|
@@ -63,6 +63,19 @@ export interface SavingsReport {
|
|
|
63
63
|
coldResumes: number;
|
|
64
64
|
coldResumeNetUsd: number;
|
|
65
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
|
+
}
|
|
66
79
|
/**
|
|
67
80
|
* Replay one Claude Code transcript. Undefined when it holds too few requests
|
|
68
81
|
* to mean anything. `runRows` is shared by every transcript of one report: a
|
|
@@ -71,7 +84,7 @@ export interface SavingsReport {
|
|
|
71
84
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
72
85
|
* transcript again after the replay has added its rows to `runRows`.
|
|
73
86
|
*/
|
|
74
|
-
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;
|
|
75
88
|
export declare function estimateSavings(days?: number, options?: AutoClearOptions, paths?: string[], onProgress?: (done: number, total: number) => void): SavingsReport;
|
|
76
89
|
/** Optional third lever, computed by compactwindow.ts and passed in by the CLI. */
|
|
77
90
|
export interface CompactWindowLine {
|
|
@@ -81,7 +94,7 @@ export interface CompactWindowLine {
|
|
|
81
94
|
nowPerWeek: number;
|
|
82
95
|
isCurrent: boolean;
|
|
83
96
|
}
|
|
84
|
-
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine): string;
|
|
97
|
+
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[]): string;
|
|
85
98
|
/**
|
|
86
99
|
* `savings --share`: a few lines people can paste or screenshot. Totals only:
|
|
87
100
|
* no project names, paths or session ids, so sharing it leaks nothing.
|
package/dist/savings.js
CHANGED
|
@@ -33,13 +33,6 @@ export function autopilotReaches(entrypoint) {
|
|
|
33
33
|
}
|
|
34
34
|
/** Without a price on file the arms still need relative weights: Claude's usual 10% read rate. */
|
|
35
35
|
const UNPRICED = { inputPerM: 1, outputPerM: 5, cacheReadPerM: 0.1 };
|
|
36
|
-
/**
|
|
37
|
-
* One arm of the replay: the history as sent, priced incrementally at each
|
|
38
|
-
* request's own model. Reads are priced as they go; writes are kept at the
|
|
39
|
-
* input price and multiplied by the session's write TTL mix at the end
|
|
40
|
-
* (`usd(writeMult)`), since the mix is only known once the whole transcript
|
|
41
|
-
* has been read.
|
|
42
|
-
*/
|
|
43
36
|
function arm(model, clearer) {
|
|
44
37
|
const msgs = [];
|
|
45
38
|
const tok = [];
|
|
@@ -90,9 +83,9 @@ function arm(model, clearer) {
|
|
|
90
83
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
91
84
|
* transcript again after the replay has added its rows to `runRows`.
|
|
92
85
|
*/
|
|
93
|
-
export function replaySession(path, options = {}, since = 0, runRows, coldRows) {
|
|
86
|
+
export function replaySession(path, options = {}, since = 0, runRows, coldRows, makeClearer = () => new AutoClearer(options)) {
|
|
94
87
|
let model;
|
|
95
|
-
let base = arm(undefined, null), auto = arm(undefined,
|
|
88
|
+
let base = arm(undefined, null), auto = arm(undefined, makeClearer());
|
|
96
89
|
let baseUsd = 0, autoUsd = 0, baseRaw = 0, autoRaw = 0;
|
|
97
90
|
let entrypoint;
|
|
98
91
|
let billed = 0, billedUsd = 0, billedRaw = 0, requests = 0, lastId, lastTs = null;
|
|
@@ -118,7 +111,7 @@ export function replaySession(path, options = {}, since = 0, runRows, coldRows)
|
|
|
118
111
|
// Compaction replaces the history in both arms alike: start fresh.
|
|
119
112
|
flush();
|
|
120
113
|
base = arm(model, null);
|
|
121
|
-
auto = arm(model,
|
|
114
|
+
auto = arm(model, makeClearer(model));
|
|
122
115
|
return;
|
|
123
116
|
}
|
|
124
117
|
if (e.type === "assistant" && e.message) {
|
|
@@ -248,7 +241,7 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress) {
|
|
|
248
241
|
}
|
|
249
242
|
const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
|
|
250
243
|
const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
251
|
-
export function renderSavings(r, autopilotOn = false, cw) {
|
|
244
|
+
export function renderSavings(r, autopilotOn = false, cw, missLines) {
|
|
252
245
|
const lines = [];
|
|
253
246
|
if (r.sessions.length === 0) {
|
|
254
247
|
lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
|
|
@@ -295,6 +288,11 @@ export function renderSavings(r, autopilotOn = false, cw) {
|
|
|
295
288
|
if (!cw.isCurrent)
|
|
296
289
|
lines.push(` Set it with: context-doctor compact-window ${Math.round(cw.window / 1000)}k`);
|
|
297
290
|
}
|
|
291
|
+
if (missLines?.length) {
|
|
292
|
+
// Not a lever of ours: money the cache lost on its own, said once, with where to look.
|
|
293
|
+
lines.push("");
|
|
294
|
+
lines.push(...missLines);
|
|
295
|
+
}
|
|
298
296
|
lines.push("");
|
|
299
297
|
lines.push("Replayed request by request through the shipped code and priced as the");
|
|
300
298
|
lines.push("prompt cache bills. On a subscription the same tokens come out of your");
|
package/dist/session.js
CHANGED
|
@@ -323,8 +323,9 @@ function startsWithArray(path) {
|
|
|
323
323
|
* rest of this parser understands, or return null for lines that carry no
|
|
324
324
|
* context (reasoning is encrypted, world_state is bookkeeping).
|
|
325
325
|
*
|
|
326
|
-
* response_item/message → user or assistant text
|
|
327
|
-
*
|
|
326
|
+
* response_item/message → user or assistant text; developer (and
|
|
327
|
+
* system) messages as role "system"
|
|
328
|
+
* response_item/function_call | custom_tool_call | local_shell_call → assistant tool_use
|
|
328
329
|
* response_item/*_call_output → user tool_result
|
|
329
330
|
* event_msg/token_count → the API's own usage figures
|
|
330
331
|
* turn_context → model
|
|
@@ -367,11 +368,25 @@ function fromCodexLine(entry) {
|
|
|
367
368
|
: typeof parts === "string" ? parts : "";
|
|
368
369
|
switch (payload.type) {
|
|
369
370
|
case "message": {
|
|
371
|
+
// Developer messages (sandbox and approval rules, AGENTS.md, skills) are
|
|
372
|
+
// in every request Codex sends; dropping them undercounted the context.
|
|
373
|
+
if (payload.role === "developer" || payload.role === "system") {
|
|
374
|
+
return { type: "user", timestamp, message: { role: "system", content: text(payload.content) } };
|
|
375
|
+
}
|
|
370
376
|
const role = payload.role === "assistant" ? "assistant" : payload.role === "user" ? "user" : null;
|
|
371
377
|
if (!role)
|
|
372
378
|
return null;
|
|
373
379
|
return { type: role, timestamp, message: { role, content: text(payload.content) } };
|
|
374
380
|
}
|
|
381
|
+
case "local_shell_call": {
|
|
382
|
+
// Codex's built-in shell (older models): the command is in `action`.
|
|
383
|
+
const id = payload.call_id ?? payload.id;
|
|
384
|
+
return {
|
|
385
|
+
type: "assistant",
|
|
386
|
+
timestamp,
|
|
387
|
+
message: { role: "assistant", content: [{ type: "tool_use", id, name: "local_shell", input: payload.action ?? {} }] },
|
|
388
|
+
};
|
|
389
|
+
}
|
|
375
390
|
case "function_call":
|
|
376
391
|
case "custom_tool_call":
|
|
377
392
|
case "web_search_call": {
|
|
@@ -392,7 +407,8 @@ function fromCodexLine(entry) {
|
|
|
392
407
|
};
|
|
393
408
|
}
|
|
394
409
|
case "function_call_output":
|
|
395
|
-
case "custom_tool_call_output":
|
|
410
|
+
case "custom_tool_call_output":
|
|
411
|
+
case "local_shell_call_output": {
|
|
396
412
|
return {
|
|
397
413
|
type: "user",
|
|
398
414
|
timestamp,
|
package/dist/sketch.d.ts
CHANGED
|
@@ -57,6 +57,8 @@ export interface SketchProfile {
|
|
|
57
57
|
export declare function blockTokens(b: SketchBlock, model?: string): number;
|
|
58
58
|
/** Tokens for one plain exchange under this model's tokenizer. */
|
|
59
59
|
export declare function exchangeTokens(model?: string): number;
|
|
60
|
+
/** Longest label echoed back, in characters. */
|
|
61
|
+
export declare const MAX_LABEL_CHARS = 60;
|
|
60
62
|
export declare function profileSketch(sketch: ConversationSketch): SketchProfile;
|
|
61
63
|
export declare function renderSketchProfile(p: SketchProfile): string;
|
|
62
64
|
/** Profile a sketch, log it to the ledger like a hook check, and render. */
|
package/dist/sketch.js
CHANGED
|
@@ -65,9 +65,18 @@ export function blockTokens(b, model) {
|
|
|
65
65
|
export function exchangeTokens(model) {
|
|
66
66
|
return Math.round(CHARS_PER_EXCHANGE / CHARS_PER_TOKEN[providerFor(model)].prose);
|
|
67
67
|
}
|
|
68
|
+
/** Longest label echoed back, in characters. */
|
|
69
|
+
export const MAX_LABEL_CHARS = 60;
|
|
70
|
+
function shortLabel(label) {
|
|
71
|
+
const clean = String(label ?? "").replace(/\s+/g, " ").trim() || "unnamed block";
|
|
72
|
+
return clean.length > MAX_LABEL_CHARS ? clean.slice(0, MAX_LABEL_CHARS - 1) + "…" : clean;
|
|
73
|
+
}
|
|
68
74
|
export function profileSketch(sketch) {
|
|
69
75
|
const turns = Math.max(0, Math.floor(sketch.turns || 0));
|
|
70
|
-
|
|
76
|
+
// A label is a short name the model chose. One that is really the content
|
|
77
|
+
// (a pasted block as its own "label") would be echoed into every finding,
|
|
78
|
+
// re-adding the tokens the sketch exists to avoid; it is cut to a name.
|
|
79
|
+
const blocks = (Array.isArray(sketch.blocks) ? sketch.blocks : []).map((b) => ({ ...b, label: shortLabel(b?.label) }));
|
|
71
80
|
const perExchange = exchangeTokens(sketch.model);
|
|
72
81
|
const baselineTokens = turns * perExchange;
|
|
73
82
|
// A repeated block costs its size every time it appears.
|
package/dist/tokens.js
CHANGED
|
@@ -19,6 +19,9 @@ const MODEL_WINDOWS = [
|
|
|
19
19
|
[/gpt-4(?!o|\.|-turbo)/i, 8_192],
|
|
20
20
|
[/gpt-3\.5/i, 16_385],
|
|
21
21
|
[/gemini.*(1\.5|2\.|2-5)/i, 1_000_000],
|
|
22
|
+
// Every Gemini 3 text model (3 Flash, 3.1 Pro, 3.1/3.5 Flash-Lite, 3.6/3.8
|
|
23
|
+
// Flash): 1,048,576 input tokens (ai.google.dev/gemini-api/docs/models, Oct 2026).
|
|
24
|
+
[/gemini-?3/i, 1_048_576],
|
|
22
25
|
[/llama.*3/i, 128_000],
|
|
23
26
|
[/mistral|mixtral/i, 32_000],
|
|
24
27
|
];
|
|
@@ -104,15 +107,23 @@ export function formatTokens(n) {
|
|
|
104
107
|
// rather than something false.
|
|
105
108
|
if (!Number.isFinite(n))
|
|
106
109
|
return "0";
|
|
107
|
-
if (n
|
|
108
|
-
return
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
110
|
+
if (n < 0)
|
|
111
|
+
return `-${formatTokens(-n)}`;
|
|
112
|
+
// Round to what is shown BEFORE choosing the unit: choosing first printed
|
|
113
|
+
// 999,999.9 as "1000k" and 9,999 as "10.0k".
|
|
114
|
+
const r = Math.round(n);
|
|
115
|
+
if (r < 1_000)
|
|
116
|
+
return String(r);
|
|
117
|
+
const tenthsK = Math.round(r / 100);
|
|
118
|
+
if (tenthsK < 100)
|
|
119
|
+
return `${(tenthsK / 10).toFixed(1)}k`;
|
|
120
|
+
const k = Math.round(r / 1_000);
|
|
121
|
+
if (k < 1_000)
|
|
122
|
+
return `${k}k`;
|
|
123
|
+
const tenthsM = Math.round(r / 100_000);
|
|
124
|
+
if (tenthsM < 10_000)
|
|
125
|
+
return `${(tenthsM / 10).toFixed(1)}M`;
|
|
126
|
+
return `${(Math.round(r / 100_000_000) / 10).toFixed(1)}B`;
|
|
116
127
|
}
|
|
117
128
|
/**
|
|
118
129
|
* A transcript's model field, unless it is a placeholder: Claude Code writes
|
package/dist/wrap.js
CHANGED
|
@@ -217,15 +217,37 @@ export function withContextDoctor(client, options = {}) {
|
|
|
217
217
|
clearer.noteEditsRejected(account);
|
|
218
218
|
stats.changed--;
|
|
219
219
|
stats.tokensRemoved -= result.tokensRemoved;
|
|
220
|
-
clearer.forget(accepted ? result.appliedIds : result.newIds);
|
|
220
|
+
clearer.forget(accepted ? result.appliedIds : result.newIds, result.conversation);
|
|
221
|
+
};
|
|
222
|
+
// The client itself is the receiver for everything not wrapped: a getter
|
|
223
|
+
// or method that reads a #private field throws a TypeError when `this` is
|
|
224
|
+
// the Proxy (it has no private slots), which broke SDK clients built on
|
|
225
|
+
// them. Methods are bound to the client, once each, so identity holds.
|
|
226
|
+
const bound = new WeakMap();
|
|
227
|
+
const boundTo = (obj, fn) => {
|
|
228
|
+
// Classes keep their identity: binding one loses its statics.
|
|
229
|
+
if (/^class[\s{]/.test(Function.prototype.toString.call(fn)))
|
|
230
|
+
return fn;
|
|
231
|
+
let perObj = bound.get(obj);
|
|
232
|
+
if (!perObj)
|
|
233
|
+
bound.set(obj, (perObj = new WeakMap()));
|
|
234
|
+
const known = perObj.get(fn);
|
|
235
|
+
if (known)
|
|
236
|
+
return known;
|
|
237
|
+
const b = fn.bind(obj);
|
|
238
|
+
perObj.set(fn, b);
|
|
239
|
+
return b;
|
|
221
240
|
};
|
|
222
241
|
const wrap = (target, path) => new Proxy(target, {
|
|
223
|
-
|
|
242
|
+
set(obj, prop, value) {
|
|
243
|
+
return Reflect.set(obj, prop, value);
|
|
244
|
+
},
|
|
245
|
+
get(obj, prop) {
|
|
224
246
|
if (prop === STATS && path === "")
|
|
225
247
|
return stats;
|
|
226
|
-
const value = Reflect.get(obj, prop
|
|
248
|
+
const value = Reflect.get(obj, prop);
|
|
227
249
|
if (typeof prop !== "string")
|
|
228
|
-
return value;
|
|
250
|
+
return typeof value === "function" ? boundTo(obj, value) : value;
|
|
229
251
|
const full = path ? `${path}.${prop}` : prop;
|
|
230
252
|
if (WRAPPED.has(full) && typeof value === "function") {
|
|
231
253
|
return function (params, ...rest) {
|
|
@@ -238,7 +260,7 @@ export function withContextDoctor(client, options = {}) {
|
|
|
238
260
|
}
|
|
239
261
|
if (PARENTS.has(full) && value && typeof value === "object")
|
|
240
262
|
return wrap(value, full);
|
|
241
|
-
return value;
|
|
263
|
+
return typeof value === "function" ? boundTo(obj, value) : value;
|
|
242
264
|
},
|
|
243
265
|
});
|
|
244
266
|
return wrap(client, "");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.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",
|