sprag-cli 3.123.1 → 3.124.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -146,6 +146,24 @@ function columnsFromArgs({ useEnv = true } = {}) {
146
146
  return positive(getArg('--columns')) || (useEnv ? positive(process.env.COLUMNS) : 0);
147
147
  }
148
148
 
149
+ /**
150
+ * Label length and compact level for a statusline render. `--compact-level N`
151
+ * (0-3) wins; 0 means verbose labels and 1+ short ones. Without it the older
152
+ * `--verbose` / `--no-verbose` / `--compact` flags decide the labels, and the
153
+ * stored level (`sprag mode compact=2`) applies unless those flags asked for
154
+ * verbose. A bad `--compact-level` value is ignored rather than thrown: the
155
+ * statusline runs from a fixed command and must not go blank over a typo.
156
+ */
157
+ function compactFromArgs(cfg) {
158
+ const raw = getArg('--compact-level');
159
+ const n = raw === undefined ? NaN : Number(raw);
160
+ if (Number.isInteger(n) && n >= 0 && n <= 3) return { level: n, verbose: n === 0 };
161
+ const verbose = hasFlag('--verbose')
162
+ ? true
163
+ : (hasFlag('--no-verbose') || hasFlag('--compact') ? false : cfg.verbose);
164
+ return { level: verbose ? 0 : Math.max(1, cfg.compactLevel || 0), verbose };
165
+ }
166
+
149
167
  const KNOWN_SUBCOMMANDS = new Set([
150
168
  'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
151
169
  'doc2md', 'delegate', 'proof', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
@@ -164,7 +182,7 @@ const KNOWN_SUBCOMMANDS = new Set([
164
182
  const FLAG_SPECS = {
165
183
  report: {
166
184
  value: ['--format', '-f', '--project', '-p', '--days', '-d', '--hours', '--demo',
167
- '--demo-cycle-sec', '--segments', '--exclude-session', '--threshold', '--columns'],
185
+ '--demo-cycle-sec', '--segments', '--exclude-session', '--threshold', '--columns', '--compact-level'],
168
186
  bool: ['--statusline', '--verbose', '--no-verbose', '--compact', '--no-color', '--icon',
169
187
  '--no-icon', '--text', '--narrow', '--no-timer', '--single-line', '--demo-label',
170
188
  '--version', '-v', '--help', '-h', '--hook', '--hook-run', '--install-hook', '--uninstall-hook'],
@@ -635,15 +653,14 @@ async function main() {
635
653
  // where the real line would not is worse than no demo at all.
636
654
  const { resolveLabelMode } = await import('../src/statusline-mode.js');
637
655
  const { mode: labelMode } = resolveLabelMode({ hasFlag, cfg });
638
- const isVerbose = hasFlag('--verbose')
639
- ? true
640
- : (hasFlag('--no-verbose') || hasFlag('--compact') ? false : cfg.verbose);
656
+ const { level: compactLevel, verbose: isVerbose } = compactFromArgs(cfg);
641
657
  const showTimer = hasFlag('--no-timer') ? false : cfg.timer;
642
658
  const colorOk = !hasFlag('--no-color') && !process.env.NO_COLOR && cfg.color;
643
659
  const segments = segmentsFromArgs();
644
660
  const out = formatReport(data, {
645
661
  color: colorOk,
646
662
  verbose: isVerbose,
663
+ compactLevel,
647
664
  timer: showTimer,
648
665
  mode: labelMode,
649
666
  segments,
@@ -787,7 +804,7 @@ async function main() {
787
804
  const { withBaseStatusline } = await import('../src/statusline-base.js');
788
805
  const noSessionOut = withBaseStatusline(formatNoSession(
789
806
  { caps, model, effort, ultra, windowLabel, version: PKG_VERSION, update: readUpdateChip(PKG_VERSION), team: (await import('../src/team-sync.js')).readTeamChip() },
790
- { color: colorOk, mode: labelMode, segments: segmentsFromArgs(), columns: columnsFromArgs() },
807
+ { color: colorOk, mode: labelMode, segments: segmentsFromArgs(), columns: columnsFromArgs(), compactLevel: compactFromArgs(cfg).level },
791
808
  ), { input: readStdinRaw() });
792
809
  if (guard) guard.finish(noSessionOut);
793
810
  console.log(noSessionOut);
@@ -1218,9 +1235,7 @@ async function main() {
1218
1235
  // the escape hatch out of it (SPRAG_ICON=force / `sprag mode icon-force`).
1219
1236
  const { resolveLabelMode } = await import('../src/statusline-mode.js');
1220
1237
  const { mode: labelMode } = resolveLabelMode({ hasFlag, cfg });
1221
- const isVerbose = hasFlag('--verbose')
1222
- ? true
1223
- : (hasFlag('--no-verbose') || hasFlag('--compact') ? false : cfg.verbose);
1238
+ const { level: compactLevel, verbose: isVerbose } = compactFromArgs(cfg);
1224
1239
  const showTimer = hasFlag('--no-timer') ? false : cfg.timer;
1225
1240
  const colorOk =
1226
1241
  !hasFlag('--no-color') && !process.env.NO_COLOR && cfg.color;
@@ -1229,6 +1244,7 @@ async function main() {
1229
1244
  output = formatReport(data, {
1230
1245
  color: colorOk,
1231
1246
  verbose: isVerbose,
1247
+ compactLevel,
1232
1248
  timer: showTimer,
1233
1249
  mode: labelMode,
1234
1250
  segments,
package/docs/DATA.ko.md CHANGED
@@ -1,4 +1,4 @@
1
- # Sprag 이 보내는 데이터
1
+ # Sprag가 보내는 데이터
2
2
 
3
3
  [← README](../README.ko.md) · [English](./DATA.md)
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.123.1",
3
+ "version": "3.124.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -6,26 +6,52 @@
6
6
  * direct call and uses the list table. Kept apart from cost.js because
7
7
  * litellm-models.js imports cost.js, and this needs both.
8
8
  */
9
- import { estimateCost, estimateCostAcross } from './cost.js';
9
+ import { pathToFileURL } from 'node:url';
10
+ import { estimateCost, estimateCostAcross, isUnknownModel } from './cost.js';
10
11
  import { gatewayPriceFor, gatewayPriceMiss } from './litellm-models.js';
11
12
  import { gatewayBase } from './gateway-auth.js';
12
- import { diagActive, recordDiag } from './diag-log.js';
13
+ import { diagActive, recordDiag, diagSrcDir } from './diag-log.js';
13
14
 
14
15
  // `at` is when the tokens were spent; list prices and gateway prices (from the
15
16
  // gateway's dated price history) are looked up for that time.
16
17
  export function sessionCost(totals, model, { env = process.env, now, at } = {}) {
17
18
  if (!gatewayBase(env)) return estimateCost(totals, model, { at });
18
19
  const price = gatewayPriceFor(model, env, now, at);
19
- if (!price) noteUnpriced(model, env, now, at);
20
+ if (!price) noteUnpriced(model, env, now, at, totals);
20
21
  return price ? estimateCost(totals, model, { price }) : null;
21
22
  }
22
23
 
24
+ const tokenBucket = (n) => (n <= 0 ? '0' : n < 1000 ? '<1k' : n < 100000 ? '<100k' : '100k+');
25
+
26
+ /** `src/<file>.js:<line>` of the first stack frame outside this file, or '?'. */
27
+ function callerFrame(stack) {
28
+ if (typeof stack !== 'string') return '?';
29
+ for (const line of stack.split('\n').slice(1)) {
30
+ if (line.includes('claude-price.js')) continue;
31
+ for (const needle of [diagSrcDir, pathToFileURL(diagSrcDir).href]) {
32
+ const at = line.indexOf(needle);
33
+ if (at < 0) continue;
34
+ const m = /^[\\/]([^\s():]+?\.c?js):(\d+)/.exec(line.slice(at + needle.length));
35
+ if (m) return `src/${m[1].replace(/\\/g, '/')}:${m[2]}`;
36
+ }
37
+ }
38
+ return '?';
39
+ }
40
+
23
41
  // A gateway session with no price is invisible otherwise: the figure just reads
24
42
  // as unpriced. The diagnostics log records why, once per distinct message per
25
43
  // process (recordDiag dedupes), so the message must not carry `at`.
26
- function noteUnpriced(model, env, now, at) {
44
+ // An unknown model has nothing to list, so its message names the size of the
45
+ // spend and the caller instead; both are bucketed to keep the message stable.
46
+ function noteUnpriced(model, env, now, at, totals) {
27
47
  try {
28
48
  if (!diagActive({ env })) return;
49
+ if (isUnknownModel(model)) {
50
+ const t = totals || {};
51
+ const sum = (t.input || 0) + (t.cacheCreation || 0) + (t.cacheRead || 0) + (t.output || 0);
52
+ recordDiag('price:unpriced', new Error(`model=unknown tokens=${tokenBucket(sum)} via=${callerFrame(new Error().stack)}`), { env });
53
+ return;
54
+ }
29
55
  const { reason, keys } = gatewayPriceMiss(model, env, now, at);
30
56
  recordDiag('price:unpriced', new Error(`model=${model} reason=${reason} known=${keys.join(',')}`), { env });
31
57
  } catch { /* diagnostics only */ }
@@ -3,6 +3,7 @@
3
3
  * them up without flags or wrapper edits.
4
4
  * sprag mode # show current config
5
5
  * sprag mode icon verbose # set icon + verbose
6
+ * sprag mode compact=2 # short labels, folded headlines, fewer chips
6
7
  * sprag mode reset # clear back to defaults
7
8
  */
8
9
 
@@ -33,6 +34,7 @@ export async function run({ args }) {
33
34
  }
34
35
  console.log(` icon-force: ${eff.iconForce}`);
35
36
  console.log(` verbose: ${eff.verbose}`);
37
+ console.log(` compact: ${eff.compactLevel}`);
36
38
  console.log(` timer: ${eff.timer}`);
37
39
  console.log(` color: ${eff.color}`);
38
40
  console.log(` window: ${eff.windowLabel} (${eff.windowHours}h)`);
@@ -56,7 +58,7 @@ export async function run({ args }) {
56
58
  }
57
59
  const eff = statuslineDefaults();
58
60
  console.log(`Updated: ${applied.join(', ')}`);
59
- console.log(`Now: labels=${eff.labels} icon-force=${eff.iconForce} verbose=${eff.verbose} timer=${eff.timer} color=${eff.color} window=${eff.windowLabel} language=${userLanguage()}`);
61
+ console.log(`Now: labels=${eff.labels} icon-force=${eff.iconForce} verbose=${eff.verbose} compact=${eff.compactLevel} timer=${eff.timer} color=${eff.color} window=${eff.windowLabel} language=${userLanguage()}`);
60
62
  const { mode: renders } = resolveLabelMode({ cfg: eff });
61
63
  if (renders !== eff.labels) {
62
64
  console.log(`Renders as: ${renders}${isJetBrainsTerminal() ? ' (IntelliJ detected)' : ''}`);
@@ -10,6 +10,7 @@ import { createRequire } from 'node:module';
10
10
  const require = createRequire(import.meta.url);
11
11
  import { readStdinJson } from '../stdin-payload.js';
12
12
  import { debug } from '../debug.js';
13
+ import { parseJsonText } from '../json-text.js';
13
14
  import { routingEnabled } from '../routing-switch.js';
14
15
  import { signedUsd } from '../money.js';
15
16
  import { agentForRule, TIER_MODEL } from '../agents.js';
@@ -24,7 +25,7 @@ import { agentForRule, TIER_MODEL } from '../agents.js';
24
25
  function doc2mdHookRegistered() {
25
26
  try {
26
27
  const { homedir } = require('node:os');
27
- const settings = JSON.parse(readFileSync(join(homedir(), '.claude', 'settings.json'), 'utf8'));
28
+ const settings = parseJsonText(readFileSync(join(homedir(), '.claude', 'settings.json'), 'utf8'));
28
29
  return Object.values(settings?.hooks || {}).some((matchers) =>
29
30
  (matchers || []).some((m) =>
30
31
  (m.hooks || []).some((h) => typeof h.command === 'string' && h.command.includes('doc2md --hook')),
@@ -33,6 +33,7 @@ import { execFileSync } from 'node:child_process';
33
33
  import { debug } from './debug.js';
34
34
  import { writePrivateFile } from './private-file.js';
35
35
  import { isNewer } from './update-check.js';
36
+ import { parseJsonText } from './json-text.js';
36
37
 
37
38
  // First Claude Code release that reads `modelSettings[<model>].autoCompactWindow`.
38
39
  // An older one ignores the entry, so a per-model `set` would silently do nothing.
@@ -44,7 +45,8 @@ export function claudeCodeVersion({ run = () => execFileSync('claude', ['--versi
44
45
  const m = String(run()).match(/(\d+\.\d+\.\d+)/);
45
46
  return m ? m[1] : null;
46
47
  } catch (e) {
47
- debug('compact-window:claude-version', e);
48
+ // claude missing from a hook's PATH is normal there, not worth a log line.
49
+ if (e?.code !== 'ENOENT') debug('compact-window:claude-version', e);
48
50
  return null;
49
51
  }
50
52
  }
@@ -109,7 +111,7 @@ export function projectSettingsPaths(root) {
109
111
  function readJson(path) {
110
112
  try {
111
113
  if (!existsSync(path)) return null;
112
- return JSON.parse(readFileSync(path, 'utf8'));
114
+ return parseJsonText(readFileSync(path, 'utf8'));
113
115
  } catch (e) {
114
116
  debug('compact-window:read', e);
115
117
  return null; // malformed settings — treat as "nothing configured"
@@ -343,7 +345,7 @@ export function setAutoCompactWindow({ root = process.cwd(), scope = 'global', v
343
345
  if (existsSync(path)) {
344
346
  const raw = readFileSync(path, 'utf8');
345
347
  try {
346
- json = JSON.parse(raw);
348
+ json = parseJsonText(raw);
347
349
  } catch (e) {
348
350
  debug('compact-window:parse', e);
349
351
  // Refuse to overwrite a file we cannot parse — silently replacing a
package/src/config.js CHANGED
@@ -100,6 +100,7 @@ export const VALID_KEYWORDS = Object.keys(KEYWORDS)
100
100
  '<N>d (e.g. 1d, 7d, 30d)',
101
101
  'lang=en | lang=ko',
102
102
  'ttl=5m | ttl=1h | ttl=auto',
103
+ 'compact=0..3 (0 verbose, 1 short labels, 2 fewer chips, 3 only alarms)',
103
104
  'reset',
104
105
  'default',
105
106
  ]);
@@ -147,6 +148,18 @@ export function applyMode(words) {
147
148
  applied.push(`ttl=${ttlMatch[1]}`);
148
149
  continue;
149
150
  }
151
+ // `compact=0..3` is one setting with four values. 0 and 1 are the verbose
152
+ // and short-label layouts; 2 and 3 also fold the headline lines and trim the
153
+ // chips, so only those two store a level.
154
+ const compactMatch = lower.match(/^compact=([0-3])$/);
155
+ if (compactMatch) {
156
+ const n = Number(compactMatch[1]);
157
+ cfg.statusline.verbose = n === 0;
158
+ if (n >= 2) cfg.statusline.compactLevel = n;
159
+ else delete cfg.statusline.compactLevel;
160
+ applied.push(`compact=${n}`);
161
+ continue;
162
+ }
150
163
  const hours = parseWindow(lower);
151
164
  if (hours !== null && hours > 0) {
152
165
  cfg.statusline.windowHours = hours;
@@ -161,6 +174,9 @@ export function applyMode(words) {
161
174
  continue;
162
175
  }
163
176
  cfg.statusline[kw.key] = kw.value;
177
+ // `verbose` and `compact` pick the label length outright, so a stored
178
+ // compact level (2 or 3) would contradict them.
179
+ if (kw.key === 'verbose') delete cfg.statusline.compactLevel;
164
180
  applied.push(lower);
165
181
  }
166
182
 
@@ -192,6 +208,10 @@ export function statuslineDefaults() {
192
208
  // written before it existed. labelPreference() owns that fallback so the
193
209
  // resolver and this function cannot disagree about what an old config means.
194
210
  const labels = labelPreference(s);
211
+ // Stored only for 2 and 3; 0 and 1 are what `verbose` already says.
212
+ const compactLevel = s.compactLevel === 2 || s.compactLevel === 3
213
+ ? s.compactLevel
214
+ : (s.verbose !== false ? 0 : 1);
195
215
  return {
196
216
  labels,
197
217
  // Kept for callers that only ask "emoji or not".
@@ -199,7 +219,8 @@ export function statuslineDefaults() {
199
219
  // Off unless asked for: narrow labels are the IntelliJ default now, and only
200
220
  // the user knows whether they would rather have garbled emoji than glyphs.
201
221
  iconForce: s.iconForce === true,
202
- verbose: s.verbose !== false,
222
+ verbose: compactLevel === 0,
223
+ compactLevel,
203
224
  timer: s.timer !== false,
204
225
  color: s.color !== false,
205
226
  modelShare: s.modelShare !== false,
@@ -680,18 +680,41 @@ function buildCapWarnSeg(capWarn, c, isIcon, g, color, mode) {
680
680
  // unused ticks are dimmed, the second which pair of tick glyphs to draw.
681
681
  if (!capWarn) return null;
682
682
  const pct = Math.round(capWarn.usedPct);
683
- const clock = formatResetClock(capWarn.resetsAt);
684
- // Text mode has no glyph vocabulary, so it names the thing instead of
685
- // borrowing an emoji it otherwise avoids.
686
- const clockTail = clock ? (isIcon ? ` ${g.reset} ${clock}` : ` resets ${clock}`) : '';
683
+ // The chip replaces the window's always-on segment, so it carries the same
684
+ // facts: a budget window keeps its `$used/$limit`, its `(user)` source mark
685
+ // and its countdown reset. Without them a 94% budget chip showed neither the
686
+ // money nor a usable reset ("Sun 10:55" for a reset nine days out).
687
+ const { tail, money, src } = windowSegParts(labelForKey(capWarn.key), capWarn, isIcon, g);
687
688
  if (isIcon) {
688
689
  // Gauge keeps shape parity with the always-on usage segment — the
689
690
  // cap-warn is just the same gauge "filled to alarm". Visual continuity
690
691
  // helps the eye understand "this is the 5H bar I was watching, just red now."
691
692
  const bar = gaugeColored(pct, c, RED, color, mode);
692
- return `${c(BOLD)}${c(RED)}${g.capWarn} ${capWarn.label} ${bar} ${pct}%${clockTail}${c(RESET)}`;
693
+ return `${c(BOLD)}${c(RED)}${g.capWarn} ${capWarn.label}${src} ${bar} ${pct}%${money}${tail}${c(RESET)}`;
693
694
  }
694
- return `${c(BOLD)}${c(RED)}${capWarn.label} cap ${pct}%${clockTail}${c(RESET)}`;
695
+ return `${c(BOLD)}${c(RED)}${capWarn.label}${src} cap ${pct}%${money}${tail}${c(RESET)}`;
696
+ }
697
+
698
+ /**
699
+ * What a rate-limit window shows next to its percent, shared by the always-on
700
+ * segment and the cap-warn chip so the two never drift apart.
701
+ * - `tail`: the reset, as a wall-clock time or, for windows whose labels ask
702
+ * for it (budgets), the time left. Text mode names it instead of using 🔄.
703
+ * - `money`: ` $used/$limit` when the window carries dollar amounts.
704
+ * - `src`: ` (user)` when a LiteLLM gauge is drawn from the internal user
705
+ * limit, which is not the limit that blocks requests.
706
+ */
707
+ function windowSegParts(labels, info, isIcon, g) {
708
+ const clock = labels.resetStyle === 'countdown'
709
+ ? formatResetIn(info.resetsAt)
710
+ : formatResetClock(info.resetsAt);
711
+ const tail = clock ? (isIcon ? ` ${g.reset} ${clock}` : ` resets ${clock}`) : '';
712
+ const money =
713
+ Number.isFinite(info.maxBudget) && info.maxBudget > 0
714
+ ? ` ${formatMoney(Number(info.spend) || 0)}/${formatMoney(info.maxBudget)}`
715
+ : '';
716
+ const src = info.source === 'user' ? ' (user)' : '';
717
+ return { tail, money, src };
695
718
  }
696
719
 
697
720
  // Room Claude Code keeps for its own padding around the statusline. A guess
@@ -863,35 +886,47 @@ function fitChips(segs, { columns, maxLines = 3, eol = '', protectedSegs = new S
863
886
  * note. With `columns` the chips wrap onto at most `maxLines` lines (see
864
887
  * layoutChips).
865
888
  */
866
- export function formatNoSession({ caps = null, model = null, effort = null, ultra = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null, columns = 0, maxLines = 3 } = {}) {
889
+ export function formatNoSession({ caps = null, model = null, effort = null, ultra = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null, columns = 0, maxLines: maxLinesOpt = 3, compactLevel = 0 } = {}) {
867
890
  const c = (v) => (color ? v : '');
868
891
  // narrow shares the icon layout and swaps only the glyphs, so both modes take
869
892
  // the same branches from here on.
870
893
  const isIcon = mode === 'icon' || mode === 'narrow';
871
894
  const g = glyphsFor(mode);
895
+ // Compact level, as in formatReport. The chip trim is skipped when the caller
896
+ // named `segments`, which keeps this line's existing behaviour for them.
897
+ const level = normalizeCompactLevel(compactLevel);
898
+ const maxLines = level >= 3 ? 1 : level >= 2 ? Math.min(maxLinesOpt, 2) : maxLinesOpt;
899
+ const trim = !(segments && segments.length);
900
+ const dropUnder2 = trim && level >= 2;
901
+ const onlyCore = trim && level >= 3;
872
902
  const segs = [];
873
903
  const capSeg = buildCapWarnSeg(pickCapWarn(caps), c, isIcon, g, color, mode);
874
904
  if (capSeg) segs.push(capSeg);
875
905
  const versionSeg = buildVersionSeg(version, update, c, isIcon, false, g);
876
- if (versionSeg && update && update.available) segs.push(versionSeg);
906
+ if (versionSeg && update && update.available && !onlyCore) segs.push(versionSeg);
877
907
  // Same rule as the full report: a healthy 🅷 stays off the line unless
878
908
  // `--segments` named it. This line has no other opt-in, so `segments` is only
879
909
  // read for that one name.
880
910
  const named = (name) => !!(segments && segments.some((s) => String(s).toLowerCase() === name));
881
- const harnessSeg = buildHarnessSeg(c, isIcon, g, null, named('harness'));
911
+ const harnessSeg = dropUnder2 ? null : buildHarnessSeg(c, isIcon, g, null, named('harness'));
882
912
  if (harnessSeg) segs.push(harnessSeg);
883
- const modelSeg = buildModelSeg(model, c, isIcon, g);
913
+ const modelSeg = onlyCore ? null : buildModelSeg(model, c, isIcon, g);
884
914
  if (modelSeg) segs.push(modelSeg);
885
- const effortSeg = buildEffortSeg(effort, c, isIcon, g);
915
+ const effortSeg = onlyCore ? null : buildEffortSeg(effort, c, isIcon, g);
886
916
  if (effortSeg) segs.push(effortSeg);
887
- const ultraSeg = buildUltraSeg(ultra, c, isIcon, g);
917
+ const ultraSeg = onlyCore ? null : buildUltraSeg(ultra, c, isIcon, g);
888
918
  if (ultraSeg) segs.push(ultraSeg);
889
- segs.push(`${c(GRAY)}${g.hit} no session data${windowLabel ? ` · ${windowLabel}` : ''}${c(RESET)}`);
890
- const teamSeg = buildTeamSeg(team, c, mode);
919
+ const noSessionSeg = `${c(GRAY)}${g.hit} no session data${windowLabel ? ` · ${windowLabel}` : ''}${c(RESET)}`;
920
+ segs.push(noSessionSeg);
921
+ const teamSeg = dropUnder2 ? null : buildTeamSeg(team, c, mode);
891
922
  if (teamSeg) segs.push(teamSeg);
892
- if (versionSeg && !(update && update.available)) segs.push(versionSeg);
923
+ if (versionSeg && !(update && update.available) && !dropUnder2) segs.push(versionSeg);
924
+ // At level 3 the line is these two chips only, so the second must survive the
925
+ // one-line budget.
926
+ const protectedSegs = new Set(capSeg ? [capSeg] : []);
927
+ if (onlyCore) protectedSegs.add(noSessionSeg);
893
928
  return layoutChips(segs, {
894
- columns, maxLines, eol: color ? '\x1b[K' : '', protectedSegs: new Set(capSeg ? [capSeg] : []), color,
929
+ columns, maxLines, eol: color ? '\x1b[K' : '', protectedSegs, color,
895
930
  });
896
931
  }
897
932
 
@@ -1156,10 +1191,6 @@ function buildUsageSeg({ labels, info, tone, suppressed }, c, isIcon, verbose, g
1156
1191
  // nothing ("Thu 00:00" — which Thursday?). Those windows report how long is
1157
1192
  // left instead. Short windows keep the clock, which is the more useful form
1158
1193
  // when the reset is later today.
1159
- const clock = labels.resetStyle === 'countdown'
1160
- ? formatResetIn(info.resetsAt)
1161
- : formatResetClock(info.resetsAt);
1162
- const tail = clock ? (isIcon ? ` ${g.reset} ${clock}` : ` resets ${clock}`) : '';
1163
1194
  // `cap` reads as a rate-limit ceiling rather than a duration. Icon mode
1164
1195
  // leans on the icon to identify the window (✦ = session/now, 📅 = week),
1165
1196
  // so the 5H label is empty while the 7D label spells out "weekly". Text and
@@ -1169,14 +1200,11 @@ function buildUsageSeg({ labels, info, tone, suppressed }, c, isIcon, verbose, g
1169
1200
  // and the gauge stays the same width as the percent climbs.
1170
1201
  // LiteLLM 예산 윈도우는 퍼센트만으로는 감이 안 오므로(예산 크기를 모름)
1171
1202
  // 금액을 함께 보여 준다: `💳 budget ▰▱ 34% $34/$100`.
1172
- const money =
1173
- Number.isFinite(info.maxBudget) && info.maxBudget > 0
1174
- ? ` ${formatMoney(Number(info.spend) || 0)}/${formatMoney(info.maxBudget)}`
1175
- : '';
1176
1203
  // LiteLLM 의 internal user 한도는 차단 판정에 쓰이는 값이 아니라서, 팀
1177
1204
  // 멤버십 한도와 수백 배 어긋나는 배포가 있습니다. 그 한도로 그린 게이지는
1178
1205
  // 출처를 밝혀 두어야 사용자가 정확한 값으로 오해하지 않습니다.
1179
- const src = info.source === 'user' ? ' (user)' : '';
1206
+ // 리셋 시각, 금액, 출처는 cap-warn 칩과 같은 함수로 만듭니다.
1207
+ const { tail, money, src } = windowSegParts(labels, info, isIcon, g);
1180
1208
  if (isIcon) {
1181
1209
  const labelPart = labels.usageLabel ? `${labels.usageLabel}${src} ` : '';
1182
1210
  const bar = gaugeColored(pct, c, tone, color, mode);
@@ -1633,10 +1661,32 @@ function segmentsNamed(name, s, usageByKey) {
1633
1661
  }
1634
1662
  }
1635
1663
 
1664
+ /**
1665
+ * `compactLevel` as an integer 0..3; anything else reads as 0.
1666
+ * 0 = verbose labels, 1 = short labels, 2 = also fewer chips and no headline
1667
+ * lines, 3 = only the chips that stop the work.
1668
+ */
1669
+ function normalizeCompactLevel(level) {
1670
+ const n = Math.trunc(Number(level));
1671
+ return Number.isFinite(n) && n >= 1 ? Math.min(n, 3) : 0;
1672
+ }
1673
+
1674
+ // Names kept in the default order at compact level 2 and 3. `usage` stands for
1675
+ // every rate-limit window; `version` joins only while an upgrade is available.
1676
+ const COMPACT_KEEP_3 = ['cap-warn', 'spike', 'usage', 'ctx', 'ttl'];
1677
+ const COMPACT_KEEP_2 = [...COMPACT_KEEP_3, 'model', 'effort', 'ultra', 'delegated'];
1678
+
1679
+ /** The default-order names a compact level keeps, or null when it keeps all. */
1680
+ function compactKeepNames(level, updateAvailable) {
1681
+ if (level >= 3) return new Set(COMPACT_KEEP_3);
1682
+ if (level >= 2) return new Set(updateAvailable ? [...COMPACT_KEEP_2, 'version'] : COMPACT_KEEP_2);
1683
+ return null;
1684
+ }
1685
+
1636
1686
  /**
1637
1687
  * The names to render, in order: the default sequence, or the caller's list.
1638
1688
  */
1639
- function resolveSegmentOrder(segments, caps, updateAvailable) {
1689
+ function resolveSegmentOrder(segments, caps, updateAvailable, compactLevel = 0) {
1640
1690
  // An available upgrade is an "act on this" chip, so it moves up behind the
1641
1691
  // warning chips. With nothing to upgrade to it stays pure identity, at the
1642
1692
  // tail position DEFAULT_SEGMENT_ORDER gives it.
@@ -1656,6 +1706,11 @@ function resolveSegmentOrder(segments, caps, updateAvailable) {
1656
1706
  && caps.windows.some((w) => w && (w.key === 'litellm_budget' || w.key === 'spend_limit')));
1657
1707
  if (hasGatewayBudget) defaultOrder = defaultOrder.filter((n) => n !== 'month');
1658
1708
 
1709
+ // The compact level trims the default chip set. A caller-supplied list below
1710
+ // replaces the default order, so it is never filtered by the level.
1711
+ const levelKeep = compactKeepNames(compactLevel, updateAvailable);
1712
+ if (levelKeep) defaultOrder = defaultOrder.filter((n) => levelKeep.has(n));
1713
+
1659
1714
  // A caller-supplied list sets the filter AND the order. Warning chips keep
1660
1715
  // the lead wherever they were written: being seen first is their whole job,
1661
1716
  // and someone reordering segments is not asking to bury an alarm.
@@ -1744,8 +1799,17 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1744
1799
  * @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line). It also ignores `columns`.
1745
1800
  * @param {number} [opts.columns=0] - terminal width in cells (Claude Code exports it as COLUMNS). When set, the chips wrap at chip boundaries instead of being truncated by the terminal; 0 keeps one unbounded line. A verbose layout that would need chips dropped is re-rendered once in the compact layout first.
1746
1801
  * @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.
1802
+ * @param {number} [opts.compactLevel=0] - 0 keeps `verbose` as given, 1 forces short labels, 2 adds folded headline lines (chips instead), the default chip set cut to cap-warn, spike, usage, ctx, ttl, model, effort, ultra, delegated (plus version while an upgrade is available) and at most 2 chip lines, 3 keeps cap-warn, spike, usage, ctx, ttl on one line. An explicit `segments` list is never filtered by the level.
1747
1803
  */
1748
- export function formatReport(data, { color = true, verbose = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines = 3 } = {}) {
1804
+ export function formatReport(data, { color = true, verbose: verboseOpt = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines: maxLinesOpt = 3, compactLevel = 0 } = {}) {
1805
+ // Compact level: 1+ means short labels, 2+ folds the headline lines and trims
1806
+ // the default chips, 3 keeps only the chips that stop the work. `foldHeadlines`
1807
+ // is separate from `singleLine` on purpose: it makes the headline builders hand
1808
+ // back chips, but the columns-based wrap below still applies.
1809
+ const level = normalizeCompactLevel(compactLevel);
1810
+ const verbose = verboseOpt && level === 0;
1811
+ const foldHeadlines = level >= 2;
1812
+ const maxLines = level >= 3 ? 1 : level >= 2 ? Math.min(maxLinesOpt, 2) : maxLinesOpt;
1749
1813
  const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, ultra, liveModel } = data;
1750
1814
 
1751
1815
  const c = (v) => (color ? v : '');
@@ -1778,8 +1842,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1778
1842
  const capWarn = pickCapWarn(caps);
1779
1843
 
1780
1844
  // Routing and doc2md each return a chip and, for real money, a headline line.
1781
- const delegated = buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g);
1782
- const doc2md = buildDoc2mdSeg(data.doc2mdTotals, singleLine, c, isIcon, verbose, g);
1845
+ const delegated = buildDelegatedSeg(data, singleLine || foldHeadlines, c, isIcon, verbose, g);
1846
+ const doc2md = buildDoc2mdSeg(data.doc2mdTotals, singleLine || foldHeadlines, c, isIcon, verbose, g);
1783
1847
 
1784
1848
  // An available upgrade moves the version chip forward (see resolveSegmentOrder).
1785
1849
  const updateAvailable = !!(data.update && data.update.available);
@@ -1788,7 +1852,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1788
1852
  // these slots, so this is the only place that knows how each chip is built.
1789
1853
  // The team gets a line of its own in the multi-line layout (buildTeamLine),
1790
1854
  // and its chip steps aside; the single-line layout keeps the chip.
1791
- const teamLine = singleLine ? null : buildTeamLine(data.team, c, isIcon, g, mode, Date.now(), color);
1855
+ const teamLine = singleLine || foldHeadlines ? null : buildTeamLine(data.team, c, isIcon, g, mode, Date.now(), color);
1792
1856
  const built = {
1793
1857
  capWarn: buildCapWarnSeg(capWarn, c, isIcon, g, color, mode),
1794
1858
  spike: buildSpikeSeg(spikeChip, c),
@@ -1831,13 +1895,13 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1831
1895
  rules: buildRulesSeg(data.ruleStats, c, g),
1832
1896
  };
1833
1897
 
1834
- const order = resolveSegmentOrder(segments, caps, updateAvailable);
1898
+ const order = resolveSegmentOrder(segments, caps, updateAvailable, level);
1835
1899
  const segs = arrangeSegments(order, built);
1836
1900
 
1837
1901
  // Leads the first line, ahead of every segment. A caller's `--segments` list
1838
1902
  // is a filter, so the chip needs a name in it too: `running`, or the
1839
1903
  // subagent names it belongs with.
1840
- const runningSeg = !allow || ['running', 'subagents', 'delegated'].some((n) => allow.has(n))
1904
+ const runningSeg = (allow ? ['running', 'subagents', 'delegated'].some((n) => allow.has(n)) : level < 3)
1841
1905
  ? buildRunningSeg(data.runningSubagents, c, isIcon, g)
1842
1906
  : null;
1843
1907
  // Items the user picked are never given up for width: only the default layout
@@ -1868,7 +1932,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1868
1932
  // Verbose labels are the first thing to give up: if they only fit by dropping
1869
1933
  // chips, the compact layout (same chips, shorter text) may keep all of them.
1870
1934
  if (verbose && fitted.dropped) {
1871
- return formatReport(data, { color, verbose: false, timer, mode, segments, singleLine, columns, maxLines });
1935
+ return formatReport(data, { color, verbose: false, timer, mode, segments, singleLine, columns, maxLines: maxLinesOpt, compactLevel });
1872
1936
  }
1873
1937
  return headlines + fitted.text;
1874
1938
  }
@@ -24,6 +24,7 @@ import { execSync } from 'node:child_process';
24
24
  import { join, resolve, dirname } from 'node:path';
25
25
  import { homedir } from 'node:os';
26
26
  import { debug } from './debug.js';
27
+ import { parseJsonText } from './json-text.js';
27
28
 
28
29
  export const HELPER_TIMEOUT_MS = 10000;
29
30
 
@@ -92,7 +93,7 @@ export function keyFromApiKeyHelper(cwd = process.cwd()) {
92
93
  for (const p of candidates) {
93
94
  let helper;
94
95
  try {
95
- helper = JSON.parse(readFileSync(p, 'utf8'))?.apiKeyHelper;
96
+ helper = parseJsonText(readFileSync(p, 'utf8'))?.apiKeyHelper;
96
97
  } catch {
97
98
  continue;
98
99
  }
@@ -133,7 +134,7 @@ export function withClaudeSettingsEnv(env = process.env, { home = homedir() } =
133
134
  if ((env.ANTHROPIC_BASE_URL || '').trim()) return env;
134
135
  let fromSettings;
135
136
  try {
136
- fromSettings = JSON.parse(readFileSync(join(home, '.claude', 'settings.json'), 'utf8'))?.env;
137
+ fromSettings = parseJsonText(readFileSync(join(home, '.claude', 'settings.json'), 'utf8'))?.env;
137
138
  } catch {
138
139
  return env;
139
140
  }
package/src/installer.js CHANGED
@@ -21,6 +21,7 @@ import { join, dirname, resolve } from 'node:path';
21
21
  import { homedir } from 'node:os';
22
22
  import { fileURLToPath } from 'node:url';
23
23
  import { claudeUserDir, userDataDir } from './paths.js';
24
+ import { parseJsonText } from './json-text.js';
24
25
 
25
26
  /**
26
27
  * The command every entry we write invokes.
@@ -135,7 +136,7 @@ export function readSettings(file) {
135
136
  }
136
137
  let parsed;
137
138
  try {
138
- parsed = JSON.parse(raw);
139
+ parsed = parseJsonText(raw);
139
140
  } catch (e) {
140
141
  return { state: 'unusable', reason: `unreadable JSON (${e.message})` };
141
142
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * json-text: JSON parsing for files other tools write.
3
+ *
4
+ * Windows PowerShell saves UTF-8 files with a leading BOM (U+FEFF), and
5
+ * JSON.parse rejects it ("Unexpected token"). Claude Code's own settings.json
6
+ * reads fine with a BOM, so sprag must too. Leaf module: no imports.
7
+ */
8
+
9
+ /** JSON.parse that first strips one leading U+FEFF. */
10
+ export function parseJsonText(text) {
11
+ const s = String(text);
12
+ return JSON.parse(s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
13
+ }
@@ -247,7 +247,11 @@ function stripCode(text) {
247
247
  out.push('');
248
248
  continue;
249
249
  }
250
- out.push(fenced ? '' : line.replace(/`[^`]*`/g, ' '));
250
+ // An Obsidian wikilink `[[note|label]]` keeps its `|` for the link syntax;
251
+ // the reader sees only the label, so that is what gets linted.
252
+ out.push(fenced ? '' : line
253
+ .replace(/`[^`]*`/g, ' ')
254
+ .replace(/!?\[\[([^\]|\n]*)(?:\|([^\]\n]*))?\]\]/g, (_, t, a) => a ?? t));
251
255
  }
252
256
  return out;
253
257
  }
@@ -434,6 +438,72 @@ function writtenTextOf(toolName, toolInput) {
434
438
  return null;
435
439
  }
436
440
 
441
+ /**
442
+ * Commands that only copy, filter or list text that already exists. Their
443
+ * redirect target holds a dump, not something a person or model just wrote.
444
+ * echo, printf, node and python are absent on purpose: they author text.
445
+ */
446
+ const DUMP_COMMANDS = new Set([
447
+ 'cat', 'grep', 'rg', 'egrep', 'fgrep', 'head', 'tail', 'sort', 'uniq', 'cut', 'tr', 'wc',
448
+ 'jq', 'yq', 'awk', 'sed', 'curl', 'wget', 'git', 'ls', 'find', 'diff', 'pbpaste', 'column',
449
+ 'xxd', 'strings', 'iconv',
450
+ ]);
451
+
452
+ /** [start, end) ranges of the command parts split by `;`, `&&`, `||`, `&` and newlines outside quotes. */
453
+ function commandSegments(command) {
454
+ const segs = [];
455
+ let start = 0;
456
+ let quote = null;
457
+ for (let i = 0; i < command.length; i++) {
458
+ const c = command[i];
459
+ if (quote) {
460
+ if (c === '\\' && quote === '"') i++;
461
+ else if (c === quote) quote = null;
462
+ continue;
463
+ }
464
+ if (c === '\\') { i++; continue; }
465
+ if (c === '"' || c === "'") { quote = c; continue; }
466
+ let len = 0;
467
+ if (c === ';' || c === '\n') len = 1;
468
+ else if ((c === '&' || c === '|') && command[i + 1] === c) len = 2;
469
+ else if (c === '&' && command[i + 1] !== '>' && command[i - 1] !== '>' && command[i - 1] !== '<') len = 1;
470
+ if (!len) continue;
471
+ segs.push([start, i]);
472
+ start = i + len;
473
+ i += len - 1;
474
+ }
475
+ segs.push([start, command.length]);
476
+ return segs;
477
+ }
478
+
479
+ /** First command word of a pipeline: `VAR=x`, sudo, command and env are looked through. */
480
+ function firstCommandWord(text) {
481
+ const stage = text.split(/(?<!\|)\|(?!\|)/)[0];
482
+ const words = stage.trim().replace(/^[({\s]+/, '').split(/\s+/);
483
+ for (let i = 0; i < words.length; i++) {
484
+ const w = words[i].replace(/^["']|["']$/g, '');
485
+ if (!w || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) continue;
486
+ if (w === 'sudo' || w === 'command' || w === 'env') {
487
+ while (i + 1 < words.length && words[i + 1].startsWith('-')) i++;
488
+ continue;
489
+ }
490
+ return { word: w.split('/').pop(), stage };
491
+ }
492
+ return null;
493
+ }
494
+
495
+ /** True when the redirect at `index` belongs to a command that dumps existing text. */
496
+ function redirectsDump(command, segments, index) {
497
+ const seg = segments.find(([a, b]) => index >= a && index <= b);
498
+ if (!seg) return false;
499
+ const text = command.slice(seg[0], seg[1]);
500
+ if (text.includes('<<')) return false;
501
+ const first = firstCommandWord(text);
502
+ if (!first || !DUMP_COMMANDS.has(first.word)) return false;
503
+ if (first.word === 'sed' && /\s(?:-\w*i\w*|--in-place)(?:\s|=|$)/.test(first.stage)) return false;
504
+ return true;
505
+ }
506
+
437
507
  /**
438
508
  * Files a shell command just wrote.
439
509
  *
@@ -457,7 +527,13 @@ function writtenPathsOfBash(command) {
457
527
  if (clean && !clean.startsWith('/dev/') && !/[*?]/.test(clean)) out.add(clean);
458
528
  };
459
529
  // `> file`, `>> file` — the redirection that covers heredocs and echo alike.
460
- for (const m of command.matchAll(/(?<![0-9&])>>?\s*("[^"]+"|'[^']+'|[^\s|&;<>()]+)/g)) add(m[1]);
530
+ // A redirect whose command only moves existing text (`cat a.md > dump.txt`)
531
+ // wrote nothing new, so it is skipped; see redirectsDump.
532
+ const segments = commandSegments(command);
533
+ for (const m of command.matchAll(/(?<![0-9&])>>?\s*("[^"]+"|'[^']+'|[^\s|&;<>()]+)/g)) {
534
+ if (redirectsDump(command, segments, m.index)) continue;
535
+ add(m[1]);
536
+ }
461
537
  // `tee file`, `tee -a file`
462
538
  for (const m of command.matchAll(/\btee\b(?:\s+-\w+)*\s+("[^"]+"|'[^']+'|[^\s|&;<>()]+)/g)) add(m[1]);
463
539
  // In-place edits name their target at the end of the argument list.
@@ -319,6 +319,41 @@ export function resolveModelAlias(rawModel, { env = process.env } = {}) {
319
319
  return UNKNOWN_MODEL;
320
320
  }
321
321
 
322
+ /** Why the gateway table did not answer: none, base-mismatch, stale-<n>d or no-key. */
323
+ function gatewayTableState(map, env, now) {
324
+ const gw = map.gateway;
325
+ if (!gw || !gw.aliases) return 'gw=none';
326
+ if (gw.base !== gatewayBase(env)) return 'gw=base-mismatch';
327
+ const fetchedAt = Date.parse(gw.fetchedAt);
328
+ if (!Number.isFinite(fetchedAt)) return 'gw=stale-?d';
329
+ if (now - fetchedAt > MODEL_MAP_GRACE_MS) return `gw=stale-${Math.floor((now - fetchedAt) / 86400000)}d`;
330
+ return 'gw=no-key';
331
+ }
332
+
333
+ /**
334
+ * Diagnostic twin of resolveModelAlias: follows the same steps in the same
335
+ * order and says why the result is 'unknown', e.g. `not-learned gw=no-key`.
336
+ * Returns null when resolveModelAlias would produce anything but 'unknown'.
337
+ * Reasons: empty, no-profile-id, not-learned, learned-no-role, role-no-alias.
338
+ */
339
+ export function explainUnresolved(rawModel, { env = process.env, now = Date.now() } = {}) {
340
+ const map = loadProfileMap();
341
+ const gw = gatewayTableState(map, env, now);
342
+ if (!rawModel) return `empty ${gw}`;
343
+ const model = String(rawModel);
344
+ if (overrideAlias(model, map)) return null;
345
+ if (gatewayAlias(model, map, env, now)) return null;
346
+ if (!isGatewayModelId(model)) return null;
347
+ const pid = profileIdFrom(model);
348
+ if (!pid) return `no-profile-id ${gw}`;
349
+ if (/claude/i.test(pid)) return null;
350
+ const entry = map.learned?.[pid];
351
+ if (!entry) return `not-learned ${gw}`;
352
+ if (!entry.role) return `learned-no-role ${gw}`;
353
+ if (aliasForRole(entry.role, env)) return null;
354
+ return `role-no-alias ${gw}`;
355
+ }
356
+
322
357
  // ── learning ─────────────────────────────────────────────────────────────
323
358
 
324
359
  // A single observation can be wrong: the time-adjacent parent records leak
package/src/parser.js CHANGED
@@ -5,7 +5,8 @@ import { transcriptLines } from './transcript-lines.js';
5
5
  import { join, isAbsolute, basename } from 'node:path';
6
6
  import { homedir } from 'node:os';
7
7
  import { loadCache, getCached, putCached, saveCache, getCachedSince, putCachedSince } from './session-cache.js';
8
- import { resolveModelAlias, isGatewayModelId } from './model-alias.js';
8
+ import { resolveModelAlias, isGatewayModelId, explainUnresolved, UNKNOWN_MODEL } from './model-alias.js';
9
+ import { diagActive, recordDiag } from './diag-log.js';
9
10
  import { LONG_PROMPT_THRESHOLD } from './cost.js';
10
11
  import { storeEligible, readStore, writeStore, hashBefore } from './request-store.js';
11
12
  import { debug } from './debug.js';
@@ -62,6 +63,8 @@ function newParseState(track) {
62
63
  requests: new Map(),
63
64
  // Raw model id per request, kept only when a request store is being written.
64
65
  raw: track ? new Map() : null,
66
+ // Raw model id of each request that resolved to 'unknown' (diagnostics only).
67
+ unresolved: new Map(),
65
68
  sessionId: null,
66
69
  firstTimestamp: null,
67
70
  lastTimestamp: null,
@@ -69,6 +72,37 @@ function newParseState(track) {
69
72
  };
70
73
  }
71
74
 
75
+ /** Remember the raw id of a request that resolved to 'unknown'; last write wins like the request itself. */
76
+ function trackUnresolved(st, id, model, raw) {
77
+ if (model === UNKNOWN_MODEL) st.unresolved.set(id, raw ?? null);
78
+ else st.unresolved.delete(id);
79
+ }
80
+
81
+ const reqBucket = (n) => (n <= 1 ? '1' : n < 10 ? '2-9' : '10+');
82
+
83
+ /**
84
+ * Log, per raw model id, the billed requests whose model stayed 'unknown' and
85
+ * why (see explainUnresolved). The bucketed count keeps the message, which is
86
+ * the dedupe key, from changing on every request. Never throws.
87
+ */
88
+ function recordUnresolved(st, reqs) {
89
+ try {
90
+ if (!st.unresolved.size || !diagActive()) return;
91
+ const byRaw = new Map();
92
+ for (const r of reqs) {
93
+ if (r.model !== UNKNOWN_MODEL || !st.unresolved.has(r.requestId)) continue;
94
+ if (!(r.inputTokens + r.cacheCreationTokens + r.cacheReadTokens + r.outputTokens > 0)) continue;
95
+ const raw = st.unresolved.get(r.requestId);
96
+ byRaw.set(raw, (byRaw.get(raw) || 0) + 1);
97
+ }
98
+ for (const [raw, n] of byRaw) {
99
+ const shown = String(raw ?? '').replace(/\d{12}/g, '<acct>').slice(0, 120);
100
+ const why = explainUnresolved(raw) || '?';
101
+ recordDiag('model:unresolved', new Error(`raw=${shown} why=${why} reqs=${reqBucket(n)}`));
102
+ }
103
+ } catch { /* diagnostics must never break parsing */ }
104
+ }
105
+
72
106
  /** Fold one transcript line into the parse state. Shared by the whole-file and the resumed read. */
73
107
  function consumeLine(st, line) {
74
108
  let entry;
@@ -109,13 +143,15 @@ function consumeLine(st, line) {
109
143
  st.gatewayObserved = true;
110
144
  }
111
145
 
146
+ const model = resolveModelAlias(msg.model);
147
+ trackUnresolved(st, reqId, model, msg.model);
112
148
  st.requests.set(reqId, {
113
149
  requestId: reqId,
114
150
  // Per-request timestamp so callers can filter by time window — the
115
151
  // mtime-based file filter alone lets a long-lived session drag
116
152
  // months-old requests into a narrow --days window.
117
153
  ts: ts ? Date.parse(ts) : null,
118
- model: resolveModelAlias(msg.model),
154
+ model,
119
155
  inputTokens: usage.input_tokens || 0,
120
156
  cacheCreationTokens: usage.cache_creation_input_tokens || 0,
121
157
  cacheReadTokens: usage.cache_read_input_tokens || 0,
@@ -150,10 +186,12 @@ function restoreState(st, stored) {
150
186
  for (const row of stored.reqs) {
151
187
  if (!Array.isArray(row) || row.length < 9) throw new Error('malformed request row');
152
188
  const [id, ts, rawModel, input, cacheCreation, cacheRead, e5m, e1h, output] = row;
189
+ const model = resolveModelAlias(rawModel);
190
+ trackUnresolved(st, id, model, rawModel);
153
191
  st.requests.set(id, {
154
192
  requestId: id,
155
193
  ts: ts === 'NaN' ? NaN : ts,
156
- model: resolveModelAlias(rawModel),
194
+ model,
157
195
  inputTokens: input,
158
196
  cacheCreationTokens: cacheCreation,
159
197
  cacheReadTokens: cacheRead,
@@ -256,6 +294,7 @@ export async function parseSessionFile(filePath, { store = true, minBytes } = {}
256
294
  }
257
295
 
258
296
  const reqs = [...st.requests.values()];
297
+ recordUnresolved(st, reqs);
259
298
  // Representative model: the one that handled the most requests, skipping
260
299
  // "<synthetic>" (Claude Code's local error-stub placeholder — no real API
261
300
  // call). Taking reqs[0] blindly let an error stub at session start
@@ -361,7 +361,10 @@ export function npmRegistry({
361
361
  const m = line.match(/^registry\s*=\s*(.+)$/);
362
362
  if (m && unquote(m[1])) return unquote(m[1]);
363
363
  }
364
- } catch (e) { debug('update-check:npmrc', e); }
364
+ } catch (e) {
365
+ // No ~/.npmrc is the common case, not a fault.
366
+ if (e?.code !== 'ENOENT') debug('update-check:npmrc', e);
367
+ }
365
368
  return 'https://registry.npmjs.org/';
366
369
  }
367
370