context-doctor 0.49.0 → 0.49.1

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.
@@ -50,16 +50,6 @@ export type Band = {
50
50
  text: string;
51
51
  compact: string;
52
52
  };
53
- /** The band shows within this long of the cache going cold... */
54
- export declare const WARN_BEFORE_MS: number;
55
- /**
56
- * ...or within this share of the cache's life, when that is shorter: the last
57
- * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
58
- * after every turn), the last five of the 1-hour cache.
59
- */
60
- export declare const WARN_SHARE: number;
61
- /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
62
- export declare function warnBeforeMs(ttlMs: number): number;
63
53
  /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
64
54
  export declare const DEFAULT_THRESHOLDS: number[];
65
55
  /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
@@ -77,15 +67,17 @@ export declare function priceText(d: Pick<BandData, "usd" | "ccUsd">): string |
77
67
  export interface BandOptions {
78
68
  /** Keys the person hid this session. */
79
69
  hidden?: ReadonlySet<string>;
80
- /** CONTEXT_DOCTOR_MOD_BAND=always: show the cache clock and the price at all times, not only when they pay. */
70
+ /** CONTEXT_DOCTOR_MOD_BAND=cold: show the cold-return offer (Compact first). */
71
+ cold?: boolean;
72
+ /** CONTEXT_DOCTOR_MOD_BAND=always: the cold return, and the cache clock and the price at all times. */
81
73
  always?: boolean;
82
74
  }
83
75
  /**
84
- * The band above the prompt at `now`. Quiet unless it pays (the cache about
85
- * to go cold, or gone cold, on a context worth caring about; the session
86
- * past a price threshold), except with `always`. The terminal has the
87
- * status line for the clock and the price, so there the band shows only the
88
- * cold return, the one thing with a button. Nothing on mobile.
76
+ * The band above the prompt at `now`. Off by default: on a big session it came
77
+ * up after nearly every reply, and the every-prompt hook already has Claude
78
+ * offer to compact on a cold return. `cold` shows that return (back at a big
79
+ * session after its cache expired) with Compact first; `always` adds the cache
80
+ * clock, the expired notice and the session price. Nothing on mobile.
89
81
  */
90
82
  export declare function band(d: BandData | undefined, now: number, surface: Surface, opts?: BandOptions): Band;
91
83
  /** A lever as `context-doctor fix --json` prints it (the fields the pane reads). */
package/dist/mod/logic.js CHANGED
@@ -8,19 +8,7 @@
8
8
  * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
9
  * suite exercises these functions directly.
10
10
  */
11
- /** The band shows within this long of the cache going cold... */
12
- export const WARN_BEFORE_MS = 5 * 60_000;
13
11
  const MIN = 60_000;
14
- /**
15
- * ...or within this share of the cache's life, when that is shorter: the last
16
- * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
17
- * after every turn), the last five of the 1-hour cache.
18
- */
19
- export const WARN_SHARE = 1 / 5;
20
- /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
21
- export function warnBeforeMs(ttlMs) {
22
- return Math.min(WARN_BEFORE_MS, ttlMs * WARN_SHARE);
23
- }
24
12
  /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
25
13
  export const DEFAULT_THRESHOLDS = [25, 100, 500];
26
14
  /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
@@ -79,56 +67,56 @@ export function priceText(d) {
79
67
  return `session ${money(d.ccUsd)} (Claude Code's figure)`;
80
68
  return undefined;
81
69
  }
70
+ /** "~$0.04", or "under $0.01" where `money` would say "<$0.01". */
71
+ function about(n) {
72
+ return n < 0.01 ? "under $0.01" : `~${money(n)}`;
73
+ }
82
74
  /**
83
- * The band above the prompt at `now`. Quiet unless it pays (the cache about
84
- * to go cold, or gone cold, on a context worth caring about; the session
85
- * past a price threshold), except with `always`. The terminal has the
86
- * status line for the clock and the price, so there the band shows only the
87
- * cold return, the one thing with a button. Nothing on mobile.
75
+ * The band above the prompt at `now`. Off by default: on a big session it came
76
+ * up after nearly every reply, and the every-prompt hook already has Claude
77
+ * offer to compact on a cold return. `cold` shows that return (back at a big
78
+ * session after its cache expired) with Compact first; `always` adds the cache
79
+ * clock, the expired notice and the session price. Nothing on mobile.
88
80
  */
