sprag-cli 3.138.1 → 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 +34 -4
- package/mod/sprag-statusline/hooks/register.tsx +37 -1
- package/package.json +1 -1
- package/src/agent-usage.js +5 -2
- package/src/brief.js +12 -6
- package/src/ctx-fill.js +102 -0
- package/src/ctx-window-cache.js +28 -5
- package/src/formatters/statusline.js +39 -11
- package/src/stdin-payload.js +49 -5
package/bin/cli.js
CHANGED
|
@@ -38,11 +38,13 @@ import {
|
|
|
38
38
|
extractContextUsage,
|
|
39
39
|
extractEffort,
|
|
40
40
|
extractModel,
|
|
41
|
+
extractPromptCache,
|
|
41
42
|
extractSessionId,
|
|
42
43
|
extractTranscriptPath,
|
|
43
44
|
} from '../src/stdin-payload.js';
|
|
44
45
|
|
|
45
46
|
import { ultracodeChipState } from '../src/ultracode.js';
|
|
47
|
+
import { liveContextFor } from '../src/ctx-fill.js';
|
|
46
48
|
|
|
47
49
|
import { parseAllSessions, sessionsSince, getLastUserMessageTime, flushPendingSessionCache, parseStats } from '../src/parser.js';
|
|
48
50
|
import {
|
|
@@ -798,11 +800,21 @@ async function main() {
|
|
|
798
800
|
} catch (e) { debug('session-effort:record', e); }
|
|
799
801
|
// Recorded here too: a fresh session can render before it has any request
|
|
800
802
|
// in the analysis window, and its first prompt is briefed from this.
|
|
801
|
-
const ctxLive =
|
|
803
|
+
const ctxLive = liveContextFor(stdinJson, {
|
|
804
|
+
root: process.cwd(),
|
|
805
|
+
model: liveModelIdOf(stdinJson),
|
|
806
|
+
sessionId: extractSessionId(stdinJson),
|
|
807
|
+
});
|
|
802
808
|
if (ctxLive?.size) {
|
|
803
809
|
try {
|
|
804
810
|
const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
|
|
805
|
-
recordLiveWindow(
|
|
811
|
+
recordLiveWindow(
|
|
812
|
+
extractSessionId(stdinJson),
|
|
813
|
+
ctxLive.size,
|
|
814
|
+
Date.now(),
|
|
815
|
+
liveModelIdOf(stdinJson),
|
|
816
|
+
ctxLive.basis === 'compact' ? ctxLive.window : null,
|
|
817
|
+
);
|
|
806
818
|
} catch (e) { debug('ctx-window-cache:record', e); }
|
|
807
819
|
}
|
|
808
820
|
if (caps || model) {
|
|
@@ -881,13 +893,27 @@ async function main() {
|
|
|
881
893
|
debug('session-effort:record', e);
|
|
882
894
|
}
|
|
883
895
|
}
|
|
884
|
-
|
|
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);
|
|
885
905
|
// The prompt-submit briefing has no payload field for the window, so it reads
|
|
886
906
|
// back what this render was told (see src/ctx-window-cache.js).
|
|
887
907
|
if (isStatusline && ctxLive?.size) {
|
|
888
908
|
try {
|
|
889
909
|
const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
|
|
890
|
-
recordLiveWindow(
|
|
910
|
+
recordLiveWindow(
|
|
911
|
+
extractSessionId(stdinJson),
|
|
912
|
+
ctxLive.size,
|
|
913
|
+
Date.now(),
|
|
914
|
+
liveModelIdOf(stdinJson),
|
|
915
|
+
ctxLive.basis === 'compact' ? ctxLive.window : null,
|
|
916
|
+
);
|
|
891
917
|
} catch (e) {
|
|
892
918
|
debug('ctx-window-cache:record', e);
|
|
893
919
|
}
|
|
@@ -1230,6 +1256,10 @@ async function main() {
|
|
|
1230
1256
|
? readStarChip({ savedUsd: delegationSaved + (Number(doc2mdTotals?.total) || 0) })
|
|
1231
1257
|
: null,
|
|
1232
1258
|
lastActivity,
|
|
1259
|
+
// Claude Code's own cache figures for this session (2.1.333+, and the
|
|
1260
|
+
// desktop mod); when present the TTL chip counts down to them instead of
|
|
1261
|
+
// estimating from the last activity across transcripts.
|
|
1262
|
+
promptCache: isStatusline ? extractPromptCache(stdinJson) : null,
|
|
1233
1263
|
monthSpend: monthSpendInfo,
|
|
1234
1264
|
modelShare,
|
|
1235
1265
|
spikeReport,
|
|
@@ -63,7 +63,8 @@ export function statuslineArgv(settings: Readonly<Record<string, unknown>>): str
|
|
|
63
63
|
* The JSON Claude Code's statusline would have been fed. Fields the engine has
|
|
64
64
|
* no value for are left out, never zeroed: sprag reads an absent rate_limits as
|
|
65
65
|
* "no data" but a 0 as "0% used". transcript_path is left out because the mod
|
|
66
|
-
* cannot know it, and sprag takes it only for the effort chip.
|
|
66
|
+
* cannot know it, and sprag takes it only for the effort chip. prompt_cache
|
|
67
|
+
* lets the cache chip count down to the engine's own expiry time.
|
|
67
68
|
*/
|
|
68
69
|
export function statuslinePayload(input: {
|
|
69
70
|
sessionId: string
|
|
@@ -79,9 +80,13 @@ export function statuslinePayload(input: {
|
|
|
79
80
|
model: { id: input.model, display_name: input.model },
|
|
80
81
|
}
|
|
81
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.
|
|
82
86
|
payload.context_window = {
|
|
83
87
|
context_window_size: usage.context.window,
|
|
84
88
|
used_percentage: usage.context.percent,
|
|
89
|
+
...(Number.isFinite(usage.context.tokens) ? { total_input_tokens: usage.context.tokens } : {}),
|
|
85
90
|
}
|
|
86
91
|
}
|
|
87
92
|
if (usage.rateLimits.length) {
|
|
@@ -96,9 +101,40 @@ export function statuslinePayload(input: {
|
|
|
96
101
|
payload.rate_limits = limits
|
|
97
102
|
}
|
|
98
103
|
if (usage.cost) payload.cost = { total_cost_usd: usage.cost.usd }
|
|
104
|
+
const cache = promptCacheOf(usage)
|
|
105
|
+
if (cache) payload.prompt_cache = cache
|
|
99
106
|
return payload
|
|
100
107
|
}
|
|
101
108
|
|
|
109
|
+
/**
|
|
110
|
+
* The engine's prompt cache figures (2.1.333+) as the terminal statusline gets
|
|
111
|
+
* them in `prompt_cache`: epoch seconds for the expiry, null when nothing is
|
|
112
|
+
* cached. Read through a local type so the module still type-checks against
|
|
113
|
+
* engines whose SessionUsage has no promptCache; there it is simply absent and
|
|
114
|
+
* sprag keeps estimating the countdown from the transcripts.
|
|
115
|
+
*/
|
|
116
|
+
type EnginePromptCache = {
|
|
117
|
+
isWarm?: unknown
|
|
118
|
+
expiresAt?: unknown
|
|
119
|
+
ttl?: unknown
|
|
120
|
+
lastMissCauses?: unknown
|
|
121
|
+
recacheTokens?: unknown
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function promptCacheOf(usage: SessionUsage): Record<string, unknown> | undefined {
|
|
125
|
+
const pc = (usage as { promptCache?: EnginePromptCache }).promptCache
|
|
126
|
+
if (!pc || (pc.ttl !== '5m' && pc.ttl !== '1h')) return undefined
|
|
127
|
+
const at = typeof pc.expiresAt === 'number' && Number.isFinite(pc.expiresAt) ? Math.floor(pc.expiresAt / 1000) : null
|
|
128
|
+
const causes = Array.isArray(pc.lastMissCauses) ? pc.lastMissCauses.filter(c => typeof c === 'string') : undefined
|
|
129
|
+
return {
|
|
130
|
+
warm: pc.isWarm === true,
|
|
131
|
+
ttl: pc.ttl,
|
|
132
|
+
expires_at: at,
|
|
133
|
+
...(causes?.length ? { last_miss_cause: { causes } } : {}),
|
|
134
|
+
...(typeof pc.recacheTokens === 'number' ? { recache_tokens_if_cold: pc.recacheTokens } : {}),
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
102
138
|
/**
|
|
103
139
|
* The argv with `--columns <n>` added, so sprag fits its chips to the band and
|
|
104
140
|
* wraps them at chip boundaries instead of the band wrapping them mid-chip. A
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
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": {
|
package/src/agent-usage.js
CHANGED
|
@@ -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
|
package/src/ctx-fill.js
ADDED
|
@@ -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
|
+
}
|
package/src/ctx-window-cache.js
CHANGED
|
@@ -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
|
-
/**
|
|
47
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -993,7 +993,15 @@ function buildPeriodSeg(options, c, verbose) {
|
|
|
993
993
|
* Which cache bucket the session is in, and the countdown length that follows
|
|
994
994
|
* from it: `{ is1h, bucketLabel, bucketColor, ttlSeconds }`.
|
|
995
995
|
*/
|
|
996
|
-
function resolveTtlBucket(ttl, ttlBucket) {
|
|
996
|
+
function resolveTtlBucket(ttl, ttlBucket, promptCache) {
|
|
997
|
+
// Claude Code's own report of the bucket the last request wrote is a
|
|
998
|
+
// measurement of this very session, so it settles what the transcript split
|
|
999
|
+
// and the gateway guess below can only estimate. A pinned bucket still wins:
|
|
1000
|
+
// it exists for providers whose reports cannot be trusted.
|
|
1001
|
+
if (promptCache && (promptCache.ttl === '5m' || promptCache.ttl === '1h') && ttlBucket !== '5m' && ttlBucket !== '1h') {
|
|
1002
|
+
const is1h = promptCache.ttl === '1h';
|
|
1003
|
+
return { is1h, bucketLabel: promptCache.ttl, bucketColor: is1h ? GREEN : YELLOW, ttlSeconds: is1h ? 3600 : 300 };
|
|
1004
|
+
}
|
|
997
1005
|
// TTL dominance → color signal (1h = good, 5m = warning).
|
|
998
1006
|
// The subscription plan fixes this, so the bucket rarely changes — it's the countdown that matters.
|
|
999
1007
|
// When ttl.total === 0 (no cache writes observed in the window), we cannot
|
|
@@ -1029,8 +1037,16 @@ function resolveTtlBucket(ttl, ttlBucket) {
|
|
|
1029
1037
|
* Cache TTL chip: the countdown on the last call's cache entry, or just the
|
|
1030
1038
|
* bucket when the timer is off or there is no last call.
|
|
1031
1039
|
*/
|
|
1032
|
-
function buildTtlSeg({ ttl, ttlBucket, lastActivity }, timer, c, isIcon, verbose, g) {
|
|
1033
|
-
const { is1h, bucketLabel, bucketColor, ttlSeconds } = resolveTtlBucket(ttl, ttlBucket);
|
|
1040
|
+
function buildTtlSeg({ ttl, ttlBucket, lastActivity, promptCache }, timer, c, isIcon, verbose, g) {
|
|
1041
|
+
const { is1h, bucketLabel, bucketColor, ttlSeconds } = resolveTtlBucket(ttl, ttlBucket, promptCache);
|
|
1042
|
+
// With Claude Code's figures in hand the countdown runs to its expiry time.
|
|
1043
|
+
// A null expiry there means the last response cached nothing, so there is no
|
|
1044
|
+
// clock to show, only the bucket; estimating one from other sessions'
|
|
1045
|
+
// activity would count down a cache this session does not have.
|
|
1046
|
+
const reported = promptCache && (promptCache.ttl === '5m' || promptCache.ttl === '1h');
|
|
1047
|
+
if (reported) {
|
|
1048
|
+
lastActivity = Number.isFinite(promptCache.expiresAtMs) ? promptCache.expiresAtMs - ttlSeconds * 1000 : null;
|
|
1049
|
+
}
|
|
1034
1050
|
|
|
1035
1051
|
// TTL countdown — how much time is left on the last API call's cache entry.
|
|
1036
1052
|
// Matches Anthropic's actual prompt-cache behaviour: each call starts a fresh
|
|
@@ -1105,9 +1121,14 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
|
|
|
1105
1121
|
// Context chip. Two data sources, best first:
|
|
1106
1122
|
//
|
|
1107
1123
|
// 1. Live fill level from Claude Code's stdin (`context_window.used_percentage`)
|
|
1108
|
-
// — the current session's actual usage, refreshed every render.
|
|
1109
|
-
//
|
|
1110
|
-
//
|
|
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.
|
|
1111
1132
|
// 2. Fallback (table view / older Claude Code): transcript-inferred window
|
|
1112
1133
|
// size. Note the semantics: `size === '1M'` means a real request already
|
|
1113
1134
|
// carried >210k input tokens — actual heavy usage, not just the model
|
|
@@ -1118,10 +1139,17 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
|
|
|
1118
1139
|
if (ctxLive && Number.isFinite(ctxLive.usedPct)) {
|
|
1119
1140
|
const pct = Math.max(0, Math.round(ctxLive.usedPct));
|
|
1120
1141
|
const tone = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
const
|
|
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
|
+
}
|
|
1125
1153
|
if (isIcon && verbose) {
|
|
1126
1154
|
ctxSeg = `${c(tone)}${g.ctx} Ctx ${longLabel}${c(RESET)}`;
|
|
1127
1155
|
} else if (isIcon) {
|
|
@@ -1907,7 +1935,7 @@ export function formatReport(data, { color = true, verbose: verboseOpt = false,
|
|
|
1907
1935
|
usage: buildUsageSegs(caps, capWarn, c, isIcon, verbose, g, color, mode),
|
|
1908
1936
|
ctx: buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g),
|
|
1909
1937
|
compactions: buildCompactionsSeg(data.compactions, c, isIcon, verbose, g),
|
|
1910
|
-
ttl: buildTtlSeg({ ttl, ttlBucket: data.ttlBucket, lastActivity }, timer, c, isIcon, verbose, g),
|
|
1938
|
+
ttl: buildTtlSeg({ ttl, ttlBucket: data.ttlBucket, lastActivity, promptCache: data.promptCache }, timer, c, isIcon, verbose, g),
|
|
1911
1939
|
// Model, then the effort that qualifies it: the same model answers
|
|
1912
1940
|
// differently at `low` and at `max`, and the pair is one glance.
|
|
1913
1941
|
model: buildModelSeg(model, c, isIcon, g),
|
package/src/stdin-payload.js
CHANGED
|
@@ -158,17 +158,61 @@ 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": {
|
|
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;
|
|
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;
|
|
187
|
+
};
|
|
166
188
|
const usedPct = normalizePct(cw.used_percentage);
|
|
167
|
-
const
|
|
168
|
-
|
|
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 };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The main conversation's prompt cache as Claude Code 2.1.333+ reports it
|
|
199
|
+
* (`prompt_cache`), the desktop mod passing `$.session.usage().promptCache` in
|
|
200
|
+
* the same shape. Subset used:
|
|
201
|
+
* "prompt_cache": { "warm": true, "ttl": "1h", "expires_at": 1764550000 }
|
|
202
|
+
* `expires_at` is epoch seconds, or null when the last response cached
|
|
203
|
+
* nothing. Returns `{ ttl, expiresAtMs }` with `expiresAtMs` null in that case,
|
|
204
|
+
* or null when the key is absent or its ttl is not one of the two buckets: an
|
|
205
|
+
* older Claude Code, or a payload this reader does not understand, keeps the
|
|
206
|
+
* transcript-based estimate.
|
|
207
|
+
*/
|
|
208
|
+
export function extractPromptCache(stdinJson) {
|
|
209
|
+
const pc = stdinJson && stdinJson.prompt_cache;
|
|
210
|
+
if (!pc || typeof pc !== 'object') return null;
|
|
211
|
+
if (pc.ttl !== '5m' && pc.ttl !== '1h') return null;
|
|
212
|
+
const at = typeof pc.expires_at === 'number' ? pc.expires_at : NaN;
|
|
169
213
|
return {
|
|
170
|
-
|
|
171
|
-
|
|
214
|
+
ttl: pc.ttl,
|
|
215
|
+
expiresAtMs: Number.isFinite(at) && at > 0 ? (at < 1e12 ? at * 1000 : at) : null,
|
|
172
216
|
};
|
|
173
217
|
}
|
|
174
218
|
|