sprag-cli 3.123.2 → 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 +24 -8
- package/package.json +1 -1
- package/src/claude-price.js +30 -4
- package/src/commands/mode.js +3 -1
- package/src/commands/route-scan.js +2 -1
- package/src/compact-window.js +5 -3
- package/src/config.js +22 -1
- package/src/formatters/statusline.js +66 -18
- package/src/gateway-auth.js +3 -2
- package/src/installer.js +2 -1
- package/src/json-text.js +13 -0
- package/src/korean-lint.cjs +78 -2
- package/src/model-alias.js +35 -0
- package/src/parser.js +42 -3
- package/src/update-check.js +4 -1
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 =
|
|
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 =
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
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": {
|
package/src/claude-price.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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 */ }
|
package/src/commands/mode.js
CHANGED
|
@@ -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 =
|
|
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')),
|
package/src/compact-window.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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 =
|
|
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:
|
|
222
|
+
verbose: compactLevel === 0,
|
|
223
|
+
compactLevel,
|
|
203
224
|
timer: s.timer !== false,
|
|
204
225
|
color: s.color !== false,
|
|
205
226
|
modelShare: s.modelShare !== false,
|
|
@@ -886,35 +886,47 @@ function fitChips(segs, { columns, maxLines = 3, eol = '', protectedSegs = new S
|
|
|
886
886
|
* note. With `columns` the chips wrap onto at most `maxLines` lines (see
|
|
887
887
|
* layoutChips).
|
|
888
888
|
*/
|
|
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 = 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 } = {}) {
|
|
890
890
|
const c = (v) => (color ? v : '');
|
|
891
891
|
// narrow shares the icon layout and swaps only the glyphs, so both modes take
|
|
892
892
|
// the same branches from here on.
|
|
893
893
|
const isIcon = mode === 'icon' || mode === 'narrow';
|
|
894
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;
|
|
895
902
|
const segs = [];
|
|
896
903
|
const capSeg = buildCapWarnSeg(pickCapWarn(caps), c, isIcon, g, color, mode);
|
|
897
904
|
if (capSeg) segs.push(capSeg);
|
|
898
905
|
const versionSeg = buildVersionSeg(version, update, c, isIcon, false, g);
|
|
899
|
-
if (versionSeg && update && update.available) segs.push(versionSeg);
|
|
906
|
+
if (versionSeg && update && update.available && !onlyCore) segs.push(versionSeg);
|
|
900
907
|
// Same rule as the full report: a healthy 🅷 stays off the line unless
|
|
901
908
|
// `--segments` named it. This line has no other opt-in, so `segments` is only
|
|
902
909
|
// read for that one name.
|
|
903
910
|
const named = (name) => !!(segments && segments.some((s) => String(s).toLowerCase() === name));
|
|
904
|
-
const harnessSeg = buildHarnessSeg(c, isIcon, g, null, named('harness'));
|
|
911
|
+
const harnessSeg = dropUnder2 ? null : buildHarnessSeg(c, isIcon, g, null, named('harness'));
|
|
905
912
|
if (harnessSeg) segs.push(harnessSeg);
|
|
906
|
-
const modelSeg = buildModelSeg(model, c, isIcon, g);
|
|
913
|
+
const modelSeg = onlyCore ? null : buildModelSeg(model, c, isIcon, g);
|
|
907
914
|
if (modelSeg) segs.push(modelSeg);
|
|
908
|
-
const effortSeg = buildEffortSeg(effort, c, isIcon, g);
|
|
915
|
+
const effortSeg = onlyCore ? null : buildEffortSeg(effort, c, isIcon, g);
|
|
909
916
|
if (effortSeg) segs.push(effortSeg);
|
|
910
|
-
const ultraSeg = buildUltraSeg(ultra, c, isIcon, g);
|
|
917
|
+
const ultraSeg = onlyCore ? null : buildUltraSeg(ultra, c, isIcon, g);
|
|
911
918
|
if (ultraSeg) segs.push(ultraSeg);
|
|
912
|
-
|
|
913
|
-
|
|
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);
|
|
914
922
|
if (teamSeg) segs.push(teamSeg);
|
|
915
|
-
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);
|
|
916
928
|
return layoutChips(segs, {
|
|
917
|
-
columns, maxLines, eol: color ? '\x1b[K' : '', protectedSegs
|
|
929
|
+
columns, maxLines, eol: color ? '\x1b[K' : '', protectedSegs, color,
|
|
918
930
|
});
|
|
919
931
|
}
|
|
920
932
|
|
|
@@ -1649,10 +1661,32 @@ function segmentsNamed(name, s, usageByKey) {
|
|
|
1649
1661
|
}
|
|
1650
1662
|
}
|
|
1651
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
|
+
|
|
1652
1686
|
/**
|
|
1653
1687
|
* The names to render, in order: the default sequence, or the caller's list.
|
|
1654
1688
|
*/
|
|
1655
|
-
function resolveSegmentOrder(segments, caps, updateAvailable) {
|
|
1689
|
+
function resolveSegmentOrder(segments, caps, updateAvailable, compactLevel = 0) {
|
|
1656
1690
|
// An available upgrade is an "act on this" chip, so it moves up behind the
|
|
1657
1691
|
// warning chips. With nothing to upgrade to it stays pure identity, at the
|
|
1658
1692
|
// tail position DEFAULT_SEGMENT_ORDER gives it.
|
|
@@ -1672,6 +1706,11 @@ function resolveSegmentOrder(segments, caps, updateAvailable) {
|
|
|
1672
1706
|
&& caps.windows.some((w) => w && (w.key === 'litellm_budget' || w.key === 'spend_limit')));
|
|
1673
1707
|
if (hasGatewayBudget) defaultOrder = defaultOrder.filter((n) => n !== 'month');
|
|
1674
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
|
+
|
|
1675
1714
|
// A caller-supplied list sets the filter AND the order. Warning chips keep
|
|
1676
1715
|
// the lead wherever they were written: being seen first is their whole job,
|
|
1677
1716
|
// and someone reordering segments is not asking to bury an alarm.
|
|
@@ -1760,8 +1799,17 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
|
|
|
1760
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`.
|
|
1761
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.
|
|
1762
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.
|
|
1763
1803
|
*/
|
|
1764
|
-
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;
|
|
1765
1813
|
const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, ultra, liveModel } = data;
|
|
1766
1814
|
|
|
1767
1815
|
const c = (v) => (color ? v : '');
|
|
@@ -1794,8 +1842,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1794
1842
|
const capWarn = pickCapWarn(caps);
|
|
1795
1843
|
|
|
1796
1844
|
// Routing and doc2md each return a chip and, for real money, a headline line.
|
|
1797
|
-
const delegated = buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g);
|
|
1798
|
-
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);
|
|
1799
1847
|
|
|
1800
1848
|
// An available upgrade moves the version chip forward (see resolveSegmentOrder).
|
|
1801
1849
|
const updateAvailable = !!(data.update && data.update.available);
|
|
@@ -1804,7 +1852,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1804
1852
|
// these slots, so this is the only place that knows how each chip is built.
|
|
1805
1853
|
// The team gets a line of its own in the multi-line layout (buildTeamLine),
|
|
1806
1854
|
// and its chip steps aside; the single-line layout keeps the chip.
|
|
1807
|
-
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);
|
|
1808
1856
|
const built = {
|
|
1809
1857
|
capWarn: buildCapWarnSeg(capWarn, c, isIcon, g, color, mode),
|
|
1810
1858
|
spike: buildSpikeSeg(spikeChip, c),
|
|
@@ -1847,13 +1895,13 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1847
1895
|
rules: buildRulesSeg(data.ruleStats, c, g),
|
|
1848
1896
|
};
|
|
1849
1897
|
|
|
1850
|
-
const order = resolveSegmentOrder(segments, caps, updateAvailable);
|
|
1898
|
+
const order = resolveSegmentOrder(segments, caps, updateAvailable, level);
|
|
1851
1899
|
const segs = arrangeSegments(order, built);
|
|
1852
1900
|
|
|
1853
1901
|
// Leads the first line, ahead of every segment. A caller's `--segments` list
|
|
1854
1902
|
// is a filter, so the chip needs a name in it too: `running`, or the
|
|
1855
1903
|
// subagent names it belongs with.
|
|
1856
|
-
const runningSeg =
|
|
1904
|
+
const runningSeg = (allow ? ['running', 'subagents', 'delegated'].some((n) => allow.has(n)) : level < 3)
|
|
1857
1905
|
? buildRunningSeg(data.runningSubagents, c, isIcon, g)
|
|
1858
1906
|
: null;
|
|
1859
1907
|
// Items the user picked are never given up for width: only the default layout
|
|
@@ -1884,7 +1932,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1884
1932
|
// Verbose labels are the first thing to give up: if they only fit by dropping
|
|
1885
1933
|
// chips, the compact layout (same chips, shorter text) may keep all of them.
|
|
1886
1934
|
if (verbose && fitted.dropped) {
|
|
1887
|
-
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 });
|
|
1888
1936
|
}
|
|
1889
1937
|
return headlines + fitted.text;
|
|
1890
1938
|
}
|
package/src/gateway-auth.js
CHANGED
|
@@ -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 =
|
|
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 =
|
|
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 =
|
|
139
|
+
parsed = parseJsonText(raw);
|
|
139
140
|
} catch (e) {
|
|
140
141
|
return { state: 'unusable', reason: `unreadable JSON (${e.message})` };
|
|
141
142
|
}
|
package/src/json-text.js
ADDED
|
@@ -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
|
+
}
|
package/src/korean-lint.cjs
CHANGED
|
@@ -247,7 +247,11 @@ function stripCode(text) {
|
|
|
247
247
|
out.push('');
|
|
248
248
|
continue;
|
|
249
249
|
}
|
|
250
|
-
|
|
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
|
-
|
|
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.
|
package/src/model-alias.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
package/src/update-check.js
CHANGED
|
@@ -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) {
|
|
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
|
|