89
81
  export function band(d, now, surface, opts = {}) {
90
- if (!d || surface === "mobile")
82
+ if (!d || surface === "mobile" || !(opts.cold || opts.always))
91
83
  return { kind: "none" };
92
84
  const hidden = opts.hidden ?? new Set();
93
85
  const show = (b) => (hidden.has(b.key) ? { kind: "none" } : b);
94
- const terminal = surface === "terminal";
86
+ // The terminal's status line already shows the clock and the price.
87
+ const extra = opts.always === true && surface !== "terminal";
95
88
  const price = priceText(d);
96
89
  const big = d.tokens !== undefined && d.tokens >= d.coldMinTokens;
97
90
  const known = d.tokens !== undefined && d.lastReplyAt !== undefined && d.ttlMs !== undefined;
98
91
  if (known) {
99
92
  const expiresAt = d.lastReplyAt + d.ttlMs;
100
93
  const coldAt = expiresAt + (d.coldMarginMs ?? 0);
101
- const rewrite = `${tokens(d.tokens)} tokens${d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : ""}`;
102
- const tail = price && !terminal ? ` · ${price}` : "";
94
+ const cost = d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : "";
103
95
  // The return the cold-resume offer is about: past the cache's life by the margin, big enough, and not about to be compacted by Claude Code anyway.
104
96
  if (now >= coldAt && big && d.tokens < (d.autoCompactAt ?? Infinity)) {
105
- const each = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
106
- ? `each later message re-reads ~${money(d.perMessageUsd)} of context now, ~${money(d.afterCompactPerMessageUsd)} after`
107
- : `each later message re-reads ${tokens(d.tokens)} tokens now, far fewer after`;
97
+ const after = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
98
+ ? `each message after that costs ${about(d.afterCompactPerMessageUsd)} instead of ${about(d.perMessageUsd)}`
99
+ : `each message after that re-reads far fewer than ${tokens(d.tokens)} tokens`;
108
100
  return show({
109
101
  kind: "cold",
110
102
  key: `cold:${d.lastReplyAt}`,
111
- text: `context-doctor: idle ${duration(now - d.lastReplyAt)}, the cache expired: your next message re-writes ${rewrite}${tail}`,
112
- compact: `Compact first: ${each}`,
103
+ text: `context-doctor: you were away ${duration(now - d.lastReplyAt)}, so the cache expired. Your next message re-sends this ${tokens(d.tokens)}-token chat at full price${cost}.`,
104
+ compact: `Compact first to shrink it: ${after}.`,
113
105
  });
114
106
  }
115
- if (terminal)
107
+ if (!extra)
116
108
  return { kind: "none" };
117
- if (now >= expiresAt && (big || opts.always)) {
109
+ const tail = price ? ` · ${price}` : "";
110
+ const rewrite = `${tokens(d.tokens)} tokens${cost}`;
111
+ if (now >= expiresAt) {
118
112
  return show({ kind: "expired", key: `expired:${d.lastReplyAt}`, text: `context-doctor: the cache expired, so your next message re-writes ${rewrite}${tail}` });
119
113
  }
120
- if (now < expiresAt && (opts.always || (big && expiresAt - now <= warnBeforeMs(d.ttlMs)))) {
121
- return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
122
- }
114
+ return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
123
115
  }
124
- if (terminal)
116
+ if (!extra || !price)
125
117
  return { kind: "none" };
126
- const usd = d.usd ?? d.ccUsd;
127
- const t = passedThreshold(usd, d.thresholds);
128
- if (price && (t !== undefined || opts.always)) {
129
- return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
130
- }
131
- return { kind: "none" };
118
+ const t = passedThreshold(d.usd ?? d.ccUsd, d.thresholds);
119
+ return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
132
120
  }
133
121
  /** The lever that changes which model runs: never applied by `--apply all`, and marked as such here. */
134
122
  export const MODEL_CHANGE = "subagent-model";
@@ -49,6 +49,8 @@ export declare const USAGE_PANE = "context-doctor-usage";
49
49
  /** The mod's state for this load (a reload starts it over; the next turn measures again). */
50
50
  interface State {
51
51
  off: boolean;
52
+ /** CONTEXT_DOCTOR_MOD_BAND: the band is off unless it says `cold` or `always`. */
53
+ cold: boolean;
52
54
  always: boolean;
53
55
  /** The session price thresholds in force, for when the CLI cannot say them (no Node). */
54
56
  thresholds: number[];
@@ -52,7 +52,7 @@ const FIX_TIMEOUT_MS = 10 * 60_000;
52
52
  const MEASURE_TIMEOUT_MS = 30_000;
53
53
  /** `mod usage` measures 30 days the first time (~3 s cold on 22,000 requests); later runs read its 5-minute cache. */
54
54
  const USAGE_TIMEOUT_MS = 2 * 60_000;
55
- const fresh = () => ({ off: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map(), pinging: false, usageOpen: false, usageLoading: false, period: "today", usageDrawn: "" });
55
+ const fresh = () => ({ off: false, cold: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map(), pinging: false, usageOpen: false, usageLoading: false, period: "today", usageDrawn: "" });
56
56
  let S = fresh();
57
57
  /** For tests: the state the hooks share. */
58
58
  export const state = () => S;
@@ -65,7 +65,7 @@ function cliOf($) {
65
65
  return `${root}${sep}dist${sep}cli.js`;
66
66
  }
67
67
  function bandKey(now, surface) {
68
- const b = band(S.data, now, surface, { hidden: S.hidden, always: S.always });
68
+ const b = band(S.data, now, surface, { hidden: S.hidden, cold: S.cold, always: S.always });
69
69
  return b.kind === "none" ? "" : `${b.key}|${b.text}`;
70
70
  }
71
71
  /** Hand the reading to the CLI; with no CLI (no node on PATH), keep what Claude Code said. */
@@ -348,7 +348,9 @@ export function register(on) {
348
348
  on("session.start", async ($, e, next) => {
349
349
  try {
350
350
  S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
351
- S.always = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND")) === "always";
351
+ const bandMode = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND"))?.trim().toLowerCase();
352
+ S.cold = bandMode === "cold";
353
+ S.always = bandMode === "always";
352
354
  S.thresholds = thresholdsFrom(await $.env.get("CONTEXT_DOCTOR_SESSION_PRICE"), await $.env.get("CONTEXT_DOCTOR_NO_SESSION_PRICE"));
353
355
  S.pingEveryMs = keepWarmTestEvery(await $.env.get("CONTEXT_DOCTOR_KEEP_WARM_PING_MS"));
354
356
  if (!S.off) {
@@ -405,7 +407,7 @@ export function register(on) {
405
407
  const { Box, Text, Button } = $.ui.resolve(e);
406
408
  return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, keepWarmText(S.kw, now)), h(Button, { key: "cd-keep-warm-stop", label: "Stop", onPress: () => stopKeepWarm($, "you stopped it") }));
407
409
  }
408
- const b = band(S.data, now, e.surface, { hidden: S.hidden, always: S.always });
410
+ const b = band(S.data, now, e.surface, { hidden: S.hidden, cold: S.cold, always: S.always });
409
411
  // A compaction only runs between turns: no button while one runs.
410
412
  if (b.kind === "none" || (b.kind === "cold" && e.props.isWorking))
411
413
  return next(e);
@@ -413,7 +415,9 @@ export function register(on) {
413
415
  const hideButton = h(Button, { key: "cd-hide", label: "Hide", onPress: () => hide($, b.key) });
414
416
  if (b.kind !== "cold")
415
417
  return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, b.text), hideButton);
416
- return h(Box, { flexDirection: "column" }, h(Text, { dimColor: true }, b.text), h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Button, { key: "cd-compact", label: S.compacting ? "Compacting…" : "Compact first", variant: "primary", onPress: () => compact($) }), h(Text, { dimColor: true }, b.compact), hideButton));
418
+ return h(Box, { flexDirection: "column" }, h(Text, { dimColor: true }, b.text), h(Text, { dimColor: true }, b.compact),
419
+ // The buttons on a row of their own: between lines of wrapped text they read as part of it.
420
+ h(Box, { flexDirection: "row", columnGap: 1 }, h(Button, { key: "cd-compact", label: S.compacting ? "Compacting…" : "Compact first", variant: "primary", onPress: () => compact($) }), hideButton));
417
421
  });
