sprag-cli 3.98.0 → 3.99.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +16 -8
- package/docs/TEAM.ko.md +2 -0
- package/docs/TEAM.md +2 -0
- package/package.json +1 -1
- package/src/brief.js +11 -6
- package/src/commands/compact-window.js +62 -20
- package/src/compact-window.js +202 -26
- package/src/ctx-window-cache.js +28 -5
- package/src/formatters/statusline.js +4 -4
- package/src/harness.js +5 -5
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/docs/TEAM.ko.md
CHANGED
|
@@ -167,6 +167,8 @@ Sprag 운영자는 ops 콘솔(sprag.io/ops/)에서 조직마다 최소 Sprag 버
|
|
|
167
167
|
|
|
168
168
|
https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드로 로그인하고, 팀을 만들고, 초대 토큰을 받습니다. 새 조직은 support@sprag.io 로 문의합니다. 오너, 어드민, 초대 대기 중 어느 쪽에도 없는 이메일은 코드를 보내기 전에 거절하며, 조직 오너에게 추가를 요청하라고 안내합니다. 초대받은 사람은 처음 로그인할 때 자동으로 오너나 어드민이 됩니다. 여기서 구성원별 지출과 절감액을 보고, 규칙 탭에서 조직 룰과 팀 룰을 관리하고, 구성원을 내보낼 수 있습니다. 조직 패널에는 요금제, 한도 대비 사용 좌석, 어드민, 전체 팀이 보입니다. 슈퍼유저는 sprag.io/ops/ 에서 모든 조직을 보고, 조직의 개요 탭에서 어느 조직에든 팀을 만들 수 있습니다. 팀을 만들면 그 팀의 초대 토큰이 화면에 나옵니다. 오너와 어드민과 슈퍼유저는 팀을 삭제할 수 있습니다. 팀 화면에서 초대와 등록을 다루는 탭에 있는 '팀 삭제' 버튼을 쓰거나 /ops/ 조직 개요 탭의 팀 행에서 삭제 버튼을 누릅니다. 일시정지 멤버를 포함해 활동 멤버가 남아 있으면 거절하므로 먼저 멤버를 모두 제거해야 합니다. 팀을 삭제하면 과거 멤버의 사용 기록과 이전 활동 기록도 함께 지워지고 되돌릴 수 없습니다. 활동 로그에는 기계마다 '삭제됨' 항목이 하나씩 남습니다.
|
|
169
169
|
|
|
170
|
+
여러 팀을 한 번에 만들려면 "+ 새 팀"을 누르고 "여러 팀 한 번에 만들기"를 펼친 뒤 한 줄에 팀 이름을 하나씩 붙여 넣습니다. 한 번에 50개까지 만들 수 있습니다. 빈 줄과 조직에 이미 있는 이름, 목록에 두 번 나온 이름, 80자를 넘는 이름은 건너뛰고 따로 알려 줍니다. 만들다가 하나가 실패하면 그 이름에서 멈추고 아직 만들지 못한 이름은 다시 실행할 수 있도록 입력란에 남겨 둡니다. 팀 목록과 타운 탭의 "가입 명령어 내보내기"를 누르면 팀마다 한 줄씩 담긴 CSV를 받습니다. 열은 `team`, `team_id`, `invite_token`, `join_command`(`npm i -g sprag-cli@latest && sprag team join <토큰>`), `shell_profile`(`export SPRAG_TEAM_TOKEN=<토큰>`), `managed_settings`(관리형 설정 JSON)입니다. 일괄 생성이 끝나면 방금 만든 팀만 내보내는 버튼도 나옵니다. 이 파일에는 목록에 있는 모든 팀의 초대 토큰이 들어 있으므로 각 줄은 해당 팀에만 전달하고, 파일이 새어 나가면 그 팀의 토큰을 교체하십시오.
|
|
171
|
+
|
|
170
172
|
대시보드 맨 위의 기간 선택(7일, 30일, 90일, 이번 달, 지난 달, 직접 선택)이 멤버 표, 사용량 차트, 프롬프트 사용량 탭의 기간을 정합니다. 기본값은 최근 30일이고, 내 컴퓨터의 달력 날짜를 쓰며 종료일도 포함합니다. 최대 365일까지 고를 수 있습니다. 고른 기간은 주소(`?from=2026-10-01&to=2026-10-18`)에 남으므로 새로고침하거나 링크를 공유해도 같은 기간이 보입니다. sprag.io/ops/ 슈퍼유저 콘솔에도 같은 선택이 있어 조직 표, 조직 머리말, 조직의 프롬프트 사용량에 적용됩니다.
|
|
171
173
|
|
|
172
174
|
### 좌석 현황
|
package/docs/TEAM.md
CHANGED
|
@@ -168,6 +168,8 @@ If the upgrade fails, for example because the required version is not published
|
|
|
168
168
|
|
|
169
169
|
https://sprag.io/team/ is where a registered owner or admin signs in with an email code, creates a team and gets the invite token. A new organization starts by writing to support@sprag.io. An email that is not an owner, an admin or a pending invite is refused before any code is sent, with a message to ask the organization's owner to add it. Invited people become owner or admin automatically on their first sign-in. From there they see per-member spend and savings, manage organization and team rules on the Rules tab, and remove members. The organization panel shows the plan, seats used against the limit, admins and every team. The superuser sees every organization at sprag.io/ops/ and can create a team in any of them from the organization's Overview tab, which shows the new team's invite token. Owners, admins and the superuser can delete a team (the "Delete team" button in the "Invite & enroll" tab of a team, or the Delete button on the team's row in the organization's Overview tab at /ops/). Sprag refuses while the team still has active members, including paused ones, so remove them first. Deleting a team also erases the usage history and earlier activity of its past members, and it cannot be undone; the activity log keeps one "deleted" entry per machine.
|
|
170
170
|
|
|
171
|
+
To create several teams at once, open "+ New team", then "Create several teams at once", and paste one team name per line (up to 50 per run). Blank lines, names already in the organization, names listed twice and names over 80 characters are skipped and listed. If one creation fails, the run stops there and the names not yet created stay in the box for another run. "Export join commands" (under the Teams list and on the Town tab) downloads a CSV with one row per team: `team`, `team_id`, `invite_token`, `join_command` (`npm i -g sprag-cli@latest && sprag team join <token>`), `shell_profile` (`export SPRAG_TEAM_TOKEN=<token>`) and `managed_settings` (the managed settings JSON). After a bulk run, a button exports only the teams it created. The file holds every listed team's invite token, so share each row only with that team, and rotate a team's token if the file leaks.
|
|
172
|
+
|
|
171
173
|
A date range control at the top of the dashboard (7d, 30d, 90d, This month, Last month or Custom) sets the period for the members table, the Usage chart and the prompt usage tab. It defaults to the last 30 days, uses your local calendar days with the end date included, and allows 365 days at most. The choice is kept in the page address (`?from=2026-10-01&to=2026-10-18`), so a reload or a shared link shows the same period. The superuser console at /ops/ has the same control for the organization table, the organization header and its prompt usage.
|
|
172
174
|
|
|
173
175
|
### The seat roster
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.99.1",
|
|
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 */ }
|
|
@@ -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/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
|