context-doctor 0.34.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/dist/proxy.js CHANGED
@@ -21,8 +21,10 @@ import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
21
21
  import { recordLedger } from "./ledger.js";
22
22
  import { minCacheableTokens } from "./cacheplan.js";
23
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;
24
26
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
25
- export const PROXY_VERSION = "0.34.0";
27
+ export const PROXY_VERSION = "0.35.0";
26
28
  /** Connection-level headers that must not be forwarded. */
27
29
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
28
30
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
@@ -270,9 +272,30 @@ export function startProxy(opts = {}) {
270
272
  res.end(JSON.stringify({ error: `context-doctor proxy: unsupported path ${url} (supported: /v1/messages, /v1/chat/completions, /v1/responses)` }));
271
273
  return;
272
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
+ }
273
287
  const chunks = [];
274
- for await (const chunk of req)
275
- chunks.push(chunk);
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
+ }
276
299
  // Keep the original bytes: only conversation JSON is ever rewritten, and
277
300
  // anything else (a multipart file upload) must reach upstream byte for
278
301
  // byte. Decoding everything as UTF-8 corrupted binary bodies.
@@ -338,7 +361,7 @@ export function startProxy(opts = {}) {
338
361
  // Refused unedited as well: the earlier clearings are what
339
362
  // older thinking is bound to; only this request's new ones
340
363
  // never reached the model.
341
- clearer.forget(originalAccepted ? r.appliedIds : r.newIds);
364
+ clearer.forget(originalAccepted ? r.appliedIds : r.newIds, r.conversation);
342
365
  };
343
366
  note = `autopilot: ${formatTokens(r.tokensRemoved)} tokens of stale tool output not sent (${r.reason})`;
344
367
  }
@@ -470,10 +493,13 @@ export function startProxy(opts = {}) {
470
493
  note += `; prompt_cache_key ${keyed.key.slice(0, 11)}…`;
471
494
  }
472
495
  }
473
- const headers = {};
496
+ // Repeated request headers arrive as arrays; each value is forwarded.
497
+ const headers = new Headers();
474
498
  for (const [key, value] of Object.entries(req.headers)) {
475
- if (!SKIP_REQUEST_HEADERS.has(key.toLowerCase()) && typeof value === "string")
476
- headers[key] = value;
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);
477
503
  }
478
504
  const upstreamStart = Date.now();
479
505
  const send = (payload) => fetch(upstreamBase + url, {
@@ -507,10 +533,20 @@ export function startProxy(opts = {}) {
507
533
  console.error(`[context-doctor] ${req.method} ${url} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
508
534
  (stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
509
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();
510
540
  upstream.headers.forEach((value, key) => {
511
- if (!SKIP_RESPONSE_HEADERS.has(key))
512
- res.setHeader(key, value);
541
+ if (SKIP_RESPONSE_HEADERS.has(key) || key === "set-cookie")
542
+ return;
543
+ outHeaders.set(key, [...(outHeaders.get(key) ?? []), value]);
513
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);
514
550
  if (upstream.body) {
515
551
  // Pipe through chunk-by-chunk so SSE streaming works unchanged, while
516
552
  // accumulating a bounded copy to read exact usage after the fact.
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
- lines.push(`⚠ ${p.parseWarning}`);
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
- const more = held.savings > 0 ? `, ~${formatTokens(held.savings)} more recoverable` : "";
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
@@ -94,7 +94,7 @@ export interface CompactWindowLine {
94
94
  nowPerWeek: number;
95
95
  isCurrent: boolean;
96
96
  }
97
- 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;
98
98
  /**
99
99
  * `savings --share`: a few lines people can paste or screenshot. Totals only:
100
100
  * no project names, paths or session ids, so sharing it leaks nothing.
package/dist/savings.js CHANGED
@@ -241,7 +241,7 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress) {
241
241
  }
242
242
  const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
243
243
  const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
244
- export function renderSavings(r, autopilotOn = false, cw) {
244
+ export function renderSavings(r, autopilotOn = false, cw, missLines) {
245
245
  const lines = [];
246
246
  if (r.sessions.length === 0) {
247
247
  lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
@@ -288,6 +288,11 @@ export function renderSavings(r, autopilotOn = false, cw) {
288
288
  if (!cw.isCurrent)
289
289
  lines.push(` Set it with: context-doctor compact-window ${Math.round(cw.window / 1000)}k`);
290
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
+ }
291
296
  lines.push("");
292
297
  lines.push("Replayed request by request through the shipped code and priced as the");
293
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
- * response_item/function_call | custom_tool_call → assistant tool_use
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
- const blocks = Array.isArray(sketch.blocks) ? sketch.blocks : [];
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 >= 1_000_000_000)
108
- return `${(n / 1_000_000_000).toFixed(1)}B`;
109
- if (n >= 1_000_000)
110
- return `${(n / 1_000_000).toFixed(1)}M`;
111
- if (n >= 10_000)
112
- return `${Math.round(n / 1000)}k`;
113
- if (n >= 1_000)
114
- return `${(n / 1000).toFixed(1)}k`;
115
- return String(n);
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
- get(obj, prop, receiver) {
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, receiver);
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.34.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",