sprag-cli 3.139.0 → 3.140.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/bin/cli.js CHANGED
@@ -44,6 +44,7 @@ import {
44
44
  } from '../src/stdin-payload.js';
45
45
 
46
46
  import { ultracodeChipState } from '../src/ultracode.js';
47
+ import { liveContextFor } from '../src/ctx-fill.js';
47
48
 
48
49
  import { parseAllSessions, sessionsSince, getLastUserMessageTime, flushPendingSessionCache, parseStats } from '../src/parser.js';
49
50
  import {
@@ -799,11 +800,21 @@ async function main() {
799
800
  } catch (e) { debug('session-effort:record', e); }
800
801
  // Recorded here too: a fresh session can render before it has any request
801
802
  // in the analysis window, and its first prompt is briefed from this.
802
- const ctxLive = extractContextUsage(stdinJson);
803
+ const ctxLive = liveContextFor(stdinJson, {
804
+ root: process.cwd(),
805
+ model: liveModelIdOf(stdinJson),
806
+ sessionId: extractSessionId(stdinJson),
807
+ });
803
808
  if (ctxLive?.size) {
804
809
  try {
805
810
  const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
806
- recordLiveWindow(extractSessionId(stdinJson), ctxLive.size, Date.now(), liveModelIdOf(stdinJson));
811
+ recordLiveWindow(
812
+ extractSessionId(stdinJson),
813
+ ctxLive.size,
814
+ Date.now(),
815
+ liveModelIdOf(stdinJson),
816
+ ctxLive.basis === 'compact' ? ctxLive.window : null,
817
+ );
807
818
  } catch (e) { debug('ctx-window-cache:record', e); }
808
819
  }
809
820
  if (caps || model) {
@@ -882,13 +893,27 @@ async function main() {
882
893
  debug('session-effort:record', e);
883
894
  }
884
895
  }
885
- const ctxLive = extractContextUsage(stdinJson);
896
+ // Counted against the auto-compact window (src/ctx-fill.js), so every screen
897
+ // shows the same percentage. Only the statusline reads the settings for it.
898
+ const ctxLive = isStatusline
899
+ ? liveContextFor(stdinJson, {
900
+ root: process.cwd(),
901
+ model: liveModelIdOf(stdinJson),
902
+ sessionId: extractSessionId(stdinJson),
903
+ })
904
+ : extractContextUsage(stdinJson);
886
905
  // The prompt-submit briefing has no payload field for the window, so it reads
887
906
  // back what this render was told (see src/ctx-window-cache.js).
888
907
  if (isStatusline && ctxLive?.size) {
889
908
  try {
890
909
  const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
891
- recordLiveWindow(extractSessionId(stdinJson), ctxLive.size, Date.now(), liveModelIdOf(stdinJson));
910
+ recordLiveWindow(
911
+ extractSessionId(stdinJson),
912
+ ctxLive.size,
913
+ Date.now(),
914
+ liveModelIdOf(stdinJson),
915
+ ctxLive.basis === 'compact' ? ctxLive.window : null,
916
+ );
892
917
  } catch (e) {
893
918
  debug('ctx-window-cache:record', e);
894
919
  }
@@ -80,9 +80,13 @@ export function statuslinePayload(input: {
80
80
  model: { id: input.model, display_name: input.model },
81
81
  }
82
82
  if (usage.context.percent !== undefined) {
83
+ // The mod's percent counts against the full window. The token count lets
84
+ // the CLI work out which window a percentage used and recount it against
85
+ // the auto-compact window, so this screen agrees with the others.
83
86
  payload.context_window = {
84
87
  context_window_size: usage.context.window,
85
88
  used_percentage: usage.context.percent,
89
+ ...(Number.isFinite(usage.context.tokens) ? { total_input_tokens: usage.context.tokens } : {}),
86
90
  }
87
91
  }
88
92
  if (usage.rateLimits.length) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.139.0",
3
+ "version": "3.140.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -26,7 +26,7 @@ import { readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
26
26
  import { execFileSync } from 'node:child_process';
27
27
  import { dirname, join, sep } from 'node:path';
28
28
  import { loadRecentSnapshot } from './caps-cache.js';
29
- import { liveModelFor, liveWindowFor } from './ctx-window-cache.js';
29
+ import { liveCompactWindowFor, liveModelFor, liveWindowFor } from './ctx-window-cache.js';
30
30
  import { peekCached } from './session-cache.js';
31
31
  import { sessionCostAcross } from './claude-price.js';
32
32
  import { labelForKey, windowLabel } from './window-labels.js';
@@ -182,6 +182,9 @@ export function claudeUsage({ cache, transcript, sessionId, env, now }) {
182
182
  * from its own cache entry (a subagent's are not added), and null when the
183
183
  * transcript has no entry yet.
184
184
  *
185
+ * `context.window` is the auto-compact window the statusline counted against
186
+ * when it recorded one, otherwise the full window it reported.
187
+ *
185
188
  * @returns {{ model: string|null, modelName: string|null,
186
189
  * context: { tokens: number, window: number|null, pct: number|null }|null,
187
190
  * usage: object|null, compactions: number|null }}
@@ -199,7 +202,7 @@ export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env
199
202
  if (wide) tokens = lastContextTokens(wide);
200
203
  }
201
204
  if (tokens !== null) {
202
- const window = liveWindowFor(sessionId, ctxPath);
205
+ const window = liveCompactWindowFor(sessionId, ctxPath) ?? liveWindowFor(sessionId, ctxPath);
203
206
  detail.context = { tokens, window, pct: window ? Math.round(tokens / window * 100) : null };
204
207
  }
205
208
  detail.usage = claudeUsage({ cache, transcript, sessionId, env, now });
package/src/brief.js CHANGED
@@ -30,7 +30,7 @@ import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, openSync,
30
30
  import { join } from 'node:path';
31
31
  import { userDataDir } from './paths.js';
32
32
  import { resolveModelId, isOneMillionModel, effectiveWindow, canonicalModelId } from './compact-window.js';
33
- import { liveWindowFor, liveModelFor, liveWindowsByModel } from './ctx-window-cache.js';
33
+ import { liveWindowFor, liveCompactWindowFor, liveModelFor, liveWindowsByModel } from './ctx-window-cache.js';
34
34
  import { routingEnabled } from './routing-switch.js';
35
35
 
36
36
  // Context tiers as a fraction of the session's context window. Tier 1 warns
@@ -91,8 +91,13 @@ function saveState(state, now) {
91
91
  * statusline for this session, so the briefing and the statusline count against
92
92
  * the same window. The model id cannot stand in for it: a model that is 1M
93
93
  * without a `[1m]` suffix reads as 200k there.
94
+ *
95
+ * `liveCompact` is the auto-compact window the statusline actually counted this
96
+ * session against. It outranks the settings lookup for the cap: the statusline
97
+ * also sees a window no settings file mentions (the server's default for the
98
+ * account), and the briefing has to warn at the same fill the statusline shows.
94
99
  */
95
- export function ctxWindowFor(observedMax = 0, root = process.cwd(), { liveWindow = null } = {}) {
100
+ export function ctxWindowFor(observedMax = 0, root = process.cwd(), { liveWindow = null, liveCompact = null } = {}) {
96
101
  let modelWindow = observedMax > WINDOW_1M_MIN_INPUT ? 1_000_000 : 200_000;
97
102
  const reported = Number.isFinite(liveWindow) && liveWindow > 0;
98
103
  if (reported) modelWindow = liveWindow;
@@ -119,7 +124,7 @@ export function ctxWindowFor(observedMax = 0, root = process.cwd(), { liveWindow
119
124
  const seen = key ? liveWindowsByModel().find((e) => same(e.model)) : null;
120
125
  if (seen) modelWindow = window = Math.max(seen.size, modelWindow);
121
126
  }
122
- const cap = effectiveWindow(root).value;
127
+ const cap = Number.isFinite(liveCompact) && liveCompact > 0 ? liveCompact : effectiveWindow(root).value;
123
128
  if (cap !== null && cap < window) {
124
129
  window = cap;
125
130
  compactCapped = true;
@@ -132,7 +137,7 @@ export function ctxWindowFor(observedMax = 0, root = process.cwd(), { liveWindow
132
137
  * Last request's input size for THIS session, from the transcript tail.
133
138
  * Reads at most TAIL_BYTES — prompt-submit hooks must stay fast.
134
139
  */
135
- export function sessionCtx(transcriptPath, { root = process.cwd(), liveWindow = null } = {}) {
140
+ export function sessionCtx(transcriptPath, { root = process.cwd(), liveWindow = null, liveCompact = null } = {}) {
136
141
  let size;
137
142
  try { size = statSync(transcriptPath).size; } catch { return null; }
138
143
  const start = Math.max(0, size - TAIL_BYTES);
@@ -158,7 +163,7 @@ export function sessionCtx(transcriptPath, { root = process.cwd(), liveWindow =
158
163
  if (total > 0) { input = total; maxInput = Math.max(maxInput, total); }
159
164
  }
160
165
  if (input == null) return null;
161
- const { window, modelWindow, compactCapped } = ctxWindowFor(maxInput, root, { liveWindow });
166
+ const { window, modelWindow, compactCapped } = ctxWindowFor(maxInput, root, { liveWindow, liveCompact });
162
167
  return { input, window, modelWindow, compactCapped, pct: input / window };
163
168
  }
164
169
 
@@ -246,6 +251,7 @@ export function seedSessionBriefed(sessionId, signatures, now = Date.now()) {
246
251
  export async function runBrief({ sessionId, transcriptPath, root = process.cwd(), now = Date.now() }) {
247
252
  if (!sessionId) return null;
248
253
  const liveWindow = liveWindowFor(sessionId);
254
+ const liveCompact = liveCompactWindowFor(sessionId);
249
255
  const liveModel = liveModelFor(sessionId);
250
256
  const state = loadState();
251
257
  const s = state.sessions[sessionId] || { ctxTier: 0, briefed: [] };
@@ -253,7 +259,7 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
253
259
  const urgent = [];
254
260
 
255
261
  // ── context tier crossing (per-session) ──
256
- const ctx = transcriptPath ? sessionCtx(transcriptPath, { root, liveWindow }) : null;
262
+ const ctx = transcriptPath ? sessionCtx(transcriptPath, { root, liveWindow, liveCompact }) : null;
257
263
  if (ctx) {
258
264
  const tier = ctxTierOf(ctx.pct);
259
265
  // The tier is not monotonic: auto-compaction drops the live context back to
@@ -0,0 +1,102 @@
1
+ /**
2
+ * How full the context is, counted against one window on every screen.
3
+ *
4
+ * Claude Code 2.1.336+ divides `context_window.used_percentage` by the
5
+ * auto-compact window when one is set, while `context_window_size` stays the
6
+ * model's full window. Older builds, the desktop mod and `sprag bar` count
7
+ * against the full window. The same session therefore read 68% in one place and
8
+ * 34% in another. This module settles on the compact window: it works out which
9
+ * base a payload used, then recomputes the percentage when it was the full one.
10
+ *
11
+ * `total_input_tokens` is the context's token count in every build, and
12
+ * `context_window_size` the full window in every build, so their ratio is the
13
+ * full-window percentage no matter what `used_percentage` was divided by.
14
+ */
15
+
16
+ import { extractContextUsage } from './stdin-payload.js';
17
+ import { effectiveWindow } from './compact-window.js';
18
+ import { liveCompactWindowFor } from './ctx-window-cache.js';
19
+
20
+ const isPos = (v) => Number.isFinite(v) && v > 0;
21
+ // Claude Code rounds the percentage; this much slack absorbs that rounding.
22
+ const ROUND_SLACK = 1;
23
+ // A percentage rounded to whole numbers pins the window to [lo, hi]. Past this
24
+ // width the range holds several plausible windows and guessing one would be a
25
+ // coin flip, so no window is reported.
26
+ const MAX_GUESS_SPAN = 20_000;
27
+ const GUESS_STEP = 10_000;
28
+
29
+ /**
30
+ * @param {{ usedPct: number|null, size: number|null, tokens: number|null }|null} live
31
+ * `extractContextUsage()` result.
32
+ * @param {{ compactWindow?: number|null, knownCompact?: number|null }} [known]
33
+ * `compactWindow`: the auto-compact window the settings say. `knownCompact`:
34
+ * the one an earlier render of this session recorded (ctx-window.json).
35
+ * @returns {{ usedPct: number|null, size: number|null, window: number|null,
36
+ * basis: 'compact'|'full', fullPct: number|null,
37
+ * tokens: number|null }|null}
38
+ * `usedPct` is measured against `window`; `size` is always the full window.
39
+ */
40
+ export function contextFill(live, { compactWindow = null, knownCompact = null } = {}) {
41
+ if (!live) return null;
42
+ const { usedPct: inPct, size, tokens } = live;
43
+ const compact = isPos(compactWindow) ? compactWindow : null;
44
+ const known = isPos(knownCompact) ? knownCompact : null;
45
+ const fullPct = tokens !== null && isPos(size) ? Math.round(tokens / size * 100) : null;
46
+ const out = (usedPct, window, basis) => ({ usedPct, size, window, basis, fullPct, tokens });
47
+
48
+ // The payload counted against a smaller window when its percentage runs
49
+ // ahead of the one the token count gives on the full window.
50
+ const payloadIsCompact = inPct !== null && tokens !== null && tokens > 0 && isPos(size)
51
+ && inPct > Math.round(tokens / size * 100) + ROUND_SLACK;
52
+
53
+ if (payloadIsCompact) {
54
+ let window = null;
55
+ if (inPct >= 1 && inPct <= 99) {
56
+ const lo = tokens * 100 / (inPct + 0.5);
57
+ const hi = tokens * 100 / (inPct - 0.5);
58
+ window = [compact, known].find((w) => w !== null && w >= lo && w <= hi) ?? null;
59
+ if (window === null && hi - lo <= MAX_GUESS_SPAN) {
60
+ window = Math.round(tokens * 100 / inPct / GUESS_STEP) * GUESS_STEP;
61
+ }
62
+ } else {
63
+ window = compact ?? known ?? null;
64
+ }
65
+ return out(inPct, window, 'compact');
66
+ }
67
+
68
+ if (compact !== null && isPos(size) && compact < size && inPct !== null) {
69
+ // Without a token count (a very old Claude Code) the full-window percentage
70
+ // gives it back.
71
+ const numerator = tokens !== null ? tokens : inPct * size / 100;
72
+ const pct = Math.max(0, Math.min(100, Math.round(numerator / compact * 100)));
73
+ return out(pct, compact, 'compact');
74
+ }
75
+
76
+ return out(inPct, size, 'full');
77
+ }
78
+
79
+ const disabled = (v) => v === '1' || (typeof v === 'string' && v.toLowerCase() === 'true');
80
+
81
+ /**
82
+ * `contextFill()` for a statusline payload, with the compact window read from
83
+ * the settings and from what this session's earlier renders recorded. Null when
84
+ * the payload carries no context data.
85
+ *
86
+ * Auto-compaction turned off by environment means the full window is the only
87
+ * one there is, so no compact window is applied.
88
+ */
89
+ export function liveContextFor(stdinJson, { root = process.cwd(), model = null, sessionId = null } = {}) {
90
+ const live = extractContextUsage(stdinJson);
91
+ if (!live) return null;
92
+ let compactWindow = null;
93
+ if (!disabled(process.env.DISABLE_AUTO_COMPACT) && !disabled(process.env.DISABLE_COMPACT)) {
94
+ try {
95
+ const w = model ? effectiveWindow(root, { model }) : effectiveWindow(root);
96
+ compactWindow = w.value;
97
+ } catch { /* settings unreadable: the recorded window still applies */ }
98
+ }
99
+ let knownCompact = null;
100
+ try { knownCompact = liveCompactWindowFor(sessionId); } catch { /* no record */ }
101
+ return contextFill(live, { compactWindow, knownCompact });
102
+ }
@@ -13,8 +13,13 @@
13
13
  * reads it back to look up the session's own `modelSettings` entry, which a
14
14
  * settings-only lookup cannot see when the model was picked with `/model`.
15
15
  *
16
+ * The auto-compact window the statusline counted this session's percentage
17
+ * against (`compact`) is stored too, when it knew one. The briefing and `sprag
18
+ * bar` read it back so their percentages use the same window as the statusline,
19
+ * including a server default that no settings file mentions.
20
+ *
16
21
  * State: <stateDir>/ctx-window.json
17
- * { sessions: { [session_id]: { size, ts, model? } } }
22
+ * { sessions: { [session_id]: { size, ts, model?, compact? } } }
18
23
  * Entries untouched for 7 days are pruned on write.
19
24
  */
20
25
 
@@ -43,14 +48,22 @@ function load(path = ctxWindowCachePath()) {
43
48
 
44
49
  const validSize = (size) => Number.isFinite(size) && size > 0;
45
50
 
46
- /** Record the window the statusline payload reported. Returns true when the file was written. */
47
- export function recordLiveWindow(sessionId, size, now = Date.now(), model = null) {
51
+ /**
52
+ * Record the window the statusline payload reported, and the auto-compact
53
+ * window its percentage was counted against when there is one. Returns true
54
+ * when the file was written.
55
+ */
56
+ export function recordLiveWindow(sessionId, size, now = Date.now(), model = null, compact = null) {
48
57
  if (typeof sessionId !== 'string' || sessionId === '' || !validSize(size)) return false;
49
58
  const m = typeof model === 'string' && model !== '' ? model : undefined;
59
+ const c = validSize(compact) ? compact : undefined;
50
60
  const state = load();
51
61
  const prev = state.sessions[sessionId];
52
- if (prev && prev.size === size && prev.model === m && now - prev.ts < REFRESH_MS) return false;
53
- state.sessions[sessionId] = m ? { size, ts: now, model: m } : { size, ts: now };
62
+ if (prev && prev.size === size && prev.model === m && prev.compact === c && now - prev.ts < REFRESH_MS) return false;
63
+ const entry = { size, ts: now };
64
+ if (m) entry.model = m;
65
+ if (c) entry.compact = c;
66
+ state.sessions[sessionId] = entry;
54
67
  for (const [id, s] of Object.entries(state.sessions)) {
55
68
  if (!s || !Number.isFinite(s.ts) || now - s.ts > PRUNE_MS) delete state.sessions[id];
56
69
  }
@@ -68,6 +81,16 @@ export function liveWindowFor(sessionId, file = ctxWindowCachePath()) {
68
81
  return s && validSize(s.size) ? s.size : null;
69
82
  }
70
83
 
84
+ /**
85
+ * The auto-compact window the session's statusline counted against, or null
86
+ * when it recorded none. `file` is as in liveWindowFor.
87
+ */
88
+ export function liveCompactWindowFor(sessionId, file = ctxWindowCachePath()) {
89
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
90
+ const s = load(file).sessions[sessionId];
91
+ return s && validSize(s.compact) ? s.compact : null;
92
+ }
93
+
71
94
  /**
72
95
  * The window most recently reported by any session's statusline, or null.
73
96
  * `sprag compact-window` runs outside a session and has no payload of its own;
@@ -1121,9 +1121,14 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
1121
1121
  // Context chip. Two data sources, best first:
1122
1122
  //
1123
1123
  // 1. Live fill level from Claude Code's stdin (`context_window.used_percentage`)
1124
- // — the current session's actual usage, refreshed every render. Rendered
1125
- // as `📦 68%` and colored by fill (green <70, yellow 70–89, red 90+),
1126
- // matching the cap-segment tone scale.
1124
+ // — the current session's actual usage, refreshed every render. The
1125
+ // percentage counts against the auto-compact window when one is set
1126
+ // (`Ctx 68% of 500k`), the same base Claude Code 2.1.336+ uses. Payloads
1127
+ // from older builds and the desktop mod arrive against the full window;
1128
+ // src/ctx-fill.js recomputes those, so every screen agrees. `verbose` adds
1129
+ // the full-window figure (`(34% of 1M)`). Rendered as `📦 68%` and colored
1130
+ // by that percentage (green <70, yellow 70–89, red 90+), matching the
1131
+ // cap-segment tone scale.
1127
1132
  // 2. Fallback (table view / older Claude Code): transcript-inferred window
1128
1133
  // size. Note the semantics: `size === '1M'` means a real request already
1129
1134
  // carried >210k input tokens — actual heavy usage, not just the model
@@ -1134,10 +1139,17 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
1134
1139
  if (ctxLive && Number.isFinite(ctxLive.usedPct)) {
1135
1140
  const pct = Math.max(0, Math.round(ctxLive.usedPct));
1136
1141
  const tone = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;
1137
- const sizeLabel = ctxLive.size
1138
- ? (ctxLive.size >= 900_000 ? '1M' : `${Math.round(ctxLive.size / 1000)}k`)
1139
- : null;
1140
- const longLabel = sizeLabel ? `${pct}% of ${sizeLabel}` : `${pct}%`;
1142
+ // A fixture without `window` is a plain full-window reading.
1143
+ const win = ctxLive.window !== undefined ? ctxLive.window : ctxLive.size;
1144
+ const windowLabel = (n) => (n >= 900_000 ? '1M' : `${Math.round(n / 1000)}k`);
1145
+ const sizeLabel = win ? windowLabel(win) : null;
1146
+ let longLabel = sizeLabel ? `${pct}% of ${sizeLabel}` : `${pct}%`;
1147
+ if (
1148
+ verbose && ctxLive.basis === 'compact' && Number.isFinite(ctxLive.fullPct)
1149
+ && ctxLive.size && win && win < ctxLive.size
1150
+ ) {
1151
+ longLabel += ` (${ctxLive.fullPct}% of ${windowLabel(ctxLive.size)})`;
1152
+ }
1141
1153
  if (isIcon && verbose) {
1142
1154
  ctxSeg = `${c(tone)}${g.ctx} Ctx ${longLabel}${c(RESET)}`;
1143
1155
  } else if (isIcon) {
@@ -158,18 +158,40 @@ export function bedrockDisplayFromId(id) {
158
158
  * Live context usage from Claude Code's stdin payload (`context_window`).
159
159
  * More accurate than inferring from transcripts: it's the CURRENT session's
160
160
  * real fill level, updated every refresh. Shape (subset):
161
- * "context_window": { "context_window_size": 200000, "used_percentage": 68 }
161
+ * "context_window": {
162
+ * "context_window_size": 1000000, // the model's full window
163
+ * "total_input_tokens": 340000, // tokens in the context right now
164
+ * "used_percentage": 68 // see below
165
+ * }
166
+ *
167
+ * What `used_percentage` is measured against depends on the Claude Code build:
168
+ * 2.1.336+ divides by the auto-compact window when one is set (500k above, so
169
+ * 340k reads 68), older builds and the desktop mod divide by the full window
170
+ * (34 for the same session). `context_window_size` and `total_input_tokens`
171
+ * mean the same thing in both, which is what src/ctx-fill.js uses to tell the
172
+ * two apart.
173
+ *
174
+ * Returns `{ usedPct, size, tokens }`, each null when its field is absent or
175
+ * unusable, or null when there is neither a percentage nor a window size. A new
176
+ * session's first render has no percentage yet (Claude Code sends null at zero
177
+ * tokens), and its window size is still worth recording.
162
178
  */
163
179
  export function extractContextUsage(stdinJson) {
164
180
  const cw = stdinJson && stdinJson.context_window;
165
181
  if (!cw || typeof cw !== 'object') return null;
166
- const usedPct = normalizePct(cw.used_percentage);
167
- const size = Number(cw.context_window_size);
168
- if (usedPct === null) return null;
169
- return {
170
- usedPct,
171
- size: Number.isFinite(size) && size > 0 ? size : null,
182
+ // Same trap as normalizePct: Number(null|''|[]) is 0, so only a real number
183
+ // or a numeric string counts.
184
+ const num = (raw) => {
185
+ if (typeof raw === 'string' && raw.trim() !== '') raw = Number(raw);
186
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;
172
187
  };
188
+ const usedPct = normalizePct(cw.used_percentage);
189
+ const rawSize = num(cw.context_window_size);
190
+ const size = rawSize !== null && rawSize > 0 ? rawSize : null;
191
+ if (usedPct === null && size === null) return null;
192
+ const rawTokens = num(cw.total_input_tokens);
193
+ const tokens = rawTokens !== null && rawTokens >= 0 ? rawTokens : null;
194
+ return { usedPct, size, tokens };
173
195
  }
174
196
 
175
197
  /**