418
422
  on("command.run", { command: "context-doctor-usage" }, async ($) => {
419
423
  if (S.off)
package/dist/pricing.js CHANGED
@@ -144,6 +144,11 @@ const PRICING = [
144
144
  // no cached-input price (the -pro ones) read at full input. Not modelled:
145
145
  // Fast mode (priority processing; Codex records only its thread's
146
146
  // `service_tier`, not each request's) and the 10% regional uplift.
147
+ // GPT-6.2 Astra and Sol, read 2026-11-18. Astra for Law's price is
148
+ // promotional "at least through December 31, 2026": no end date yet.
149
+ [openai("gpt-6.2-astra"), ...openaiLong(8, 40, 0.4)],
150
+ [openai("gpt-6.2-astra-law"), ...openaiLong(8, 40, 0.4)],
151
+ [openai("gpt-6.2-sol"), ...openaiLong(2, 10, 0.1)],
147
152
  [openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
148
153
  // GPT-6 Astra for Law's price is promotional "at least through December
149
154
  // 31, 2026" (read 2026-11-14): no end date to record yet.
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.49.0";
86
+ export declare const PROXY_VERSION = "0.49.1";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.49.0";
28
+ export const PROXY_VERSION = "0.49.1";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { type RecordedUsage } from "./pricing.js";
39
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
40
+ export declare const SUGGESTION_PROMPT_TOKENS = 506;
41
+ /** A suggestion's output (measured: 12-17). */
42
+ export declare const SUGGESTION_OUTPUT_TOKENS = 15;
43
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
44
+ export declare const SUGGESTION_MAX_LAST_TOKENS = 10000;
45
+ /**
46
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
47
+ * Code was billed for it; undefined when the row ends no main-thread turn or
48
+ * Claude Code would have skipped it.
49
+ */
50
+ export declare function suggestionUsage(e: any): RecordedUsage | undefined;
51
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
52
+ export declare function suggestionCost(e: any): {
53
+ usage: RecordedUsage;
54
+ cost: import("./pricing.js").RequestCost;
55
+ } | undefined;
56
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
57
+ export declare const UNSETTLED_FROM = "2.1.284";
58
+ export declare const UNSETTLED_UNTIL = "2.1.299";
59
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
60
+ export declare function unsettledVersion(v: unknown): boolean;
61
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
62
+ export declare const OUTPUT_PER_CHAR = 0.4;
63
+ export declare const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
64
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
65
+ export declare function contentOutputTokens(content: unknown): number;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { isUnbilledModel, requestCost } from "./pricing.js";
39
+ import { realModel } from "./tokens.js";
40
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
41
+ export const SUGGESTION_PROMPT_TOKENS = 506;
42
+ /** A suggestion's output (measured: 12-17). */
43
+ export const SUGGESTION_OUTPUT_TOKENS = 15;
44
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
45
+ export const SUGGESTION_MAX_LAST_TOKENS = 10_000;
46
+ const n = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
47
+ /**
48
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
49
+ * Code was billed for it; undefined when the row ends no main-thread turn or
50
+ * Claude Code would have skipped it.
51
+ */
52
+ export function suggestionUsage(e) {
53
+ const m = e?.message;
54
+ if (e?.type !== "assistant" || e.isSidechain === true || m?.stop_reason !== "end_turn" || !m.usage || isUnbilledModel(m.model))
55
+ return undefined;
56
+ if (typeof e.entrypoint === "string" && e.entrypoint.startsWith("sdk"))
57
+ return undefined;
58
+ const u = m.usage;
59
+ const input = n(u.input_tokens), read = n(u.cache_read_input_tokens), write = n(u.cache_creation_input_tokens), output = n(u.output_tokens);
60
+ if (input + output + write > SUGGESTION_MAX_LAST_TOKENS || input + read + write === 0)
61
+ return undefined;
62
+ // Its reply written at the lifetime the turn's own writes used (the main thread's: an hour, unless they were all 5-minute).
63
+ const fiveMin = n(u.cache_creation?.ephemeral_5m_input_tokens) > 0 && n(u.cache_creation?.ephemeral_1h_input_tokens) === 0;
64
+ return {
65
+ input_tokens: SUGGESTION_PROMPT_TOKENS, cache_read_input_tokens: input + read + write, cache_creation_input_tokens: output,
66
+ cache_creation: fiveMin ? { ephemeral_5m_input_tokens: output, ephemeral_1h_input_tokens: 0 } : { ephemeral_1h_input_tokens: output, ephemeral_5m_input_tokens: 0 },
67
+ output_tokens: SUGGESTION_OUTPUT_TOKENS,
68
+ ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}),
69
+ };
70
+ }
71
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
72
+ export function suggestionCost(e) {
73
+ const u = suggestionUsage(e);
74
+ if (!u)
75
+ return undefined;
76
+ const c = requestCost(realModel(e.message.model), u, Date.parse(String(e.timestamp ?? "")));
77
+ return c ? { usage: u, cost: c } : undefined;
78
+ }
79
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
80
+ export const UNSETTLED_FROM = "2.1.284";
81
+ export const UNSETTLED_UNTIL = "2.1.299";
82
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
83
+ export function unsettledVersion(v) {
84
+ if (typeof v !== "string")
85
+ return false;
86
+ const x = v.split(/[.-]/).map((n) => parseInt(n, 10) || 0);
87
+ const cmp = (b) => {
88
+ const y = b.split(".").map(Number);
89
+ for (let i = 0; i < 3; i++)
90
+ if ((x[i] ?? 0) !== y[i])
91
+ return (x[i] ?? 0) - y[i];
92
+ return 0;
93
+ };
94
+ return cmp(UNSETTLED_FROM) >= 0 && cmp(UNSETTLED_UNTIL) <= 0;
95
+ }
96
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
97
+ export const OUTPUT_PER_CHAR = 0.4;
98
+ export const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
99
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
100
+ export function contentOutputTokens(content) {
101
+ if (!Array.isArray(content))
102
+ return 0;
103
+ let chars = 0, sig = 0;
104
+ for (const c of content) {
105
+ if (!c || typeof c !== "object")
106
+ continue;
107
+ if (c.type === "text" && typeof c.text === "string")
108
+ chars += c.text.length;
109
+ else if (c.type === "tool_use")
110
+ chars += JSON.stringify(c.input ?? {}).length + String(c.name ?? "").length;
111
+ else if (c.type === "thinking") {
112
+ chars += typeof c.thinking === "string" ? c.thinking.length : 0;
113
+ sig += typeof c.signature === "string" ? c.signature.length : 0;
114
+ }
115
+ }
116
+ return Math.round(chars * OUTPUT_PER_CHAR + sig * OUTPUT_PER_SIGNATURE_CHAR);
117
+ }
package/dist/spend.d.ts CHANGED
@@ -85,6 +85,8 @@ export interface SpendItem {
85
85
  key?: string;
86
86
  /** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
87
87
  compaction?: boolean;
88
+ /** Claude Code: output tokens estimated from the reply's content, inside `output` and `usd`, where its rows never settled it (sidecost.ts). */
89
+ unsettled?: number;
88
90
  /** Copilot CLI: the AI credits it used (one is $0.01), as Copilot recorded them; not in `usd`. */
89
91
  credits?: number;
90
92
  /** Copilot CLI: the premium requests it counted (its multiplier); not in `usd`. */
@@ -269,6 +271,12 @@ export interface SpendReport {
269
271
  requests: number;
270
272
  usd: number;
271
273
  };
274
+ /** Claude Code subagent replies whose rows never settled their output (2.1.284-2.1.299): the output estimated from their content, inside `usd`; absent when none. */
275
+ unsettled?: {
276
+ replies: number;
277
+ tokens: number;
278
+ usd: number;
279
+ };
272
280
  /** Claude Code: iterations billed beyond their request's top-level usage (the advisor's calls, attempts a fallback replaced), by type: inside `usd`; absent when none. */
273
281
  iterations?: Record<string, {
274
282
  calls: number;
package/dist/spend.js CHANGED
@@ -156,6 +156,8 @@ export function claudeSpend(since, until = Infinity, tops, onProgress, place = f
156
156
  label(item, { estimated: r.estimated, changedOn: r.changedOn, modifiers: extra.reduce((m, x) => minus(m, x.modifiers), { ...r.modifiers }) });
157
157
  if (r.compaction)
158
158
  item.compaction = true;
159
+ if (r.unsettled)
160
+ item.unsettled = r.unsettled;
159
161
  if (r.model)
160
162
  item.model = r.model;
161
163
  if (f.run)
@@ -633,12 +635,18 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
633
635
  const mods = { ...NO_MODIFIERS };
634
636
  const changed = new Map();
635
637
  const compactions = { requests: 0, usd: 0 };
638
+ const unsettled = { replies: 0, tokens: 0, usd: 0 };
636
639
  const iterations = {};
637
640
  for (const it of items) {
638
641
  if (it.compaction) {
639
642
  compactions.requests++;
640
643
  compactions.usd += it.usd;
641
644
  }
645
+ if (it.unsettled) {
646
+ unsettled.replies++;
647
+ unsettled.tokens += it.unsettled;
648
+ unsettled.usd += it.output > 0 ? (it.outputUsd * it.unsettled) / it.output : 0;
649
+ }
642
650
  if (it.iteration) {
643
651
  const x = (iterations[it.iteration] ??= { calls: 0, usd: 0, models: [] });
644
652
  x.calls++;
@@ -743,6 +751,7 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
743
751
  ...(anyModifier(mods) ? { modifiers: mods } : {}),
744
752
  ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
745
753
  ...(compactions.requests ? { compactions } : {}),
754
+ ...(unsettled.replies ? { unsettled } : {}),
746
755
  ...(Object.keys(iterations).length ? { iterations } : {}),
747
756
  sessions: [...sessions.values()].sort(byUsd),
748
757
  skipped,
@@ -931,6 +940,8 @@ export function renderSpend(r, top = 8) {
931
940
  // A compaction's own request is in no row's usage: estimated from the context it read and the summary it wrote.
932
941
  if (r.compactions)
933
942
  lines.push(` Of it, ${r.compactions.requests.toLocaleString("en-US")} Claude Code ${r.compactions.requests === 1 ? "compaction's own request" : "compactions' own requests"} ${usd(r.compactions.usd)}, an estimate (no row records their usage)`);
943
+ if (r.unsettled)
944
+ lines.push(` Of it, ${usd(r.unsettled.usd)} output of ${r.unsettled.replies.toLocaleString("en-US")} subagent ${r.unsettled.replies === 1 ? "reply" : "replies"} whose rows Claude Code never settled (2.1.284-2.1.299), an estimate from ${r.unsettled.replies === 1 ? "its" : "their"} content`);
934
945
  // Calls inside a request that its usage totals leave out: the advisor's, an attempt a fallback replaced.
935
946
  for (const [type, x] of Object.entries(r.iterations ?? {}))
936
947
  lines.push(` Of it, ${x.calls.toLocaleString("en-US")} ${ITERATION_NAME[type]?.[x.calls === 1 ? 0 : 1] ?? `"${type}" iterations`} ${usd(x.usd)} (${x.models.slice(0, 2).join(", ")}), beyond their requests' usage totals`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.49.0",
3
+ "version": "0.49.1",
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",