sprag-cli 3.134.0 → 3.135.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +13 -0
- package/mac/SpragBar.swift +19 -4
- package/package.json +1 -1
- package/src/agent-activity.js +1 -0
- package/src/agent-usage.js +10 -4
- package/src/bar-app.js +59 -16
- package/src/commands/route-scan.js +9 -4
- package/src/formatters/statusline.js +24 -2
- package/src/glyphs.js +5 -0
- package/src/office-species.js +1 -1
- package/src/parser.js +13 -1
- package/src/request-store.js +4 -1
- package/src/session-cache.js +7 -1
- package/src/statusline-data.js +42 -17
package/bin/cli.js
CHANGED
|
@@ -1163,6 +1163,9 @@ async function main() {
|
|
|
1163
1163
|
// This session's subagent runs, matched to the session Claude Code is
|
|
1164
1164
|
// drawing for by the transcript path / session id in its payload.
|
|
1165
1165
|
let sessionDelegation;
|
|
1166
|
+
// How many times this session's conversation was compacted, from the same
|
|
1167
|
+
// parsed sessions; null when the session is not among them.
|
|
1168
|
+
let sessionCompactionCount = null;
|
|
1166
1169
|
let runningNow = null;
|
|
1167
1170
|
// Delegation-rule counts, read only when `--segments` names `rules`: the
|
|
1168
1171
|
// chip is opt-in, so nothing else would look at them.
|
|
@@ -1178,6 +1181,15 @@ async function main() {
|
|
|
1178
1181
|
} catch (e) {
|
|
1179
1182
|
debug('statusline-data:session-delegation', e);
|
|
1180
1183
|
}
|
|
1184
|
+
try {
|
|
1185
|
+
const { sessionCompactions } = await import('../src/statusline-data.js');
|
|
1186
|
+
sessionCompactionCount = sessionCompactions(sessions, {
|
|
1187
|
+
transcriptPath: extractTranscriptPath(stdinJson),
|
|
1188
|
+
sessionId: extractSessionId(stdinJson),
|
|
1189
|
+
});
|
|
1190
|
+
} catch (e) {
|
|
1191
|
+
debug('statusline-data:compactions', e);
|
|
1192
|
+
}
|
|
1181
1193
|
// Subagents working right now, from the session's subagent transcripts: one
|
|
1182
1194
|
// readdir and a stat per file, never a parse of a whole transcript.
|
|
1183
1195
|
try {
|
|
@@ -1241,6 +1253,7 @@ async function main() {
|
|
|
1241
1253
|
relaxUntil: isStatusline ? relaxUntilNow : undefined,
|
|
1242
1254
|
delegationLevel: isStatusline ? delegationLevel : undefined,
|
|
1243
1255
|
sessionDelegation,
|
|
1256
|
+
compactions: isStatusline ? sessionCompactionCount : undefined,
|
|
1244
1257
|
runningSubagents: runningNow,
|
|
1245
1258
|
ruleStats,
|
|
1246
1259
|
ttlBucket,
|
package/mac/SpragBar.swift
CHANGED
|
@@ -34,6 +34,7 @@ struct Session: Decodable, Identifiable {
|
|
|
34
34
|
let state: String?; let stateSince: Double?; let tools: [String]; let subagents: Int
|
|
35
35
|
let cpu: Double?; let rssMb: Double?; let procs: Int?
|
|
36
36
|
let cpuPct: Double?; let model: String?; let modelName: String?; let effort: String?; let context: Ctx?; let usage: SUsage?
|
|
37
|
+
let compactions: Int? // times the conversation was compacted; optional so a snapshot from an older sprag still decodes
|
|
37
38
|
var id: Int { pid }
|
|
38
39
|
}
|
|
39
40
|
struct Totals: Decodable { let sessions: Int; let busy: Int; let subagents: Int; let cpu: Double?; let rssMb: Double?; let procs: Int?; let costUsd: Double? }
|
|
@@ -1677,6 +1678,10 @@ struct SessionRow: View {
|
|
|
1677
1678
|
Text("컨텍스트").foregroundColor(.secondary)
|
|
1678
1679
|
if let p = c.pct { Bar(value: p / 100, tint: p >= 80 ? .orange : agentTint(s.agent)).frame(width: 54); Text("\(Int(p))%").monospacedDigit() } else { Text(tokText(c.tokens)).monospacedDigit() }
|
|
1679
1680
|
}
|
|
1681
|
+
// The panel's own scale: secondary, then the orange of a filling context, then the red of a danger pill.
|
|
1682
|
+
if let n = s.compactions, n >= 1 {
|
|
1683
|
+
Text("압축 \(n)").font(.system(size: 10.5, weight: .medium)).monospacedDigit().foregroundColor(n >= 3 ? .red : n == 2 ? .orange : .secondary).fixedSize().help(compactionTip(n))
|
|
1684
|
+
}
|
|
1680
1685
|
Spacer(minLength: 0)
|
|
1681
1686
|
}.font(.system(size: 11.5)).lineLimit(1)
|
|
1682
1687
|
}
|
|
@@ -2239,6 +2244,8 @@ struct Fact: View {
|
|
|
2239
2244
|
}
|
|
2240
2245
|
}
|
|
2241
2246
|
func tokenLine(_ u: SUsage) -> String { "입력 \(tokText(u.tokens.input)), 캐시 읽기 \(tokText(u.tokens.cacheRead)), 캐시 쓰기 \(tokText(u.tokens.cacheWrite)), 출력 \(tokText(u.tokens.output))" }
|
|
2247
|
+
/** The tooltip of the compaction mark: each pass replaces the earlier conversation with a summary. */
|
|
2248
|
+
func compactionTip(_ n: Int) -> String { "이 세션에서 대화가 \(n)번 압축됐습니다. 압축될 때마다 앞에서 정한 내용이 요약으로 줄어듭니다" }
|
|
2242
2249
|
func contextLine(_ c: Ctx) -> String { c.pct.map { "\(Int($0))% (\(tokText(c.tokens))" + (c.window.map { " / \(tokText($0)))" } ?? ")") } ?? tokText(c.tokens) }
|
|
2243
2250
|
/** One session in full, opened by clicking its row. */
|
|
2244
2251
|
struct SessionView: View {
|
|
@@ -2256,6 +2263,7 @@ struct SessionView: View {
|
|
|
2256
2263
|
Divider().padding(.vertical, 2)
|
|
2257
2264
|
Fact(label: "모델", value: [s.modelName ?? s.model ?? "알 수 없음", s.effort.map { "effort \($0)" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
|
|
2258
2265
|
if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
|
|
2266
|
+
if let n = s.compactions, n >= 1 { Fact(label: "압축", value: "\(n)번") }
|
|
2259
2267
|
if let u = s.usage {
|
|
2260
2268
|
Fact(label: "토큰", value: tokenLine(u))
|
|
2261
2269
|
Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
|
|
@@ -2463,10 +2471,16 @@ struct SessionTile: View {
|
|
|
2463
2471
|
var phase: Phase = .active
|
|
2464
2472
|
var work: [(name: String, w: Work)] = []
|
|
2465
2473
|
var subs = 0, subsActive = 0 // sessions this one started, and how many of them are working
|
|
2466
|
-
func mini<V: View>(_ label: String, _ value: String, @ViewBuilder _ plot: () -> V) -> some View {
|
|
2474
|
+
func mini<V: View>(_ label: String, _ value: String, compactions: Int? = nil, @ViewBuilder _ plot: () -> V) -> some View {
|
|
2467
2475
|
VStack(alignment: .leading, spacing: 3) {
|
|
2468
2476
|
Text(label).font(.system(size: 10)).foregroundColor(pal.text2)
|
|
2469
|
-
|
|
2477
|
+
HStack(alignment: .firstTextBaseline, spacing: 5) {
|
|
2478
|
+
Text(value).font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).minimumScaleFactor(0.7)
|
|
2479
|
+
// The same scale as the context meter: muted text, then the palette's warning, then its critical colour.
|
|
2480
|
+
if let n = compactions, n >= 1 {
|
|
2481
|
+
Text("압축 \(n)").font(.system(size: 10, weight: .medium)).monospacedDigit().foregroundColor(severity(Double(n), pal.text2, pal, warnAt: 2, critAt: 3).color).lineLimit(1).fixedSize().help(compactionTip(n))
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2470
2484
|
plot().frame(height: 22)
|
|
2471
2485
|
}.frame(maxWidth: .infinity, alignment: .leading)
|
|
2472
2486
|
}
|
|
@@ -2495,10 +2509,10 @@ struct SessionTile: View {
|
|
|
2495
2509
|
HStack(alignment: .top, spacing: 12) {
|
|
2496
2510
|
if let c = s.context, let p = c.pct {
|
|
2497
2511
|
let sv = severity(p, tint, pal, warnAt: 80, critAt: 95)
|
|
2498
|
-
mini("컨텍스트", "\(Int(p))%") {
|
|
2512
|
+
mini("컨텍스트", "\(Int(p))%", compactions: s.compactions) {
|
|
2499
2513
|
HStack(spacing: 5) { Meter(value: p / 100, fill: sv.color); if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) } }.frame(maxHeight: .infinity, alignment: .center)
|
|
2500
2514
|
}
|
|
2501
|
-
} else { mini("컨텍스트", s.context.map { tokText($0.tokens) } ?? "-") { Color.clear } }
|
|
2515
|
+
} else { mini("컨텍스트", s.context.map { tokText($0.tokens) } ?? "-", compactions: s.compactions) { Color.clear } }
|
|
2502
2516
|
// Each bar is this session's share of the whole machine, the same scale on every tile. The session's own trend is in its detail.
|
|
2503
2517
|
mini("CPU", s.cpu == nil ? "-" : pct1(cpu)) { Meter(value: cpu / 100, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 전체 CPU에서 이 세션이 쓰는 몫입니다") }
|
|
2504
2518
|
mini("메모리", s.rssMb == nil ? "-" : memText(mem)) { Meter(value: mem / RAM_MB, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 메모리 \(Int((RAM_MB / 1024).rounded())) GB에서 이 세션이 쓰는 몫입니다") }
|
|
@@ -2711,6 +2725,7 @@ struct DashboardView: View {
|
|
|
2711
2725
|
Text(activity(s, now: snap.at)).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)
|
|
2712
2726
|
Divider().padding(.vertical, 2)
|
|
2713
2727
|
if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
|
|
2728
|
+
if let n = s.compactions, n >= 1 { Fact(label: "압축", value: "\(n)번") }
|
|
2714
2729
|
if let u = s.usage {
|
|
2715
2730
|
Fact(label: "토큰", value: tokenLine(u))
|
|
2716
2731
|
Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.135.1",
|
|
4
4
|
"description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/agent-activity.js
CHANGED
|
@@ -279,6 +279,7 @@ function claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail
|
|
|
279
279
|
effort,
|
|
280
280
|
context: usage.context,
|
|
281
281
|
usage: usage.usage,
|
|
282
|
+
compactions: usage.compactions,
|
|
282
283
|
cpu: table ? 0 : null,
|
|
283
284
|
cpuPct: null,
|
|
284
285
|
rssMb: table ? 0 : null,
|
package/src/agent-usage.js
CHANGED
|
@@ -175,15 +175,19 @@ export function claudeUsage({ cache, transcript, sessionId, env, now }) {
|
|
|
175
175
|
}
|
|
176
176
|
|
|
177
177
|
/**
|
|
178
|
-
* Model, context and
|
|
179
|
-
* session-cache.json, shared by every row of one snapshot.
|
|
178
|
+
* Model, context, usage and compaction count of one Claude session. `cache` is
|
|
179
|
+
* the loaded session-cache.json, shared by every row of one snapshot.
|
|
180
|
+
*
|
|
181
|
+
* `compactions` is how many times this transcript's conversation was compacted,
|
|
182
|
+
* from its own cache entry (a subagent's are not added), and null when the
|
|
183
|
+
* transcript has no entry yet.
|
|
180
184
|
*
|
|
181
185
|
* @returns {{ model: string|null, modelName: string|null,
|
|
182
186
|
* context: { tokens: number, window: number|null, pct: number|null }|null,
|
|
183
|
-
* usage: object|null }}
|
|
187
|
+
* usage: object|null, compactions: number|null }}
|
|
184
188
|
*/
|
|
185
189
|
export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env, now }) {
|
|
186
|
-
const detail = { model: null, modelName: null, context: null, usage: null };
|
|
190
|
+
const detail = { model: null, modelName: null, context: null, usage: null, compactions: null };
|
|
187
191
|
try {
|
|
188
192
|
const ctxPath = join(dataDir, 'ctx-window.json');
|
|
189
193
|
const tail = readTail(transcript);
|
|
@@ -199,6 +203,8 @@ export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env
|
|
|
199
203
|
detail.context = { tokens, window, pct: window ? Math.round(tokens / window * 100) : null };
|
|
200
204
|
}
|
|
201
205
|
detail.usage = claudeUsage({ cache, transcript, sessionId, env, now });
|
|
206
|
+
const own = typeof transcript === 'string' ? peekCached(cache, transcript) : null;
|
|
207
|
+
if (own) detail.compactions = own.compactions;
|
|
202
208
|
} catch { /* keep whatever was read */ }
|
|
203
209
|
return detail;
|
|
204
210
|
}
|
package/src/bar-app.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import * as childProcess from 'node:child_process';
|
|
16
16
|
import {
|
|
17
|
-
chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
|
|
17
|
+
chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
|
|
18
18
|
} from 'node:fs';
|
|
19
19
|
import { createRequire } from 'node:module';
|
|
20
20
|
import { createHash } from 'node:crypto';
|
|
@@ -35,6 +35,8 @@ export const LOCK_STALE_MS = 10 * 60 * 1000;
|
|
|
35
35
|
/** A failed build of this source is not retried at session start for this long. */
|
|
36
36
|
export const BUILD_RETRY_MS = 24 * 60 * 60 * 1000;
|
|
37
37
|
const BUILD_TIMEOUT_MS = 5 * 60 * 1000;
|
|
38
|
+
/** Compile errors that a second try fixes. A build that failed this way is not held back for a day. */
|
|
39
|
+
const TRANSIENT_ERROR = /was modified during the build/i;
|
|
38
40
|
const ERROR_TAIL = 600;
|
|
39
41
|
const BINARY_NAME = 'sprag-bar';
|
|
40
42
|
|
|
@@ -213,16 +215,35 @@ export function buildBar(deps = {}) {
|
|
|
213
215
|
const folder = join(paths.dir, paths.version);
|
|
214
216
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
215
217
|
const tmp = `${paths.binary}.tmp-${process.pid}`;
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
//
|
|
219
|
-
const
|
|
220
|
-
const
|
|
221
|
-
timeout: BUILD_TIMEOUT_MS, stdio: 'pipe', windowsHide: true, maxBuffer: 16 * 1024 * 1024,
|
|
222
|
-
});
|
|
218
|
+
// swiftc reads a copy of the source. `npm install -g` of the same version rewrites the package's
|
|
219
|
+
// SpragBar.swift with the same bytes and a new mtime, and swiftc fails a build whose input changed while it
|
|
220
|
+
// ran ("was modified during the build"). The copy sits in its own folder so it keeps its file name.
|
|
221
|
+
const srcDir = join(folder, `src-${process.pid}`);
|
|
222
|
+
const srcCopy = join(srcDir, basename(BAR_SOURCE));
|
|
223
223
|
let error = null;
|
|
224
|
-
|
|
225
|
-
|
|
224
|
+
let transient = false;
|
|
225
|
+
try {
|
|
226
|
+
rmSync(srcDir, { recursive: true, force: true });
|
|
227
|
+
mkdirSync(srcDir, { recursive: true, mode: 0o700 });
|
|
228
|
+
copyFileSync(deps.source ?? BAR_SOURCE, srcCopy);
|
|
229
|
+
} catch (e) {
|
|
230
|
+
// The package folder can be missing for a moment while npm swaps it, so the next session tries again.
|
|
231
|
+
error = `could not copy the source: ${String(e?.message ?? e)}`;
|
|
232
|
+
transient = true;
|
|
233
|
+
}
|
|
234
|
+
if (!error) {
|
|
235
|
+
// The compiler inside the toolchain cannot find the SDK when run by its full path ("unable to load standard
|
|
236
|
+
// library"). /usr/bin/swiftc is the system's front door to the same compiler and sets the SDK up. Running it is
|
|
237
|
+
// safe here: findSwiftc has just confirmed developer tools are installed, so it cannot pop the install dialog.
|
|
238
|
+
const compiler = existsOf(deps)('/usr/bin/swiftc') ? '/usr/bin/swiftc' : swiftc;
|
|
239
|
+
const r = runOf(deps)(compiler, ['-O', '-swift-version', '5', srcCopy, '-o', tmp], {
|
|
240
|
+
timeout: BUILD_TIMEOUT_MS, stdio: 'pipe', windowsHide: true, maxBuffer: 16 * 1024 * 1024,
|
|
241
|
+
});
|
|
242
|
+
if (r.error) error = r.error.code === 'ETIMEDOUT' ? 'timeout after 5 minutes' : String(r.error.message ?? r.error);
|
|
243
|
+
else if (r.status !== 0) error = String(r.stderr ?? '').trim().slice(-ERROR_TAIL) || `swiftc exited with status ${r.status}`;
|
|
244
|
+
if (error && TRANSIENT_ERROR.test(error)) transient = true;
|
|
245
|
+
}
|
|
246
|
+
try { rmSync(srcDir, { recursive: true, force: true }); } catch { /* a stray copy is only disk space */ }
|
|
226
247
|
if (!error) {
|
|
227
248
|
try {
|
|
228
249
|
renameSync(tmp, paths.binary);
|
|
@@ -236,9 +257,9 @@ export function buildBar(deps = {}) {
|
|
|
236
257
|
error = error.slice(-ERROR_TAIL);
|
|
237
258
|
}
|
|
238
259
|
const ms = clock() - started;
|
|
239
|
-
writeBuildState(paths, { version: paths.version, ok: !error, at: clock(), ms, error });
|
|
260
|
+
writeBuildState(paths, { version: paths.version, ok: !error, at: clock(), ms, error, ...(transient ? { transient: true } : {}) });
|
|
240
261
|
if (!error) pruneOtherVersions(paths);
|
|
241
|
-
return { ok: !error, ms, error };
|
|
262
|
+
return { ok: !error, ms, error, ...(transient ? { transient: true } : {}) };
|
|
242
263
|
} finally {
|
|
243
264
|
try { rmSync(paths.buildLock, { force: true }); } catch { /* a stale lock expires by itself */ }
|
|
244
265
|
}
|
|
@@ -278,6 +299,31 @@ export function launchBar(deps = {}) {
|
|
|
278
299
|
child.unref();
|
|
279
300
|
}
|
|
280
301
|
|
|
302
|
+
/**
|
|
303
|
+
* Whether the recorded build state keeps session start from compiling this build.
|
|
304
|
+
* A compile that failed is not retried for a day. A missing toolchain is looked for again every time: the check
|
|
305
|
+
* costs one short command, and installing the tools should bring the app at the next session. A transient failure
|
|
306
|
+
* (the source changed or vanished while a reinstall of the package rewrote it) is tried again at the next session.
|
|
307
|
+
*/
|
|
308
|
+
function buildHeldBack(state, version, now) {
|
|
309
|
+
return Boolean(state && state.version === version && state.ok === false && state.error !== 'no-toolchain'
|
|
310
|
+
&& state.transient !== true && Number.isFinite(state.at) && now - state.at < BUILD_RETRY_MS);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The line a session start prints when a failed compile holds the app back, or null when nothing does.
|
|
315
|
+
* Without it the only place the failure shows is `sprag bar status`, which nobody opens while the app is missing.
|
|
316
|
+
*/
|
|
317
|
+
export function barBuildBlockedNotice({ lang = 'en', now = Date.now(), ...deps } = {}) {
|
|
318
|
+
const paths = barPaths(deps);
|
|
319
|
+
const state = readBuildState(deps);
|
|
320
|
+
if (!buildHeldBack(state, paths.version, now)) return null;
|
|
321
|
+
const hours = Math.max(1, Math.ceil((state.at + BUILD_RETRY_MS - now) / 3_600_000));
|
|
322
|
+
return lang === 'ko'
|
|
323
|
+
? `✇ [sprag] Sprag Bar 컴파일이 실패해서 앞으로 ${hours}시간 동안 세션을 시작해도 다시 컴파일하지 않습니다. 지금 다시 하려면 \`sprag bar build --then-launch\` 를 실행하십시오. 오류는 \`sprag bar status\` 에 나옵니다. 사용자에게 이 내용을 한 줄로 알리십시오.`
|
|
324
|
+
: `✇ [sprag] The Sprag Bar compile failed, so sessions will not compile it again for the next ${hours}h. Run \`sprag bar build --then-launch\` to try now; \`sprag bar status\` shows the error. Tell the user this in one line.`;
|
|
325
|
+
}
|
|
326
|
+
|
|
281
327
|
/**
|
|
282
328
|
* Session start: make sure the app is running, building it first when needed.
|
|
283
329
|
* Returns why it did what it did and never throws. 'started', 'restarted' and
|
|
@@ -303,10 +349,7 @@ export function ensureBar({ platform = process.platform, env = process.env, cfg,
|
|
|
303
349
|
return restart ? 'restarted' : 'started';
|
|
304
350
|
}
|
|
305
351
|
const state = readBuildState(d);
|
|
306
|
-
|
|
307
|
-
// the check costs one short command, and installing the tools should bring the app at the next session.
|
|
308
|
-
if (state && state.version === paths.version && state.ok === false && state.error !== 'no-toolchain'
|
|
309
|
-
&& Number.isFinite(state.at) && now - state.at < BUILD_RETRY_MS) return 'build-failed';
|
|
352
|
+
if (buildHeldBack(state, paths.version, now)) return 'build-failed';
|
|
310
353
|
const age = lockAge(paths, now);
|
|
311
354
|
if (age !== null && age < LOCK_STALE_MS) return 'building';
|
|
312
355
|
if (!findSwiftc(d)) {
|
|
@@ -53,9 +53,14 @@ function readPackageVersion() {
|
|
|
53
53
|
* Called after the hook has printed everything, and it can neither throw nor
|
|
54
54
|
* delay the hook past a few file reads: the compile runs in a detached child.
|
|
55
55
|
*/
|
|
56
|
-
async function startBarApp() {
|
|
56
|
+
async function startBarApp(lang) {
|
|
57
57
|
try {
|
|
58
|
-
|
|
58
|
+
const bar = await import('../bar-app.js');
|
|
59
|
+
// A failed compile holds the app back for a day; say so, or the user only sees an empty menu bar.
|
|
60
|
+
if (bar.ensureBar() === 'build-failed') {
|
|
61
|
+
const notice = bar.barBuildBlockedNotice({ lang });
|
|
62
|
+
if (notice) console.log(notice);
|
|
63
|
+
}
|
|
59
64
|
} catch (e) { debug('route-scan:bar-app', e); }
|
|
60
65
|
}
|
|
61
66
|
|
|
@@ -488,7 +493,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
488
493
|
if (doc2mdBlock) console.log(doc2mdBlock);
|
|
489
494
|
if (koreanBlock) console.log(koreanBlock);
|
|
490
495
|
if (cohesionBlock) console.log(cohesionBlock);
|
|
491
|
-
await startBarApp();
|
|
496
|
+
await startBarApp(lang);
|
|
492
497
|
return; // nothing else to inject
|
|
493
498
|
}
|
|
494
499
|
if (secretsBlock) console.log(secretsBlock);
|
|
@@ -578,7 +583,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
578
583
|
...reviewRules.map((r) => `health|${r.signature}|${r.scope}`),
|
|
579
584
|
]);
|
|
580
585
|
} catch (e) { debug('route-scan:seed-briefed', e); /* worst case is one duplicate brief */ }
|
|
581
|
-
await startBarApp();
|
|
586
|
+
await startBarApp(lang);
|
|
582
587
|
return;
|
|
583
588
|
}
|
|
584
589
|
|
|
@@ -1145,6 +1145,22 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
|
|
|
1145
1145
|
return ctxSeg;
|
|
1146
1146
|
}
|
|
1147
1147
|
|
|
1148
|
+
/**
|
|
1149
|
+
* How many times this session's conversation was compacted: `Compacted 3×`.
|
|
1150
|
+
* Each compaction replaces the earlier conversation with a summary, so what was
|
|
1151
|
+
* decided early gets blurrier with every pass, and the tone darkens with the
|
|
1152
|
+
* count: gray at 1, yellow at 2, red from 3. Nothing at 0. It sits right after
|
|
1153
|
+
* the context chip because it is the history of that same fill level.
|
|
1154
|
+
*/
|
|
1155
|
+
function buildCompactionsSeg(count, c, isIcon, verbose, g) {
|
|
1156
|
+
if (!Number.isInteger(count) || count < 1) return null;
|
|
1157
|
+
const tone = count >= 3 ? RED : count === 2 ? YELLOW : GRAY;
|
|
1158
|
+
const words = `Compacted ${count}×`;
|
|
1159
|
+
let text = words;
|
|
1160
|
+
if (isIcon && g.compactions) text = verbose ? `${g.compactions} ${words}` : `${g.compactions} ${count}×`;
|
|
1161
|
+
return `${c(tone)}${text}${c(RESET)}`;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1148
1164
|
/** The warning chip the analyzer raised for this window, if any. */
|
|
1149
1165
|
function buildSpikeSeg(spikeChip, c) {
|
|
1150
1166
|
// Spike chip — one word only, keeps the statusline single-line.
|
|
@@ -1610,6 +1626,8 @@ function buildDoc2mdSeg(doc2md, singleLine, c, isIcon, verbose, g) {
|
|
|
1610
1626
|
export const DEFAULT_SEGMENT_ORDER = [
|
|
1611
1627
|
'cap-warn', 'spike',
|
|
1612
1628
|
'usage', 'ctx',
|
|
1629
|
+
// Right after the context chip: how many times that context was compacted.
|
|
1630
|
+
'compactions',
|
|
1613
1631
|
'ttl',
|
|
1614
1632
|
'model', 'effort', 'ultra',
|
|
1615
1633
|
// Grouped by the timeframe each figure covers, because mixing them was the
|
|
@@ -1677,6 +1695,7 @@ function segmentsNamed(name, s, usageByKey) {
|
|
|
1677
1695
|
case 'ttl': return [s.ttl];
|
|
1678
1696
|
case 'month': return [s.month];
|
|
1679
1697
|
case 'ctx': return [s.ctx];
|
|
1698
|
+
case 'compactions': return [s.compactions];
|
|
1680
1699
|
case 'saved': return [s.saved];
|
|
1681
1700
|
case 'period': return [s.period];
|
|
1682
1701
|
// Every rate-limit window, in payload order.
|
|
@@ -1701,7 +1720,9 @@ function normalizeCompactLevel(level) {
|
|
|
1701
1720
|
// Names kept in the default order at compact level 2 and 3. `usage` stands for
|
|
1702
1721
|
// every rate-limit window; `version` joins only while an upgrade is available.
|
|
1703
1722
|
const COMPACT_KEEP_3 = ['cap-warn', 'spike', 'usage', 'ctx', 'ttl'];
|
|
1704
|
-
|
|
1723
|
+
// `compactions` stays at level 2 but not 3: it is a health signal about the
|
|
1724
|
+
// session, not a chip that stops the work.
|
|
1725
|
+
const COMPACT_KEEP_2 = [...COMPACT_KEEP_3, 'compactions', 'model', 'effort', 'ultra', 'delegated'];
|
|
1705
1726
|
|
|
1706
1727
|
/** The default-order names a compact level keeps, or null when it keeps all. */
|
|
1707
1728
|
function compactKeepNames(level, updateAvailable) {
|
|
@@ -1826,7 +1847,7 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
|
|
|
1826
1847
|
* @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`.
|
|
1827
1848
|
* @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.
|
|
1828
1849
|
* @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.
|
|
1829
|
-
* @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.
|
|
1850
|
+
* @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, compactions, 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.
|
|
1830
1851
|
*/
|
|
1831
1852
|
export function formatReport(data, { color = true, verbose: verboseOpt = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines: maxLinesOpt = 3, compactLevel = 0 } = {}) {
|
|
1832
1853
|
// Compact level: 1+ means short labels, 2+ folds the headline lines and trims
|
|
@@ -1885,6 +1906,7 @@ export function formatReport(data, { color = true, verbose: verboseOpt = false,
|
|
|
1885
1906
|
spike: buildSpikeSeg(spikeChip, c),
|
|
1886
1907
|
usage: buildUsageSegs(caps, capWarn, c, isIcon, verbose, g, color, mode),
|
|
1887
1908
|
ctx: buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g),
|
|
1909
|
+
compactions: buildCompactionsSeg(data.compactions, c, isIcon, verbose, g),
|
|
1888
1910
|
ttl: buildTtlSeg({ ttl, ttlBucket: data.ttlBucket, lastActivity }, timer, c, isIcon, verbose, g),
|
|
1889
1911
|
// Model, then the effort that qualifies it: the same model answers
|
|
1890
1912
|
// differently at `low` and at `max`, and the pair is one glance.
|
package/src/glyphs.js
CHANGED
|
@@ -66,6 +66,10 @@ const ICON = {
|
|
|
66
66
|
// Team: the people this machine is ranked among. U+1F465, East Asian Width W.
|
|
67
67
|
team: '👥',
|
|
68
68
|
ctx: '📦',
|
|
69
|
+
// Compactions: the conversation swept into a summary. U+1F9F9, East Asian Width
|
|
70
|
+
// W. The literal compression emoji 🗜 (U+1F5DC) is width N and would shift the
|
|
71
|
+
// line, for the reason given at `effort`.
|
|
72
|
+
compactions: '🧹',
|
|
69
73
|
saved: '💰',
|
|
70
74
|
used: '📊',
|
|
71
75
|
reset: '🔄',
|
|
@@ -100,6 +104,7 @@ const NARROW = {
|
|
|
100
104
|
month: '∑', // a running total
|
|
101
105
|
team: '', // no glyph verified in the font yet; the team line's own words lead it
|
|
102
106
|
ctx: '◧', // a box filling up
|
|
107
|
+
compactions: '', // no font-verified glyph; the chip's word leads it
|
|
103
108
|
saved: '✓',
|
|
104
109
|
used: '◩', // a split square: what the spend is made of
|
|
105
110
|
reset: '↩', // the window turning over
|
package/src/office-species.js
CHANGED
|
@@ -48,7 +48,7 @@ export const SPECIES = {
|
|
|
48
48
|
* above the company median (`needDlg`). `gt` marks a strict floor. Copied from
|
|
49
49
|
* GRADES in site/assets/scene/office-scene.js, and test/office-species.test.js
|
|
50
50
|
* pins the two, so `sprag team status` and the office page show one ladder.
|
|
51
|
-
* The chick is the
|
|
51
|
+
* The chick is the last row and has no floor. A person with no usage in the period is not ranked and shows as a ghost, so the chick is for someone who used little.
|
|
52
52
|
*/
|
|
53
53
|
const row = (key, minSr, tier, needDlg = false, gt = false) => ({ key, minSr, tier, needDlg, gt });
|
|
54
54
|
export const GRADES = [
|
package/src/parser.js
CHANGED
|
@@ -69,6 +69,9 @@ function newParseState(track) {
|
|
|
69
69
|
firstTimestamp: null,
|
|
70
70
|
lastTimestamp: null,
|
|
71
71
|
gatewayObserved: false,
|
|
72
|
+
// Times Claude Code compacted this conversation. A whole-session figure like
|
|
73
|
+
// gatewayObserved: it is not windowed and it travels with the request store.
|
|
74
|
+
compactions: 0,
|
|
72
75
|
};
|
|
73
76
|
}
|
|
74
77
|
|
|
@@ -122,6 +125,12 @@ function consumeLine(st, line) {
|
|
|
122
125
|
st.sessionId = entry.sessionId;
|
|
123
126
|
}
|
|
124
127
|
|
|
128
|
+
// Decided on the parsed fields, not on a substring: transcripts quote the
|
|
129
|
+
// marker inside message text, and other subtypes (microcompact_boundary) are
|
|
130
|
+
// not a compaction of the conversation. Counted before the usage return
|
|
131
|
+
// below, because a boundary line carries no message.usage.
|
|
132
|
+
if (entry.type === 'system' && entry.subtype === 'compact_boundary') st.compactions++;
|
|
133
|
+
|
|
125
134
|
const msg = entry.message;
|
|
126
135
|
if (!msg?.usage || !msg.id) return;
|
|
127
136
|
|
|
@@ -174,7 +183,7 @@ function snapshotStore(st, offset, filePath) {
|
|
|
174
183
|
}
|
|
175
184
|
return {
|
|
176
185
|
offset, tailHash, sessionId: st.sessionId, firstTs: st.firstTimestamp, lastTs: st.lastTimestamp,
|
|
177
|
-
gatewayObserved: !!st.gatewayObserved, reqs,
|
|
186
|
+
gatewayObserved: !!st.gatewayObserved, compactions: st.compactions, reqs,
|
|
178
187
|
};
|
|
179
188
|
}
|
|
180
189
|
|
|
@@ -183,6 +192,7 @@ function restoreState(st, stored) {
|
|
|
183
192
|
st.firstTimestamp = stored.firstTs ?? null;
|
|
184
193
|
st.lastTimestamp = stored.lastTs ?? null;
|
|
185
194
|
st.gatewayObserved = !!stored.gatewayObserved;
|
|
195
|
+
st.compactions = Number.isInteger(stored.compactions) && stored.compactions >= 0 ? stored.compactions : 0;
|
|
186
196
|
for (const row of stored.reqs) {
|
|
187
197
|
if (!Array.isArray(row) || row.length < 9) throw new Error('malformed request row');
|
|
188
198
|
const [id, ts, rawModel, input, cacheCreation, cacheRead, e5m, e1h, output] = row;
|
|
@@ -326,6 +336,7 @@ export async function parseSessionFile(filePath, { store = true, minBytes } = {}
|
|
|
326
336
|
...(modelTotals ? { modelTotals } : {}),
|
|
327
337
|
...(dayTotals ? { dayTotals } : {}),
|
|
328
338
|
gatewayObserved: st.gatewayObserved,
|
|
339
|
+
compactions: st.compactions,
|
|
329
340
|
};
|
|
330
341
|
}
|
|
331
342
|
|
|
@@ -680,6 +691,7 @@ function trimToCutoff(session, cutoffMs) {
|
|
|
680
691
|
...(modelTotals ? { modelTotals } : {}),
|
|
681
692
|
...(dayTotals ? { dayTotals } : {}),
|
|
682
693
|
gatewayObserved: session.gatewayObserved,
|
|
694
|
+
compactions: session.compactions,
|
|
683
695
|
};
|
|
684
696
|
}
|
|
685
697
|
|
package/src/request-store.js
CHANGED
|
@@ -24,7 +24,10 @@ import { writeViaTmp } from './state-file.js';
|
|
|
24
24
|
import { envVar } from './env.js';
|
|
25
25
|
import { debug } from './debug.js';
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
// 2: stores carry `compactions`, the count of compact_boundary lines before the
|
|
28
|
+
// offset. A v1 store has no count for the bytes it already consumed, so resuming
|
|
29
|
+
// from it would undercount; readStore discards it and the file is read whole once.
|
|
30
|
+
export const STORE_VERSION = 2;
|
|
28
31
|
/** Transcripts smaller than this are cheap to parse whole and get no store. */
|
|
29
32
|
export const STORE_MIN_BYTES = 4 * 1024 * 1024;
|
|
30
33
|
/** How many bytes before the offset are hashed to prove the prefix is unchanged. */
|
package/src/session-cache.js
CHANGED
|
@@ -45,7 +45,10 @@ const CACHE_PATH = join(userDataDir(), 'session-cache.json');
|
|
|
45
45
|
// day and model), so cost can use each day's price row (#15). A v5 entry lacks
|
|
46
46
|
// it, so a session crossing a price change would be priced at one day's rate
|
|
47
47
|
// until its transcript changed.
|
|
48
|
-
|
|
48
|
+
// 7: sessions carry `compactions`, the number of times Claude Code compacted the
|
|
49
|
+
// conversation. A v6 entry lacks it, so a cached session would show no count
|
|
50
|
+
// until its transcript changed.
|
|
51
|
+
const CACHE_VERSION = 7;
|
|
49
52
|
// Entries for transcripts this old are pruned on write. Keeps the file
|
|
50
53
|
// bounded without an existence check per entry (which would cost the syscalls
|
|
51
54
|
// the cache exists to avoid).
|
|
@@ -63,6 +66,7 @@ const PRUNE_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
|
|
|
63
66
|
* @property {string} model
|
|
64
67
|
* @property {Record<string, object>} [modelTotals] totals per model, present only when more than one model spent tokens
|
|
65
68
|
* @property {Record<string, Record<string, object>>} [dayTotals] totals per UTC day and model, present only when the requests span more than one UTC day
|
|
69
|
+
* @property {number} compactions times the conversation was compacted (compact_boundary lines), 0 when never
|
|
66
70
|
* @property {string} [projectDir]
|
|
67
71
|
*/
|
|
68
72
|
|
|
@@ -79,6 +83,7 @@ function serialize(session) {
|
|
|
79
83
|
...(session.modelTotals ? { modelTotals: session.modelTotals } : {}),
|
|
80
84
|
...(session.dayTotals ? { dayTotals: session.dayTotals } : {}),
|
|
81
85
|
gatewayObserved: !!session.gatewayObserved,
|
|
86
|
+
compactions: Number.isInteger(session.compactions) && session.compactions >= 0 ? session.compactions : 0,
|
|
82
87
|
};
|
|
83
88
|
}
|
|
84
89
|
|
|
@@ -96,6 +101,7 @@ function deserialize(stored, filePath, projectDir) {
|
|
|
96
101
|
...(stored.modelTotals && typeof stored.modelTotals === 'object' ? { modelTotals: stored.modelTotals } : {}),
|
|
97
102
|
...(stored.dayTotals && typeof stored.dayTotals === 'object' ? { dayTotals: stored.dayTotals } : {}),
|
|
98
103
|
gatewayObserved: !!stored.gatewayObserved,
|
|
104
|
+
compactions: Number.isInteger(stored.compactions) && stored.compactions >= 0 ? stored.compactions : 0,
|
|
99
105
|
};
|
|
100
106
|
}
|
|
101
107
|
|
package/src/statusline-data.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* Statusline data helpers that need more than a number from the payload.
|
|
3
3
|
*
|
|
4
4
|
* bin/cli.js assembles the report data inline and cannot be imported (it runs
|
|
5
|
-
* on load), so the
|
|
6
|
-
*
|
|
7
|
-
* statusline reads anyway;
|
|
5
|
+
* on load), so the derivations below live here where a test can reach them.
|
|
6
|
+
* They read only what the render has already loaded or one small JSON file the
|
|
7
|
+
* statusline reads anyway; none scans a transcript.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { resolve } from 'node:path';
|
|
@@ -17,6 +17,29 @@ const FAMILY_MAX = 14;
|
|
|
17
17
|
|
|
18
18
|
const shortFamily = (name) => (name.length > FAMILY_MAX ? `${name.slice(0, FAMILY_MAX - 1)}…` : name);
|
|
19
19
|
|
|
20
|
+
/**
|
|
21
|
+
* The loaded session the statusline is drawing for. Matched by transcript path
|
|
22
|
+
* first, then by session id, because Claude Code reports both and either can be
|
|
23
|
+
* absent or spelled differently (a symlinked home).
|
|
24
|
+
*/
|
|
25
|
+
function findSession(sessions, transcriptPath, sessionId) {
|
|
26
|
+
if (!Array.isArray(sessions) || (!transcriptPath && !sessionId)) return null;
|
|
27
|
+
let hit = null;
|
|
28
|
+
if (transcriptPath) {
|
|
29
|
+
const want = resolve(transcriptPath);
|
|
30
|
+
hit = sessions.find((s) => s && s.filePath && resolve(s.filePath) === want) || null;
|
|
31
|
+
}
|
|
32
|
+
if (!hit && sessionId) {
|
|
33
|
+
// A resumed conversation can leave more than one file under one id; the
|
|
34
|
+
// most recently active is the one still being written.
|
|
35
|
+
const end = (s) => (s.endTime ? new Date(s.endTime).getTime() || 0 : 0);
|
|
36
|
+
hit = sessions
|
|
37
|
+
.filter((s) => s && s.sessionId === sessionId)
|
|
38
|
+
.sort((a, b) => end(b) - end(a))[0] || null;
|
|
39
|
+
}
|
|
40
|
+
return hit;
|
|
41
|
+
}
|
|
42
|
+
|
|
20
43
|
/**
|
|
21
44
|
* The subagent runs of the session the statusline is drawing for.
|
|
22
45
|
*
|
|
@@ -44,20 +67,7 @@ const shortFamily = (name) => (name.length > FAMILY_MAX ? `${name.slice(0, FAMIL
|
|
|
44
67
|
* null when the session cannot be found or ran no subagents
|
|
45
68
|
*/
|
|
46
69
|
export function sessionSubagentSummary(sessions, { transcriptPath = null, sessionId = null, env = process.env } = {}) {
|
|
47
|
-
|
|
48
|
-
let hit = null;
|
|
49
|
-
if (transcriptPath) {
|
|
50
|
-
const want = resolve(transcriptPath);
|
|
51
|
-
hit = sessions.find((s) => s && s.filePath && resolve(s.filePath) === want) || null;
|
|
52
|
-
}
|
|
53
|
-
if (!hit && sessionId) {
|
|
54
|
-
// A resumed conversation can leave more than one file under one id; the
|
|
55
|
-
// most recently active is the one still being written.
|
|
56
|
-
const end = (s) => (s.endTime ? new Date(s.endTime).getTime() || 0 : 0);
|
|
57
|
-
hit = sessions
|
|
58
|
-
.filter((s) => s && s.sessionId === sessionId)
|
|
59
|
-
.sort((a, b) => end(b) - end(a))[0] || null;
|
|
60
|
-
}
|
|
70
|
+
const hit = findSession(sessions, transcriptPath, sessionId);
|
|
61
71
|
const runs = hit && Array.isArray(hit.subagentRuns) ? hit.subagentRuns : [];
|
|
62
72
|
if (runs.length === 0) return null;
|
|
63
73
|
const byFamily = new Map();
|
|
@@ -74,6 +84,21 @@ export function sessionSubagentSummary(sessions, { transcriptPath = null, sessio
|
|
|
74
84
|
return { total: runs.length, families, usd: cost.actual, unpriced: cost.unpriced };
|
|
75
85
|
}
|
|
76
86
|
|
|
87
|
+
/**
|
|
88
|
+
* How many times the conversation of the session the statusline is drawing for
|
|
89
|
+
* was compacted, as the parser counted its compact_boundary lines. The figure is
|
|
90
|
+
* that transcript's own: a subagent's compactions are not added to it.
|
|
91
|
+
*
|
|
92
|
+
* @param {Array} sessions parseAllSessions result
|
|
93
|
+
* @param {{ transcriptPath?: string|null, sessionId?: string|null }} [ids]
|
|
94
|
+
* @returns {number|null} null when the session is not among those loaded
|
|
95
|
+
*/
|
|
96
|
+
export function sessionCompactions(sessions, { transcriptPath = null, sessionId = null } = {}) {
|
|
97
|
+
const hit = findSession(sessions, transcriptPath, sessionId);
|
|
98
|
+
if (!hit) return null;
|
|
99
|
+
return Number.isInteger(hit.compactions) && hit.compactions >= 0 ? hit.compactions : 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
77
102
|
/**
|
|
78
103
|
* How many delegation rules apply in this project, and how many of those are
|
|
79
104
|
* flagged for review.
|