sprag-cli 3.99.0 → 3.100.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 +16 -8
- package/package.json +1 -1
- package/src/brief.js +11 -6
- package/src/claude-price.js +3 -2
- package/src/commands/compact-window.js +62 -20
- package/src/compact-window.js +202 -26
- package/src/cost.js +152 -35
- package/src/ctx-window-cache.js +28 -5
- package/src/formatters/statusline.js +4 -4
- package/src/harness.js +5 -5
- package/src/net-saving.js +4 -4
- package/src/route-scan.js +13 -6
package/bin/cli.js
CHANGED
|
@@ -63,6 +63,12 @@ import { readUpdateChip } from '../src/update-notice.js';
|
|
|
63
63
|
import { readStarChip } from '../src/star-note.js';
|
|
64
64
|
import { selectAgent } from '../src/agent.js';
|
|
65
65
|
|
|
66
|
+
// The raw model id from the statusline payload (`claude-opus-5-5[1m]`, `opus`,
|
|
67
|
+
// a Bedrock id ...), not extractModel()'s display name: the briefing matches it
|
|
68
|
+
// against settings `modelSettings` keys.
|
|
69
|
+
const liveModelIdOf = (j) =>
|
|
70
|
+
typeof j?.model?.id === 'string' ? j.model.id : (typeof j?.model === 'string' ? j.model : null);
|
|
71
|
+
|
|
66
72
|
const selection = (() => {
|
|
67
73
|
try { return selectAgent(process.argv.slice(2)); }
|
|
68
74
|
catch (e) { console.error(`Error: ${e.message}`); process.exit(1); }
|
|
@@ -451,12 +457,12 @@ async function main() {
|
|
|
451
457
|
}
|
|
452
458
|
|
|
453
459
|
// Subcommand: compact-window — audit / pin Claude Code's autoCompactWindow.
|
|
454
|
-
// On a 1M-context model, compaction only fires
|
|
455
|
-
// capped; 200k sessions are exempt.
|
|
456
|
-
// sprag compact-window
|
|
457
|
-
// sprag compact-window set --global
|
|
458
|
-
// sprag compact-window set --project
|
|
459
|
-
// sprag compact-window off | on
|
|
460
|
+
// On a 1M-context model, compaction only fires at about 967k unless the
|
|
461
|
+
// window is capped; 200k sessions are exempt.
|
|
462
|
+
// sprag compact-window # status
|
|
463
|
+
// sprag compact-window set --global --all-models # pin 500k for every model (~/.claude/settings.json)
|
|
464
|
+
// sprag compact-window set --project --model <id> # pin 500k for one model (<root>/.claude/settings.json)
|
|
465
|
+
// sprag compact-window off | on # toggle the chip and the briefing
|
|
460
466
|
if (args[0] === 'compact-window') {
|
|
461
467
|
return (await import('../src/commands/compact-window.js')).run({ args, hasFlag });
|
|
462
468
|
}
|
|
@@ -703,7 +709,7 @@ async function main() {
|
|
|
703
709
|
if (ctxLive?.size) {
|
|
704
710
|
try {
|
|
705
711
|
const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
|
|
706
|
-
recordLiveWindow(extractSessionId(stdinJson), ctxLive.size);
|
|
712
|
+
recordLiveWindow(extractSessionId(stdinJson), ctxLive.size, Date.now(), liveModelIdOf(stdinJson));
|
|
707
713
|
} catch (e) { debug('ctx-window-cache:record', e); }
|
|
708
714
|
}
|
|
709
715
|
if (caps || model) {
|
|
@@ -780,7 +786,7 @@ async function main() {
|
|
|
780
786
|
if (isStatusline && ctxLive?.size) {
|
|
781
787
|
try {
|
|
782
788
|
const { recordLiveWindow } = await import('../src/ctx-window-cache.js');
|
|
783
|
-
recordLiveWindow(extractSessionId(stdinJson), ctxLive.size);
|
|
789
|
+
recordLiveWindow(extractSessionId(stdinJson), ctxLive.size, Date.now(), liveModelIdOf(stdinJson));
|
|
784
790
|
} catch (e) {
|
|
785
791
|
debug('ctx-window-cache:record', e);
|
|
786
792
|
}
|
|
@@ -1060,6 +1066,8 @@ async function main() {
|
|
|
1060
1066
|
spikeChip,
|
|
1061
1067
|
caps,
|
|
1062
1068
|
model,
|
|
1069
|
+
// Raw payload model id for the compact-window chip's `modelSettings` lookup.
|
|
1070
|
+
liveModel: isStatusline ? liveModelIdOf(stdinJson) : undefined,
|
|
1063
1071
|
effort,
|
|
1064
1072
|
delegationSaved,
|
|
1065
1073
|
delegationTotals,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.100.0",
|
|
4
4
|
"description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/brief.js
CHANGED
|
@@ -29,7 +29,7 @@ import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, openSync,
|
|
|
29
29
|
import { join } from 'node:path';
|
|
30
30
|
import { userDataDir } from './paths.js';
|
|
31
31
|
import { resolveModelId, isOneMillionModel, effectiveWindow } from './compact-window.js';
|
|
32
|
-
import { liveWindowFor } from './ctx-window-cache.js';
|
|
32
|
+
import { liveWindowFor, liveModelFor } from './ctx-window-cache.js';
|
|
33
33
|
import { routingEnabled } from './routing-switch.js';
|
|
34
34
|
|
|
35
35
|
// Context tiers as a fraction of the session's context window. Tier 1 warns
|
|
@@ -178,6 +178,7 @@ export function seedSessionBriefed(sessionId, signatures, now = Date.now()) {
|
|
|
178
178
|
export async function runBrief({ sessionId, transcriptPath, root = process.cwd(), now = Date.now() }) {
|
|
179
179
|
if (!sessionId) return null;
|
|
180
180
|
const liveWindow = liveWindowFor(sessionId);
|
|
181
|
+
const liveModel = liveModelFor(sessionId);
|
|
181
182
|
const state = loadState();
|
|
182
183
|
const s = state.sessions[sessionId] || { ctxTier: 0, briefed: [] };
|
|
183
184
|
const items = [];
|
|
@@ -244,20 +245,24 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
|
|
|
244
245
|
} catch { /* caches unreadable — ctx briefing above still applies */ }
|
|
245
246
|
|
|
246
247
|
// ── auto-compact window misconfigured on a 1M model (once per session) ──
|
|
247
|
-
// Config defect, not a usage trend:
|
|
248
|
-
//
|
|
248
|
+
// Config defect, not a usage trend: a native 1M model compacts at about
|
|
249
|
+
// 967k by default, so every request until then re-bills a context the session
|
|
249
250
|
// never needed. 200k sessions are exempt (their window is already <= 200k).
|
|
251
|
+
// `sprag compact-window off` silences this as well as the statusline chip.
|
|
250
252
|
try {
|
|
251
253
|
const cw = await import('./compact-window.js');
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
+
const { loadConfig } = await import('./config.js');
|
|
255
|
+
const st = cw.compactWindowWarningEnabled(loadConfig())
|
|
256
|
+
? cw.compactWindowStatus({ root, liveWindow, liveModel })
|
|
257
|
+
: null;
|
|
258
|
+
if (st && !st.ok) {
|
|
254
259
|
const sig = `compact-window|${st.reason}`;
|
|
255
260
|
const briefed = new Set(s.briefed || []);
|
|
256
261
|
if (!briefed.has(sig)) {
|
|
257
262
|
briefed.add(sig);
|
|
258
263
|
s.briefed = [...briefed];
|
|
259
264
|
const now = st.window ? `현재 ${fmtK(st.window)}` : '현재 미설정';
|
|
260
|
-
items.push(`1M 컨텍스트 모델(${st.model || 'Claude Code 기본 모델'})인데 autoCompactWindow가 ${now}
|
|
265
|
+
items.push(`1M 컨텍스트 모델(${st.model || 'Claude Code 기본 모델'})인데 autoCompactWindow가 ${now}입니다. 자동 압축이 약 97만 토큰(창이 거의 찰 때)에서야 걸려 그전까지 모든 요청이 전체 컨텍스트를 재과금합니다. 1M은 너무 크니 ${fmtK(st.recommendedMin)}~${fmtK(st.recommendedMax)} 범위를 권장합니다(그 범위 안이면 경고하지 않습니다). 1M 창 자체는 그대로 두고 압축 시점만 앞당깁니다. 등록: sprag compact-window set --global|--project --all-models|--model <모델 id> [--value ${fmtK(st.recommendedMax)}] (기본 ${fmtK(st.recommended)}, 적용 범위와 모든 모델에 같은 값을 쓸지 모델별로 쓸지는 사용자에게 확인). ${cw.modelSettingsNotice(cw.claudeCodeVersion(), true)} 끄기: sprag compact-window off`);
|
|
261
266
|
}
|
|
262
267
|
}
|
|
263
268
|
} catch { /* settings unreadable — other briefings above still apply */ }
|
package/src/claude-price.js
CHANGED
|
@@ -10,8 +10,9 @@ import { estimateCost, estimateCostAcross } from './cost.js';
|
|
|
10
10
|
import { gatewayPriceFor } from './litellm-models.js';
|
|
11
11
|
import { gatewayBase } from './gateway-auth.js';
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
// `at` is when the tokens were spent; list prices are looked up for that time.
|
|
14
|
+
export function sessionCost(totals, model, { env = process.env, now, at } = {}) {
|
|
15
|
+
if (!gatewayBase(env)) return estimateCost(totals, model, { at });
|
|
15
16
|
const price = gatewayPriceFor(model, env, now);
|
|
16
17
|
return price ? estimateCost(totals, model, { price }) : null;
|
|
17
18
|
}
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Subcommand: compact-window — audit / pin Claude Code's `autoCompactWindow`.
|
|
3
3
|
* sprag compact-window # status
|
|
4
|
-
* sprag compact-window set --global
|
|
5
|
-
* sprag compact-window set --project
|
|
6
|
-
* sprag compact-window set --global --
|
|
7
|
-
* sprag compact-window
|
|
4
|
+
* sprag compact-window set --global --all-models # 500k for every model in ~/.claude/settings.json
|
|
5
|
+
* sprag compact-window set --project --all-models # same, in <root>/.claude/settings.json
|
|
6
|
+
* sprag compact-window set --global --model claude-opus-5-5 # 500k for that model only
|
|
7
|
+
* sprag compact-window set --global --all-models --value 600k
|
|
8
|
+
* sprag compact-window off | on # toggle the statusline chip and the session briefing
|
|
8
9
|
*
|
|
9
|
-
* Scope
|
|
10
|
-
* not something to guess at, and the non-TTY hook environment
|
|
10
|
+
* Scope and models are deliberately explicit for `set`: writing a global
|
|
11
|
+
* settings.json is not something to guess at, and the non-TTY hook environment
|
|
12
|
+
* cannot prompt. `--all-models` writes the top-level key and removes per-model
|
|
13
|
+
* values in that file so one value really applies everywhere; `--model <id>`
|
|
14
|
+
* writes only that model's `modelSettings` entry, the slot `/autocompact` uses.
|
|
11
15
|
*/
|
|
12
16
|
|
|
13
17
|
export async function run({ args, hasFlag }) {
|
|
@@ -25,7 +29,7 @@ export async function run({ args, hasFlag }) {
|
|
|
25
29
|
cfg.compactWindow = cfg.compactWindow || {};
|
|
26
30
|
cfg.compactWindow.enabled = sub === 'on';
|
|
27
31
|
saveConfig(cfg);
|
|
28
|
-
console.log(`
|
|
32
|
+
console.log(`Compact-window warning (statusline chip and session briefing): ${sub}`);
|
|
29
33
|
return;
|
|
30
34
|
}
|
|
31
35
|
|
|
@@ -38,14 +42,40 @@ export async function run({ args, hasFlag }) {
|
|
|
38
42
|
process.exit(1);
|
|
39
43
|
}
|
|
40
44
|
const argv = args.slice(2);
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
const flagValue = (name) => {
|
|
46
|
+
const i = argv.indexOf(name);
|
|
47
|
+
const eq = argv.find((a) => a.startsWith(`${name}=`));
|
|
48
|
+
return i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : (eq ? eq.slice(name.length + 1) : null);
|
|
49
|
+
};
|
|
50
|
+
const raw = flagValue('--value');
|
|
51
|
+
const model = flagValue('--model');
|
|
52
|
+
const all = hasFlag('--all-models');
|
|
53
|
+
if (all === !!model) {
|
|
54
|
+
console.error(ko
|
|
55
|
+
? '적용할 모델을 하나만 고르세요 (사용자에게 먼저 확인): --all-models (모든 모델에 같은 값, 같은 파일의 모델별 값은 지웁니다) 또는 --model <모델 id> (그 모델에만, 예: claude-opus-5-5)'
|
|
56
|
+
: 'Pick exactly one (confirm with the user first): --all-models (one value for every model; per-model values in that file are removed) or --model <model id> (that model only, e.g. claude-opus-5-5)');
|
|
57
|
+
console.error(` ${cw.modelSettingsNotice(cw.claudeCodeVersion(), ko)}`);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
const r = cw.setAutoCompactWindow({ root, scope, value: raw ?? cw.RECOMMENDED_WINDOW, models: all ? 'all' : model });
|
|
45
61
|
if (!r.ok) { console.error(`❌ ${r.error}`); process.exit(1); }
|
|
46
|
-
|
|
62
|
+
const slot = r.modelKey ? `modelSettings.${r.modelKey}.autoCompactWindow` : 'autoCompactWindow';
|
|
63
|
+
console.log(`✅ ${slot} = ${r.value} (${fmt(r.value)}) → ${r.path} [${r.scope}]`);
|
|
47
64
|
if (r.previous !== null && r.previous !== undefined) console.log(` previous: ${r.previous}`);
|
|
48
65
|
if (r.backup) console.log(` backup: ${r.backup}`);
|
|
66
|
+
// An older Claude Code ignores modelSettings, so the write above would do
|
|
67
|
+
// nothing there. Name the installed version either way.
|
|
68
|
+
if (r.modelKey) {
|
|
69
|
+
const version = cw.claudeCodeVersion();
|
|
70
|
+
console.log(`\n${cw.modelSettingsSupported(version) === false ? '⚠' : 'ℹ'} ${cw.modelSettingsNotice(version, ko)}`);
|
|
71
|
+
}
|
|
72
|
+
// --all-models: a per-model entry would have beaten the top-level key for
|
|
73
|
+
// its model, so those were removed. Say which, so nothing changes silently.
|
|
74
|
+
for (const { key, value } of r.removed || []) {
|
|
75
|
+
console.log(ko
|
|
76
|
+
? ` removed: modelSettings.${key}.autoCompactWindow (${value}). 모든 모델에 같은 값을 쓰도록 지웠습니다.`
|
|
77
|
+
: ` removed: modelSettings.${key}.autoCompactWindow (${value}) so every model uses the same value.`);
|
|
78
|
+
}
|
|
49
79
|
// The env var beats settings.json, so a stale export silently defeats the
|
|
50
80
|
// write we just made — say so instead of letting the user wonder.
|
|
51
81
|
if (process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW) {
|
|
@@ -62,16 +92,26 @@ export async function run({ args, hasFlag }) {
|
|
|
62
92
|
// not (a bare `opus` carries no `[1m]`), so the last reported size decides.
|
|
63
93
|
let liveWindow = null;
|
|
64
94
|
try { liveWindow = (await import('../ctx-window-cache.js')).latestLiveWindow(); } catch { /* id-only fallback */ }
|
|
65
|
-
|
|
95
|
+
let liveModel = null;
|
|
96
|
+
try { liveModel = (await import('../ctx-window-cache.js')).latestLiveModel(); } catch { /* settings model fallback */ }
|
|
97
|
+
const s = cw.compactWindowStatus({ root, liveWindow, liveModel });
|
|
66
98
|
console.log(`model: ${s.model || '(not set — Claude Code default)'}${s.modelSource ? ` [${s.modelSource}]` : ''}`);
|
|
67
99
|
console.log(`window: ${s.is1m ? '1M context' : '200k context'}${liveWindow ? ` [statusline: ${liveWindow >= 1e6 ? `${liveWindow / 1e6}M` : fmt(liveWindow)}]` : ''}`);
|
|
68
|
-
|
|
100
|
+
const winText = s.windowAuto ? 'auto (model default)' : s.window === null ? '(unset)' : `${s.window} (${fmt(s.window)})`;
|
|
101
|
+
const keyText = s.windowModelKey ? `, modelSettings.${s.windowModelKey}` : '';
|
|
102
|
+
console.log(`autoCompactWindow: ${winText}${s.windowSource ? ` [${s.windowSource}${s.windowPath ? ` → ${s.windowPath}` : ''}${keyText}]` : ''}`);
|
|
69
103
|
if (s.ok && s.reason === 'not-1m') {
|
|
70
104
|
console.log(ko
|
|
71
105
|
? '\n✅ 200k 컨텍스트라 이 설정은 영향이 없습니다 (워닝 대상 아님).'
|
|
72
106
|
: '\n✅ 200k context — this setting changes nothing here (not warned).');
|
|
73
107
|
return;
|
|
74
108
|
}
|
|
109
|
+
if (s.ok && s.reason === 'auto') {
|
|
110
|
+
console.log(ko
|
|
111
|
+
? '\n✅ /autocompact auto 로 모델 기본값을 직접 고른 상태라 경고하지 않습니다.'
|
|
112
|
+
: '\n✅ "auto" was chosen with /autocompact auto, so the model default is left alone (not warned).');
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
75
115
|
if (s.ok) {
|
|
76
116
|
console.log(ko
|
|
77
117
|
? `\n✅ 압축 창이 권장 범위(${fmt(s.recommendedMin)}~${fmt(s.recommendedMax)}) 상한 이하입니다.`
|
|
@@ -79,15 +119,17 @@ export async function run({ args, hasFlag }) {
|
|
|
79
119
|
return;
|
|
80
120
|
}
|
|
81
121
|
console.log(ko
|
|
82
|
-
? `\n⚠ 1M 컨텍스트인데 autoCompactWindow가 ${s.reason === 'unset' ? '설정되지 않았습니다' : `${fmt(s.window)}로 너무 큽니다`}
|
|
83
|
-
: `\n⚠ 1M context with autoCompactWindow ${s.reason === 'unset' ? 'unset' : `at ${fmt(s.window)}`} — compaction only fires near
|
|
122
|
+
? `\n⚠ 1M 컨텍스트인데 autoCompactWindow가 ${s.reason === 'unset' ? '설정되지 않았습니다' : `${fmt(s.window)}로 너무 큽니다`}. 자동 압축이 약 97만 토큰에서야 걸립니다.`
|
|
123
|
+
: `\n⚠ 1M context with autoCompactWindow ${s.reason === 'unset' ? 'unset' : `at ${fmt(s.window)}`} — compaction only fires near 967k.`);
|
|
84
124
|
console.log(ko
|
|
85
125
|
? ` 그 전까지 모든 요청이 전체 컨텍스트를 재과금합니다. 1M은 너무 크니 ${fmt(s.recommendedMin)}~${fmt(s.recommendedMax)} 범위를 권장합니다 (기본값 ${fmt(s.recommended)}, --value로 조절). 1M 창 자체는 그대로 두고 압축 시점만 앞당깁니다.`
|
|
86
126
|
: ` Until then every request re-bills the whole context. 1M is too large — pick something in ${fmt(s.recommendedMin)}–${fmt(s.recommendedMax)} (default ${fmt(s.recommended)}, override with --value). The 1M window itself stays.`);
|
|
87
|
-
console.log(`\n sprag compact-window set --global (~/.claude/settings.json, ${fmt(s.recommended)})`);
|
|
88
|
-
console.log(` sprag compact-window set --project (<root>/.claude/settings.json, ${fmt(s.recommended)})`);
|
|
89
|
-
console.log(` sprag compact-window set --global --
|
|
90
|
-
console.log(
|
|
127
|
+
console.log(`\n sprag compact-window set --global --all-models (~/.claude/settings.json, ${fmt(s.recommended)})`);
|
|
128
|
+
console.log(` sprag compact-window set --project --all-models (<root>/.claude/settings.json, ${fmt(s.recommended)})`);
|
|
129
|
+
console.log(` sprag compact-window set --global --model ${cw.canonicalModelId(s.windowModelKey || s.model) || 'claude-opus-5-5'} (${ko ? '그 모델에만' : 'that model only'})`);
|
|
130
|
+
console.log(` sprag compact-window set --global --all-models --value ${fmt(s.recommendedMax)}`);
|
|
131
|
+
console.log(` ${cw.modelSettingsNotice(cw.claudeCodeVersion(), ko)}`);
|
|
132
|
+
console.log(ko ? ' (적용 범위와 모델 범위는 사용자에게 먼저 확인할 것)' : ' (confirm the scope and the models with the user first)');
|
|
91
133
|
return;
|
|
92
134
|
}
|
|
93
135
|
|
package/src/compact-window.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* compact-window — auto-compact window audit for 1M-context sessions.
|
|
3
3
|
*
|
|
4
4
|
* Claude Code compacts when context usage approaches
|
|
5
|
-
* `min(settings.autoCompactWindow, model max context)`.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* `min(settings.autoCompactWindow, model max context)`. A model with a native
|
|
6
|
+
* 1M window compacts at about 967k by default, so every request until then
|
|
7
|
+
* re-bills a context most sessions never needed. Pinning
|
|
8
8
|
* `autoCompactWindow` somewhere in 400k–700k keeps 2–3.5x the headroom of a
|
|
9
9
|
* 200k session for the genuinely large ones while capping the runaway tail.
|
|
10
10
|
*
|
|
@@ -21,12 +21,60 @@
|
|
|
21
21
|
* 2. <root>/.claude/settings.local.json
|
|
22
22
|
* 3. <root>/.claude/settings.json
|
|
23
23
|
* 4. ~/.claude/settings.json
|
|
24
|
+
* Within each settings file, `modelSettings[<canonical id>].autoCompactWindow`
|
|
25
|
+
* (what `/autocompact` writes since Claude Code 2.1.288; `"auto"` means the
|
|
26
|
+
* model default) beats the top-level `autoCompactWindow` for that model.
|
|
24
27
|
*/
|
|
25
28
|
|
|
26
29
|
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
27
30
|
import { join, dirname } from 'node:path';
|
|
28
31
|
import { homedir } from 'node:os';
|
|
32
|
+
import { execFileSync } from 'node:child_process';
|
|
29
33
|
import { debug } from './debug.js';
|
|
34
|
+
import { isNewer } from './update-check.js';
|
|
35
|
+
|
|
36
|
+
// First Claude Code release that reads `modelSettings[<model>].autoCompactWindow`.
|
|
37
|
+
// An older one ignores the entry, so a per-model `set` would silently do nothing.
|
|
38
|
+
export const MODEL_SETTINGS_MIN_VERSION = '2.1.288';
|
|
39
|
+
|
|
40
|
+
/** Installed Claude Code version (`2.1.302`), or null when it cannot be read. */
|
|
41
|
+
export function claudeCodeVersion({ run = () => execFileSync('claude', ['--version'], { encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) {
|
|
42
|
+
try {
|
|
43
|
+
const m = String(run()).match(/(\d+\.\d+\.\d+)/);
|
|
44
|
+
return m ? m[1] : null;
|
|
45
|
+
} catch (e) {
|
|
46
|
+
debug('compact-window:claude-version', e);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** true / false against MODEL_SETTINGS_MIN_VERSION, or null when the version is unknown. */
|
|
52
|
+
export function modelSettingsSupported(version) {
|
|
53
|
+
if (!version) return null;
|
|
54
|
+
return version === MODEL_SETTINGS_MIN_VERSION || isNewer(version, MODEL_SETTINGS_MIN_VERSION);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* One line telling the user whether a per-model value will be used by their
|
|
59
|
+
* Claude Code. Shown wherever `--model` is offered or written.
|
|
60
|
+
*/
|
|
61
|
+
export function modelSettingsNotice(version, ko) {
|
|
62
|
+
const min = MODEL_SETTINGS_MIN_VERSION;
|
|
63
|
+
const ok = modelSettingsSupported(version);
|
|
64
|
+
if (ok === null) {
|
|
65
|
+
return ko
|
|
66
|
+
? `모델별 값(--model)은 Claude Code ${min} 이상에서만 적용됩니다. 설치된 버전을 확인하지 못했습니다(claude --version).`
|
|
67
|
+
: `A per-model value (--model) is only used by Claude Code ${min} or later. The installed version could not be read (claude --version).`;
|
|
68
|
+
}
|
|
69
|
+
if (ok) {
|
|
70
|
+
return ko
|
|
71
|
+
? `모델별 값(--model)은 Claude Code ${min} 이상에서만 적용됩니다. 설치된 버전(${version})에서는 적용됩니다.`
|
|
72
|
+
: `A per-model value (--model) is only used by Claude Code ${min} or later. You have ${version}, so it applies.`;
|
|
73
|
+
}
|
|
74
|
+
return ko
|
|
75
|
+
? `모델별 값(--model)은 Claude Code ${min} 이상에서만 적용됩니다. 설치된 버전(${version})에서는 적용되지 않습니다. Claude Code를 업데이트하거나 --all-models를 쓰세요.`
|
|
76
|
+
: `A per-model value (--model) is only used by Claude Code ${min} or later. You have ${version}, so it is ignored. Update Claude Code or use --all-models.`;
|
|
77
|
+
}
|
|
30
78
|
|
|
31
79
|
// Claude Code clamps autoCompactWindow to [100k, 1M] (settings schema:
|
|
32
80
|
// `.int().min(1e5).max(1e6)`), so anything outside that range is not a value
|
|
@@ -115,41 +163,111 @@ export function isOneMillionModel(model) {
|
|
|
115
163
|
// Anything this large can only be the 1M window.
|
|
116
164
|
export const LIVE_1M_MIN = 900_000;
|
|
117
165
|
|
|
118
|
-
/**
|
|
119
|
-
|
|
166
|
+
/**
|
|
167
|
+
* The canonical model name Claude Code keys `modelSettings` by. It matches a
|
|
168
|
+
* model's alias, date-suffixed, `[1m]`, Bedrock and Vertex spellings to the
|
|
169
|
+
* same entry, so every one of those spellings has to fold to one id here.
|
|
170
|
+
*/
|
|
171
|
+
export function canonicalModelId(model) {
|
|
172
|
+
if (typeof model !== 'string') return null;
|
|
173
|
+
let s = model.trim().toLowerCase();
|
|
174
|
+
if (!s) return null;
|
|
175
|
+
s = s.replace(/\[1m\]$/, '');
|
|
176
|
+
const slash = s.lastIndexOf('/');
|
|
177
|
+
if (slash !== -1) s = s.slice(slash + 1); // litellm / bedrock route prefixes
|
|
178
|
+
s = s.replace(/^(?:[a-z0-9-]+\.)*anthropic\./, ''); // us.anthropic., global.anthropic., anthropic.
|
|
179
|
+
s = s.replace(/-v\d+:\d+$/, ''); // Bedrock version suffix
|
|
180
|
+
s = s.replace(/@\d{8}$/, ''); // Vertex date suffix
|
|
181
|
+
s = s.replace(/-\d{8}$/, ''); // dated snapshot
|
|
182
|
+
return s || null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const ALIAS_RE = /^(opus|sonnet|haiku|fable|mythos)$/;
|
|
186
|
+
|
|
187
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The `modelSettings` entry that applies to `model` in one settings file, as
|
|
191
|
+
* `{ key, settings }`, or null.
|
|
192
|
+
*
|
|
193
|
+
* Only an exact match counts. A bare alias such as `opus` is never resolved
|
|
194
|
+
* here: which version it means lives inside Claude Code, and picking the
|
|
195
|
+
* highest-versioned key in the file is wrong whenever the file only holds an
|
|
196
|
+
* older model's entry. Callers pass the live model id from the statusline
|
|
197
|
+
* payload instead, and without one the per-model entries are skipped.
|
|
198
|
+
*/
|
|
199
|
+
export function modelSettingsEntry(json, model) {
|
|
200
|
+
const ms = json && json.modelSettings;
|
|
201
|
+
if (!isPlainObject(ms)) return null;
|
|
202
|
+
const want = canonicalModelId(model);
|
|
203
|
+
if (!want) return null;
|
|
204
|
+
const entries = Object.entries(ms).filter(([, v]) => v !== null && typeof v === 'object');
|
|
205
|
+
for (const [key, settings] of entries) {
|
|
206
|
+
if (canonicalModelId(key) === want) return { key, settings };
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const isAuto = (v) => typeof v === 'string' && v.trim().toLowerCase() === 'auto';
|
|
212
|
+
|
|
213
|
+
function windowFromFile(json, model, source, path) {
|
|
214
|
+
if (!json) return null;
|
|
215
|
+
const entry = modelSettingsEntry(json, model);
|
|
216
|
+
if (entry) {
|
|
217
|
+
if (isAuto(entry.settings.autoCompactWindow)) {
|
|
218
|
+
return { value: null, auto: true, source, path, modelKey: entry.key };
|
|
219
|
+
}
|
|
220
|
+
const v = parseWindow(entry.settings.autoCompactWindow);
|
|
221
|
+
if (v !== null) return { value: v, source, path, modelKey: entry.key };
|
|
222
|
+
}
|
|
223
|
+
const top = parseWindow(json.autoCompactWindow);
|
|
224
|
+
if (top !== null) return { value: top, source, path };
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Effective autoCompactWindow for `model`, with the source that won. A
|
|
230
|
+
* per-model `"auto"` is an explicit setting (the model default), so it ends
|
|
231
|
+
* the search and wins over lower-precedence files, as in Claude Code.
|
|
232
|
+
*/
|
|
233
|
+
export function effectiveWindow(root, { model } = {}) {
|
|
120
234
|
const env = process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
|
|
121
235
|
if (env) {
|
|
122
236
|
const v = parseWindow(env);
|
|
123
237
|
if (v !== null) return { value: v, source: 'env' };
|
|
124
238
|
}
|
|
239
|
+
const m = model === undefined ? resolveModelId(root).model : model;
|
|
125
240
|
for (const p of projectSettingsPaths(root)) {
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
if (v !== null) return { value: v, source: 'project', path: p };
|
|
241
|
+
const w = windowFromFile(readJson(p), m, 'project', p);
|
|
242
|
+
if (w) return w;
|
|
129
243
|
}
|
|
130
244
|
const gp = userSettingsPath();
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
if (gv !== null) return { value: gv, source: 'global', path: gp };
|
|
245
|
+
const gw = windowFromFile(readJson(gp), m, 'global', gp);
|
|
246
|
+
if (gw) return gw;
|
|
134
247
|
return { value: null, source: null };
|
|
135
248
|
}
|
|
136
249
|
|
|
137
250
|
/**
|
|
138
251
|
* Full audit result. `ok` is true when there is nothing to warn about — either
|
|
139
|
-
* the session is not on a 1M model (exempt),
|
|
140
|
-
* or below the top of the recommended band (700k)
|
|
252
|
+
* the session is not on a 1M model (exempt), the window is already pinned at
|
|
253
|
+
* or below the top of the recommended band (700k), or the user chose `"auto"`
|
|
254
|
+
* with `/autocompact auto` (reason 'auto'). `auto` hands the window back to the
|
|
255
|
+
* model default on purpose, so sprag respects that choice instead of nagging.
|
|
141
256
|
*
|
|
142
257
|
* `reason` names why it is not ok: 'unset' (no autoCompactWindow anywhere) or
|
|
143
258
|
* 'too-large' (set, but above 700k — still lets context run away).
|
|
144
259
|
*
|
|
145
260
|
* `liveWindow` is the window Claude Code reported for the running session. The
|
|
146
261
|
* model id alone misses every model that is 1M without a `[1m]` suffix, so a
|
|
147
|
-
* reported size settles it whenever the caller has one.
|
|
262
|
+
* reported size settles it whenever the caller has one. `liveModel` is the
|
|
263
|
+
* model id the same payload carried; it picks the `modelSettings` entry.
|
|
148
264
|
*/
|
|
149
|
-
export function compactWindowStatus({ root = process.cwd(), liveWindow = null } = {}) {
|
|
150
|
-
const
|
|
265
|
+
export function compactWindowStatus({ root = process.cwd(), liveWindow = null, liveModel = null } = {}) {
|
|
266
|
+
const resolved = resolveModelId(root);
|
|
267
|
+
const model = liveModel || resolved.model;
|
|
268
|
+
const modelSource = liveModel ? 'live' : resolved.source;
|
|
151
269
|
const is1m = isOneMillionModel(model) || (Number.isFinite(liveWindow) && liveWindow >= LIVE_1M_MIN);
|
|
152
|
-
const win = effectiveWindow(root);
|
|
270
|
+
const win = effectiveWindow(root, { model });
|
|
153
271
|
const base = {
|
|
154
272
|
model,
|
|
155
273
|
modelSource,
|
|
@@ -157,24 +275,35 @@ export function compactWindowStatus({ root = process.cwd(), liveWindow = null }
|
|
|
157
275
|
window: win.value,
|
|
158
276
|
windowSource: win.source,
|
|
159
277
|
windowPath: win.path || null,
|
|
278
|
+
windowAuto: !!win.auto,
|
|
279
|
+
windowModelKey: win.modelKey || null,
|
|
160
280
|
recommended: RECOMMENDED_WINDOW,
|
|
161
281
|
recommendedMin: RECOMMENDED_MIN,
|
|
162
282
|
recommendedMax: RECOMMENDED_MAX,
|
|
163
283
|
};
|
|
164
284
|
if (!is1m) return { ...base, ok: true, reason: 'not-1m' };
|
|
285
|
+
if (win.auto) return { ...base, ok: true, reason: 'auto' };
|
|
165
286
|
if (win.value === null) return { ...base, ok: false, reason: 'unset' };
|
|
166
287
|
if (win.value > RECOMMENDED_MAX) return { ...base, ok: false, reason: 'too-large' };
|
|
167
288
|
return { ...base, ok: true, reason: 'configured' };
|
|
168
289
|
}
|
|
169
290
|
|
|
291
|
+
/**
|
|
292
|
+
* False once `sprag compact-window off` has switched the warning off. Read by
|
|
293
|
+
* the statusline chip and the session briefing alike.
|
|
294
|
+
*/
|
|
295
|
+
export function compactWindowWarningEnabled(cfg) {
|
|
296
|
+
return !(cfg && cfg.compactWindow && cfg.compactWindow.enabled === false);
|
|
297
|
+
}
|
|
298
|
+
|
|
170
299
|
/**
|
|
171
300
|
* Statusline chip text, or null when there is nothing to say. Kept to the same
|
|
172
301
|
* short shape as the other 🅷⚠ warnings so the line stays single-width.
|
|
173
302
|
*/
|
|
174
|
-
export function compactWindowWarningForStatusline(root = process.cwd(), cfg = null, { liveWindow = null } = {}) {
|
|
175
|
-
if (cfg
|
|
303
|
+
export function compactWindowWarningForStatusline(root = process.cwd(), cfg = null, { liveWindow = null, liveModel = null } = {}) {
|
|
304
|
+
if (!compactWindowWarningEnabled(cfg)) return null;
|
|
176
305
|
try {
|
|
177
|
-
const s = compactWindowStatus({ root, liveWindow });
|
|
306
|
+
const s = compactWindowStatus({ root, liveWindow, liveModel });
|
|
178
307
|
return s.ok ? null : 'compact-window?';
|
|
179
308
|
} catch (e) {
|
|
180
309
|
debug('compact-window:statusline', e);
|
|
@@ -187,13 +316,26 @@ export function compactWindowWarningForStatusline(root = process.cwd(), cfg = nu
|
|
|
187
316
|
* Scope 'global' → ~/.claude/settings.json, 'project' → <root>/.claude/settings.json.
|
|
188
317
|
* A `.bak` is written first whenever the file already exists.
|
|
189
318
|
*
|
|
190
|
-
*
|
|
319
|
+
* `models` picks which models the value covers, and the user has to choose it:
|
|
320
|
+
* 'all' → the top-level key. A per-model entry in the same file beats the
|
|
321
|
+
* top-level key for its model, so every per-model
|
|
322
|
+
* `autoCompactWindow` in that file is removed (listed in `removed`)
|
|
323
|
+
* and one value really applies to every model.
|
|
324
|
+
* <id> → `modelSettings[<id>].autoCompactWindow` only, the slot
|
|
325
|
+
* `/autocompact` writes. The id is stored under its canonical name
|
|
326
|
+
* (or the existing key that spells it). A bare alias such as `opus`
|
|
327
|
+
* is refused, since sprag cannot tell which version it means.
|
|
328
|
+
*
|
|
329
|
+
* Returns { path, scope, value, previous, backup, models, modelKey, removed }.
|
|
191
330
|
*/
|
|
192
|
-
export function setAutoCompactWindow({ root = process.cwd(), scope = 'global', value = RECOMMENDED_WINDOW } = {}) {
|
|
331
|
+
export function setAutoCompactWindow({ root = process.cwd(), scope = 'global', value = RECOMMENDED_WINDOW, models = 'all' } = {}) {
|
|
193
332
|
const v = parseWindow(value);
|
|
194
333
|
if (v === null || v < MIN_WINDOW || v > MAX_WINDOW) {
|
|
195
334
|
return { ok: false, error: `Invalid window: ${value} (expected ${MIN_WINDOW}–${MAX_WINDOW} tokens, e.g. 400000 or 400k)` };
|
|
196
335
|
}
|
|
336
|
+
if (typeof models !== 'string' || models.trim() === '') {
|
|
337
|
+
return { ok: false, error: 'Choose the models: all, or one model id such as claude-opus-5-5.' };
|
|
338
|
+
}
|
|
197
339
|
const path = scope === 'global' ? userSettingsPath() : join(root, '.claude', 'settings.json');
|
|
198
340
|
let json = {};
|
|
199
341
|
let backup = null;
|
|
@@ -207,13 +349,47 @@ export function setAutoCompactWindow({ root = process.cwd(), scope = 'global', v
|
|
|
207
349
|
// malformed settings.json would drop every other setting in it.
|
|
208
350
|
return { ok: false, error: `${path} is not valid JSON — fix it first (nothing was written).` };
|
|
209
351
|
}
|
|
352
|
+
if (!isPlainObject(json)) {
|
|
353
|
+
return { ok: false, error: `${path} is not a JSON object — fix it first (nothing was written).` };
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
let modelKey = null;
|
|
358
|
+
if (models !== 'all') {
|
|
359
|
+
const want = canonicalModelId(models);
|
|
360
|
+
if (!want || ALIAS_RE.test(want)) {
|
|
361
|
+
return { ok: false, error: `"${models}" is an alias, so the model version is unknown. Use the full model id, e.g. claude-${want || 'opus'}-5-5.` };
|
|
362
|
+
}
|
|
363
|
+
const existing = modelSettingsEntry(json, models);
|
|
364
|
+
modelKey = existing ? existing.key : want;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (existsSync(path)) {
|
|
210
368
|
backup = `${path}.bak`;
|
|
211
|
-
writeFileSync(backup,
|
|
369
|
+
writeFileSync(backup, readFileSync(path, 'utf8'));
|
|
212
370
|
} else {
|
|
213
371
|
mkdirSync(dirname(path), { recursive: true });
|
|
214
372
|
}
|
|
215
|
-
|
|
216
|
-
|
|
373
|
+
|
|
374
|
+
const removed = [];
|
|
375
|
+
let previous;
|
|
376
|
+
if (modelKey) {
|
|
377
|
+
if (!isPlainObject(json.modelSettings)) json.modelSettings = {};
|
|
378
|
+
if (!isPlainObject(json.modelSettings[modelKey])) json.modelSettings[modelKey] = {};
|
|
379
|
+
previous = json.modelSettings[modelKey].autoCompactWindow ?? null;
|
|
380
|
+
json.modelSettings[modelKey].autoCompactWindow = v;
|
|
381
|
+
} else {
|
|
382
|
+
previous = parseWindow(json.autoCompactWindow);
|
|
383
|
+
json.autoCompactWindow = v;
|
|
384
|
+
if (isPlainObject(json.modelSettings)) {
|
|
385
|
+
for (const [key, ms] of Object.entries(json.modelSettings)) {
|
|
386
|
+
if (!isPlainObject(ms) || ms.autoCompactWindow === undefined) continue;
|
|
387
|
+
removed.push({ key, value: ms.autoCompactWindow });
|
|
388
|
+
delete ms.autoCompactWindow;
|
|
389
|
+
if (Object.keys(ms).length === 0) delete json.modelSettings[key];
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
217
393
|
writeFileSync(path, JSON.stringify(json, null, 2) + '\n');
|
|
218
|
-
return { ok: true, path, scope, value: v, previous, backup };
|
|
394
|
+
return { ok: true, path, scope, value: v, previous, backup, models: modelKey ? 'model' : 'all', modelKey, removed };
|
|
219
395
|
}
|
package/src/cost.js
CHANGED
|
@@ -16,125 +16,239 @@ import { priceForPrompt } from './gateway-prices.js';
|
|
|
16
16
|
// `totals.long` (see parser.js) rather than relying on session-wide sums.
|
|
17
17
|
export const LONG_PROMPT_THRESHOLD = 100_000;
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
// Each tier lists its rate cards oldest first, with the date each took effect
|
|
20
|
+
// (`from`, a UTC YYYY-MM-DD; null = since the model launched). A price change
|
|
21
|
+
// or a correction is a new row, never an edit of an old one, so a run is
|
|
22
|
+
// always priced at the rate that applied when it happened (#15).
|
|
23
|
+
const PRICE_HISTORY = {
|
|
20
24
|
// Fable 5.1 / Mythos 5.1 — same prices as Fable 5 except cache reads, which
|
|
21
25
|
// drop to $0.25.
|
|
22
|
-
'claude-fable-5-1': {
|
|
26
|
+
'claude-fable-5-1': [{
|
|
27
|
+
from: null,
|
|
23
28
|
input: 10.0,
|
|
24
29
|
cacheWrite5m: 12.5,
|
|
25
30
|
cacheWrite1h: 20.0,
|
|
26
31
|
cacheRead: 0.25,
|
|
27
32
|
output: 50.0,
|
|
28
|
-
},
|
|
33
|
+
}],
|
|
29
34
|
// Fable 5 / Mythos 5 — premium tier above Opus ($10/$50). Cache write
|
|
30
35
|
// rates follow the standard multipliers (1.25x input for 5m, 2x for 1h),
|
|
31
36
|
// cache read is 0.1x input.
|
|
32
|
-
'claude-fable-5': {
|
|
37
|
+
'claude-fable-5': [{
|
|
38
|
+
from: null,
|
|
33
39
|
input: 10.0,
|
|
34
40
|
cacheWrite5m: 12.5,
|
|
35
41
|
cacheWrite1h: 20.0,
|
|
36
42
|
cacheRead: 1.0,
|
|
37
43
|
output: 50.0,
|
|
38
|
-
},
|
|
44
|
+
}],
|
|
39
45
|
// Opus 5.5 — cheaper than the Opus 4.5-5 tier below.
|
|
40
|
-
'claude-opus-5-5': {
|
|
46
|
+
'claude-opus-5-5': [{
|
|
47
|
+
from: null,
|
|
41
48
|
input: 4.0,
|
|
42
49
|
cacheWrite5m: 5.0,
|
|
43
50
|
cacheWrite1h: 8.0,
|
|
44
51
|
cacheRead: 0.2,
|
|
45
52
|
output: 20.0,
|
|
46
|
-
},
|
|
53
|
+
}],
|
|
47
54
|
// Opus 4.5+ (new pricing tier — includes 4.5, 4.6, 4.7, 4.8, and future)
|
|
48
|
-
'claude-opus-new': {
|
|
55
|
+
'claude-opus-new': [{
|
|
56
|
+
from: null,
|
|
49
57
|
input: 5.0,
|
|
50
58
|
cacheWrite5m: 6.25,
|
|
51
59
|
cacheWrite1h: 10.0,
|
|
52
60
|
cacheRead: 0.5,
|
|
53
61
|
output: 25.0,
|
|
54
|
-
},
|
|
62
|
+
}],
|
|
55
63
|
// Opus 4 / 4.1 / Opus 3 (legacy premium pricing)
|
|
56
|
-
'claude-opus-legacy': {
|
|
64
|
+
'claude-opus-legacy': [{
|
|
65
|
+
from: null,
|
|
57
66
|
input: 15.0,
|
|
58
67
|
cacheWrite5m: 18.75,
|
|
59
68
|
cacheWrite1h: 30.0,
|
|
60
69
|
cacheRead: 1.5,
|
|
61
70
|
output: 75.0,
|
|
62
|
-
},
|
|
71
|
+
}],
|
|
63
72
|
// Sonnet 5 — standard price is $2/$10. The rise to $3/$15 planned for
|
|
64
73
|
// 2026-09-01 was cancelled, so this is not an introductory rate.
|
|
65
|
-
'claude-sonnet-5': {
|
|
74
|
+
'claude-sonnet-5': [{
|
|
75
|
+
from: null,
|
|
66
76
|
input: 2.0,
|
|
67
77
|
cacheWrite5m: 2.5,
|
|
68
78
|
cacheWrite1h: 4.0,
|
|
69
79
|
cacheRead: 0.2,
|
|
70
80
|
output: 10.0,
|
|
71
|
-
},
|
|
72
|
-
// Sonnet 5.5 —
|
|
73
|
-
|
|
81
|
+
}],
|
|
82
|
+
// Sonnet 5.5 — launched 2026-09-28 with Sonnet 5's prices. Cache reads were
|
|
83
|
+
// cut from $0.20 to $0.10 on 2026-10-07 ("We've lowered the price of prompt
|
|
84
|
+
// cache reads on Claude Sonnet 5.5 from $0.20 USD to $0.10 USD", platform
|
|
85
|
+
// release notes); every other rate is unchanged.
|
|
86
|
+
'claude-sonnet-5-5': [{
|
|
87
|
+
from: null,
|
|
88
|
+
input: 2.0,
|
|
89
|
+
cacheWrite5m: 2.5,
|
|
90
|
+
cacheWrite1h: 4.0,
|
|
91
|
+
cacheRead: 0.2,
|
|
92
|
+
output: 10.0,
|
|
93
|
+
}, {
|
|
94
|
+
from: '2026-10-07',
|
|
74
95
|
input: 2.0,
|
|
75
96
|
cacheWrite5m: 2.5,
|
|
76
97
|
cacheWrite1h: 4.0,
|
|
77
98
|
cacheRead: 0.1,
|
|
78
99
|
output: 10.0,
|
|
79
|
-
},
|
|
100
|
+
}],
|
|
80
101
|
// Sonnet 4 / 4.5 / 4.6 / 3.7
|
|
81
|
-
'claude-sonnet': {
|
|
102
|
+
'claude-sonnet': [{
|
|
103
|
+
from: null,
|
|
82
104
|
input: 3.0,
|
|
83
105
|
cacheWrite5m: 3.75,
|
|
84
106
|
cacheWrite1h: 6.0,
|
|
85
107
|
cacheRead: 0.3,
|
|
86
108
|
output: 15.0,
|
|
87
|
-
},
|
|
109
|
+
}],
|
|
88
110
|
// Haiku 5.5, prompt <= LONG_PROMPT_THRESHOLD tokens.
|
|
89
|
-
'claude-haiku-5-5': {
|
|
111
|
+
'claude-haiku-5-5': [{
|
|
112
|
+
from: null,
|
|
90
113
|
input: 0.1,
|
|
91
114
|
cacheWrite5m: 0.125,
|
|
92
115
|
cacheWrite1h: 0.2,
|
|
93
116
|
cacheRead: 0.01,
|
|
94
117
|
output: 0.5,
|
|
95
|
-
},
|
|
118
|
+
}],
|
|
96
119
|
// Haiku 5.5, prompt > LONG_PROMPT_THRESHOLD tokens. Not returned by
|
|
97
120
|
// detectPricingTier: estimateCost applies it to `totals.long` only.
|
|
98
|
-
'claude-haiku-5-5-long': {
|
|
121
|
+
'claude-haiku-5-5-long': [{
|
|
122
|
+
from: null,
|
|
99
123
|
input: 0.5,
|
|
100
124
|
cacheWrite5m: 0.625,
|
|
101
125
|
cacheWrite1h: 1.0,
|
|
102
126
|
cacheRead: 0.05,
|
|
103
127
|
output: 2.5,
|
|
104
|
-
},
|
|
128
|
+
}],
|
|
105
129
|
// Haiku 4.5
|
|
106
|
-
'claude-haiku-4-5': {
|
|
130
|
+
'claude-haiku-4-5': [{
|
|
131
|
+
from: null,
|
|
107
132
|
input: 1.0,
|
|
108
133
|
cacheWrite5m: 1.25,
|
|
109
134
|
cacheWrite1h: 2.0,
|
|
110
135
|
cacheRead: 0.1,
|
|
111
136
|
output: 5.0,
|
|
112
|
-
},
|
|
137
|
+
}],
|
|
113
138
|
// Haiku 3.5
|
|
114
|
-
'claude-haiku-3-5': {
|
|
139
|
+
'claude-haiku-3-5': [{
|
|
140
|
+
from: null,
|
|
115
141
|
input: 0.8,
|
|
116
142
|
cacheWrite5m: 1.0,
|
|
117
143
|
cacheWrite1h: 1.6,
|
|
118
144
|
cacheRead: 0.08,
|
|
119
145
|
output: 4.0,
|
|
120
|
-
},
|
|
146
|
+
}],
|
|
121
147
|
// Haiku 3 (deprecated)
|
|
122
|
-
'claude-haiku-3': {
|
|
148
|
+
'claude-haiku-3': [{
|
|
149
|
+
from: null,
|
|
123
150
|
input: 0.25,
|
|
124
151
|
cacheWrite5m: 0.3,
|
|
125
152
|
cacheWrite1h: 0.5,
|
|
126
153
|
cacheRead: 0.03,
|
|
127
154
|
output: 1.25,
|
|
128
|
-
},
|
|
155
|
+
}],
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/** Milliseconds for a `from` date, or -Infinity for "since launch". */
|
|
159
|
+
const fromMs = (from) => (from ? Date.parse(`${from}T00:00:00Z`) : -Infinity);
|
|
160
|
+
|
|
161
|
+
const toMs = (at) => {
|
|
162
|
+
if (at === undefined || at === null) return Date.now();
|
|
163
|
+
const n = typeof at === 'number' ? at : Date.parse(at);
|
|
164
|
+
return Number.isFinite(n) ? n : Date.now();
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The rate card of a tier in effect at `at` (ms or a date string; default
|
|
169
|
+
* now): the newest row whose `from` is not after it. A time before the first
|
|
170
|
+
* dated row gets the first row, since that is the earliest price known.
|
|
171
|
+
*/
|
|
172
|
+
export function ratesAt(tier, at) {
|
|
173
|
+
const rows = PRICE_HISTORY[tier];
|
|
174
|
+
if (!rows) return null;
|
|
175
|
+
const t = toMs(at);
|
|
176
|
+
let pick = rows[0];
|
|
177
|
+
for (const r of rows) if (fromMs(r.from) <= t) pick = r;
|
|
178
|
+
return pick;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Every dated row of a tier, oldest first (for audits and the upstream watch). */
|
|
182
|
+
export function priceHistory(tier) {
|
|
183
|
+
return (PRICE_HISTORY[tier] || []).map((r) => ({ ...r }));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// What a bare alias meant over time: the model Claude Code sent for it from
|
|
187
|
+
// each date on, oldest first. An alias moves to a new model on launch day, so
|
|
188
|
+
// a run recorded as `opus` is priced as the Opus that was current then, not
|
|
189
|
+
// the oldest Opus in the table (#13).
|
|
190
|
+
// Dates are the launch days in the platform release notes
|
|
191
|
+
// (https://platform.claude.com/docs/en/release-notes/overview); Claude Code
|
|
192
|
+
// moved its aliases on or shortly after them. A time before the first row
|
|
193
|
+
// resolves to the first row.
|
|
194
|
+
const ALIAS_HISTORY = {
|
|
195
|
+
opus: [
|
|
196
|
+
{ from: '2025-05-22', model: 'claude-opus-4-20250514' },
|
|
197
|
+
{ from: '2025-08-05', model: 'claude-opus-4-1-20250805' },
|
|
198
|
+
{ from: '2025-11-24', model: 'claude-opus-4-5-20251101' },
|
|
199
|
+
{ from: '2026-02-05', model: 'claude-opus-4-6' },
|
|
200
|
+
{ from: '2026-04-16', model: 'claude-opus-4-7' },
|
|
201
|
+
{ from: '2026-05-28', model: 'claude-opus-4-8' },
|
|
202
|
+
{ from: '2026-07-24', model: 'claude-opus-5' },
|
|
203
|
+
{ from: '2026-09-22', model: 'claude-opus-5-5' },
|
|
204
|
+
],
|
|
205
|
+
sonnet: [
|
|
206
|
+
{ from: '2025-05-22', model: 'claude-sonnet-4-20250514' },
|
|
207
|
+
{ from: '2025-09-29', model: 'claude-sonnet-4-5-20250929' },
|
|
208
|
+
{ from: '2026-02-17', model: 'claude-sonnet-4-6' },
|
|
209
|
+
{ from: '2026-06-30', model: 'claude-sonnet-5' },
|
|
210
|
+
{ from: '2026-09-28', model: 'claude-sonnet-5-5' },
|
|
211
|
+
],
|
|
212
|
+
haiku: [
|
|
213
|
+
{ from: null, model: 'claude-3-5-haiku-20241022' },
|
|
214
|
+
{ from: '2025-10-15', model: 'claude-haiku-4-5-20251001' },
|
|
215
|
+
{ from: '2026-10-07', model: 'claude-haiku-5-5' },
|
|
216
|
+
],
|
|
217
|
+
fable: [
|
|
218
|
+
{ from: '2026-06-09', model: 'claude-fable-5' },
|
|
219
|
+
{ from: '2026-09-01', model: 'claude-fable-5-1' },
|
|
220
|
+
],
|
|
129
221
|
};
|
|
130
222
|
|
|
223
|
+
// Spellings that name an alias rather than a model: the bare family, its
|
|
224
|
+
// `[1m]` form, and the Claude Code shorthands that resolve to a family.
|
|
225
|
+
const ALIAS_OF = { opus: 'opus', opusplan: 'opus', sonnet: 'sonnet', haiku: 'haiku', fable: 'fable', best: 'fable' };
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The model a bare alias stood for at `at`, or null when `model` is not an
|
|
229
|
+
* alias (a full id passes through untouched at the call site).
|
|
230
|
+
*/
|
|
231
|
+
export function resolveAlias(model, at) {
|
|
232
|
+
if (typeof model !== 'string') return null;
|
|
233
|
+
const key = ALIAS_OF[model.trim().toLowerCase().replace(/\[1m\]$/, '')];
|
|
234
|
+
const rows = key && ALIAS_HISTORY[key];
|
|
235
|
+
if (!rows || rows.length === 0) return null;
|
|
236
|
+
const t = toMs(at);
|
|
237
|
+
let pick = null;
|
|
238
|
+
for (const r of rows) if (fromMs(r.from) <= t) pick = r;
|
|
239
|
+
return (pick || rows[0]).model;
|
|
240
|
+
}
|
|
241
|
+
|
|
131
242
|
/**
|
|
132
243
|
* Detect pricing tier from Claude model identifier.
|
|
133
244
|
* Examples: 'claude-opus-4-7', 'claude-sonnet-4-5', 'claude-haiku-4-5'.
|
|
245
|
+
* A bare alias (`opus`, `sonnet[1m]`) is first resolved to the model it meant
|
|
246
|
+
* at `at` (default now).
|
|
134
247
|
*/
|
|
135
|
-
export function detectPricingTier(model) {
|
|
248
|
+
export function detectPricingTier(model, { at } = {}) {
|
|
136
249
|
if (!model) return 'claude-sonnet';
|
|
137
|
-
const
|
|
250
|
+
const resolved = resolveAlias(model, at);
|
|
251
|
+
const m = (resolved || model).toLowerCase();
|
|
138
252
|
|
|
139
253
|
// Fable 5 / Mythos 5 — must be checked before the generic fallback:
|
|
140
254
|
// without this, 'claude-fable-5' fell through to the Sonnet tier and
|
|
@@ -283,10 +397,13 @@ function tokensToMillions(n) {
|
|
|
283
397
|
* ephemeral5m — portion of cacheCreation billed at 5m rate (1.25x input)
|
|
284
398
|
* ephemeral1h — portion of cacheCreation billed at 1h rate (2x input)
|
|
285
399
|
* output — output tokens
|
|
400
|
+
*
|
|
401
|
+
* `at` (ms or a date string, default now) is when the tokens were spent: the
|
|
402
|
+
* list price is the one in effect then (see ratesAt).
|
|
286
403
|
*/
|
|
287
|
-
export function estimateCost(totals, model, { price } = {}) {
|
|
404
|
+
export function estimateCost(totals, model, { price, at } = {}) {
|
|
288
405
|
if (price) return estimateCostAtPrice(totals, price);
|
|
289
|
-
const tier = detectPricingTier(model);
|
|
406
|
+
const tier = detectPricingTier(model, { at });
|
|
290
407
|
|
|
291
408
|
// Haiku 5.5 prices each request by its own prompt length, so the long-prompt
|
|
292
409
|
// part (`totals.long`, same shape) is priced at the long rates and the rest
|
|
@@ -294,8 +411,8 @@ export function estimateCost(totals, model, { price } = {}) {
|
|
|
294
411
|
let c;
|
|
295
412
|
if (tier === 'claude-haiku-5-5' && totals.long) {
|
|
296
413
|
const short = subtractTotals(totals, totals.long);
|
|
297
|
-
const a = priceTotals(short,
|
|
298
|
-
const b = priceTotals(totals.long,
|
|
414
|
+
const a = priceTotals(short, ratesAt(tier, at));
|
|
415
|
+
const b = priceTotals(totals.long, ratesAt('claude-haiku-5-5-long', at));
|
|
299
416
|
c = {
|
|
300
417
|
actual: a.actual + b.actual,
|
|
301
418
|
noCacheCost: a.noCacheCost + b.noCacheCost,
|
|
@@ -303,7 +420,7 @@ export function estimateCost(totals, model, { price } = {}) {
|
|
|
303
420
|
write1h: a.write1h + b.write1h,
|
|
304
421
|
};
|
|
305
422
|
} else {
|
|
306
|
-
c = priceTotals(totals,
|
|
423
|
+
c = priceTotals(totals, ratesAt(tier, at));
|
|
307
424
|
}
|
|
308
425
|
const { actual, noCacheCost, scenario5mCost, write1h } = c;
|
|
309
426
|
|
package/src/ctx-window-cache.js
CHANGED
|
@@ -9,8 +9,12 @@
|
|
|
9
9
|
* statusline records the size it was given here, and the briefing reads it back
|
|
10
10
|
* by session id before it falls back to guessing.
|
|
11
11
|
*
|
|
12
|
+
* The payload's model id (`model.id`) is stored beside the size. The briefing
|
|
13
|
+
* reads it back to look up the session's own `modelSettings` entry, which a
|
|
14
|
+
* settings-only lookup cannot see when the model was picked with `/model`.
|
|
15
|
+
*
|
|
12
16
|
* State: <stateDir>/ctx-window.json
|
|
13
|
-
* { sessions: { [session_id]: { size, ts } } }
|
|
17
|
+
* { sessions: { [session_id]: { size, ts, model? } } }
|
|
14
18
|
* Entries untouched for 7 days are pruned on write.
|
|
15
19
|
*/
|
|
16
20
|
|
|
@@ -40,12 +44,13 @@ function load() {
|
|
|
40
44
|
const validSize = (size) => Number.isFinite(size) && size > 0;
|
|
41
45
|
|
|
42
46
|
/** Record the window the statusline payload reported. Returns true when the file was written. */
|
|
43
|
-
export function recordLiveWindow(sessionId, size, now = Date.now()) {
|
|
47
|
+
export function recordLiveWindow(sessionId, size, now = Date.now(), model = null) {
|
|
44
48
|
if (typeof sessionId !== 'string' || sessionId === '' || !validSize(size)) return false;
|
|
49
|
+
const m = typeof model === 'string' && model !== '' ? model : undefined;
|
|
45
50
|
const state = load();
|
|
46
51
|
const prev = state.sessions[sessionId];
|
|
47
|
-
if (prev && prev.size === size && now - prev.ts < REFRESH_MS) return false;
|
|
48
|
-
state.sessions[sessionId] = { size, ts: now };
|
|
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 };
|
|
49
54
|
for (const [id, s] of Object.entries(state.sessions)) {
|
|
50
55
|
if (!s || !Number.isFinite(s.ts) || now - s.ts > PRUNE_MS) delete state.sessions[id];
|
|
51
56
|
}
|
|
@@ -66,10 +71,28 @@ export function liveWindowFor(sessionId) {
|
|
|
66
71
|
* judged by the settings model id alone, a bare `opus` (1M by default on Opus
|
|
67
72
|
* 5.5, with no `[1m]` suffix) read as 200k while the statusline said 1M.
|
|
68
73
|
*/
|
|
69
|
-
|
|
74
|
+
function latestEntry() {
|
|
70
75
|
let best = null;
|
|
71
76
|
for (const s of Object.values(load().sessions)) {
|
|
72
77
|
if (s && validSize(s.size) && Number.isFinite(s.ts) && (!best || s.ts > best.ts)) best = s;
|
|
73
78
|
}
|
|
79
|
+
return best;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function latestLiveWindow() {
|
|
83
|
+
const best = latestEntry();
|
|
74
84
|
return best ? best.size : null;
|
|
75
85
|
}
|
|
86
|
+
|
|
87
|
+
/** The model id a session's statusline payload reported, or null. */
|
|
88
|
+
export function liveModelFor(sessionId) {
|
|
89
|
+
if (typeof sessionId !== 'string' || sessionId === '') return null;
|
|
90
|
+
const s = load().sessions[sessionId];
|
|
91
|
+
return s && typeof s.model === 'string' && s.model !== '' ? s.model : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The model id of the most recently reported session (same pick as latestLiveWindow), or null. */
|
|
95
|
+
export function latestLiveModel() {
|
|
96
|
+
const best = latestEntry();
|
|
97
|
+
return best && typeof best.model === 'string' && best.model !== '' ? best.model : null;
|
|
98
|
+
}
|
|
@@ -400,9 +400,9 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
|
|
|
400
400
|
* is the absence of news; the chip earns its place when it is short of 5/5, red,
|
|
401
401
|
* or asked for.
|
|
402
402
|
*/
|
|
403
|
-
function buildHarnessSeg(c, isIcon, g, liveWindow = null, explicit = false) {
|
|
403
|
+
function buildHarnessSeg(c, isIcon, g, liveWindow = null, explicit = false, liveModel = null) {
|
|
404
404
|
try {
|
|
405
|
-
const harnessInfo = harnessStatusForStatusline(loadConfig(), { liveWindow });
|
|
405
|
+
const harnessInfo = harnessStatusForStatusline(loadConfig(), { liveWindow, liveModel });
|
|
406
406
|
if (!harnessInfo) return null;
|
|
407
407
|
const icon = isIcon ? g.harness : 'H';
|
|
408
408
|
if (harnessInfo.warning) {
|
|
@@ -1467,7 +1467,7 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v)
|
|
|
1467
1467
|
* @param {number} [opts.maxLines=3] - most chip lines when `columns` is set; lower-priority tail chips collapse into a `+N` chip beyond that. Counts the chip lines only: the headline lines above them wrap at their own `|` and `·` joints and are not included. Cap, usage, ctx, spike chips are never dropped.
|
|
1468
1468
|
*/
|
|
1469
1469
|
export function formatReport(data, { color = true, verbose = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines = 3 } = {}) {
|
|
1470
|
-
const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort } = data;
|
|
1470
|
+
const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, liveModel } = data;
|
|
1471
1471
|
|
|
1472
1472
|
const c = (v) => (color ? v : '');
|
|
1473
1473
|
// narrow shares the icon layout and swaps only the glyphs, so both modes take
|
|
@@ -1534,7 +1534,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1534
1534
|
// silent at a full 5/5 with no warning unless `--segments` names it. Otherwise
|
|
1535
1535
|
// 🅷 N/5 (yellow) so the user can spot a missing section at a glance and know
|
|
1536
1536
|
// to run `harness init`, or the red warning chip.
|
|
1537
|
-
harness: buildHarnessSeg(c, isIcon, g, ctxLive?.size ?? null, !!allow && allow.has('harness')),
|
|
1537
|
+
harness: buildHarnessSeg(c, isIcon, g, ctxLive?.size ?? null, !!allow && allow.has('harness'), liveModel ?? null),
|
|
1538
1538
|
// Korean-style chip — rendered only when named and the injection is on.
|
|
1539
1539
|
korean: buildKoreanSeg(c, isIcon, verbose, g, !!allow && allow.has('korean')),
|
|
1540
1540
|
// Version / upgrade chip. Read from a cache written by a detached background
|
package/src/harness.js
CHANGED
|
@@ -597,7 +597,7 @@ export function harnessRmRule(n, { root = findProjectRoot(), scope = 'project',
|
|
|
597
597
|
* has explicitly disabled harness display, or when there's no CLAUDE.md and
|
|
598
598
|
* no .claude/ at all (silent in non-init'd projects so we don't nag).
|
|
599
599
|
*/
|
|
600
|
-
export function harnessStatusForStatusline(cfg, { root, liveWindow = null } = {}) {
|
|
600
|
+
export function harnessStatusForStatusline(cfg, { root, liveWindow = null, liveModel = null } = {}) {
|
|
601
601
|
if (cfg && cfg.harness && cfg.harness.enabled === false) return null;
|
|
602
602
|
const projectRoot = root || findProjectRoot();
|
|
603
603
|
const status = harnessStatus(projectRoot);
|
|
@@ -643,11 +643,11 @@ export function harnessStatusForStatusline(cfg, { root, liveWindow = null } = {}
|
|
|
643
643
|
// One `harness init` re-run fixes it and the warning goes away for good.
|
|
644
644
|
if (status.hasBlock && !(status.hasRatchetImport && status.hasModelRatchetImport)) warnings.push('ratchet-unloaded');
|
|
645
645
|
// Same class of defect, one notch lower: the session runs on a 1M-context
|
|
646
|
-
// model with no `autoCompactWindow` cap, so compaction only fires
|
|
647
|
-
// and every request until then re-bills the whole context. 200k
|
|
648
|
-
// exempt — the setting cannot change anything for them.
|
|
646
|
+
// model with no `autoCompactWindow` cap, so compaction only fires at about
|
|
647
|
+
// 967k and every request until then re-bills the whole context. 200k
|
|
648
|
+
// sessions are exempt — the setting cannot change anything for them.
|
|
649
649
|
try {
|
|
650
|
-
const w = compactWindowWarningForStatusline(projectRoot, cfg, { liveWindow });
|
|
650
|
+
const w = compactWindowWarningForStatusline(projectRoot, cfg, { liveWindow, liveModel });
|
|
651
651
|
if (w) warnings.push(w);
|
|
652
652
|
} catch { /* settings unreadable — stay silent */ }
|
|
653
653
|
// Below session-quality warnings: a promoted delegation rule whose
|
package/src/net-saving.js
CHANGED
|
@@ -49,11 +49,11 @@ export function priceSource(env = process.env) {
|
|
|
49
49
|
* touches. Cache writes are taken at the 5-minute rate, the cheaper of the two.
|
|
50
50
|
* null when any of them has no price.
|
|
51
51
|
*/
|
|
52
|
-
export function unitRates(model, { env = process.env } = {}) {
|
|
52
|
+
export function unitRates(model, { env = process.env, at } = {}) {
|
|
53
53
|
if (!model) return null;
|
|
54
54
|
const rate = (totals) => {
|
|
55
55
|
let c;
|
|
56
|
-
try { c = sessionCost({ ...ZERO, ...totals }, model, { env }); } catch { return null; }
|
|
56
|
+
try { c = sessionCost({ ...ZERO, ...totals }, model, { env, at }); } catch { return null; }
|
|
57
57
|
return c ? c.actual / RATE_SCALE : null;
|
|
58
58
|
};
|
|
59
59
|
const cacheRead = rate({ cacheRead: RATE_SCALE });
|
|
@@ -67,7 +67,7 @@ export function unitRates(model, { env = process.env } = {}) {
|
|
|
67
67
|
* What a run's tokens cost on a model, in USD, to better than a cent. null when
|
|
68
68
|
* the model has no price on this path.
|
|
69
69
|
*/
|
|
70
|
-
export function exactCost(totals, model, { env = process.env } = {}) {
|
|
70
|
+
export function exactCost(totals, model, { env = process.env, at } = {}) {
|
|
71
71
|
if (!model) return null;
|
|
72
72
|
const scale = (t) => {
|
|
73
73
|
const out = {};
|
|
@@ -77,7 +77,7 @@ export function exactCost(totals, model, { env = process.env } = {}) {
|
|
|
77
77
|
const scaled = scale(totals);
|
|
78
78
|
if (totals.long) scaled.long = scale(totals.long);
|
|
79
79
|
let c;
|
|
80
|
-
try { c = sessionCost(scaled, model, { env }); } catch { return null; }
|
|
80
|
+
try { c = sessionCost(scaled, model, { env, at }); } catch { return null; }
|
|
81
81
|
return c ? c.actual / COST_SCALE : null;
|
|
82
82
|
}
|
|
83
83
|
|
package/src/route-scan.js
CHANGED
|
@@ -377,11 +377,17 @@ export function worthDelegating(tier, rank) {
|
|
|
377
377
|
* negative. null means a side has no price (a gateway session whose /model/info
|
|
378
378
|
* table lacks the model), which is unpriced, not zero.
|
|
379
379
|
*/
|
|
380
|
+
/** When a run spent its tokens, for the dated price lookup; undefined means now. */
|
|
381
|
+
const runTime = (run) => (Number.isFinite(run?.startedAt) ? run.startedAt : Number.isFinite(run?.endedAt) ? run.endedAt : undefined);
|
|
382
|
+
|
|
380
383
|
export function runSaving(run, mainModel, { env = process.env } = {}) {
|
|
381
384
|
if (!run.model || !mainModel) return null;
|
|
382
385
|
const totals = runTotals(run);
|
|
383
|
-
|
|
384
|
-
|
|
386
|
+
// Priced at the rates in effect when the run happened, so a later price
|
|
387
|
+
// change does not rewrite a saving already earned (#15).
|
|
388
|
+
const at = runTime(run);
|
|
389
|
+
const actual = sessionCost(totals, run.model, { env, at });
|
|
390
|
+
const counterfactual = sessionCost(totals, mainModel, { env, at });
|
|
385
391
|
if (!actual || !counterfactual) return null;
|
|
386
392
|
return counterfactual.actual - actual.actual;
|
|
387
393
|
}
|
|
@@ -403,8 +409,9 @@ export function runSavingDetail(run, mainModel, info, { env = process.env } = {}
|
|
|
403
409
|
const v3 = (() => {
|
|
404
410
|
if (!info || !Array.isArray(run.perCall) || run.perCall.length === 0) return null;
|
|
405
411
|
if (!Number.isFinite(info.resultChars)) return null;
|
|
406
|
-
const
|
|
407
|
-
const
|
|
412
|
+
const at = runTime(run);
|
|
413
|
+
const rates = unitRates(mainModel, { env, at });
|
|
414
|
+
const subActual = exactCost(runTotals(run), run.model, { env, at });
|
|
408
415
|
if (!rates || subActual === null) return null;
|
|
409
416
|
// A background launch returns only an acknowledgement; the report that
|
|
410
417
|
// follows is the run's final message.
|
|
@@ -431,7 +438,7 @@ export function runSavingDetail(run, mainModel, info, { env = process.env } = {}
|
|
|
431
438
|
*/
|
|
432
439
|
export function runCost(run) {
|
|
433
440
|
if (!run.model) return null;
|
|
434
|
-
const actual = sessionCost(runTotals(run), run.model);
|
|
441
|
+
const actual = sessionCost(runTotals(run), run.model, { at: runTime(run) });
|
|
435
442
|
return actual ? actual.actual : null;
|
|
436
443
|
}
|
|
437
444
|
|
|
@@ -967,7 +974,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
967
974
|
startedAt: e.run.startedAt ?? null,
|
|
968
975
|
cfCarry: detail.cfCarry,
|
|
969
976
|
overhead: detail.overhead,
|
|
970
|
-
firstWrite: detail.basis === 'v3' ? (e.run.perCall[0].newIn * (unitRates(baseline)?.write ?? 0)) : 0,
|
|
977
|
+
firstWrite: detail.basis === 'v3' ? (e.run.perCall[0].newIn * (unitRates(baseline, { at: runTime(e.run) })?.write ?? 0)) : 0,
|
|
971
978
|
calls: e.run.calls,
|
|
972
979
|
C: e.info?.C ?? null,
|
|
973
980
|
N: e.info?.N ?? null,
|