ccstatusline-zh 2.2.34 → 2.2.36
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/README.md +31 -7
- package/dist/{ccstatusline-rdsx5ab1.js → ccstatusline-71188a0p.js} +23 -25
- package/dist/{ccstatusline-jp52tswn.js → ccstatusline-abxfvbek.js} +4173 -8161
- package/dist/ccstatusline-er9fa25f.js +6056 -0
- package/dist/ccstatusline-mkma8vq8.js +228 -0
- package/dist/ccstatusline.js +696 -19
- package/dist/dev-reload-z0a689mw.js +23 -0
- package/dist/hooks-vgtb1rd1.js +159 -0
- package/dist/{index-pzts8765.js → index-48pdkn43.js} +1488 -1278
- package/package.json +3 -3
- package/dist/hooks-0wev7tf6.js +0 -103
package/dist/ccstatusline.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
source_default,
|
|
4
|
-
string,
|
|
5
|
-
number,
|
|
6
|
-
object,
|
|
7
|
-
looseObject,
|
|
8
|
-
union,
|
|
9
|
-
preprocess,
|
|
10
4
|
getVisibleText,
|
|
5
|
+
replaceSpacesForOutput,
|
|
11
6
|
updateColorMap,
|
|
12
7
|
prefetchClaudeStatusIfNeeded,
|
|
13
8
|
ZERO_COMPACTION_STATS,
|
|
9
|
+
withCacheLock,
|
|
14
10
|
getPackageVersion,
|
|
15
11
|
getTerminalWidth,
|
|
12
|
+
isHidden,
|
|
16
13
|
resolveExecutable,
|
|
17
14
|
sanitizeTerminalText,
|
|
18
15
|
GIT_REVIEW_REFRESH_FLAG,
|
|
@@ -22,9 +19,21 @@ import {
|
|
|
22
19
|
preRenderAllWidgets,
|
|
23
20
|
calculateMaxWidthsFromPreRendered,
|
|
24
21
|
renderStatusLine,
|
|
22
|
+
SESSION_UNDER_LIMIT_HIDEABLE_STATE,
|
|
23
|
+
SESSION_AT_LIMIT_HIDEABLE_STATE,
|
|
24
|
+
isAtSessionLimit,
|
|
25
|
+
getClaudeConfigDir,
|
|
25
26
|
setUsageField,
|
|
26
27
|
WEEKLY_MODEL_USAGE_BUCKETS,
|
|
28
|
+
isStaleUsageFallback,
|
|
29
|
+
getUsageFetchedAtMs,
|
|
30
|
+
getUsageLoginFingerprint,
|
|
31
|
+
getUsageAccountKey,
|
|
27
32
|
fetchUsageData,
|
|
33
|
+
lookUpUsageAccount,
|
|
34
|
+
fetchAccountEmail,
|
|
35
|
+
iterateJsonlLinesReverseSync,
|
|
36
|
+
parseJsonlLine,
|
|
28
37
|
getTranscriptAnalysis,
|
|
29
38
|
getWidgetSpeedWindowSeconds,
|
|
30
39
|
isWidgetSpeedWindowEnabled,
|
|
@@ -32,11 +41,22 @@ import {
|
|
|
32
41
|
initConfigPath,
|
|
33
42
|
loadSettings,
|
|
34
43
|
saveSettings
|
|
35
|
-
} from "./ccstatusline-
|
|
44
|
+
} from "./ccstatusline-abxfvbek.js";
|
|
45
|
+
import {
|
|
46
|
+
string,
|
|
47
|
+
number,
|
|
48
|
+
boolean,
|
|
49
|
+
array,
|
|
50
|
+
object,
|
|
51
|
+
looseObject,
|
|
52
|
+
union,
|
|
53
|
+
record,
|
|
54
|
+
preprocess
|
|
55
|
+
} from "./ccstatusline-er9fa25f.js";
|
|
36
56
|
import {
|
|
37
57
|
advanceGlobalPowerlineThemeIndex,
|
|
38
58
|
advanceGlobalSeparatorIndex
|
|
39
|
-
} from "./ccstatusline-
|
|
59
|
+
} from "./ccstatusline-71188a0p.js";
|
|
40
60
|
|
|
41
61
|
// src/types/StatusJSON.ts
|
|
42
62
|
var CoercedNumberSchema = preprocess((value) => {
|
|
@@ -59,6 +79,31 @@ var SpendLimitSchema = RateLimitPeriodSchema.extend({
|
|
|
59
79
|
limit_usd: CoercedNumberSchema.nullable().optional(),
|
|
60
80
|
period: string().nullable().optional()
|
|
61
81
|
});
|
|
82
|
+
function tolerant(schema) {
|
|
83
|
+
return schema.nullable().optional().catch(undefined);
|
|
84
|
+
}
|
|
85
|
+
var LastMissCauseSchema = looseObject({
|
|
86
|
+
causes: array(string()).catch([]),
|
|
87
|
+
tools_added: tolerant(CoercedNumberSchema),
|
|
88
|
+
tools_removed: tolerant(CoercedNumberSchema),
|
|
89
|
+
system_char_delta: tolerant(CoercedNumberSchema)
|
|
90
|
+
});
|
|
91
|
+
var PromptCacheSchema = object({
|
|
92
|
+
warm: tolerant(boolean()),
|
|
93
|
+
caching_observed: tolerant(boolean()),
|
|
94
|
+
ttl: tolerant(string()),
|
|
95
|
+
expires_at: tolerant(CoercedNumberSchema),
|
|
96
|
+
requests: tolerant(CoercedNumberSchema),
|
|
97
|
+
misses: tolerant(CoercedNumberSchema),
|
|
98
|
+
expected_rebuilds: tolerant(CoercedNumberSchema),
|
|
99
|
+
hit_ratio: tolerant(CoercedNumberSchema),
|
|
100
|
+
cache_write_tokens: tolerant(CoercedNumberSchema),
|
|
101
|
+
miss_recache_tokens: tolerant(CoercedNumberSchema),
|
|
102
|
+
last_miss_at: tolerant(CoercedNumberSchema),
|
|
103
|
+
last_miss_cause: tolerant(LastMissCauseSchema),
|
|
104
|
+
miss_causes: tolerant(record(string(), CoercedNumberSchema)),
|
|
105
|
+
recache_tokens_if_cold: tolerant(CoercedNumberSchema)
|
|
106
|
+
});
|
|
62
107
|
var StatusJSONSchema = looseObject({
|
|
63
108
|
hook_event_name: string().optional(),
|
|
64
109
|
session_id: string().optional(),
|
|
@@ -102,6 +147,7 @@ var StatusJSONSchema = looseObject({
|
|
|
102
147
|
remaining_percentage: CoercedNumberSchema.nullable().optional()
|
|
103
148
|
}).nullable().optional(),
|
|
104
149
|
vim: object({ mode: string().optional() }).nullable().optional(),
|
|
150
|
+
fast_mode: boolean().nullable().optional().catch(undefined),
|
|
105
151
|
worktree: object({
|
|
106
152
|
name: string().optional(),
|
|
107
153
|
path: string().optional(),
|
|
@@ -109,6 +155,7 @@ var StatusJSONSchema = looseObject({
|
|
|
109
155
|
original_cwd: string().optional(),
|
|
110
156
|
original_branch: string().optional()
|
|
111
157
|
}).nullable().optional(),
|
|
158
|
+
prompt_cache: tolerant(PromptCacheSchema),
|
|
112
159
|
rate_limits: object({
|
|
113
160
|
five_hour: RateLimitPeriodSchema.optional(),
|
|
114
161
|
seven_day: RateLimitPeriodSchema.optional(),
|
|
@@ -212,17 +259,525 @@ function handleHookInput(input) {
|
|
|
212
259
|
} catch {}
|
|
213
260
|
}
|
|
214
261
|
|
|
262
|
+
// src/utils/session-forecast.ts
|
|
263
|
+
var SESSION_WINDOW_MS = 5 * 60 * 60 * 1000;
|
|
264
|
+
var LOOKBACK_MS = 30 * 60 * 1000;
|
|
265
|
+
var MIN_SPAN_MS = 10 * 60 * 1000;
|
|
266
|
+
var FUTURE_TOLERANCE_MS = 60 * 1000;
|
|
267
|
+
function getKnownPoints({ readings, nowMs, resetAtMs, percent }) {
|
|
268
|
+
const windowStartMs = resetAtMs - SESSION_WINDOW_MS;
|
|
269
|
+
const points = [{ timeMs: windowStartMs, percent: 0 }];
|
|
270
|
+
for (const [firstSeenMs, lastSeenMs, readingPercent] of readings) {
|
|
271
|
+
if (firstSeenMs > nowMs + FUTURE_TOLERANCE_MS) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
for (const timeMs of [firstSeenMs, Math.min(lastSeenMs, nowMs)]) {
|
|
275
|
+
if (timeMs >= windowStartMs) {
|
|
276
|
+
points.push({ timeMs, percent: readingPercent });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
points.push({ timeMs: nowMs, percent });
|
|
281
|
+
return points.sort((a, b) => a.timeMs - b.timeMs);
|
|
282
|
+
}
|
|
283
|
+
function getCurrentPercent({ readings, nowMs, percent }) {
|
|
284
|
+
const seenPercents = readings.filter(([firstSeenMs]) => firstSeenMs <= nowMs + FUTURE_TOLERANCE_MS).map(([, , readingPercent]) => readingPercent);
|
|
285
|
+
return Math.max(percent, ...seenPercents);
|
|
286
|
+
}
|
|
287
|
+
function percentAt(points, timeMs) {
|
|
288
|
+
let before;
|
|
289
|
+
for (const point of points) {
|
|
290
|
+
if (point.timeMs > timeMs && before) {
|
|
291
|
+
return before.percent + (point.percent - before.percent) * (timeMs - before.timeMs) / (point.timeMs - before.timeMs);
|
|
292
|
+
}
|
|
293
|
+
before = point;
|
|
294
|
+
}
|
|
295
|
+
return before?.percent ?? 0;
|
|
296
|
+
}
|
|
297
|
+
function forecastSessionUsage(input) {
|
|
298
|
+
const { nowMs, resetAtMs } = input;
|
|
299
|
+
const percent = getCurrentPercent(input);
|
|
300
|
+
const leftMs = resetAtMs - nowMs;
|
|
301
|
+
if (leftMs <= 0 || percent >= 100) {
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
const startMs = Math.max(nowMs - LOOKBACK_MS, resetAtMs - SESSION_WINDOW_MS);
|
|
305
|
+
const spanMs = nowMs - startMs;
|
|
306
|
+
if (spanMs < MIN_SPAN_MS) {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
const rise = percent - percentAt(getKnownPoints({ ...input, percent }), startMs);
|
|
310
|
+
if (rise <= 0) {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
const projectedPercent = percent + rise * leftMs / spanMs;
|
|
314
|
+
const msToLimit = (100 - percent) * spanMs / rise;
|
|
315
|
+
return {
|
|
316
|
+
currentPercent: percent,
|
|
317
|
+
projectedPercent: Math.min(100, projectedPercent),
|
|
318
|
+
limitInMs: msToLimit < leftMs ? msToLimit : null
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// src/utils/session-usage-history.ts
|
|
323
|
+
import * as fs3 from "node:fs";
|
|
324
|
+
import * as os2 from "node:os";
|
|
325
|
+
import * as path3 from "node:path";
|
|
326
|
+
var HISTORY_SCHEMA_VERSION = 1;
|
|
327
|
+
var WINDOW_MATCH_MS = 60 * 1000;
|
|
328
|
+
var LAST_SEEN_WRITE_INTERVAL_MS = 60 * 1000;
|
|
329
|
+
var ORPHANED_TEMP_FILE_AGE_MS = 60 * 1000;
|
|
330
|
+
var STALE_LOCK_AGE_MS = 10 * 1000;
|
|
331
|
+
var SYNTHETIC_MODEL = "<synthetic>";
|
|
332
|
+
function getLastResponseAtMs(transcriptPath) {
|
|
333
|
+
if (transcriptPath === undefined) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
for (const line of iterateJsonlLinesReverseSync(transcriptPath)) {
|
|
338
|
+
const entry = parseJsonlLine(line);
|
|
339
|
+
if (entry?.type !== "assistant" || entry.isApiErrorMessage === true || entry.message?.model === SYNTHETIC_MODEL) {
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
const timestampMs = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
|
|
343
|
+
if (Number.isFinite(timestampMs)) {
|
|
344
|
+
return timestampMs;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
} catch {
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
function getDefaultSessionUsageHistoryDeps(payload, usageData) {
|
|
353
|
+
const observedAtMs = usageData?.sessionUsageObservedAtMs;
|
|
354
|
+
const defaultPercentSeenAt = typeof payload?.rate_limits?.five_hour?.used_percentage === "number" ? () => getLastResponseAtMs(payload.transcript_path) : getUsageFetchedAtMs;
|
|
355
|
+
return {
|
|
356
|
+
readFileSync: (p) => fs3.readFileSync(p, "utf-8"),
|
|
357
|
+
writeFileSync: (p, data) => {
|
|
358
|
+
fs3.writeFileSync(p, data, "utf-8");
|
|
359
|
+
},
|
|
360
|
+
createFileExclusiveSync: (p) => {
|
|
361
|
+
fs3.writeFileSync(p, "", { flag: "wx" });
|
|
362
|
+
},
|
|
363
|
+
renameSync: (from, to) => {
|
|
364
|
+
fs3.renameSync(from, to);
|
|
365
|
+
},
|
|
366
|
+
unlinkSync: (p) => {
|
|
367
|
+
fs3.unlinkSync(p);
|
|
368
|
+
},
|
|
369
|
+
readdirSync: (p) => fs3.readdirSync(p),
|
|
370
|
+
statSync: (p) => fs3.statSync(p),
|
|
371
|
+
mkdirSync: (p) => {
|
|
372
|
+
fs3.mkdirSync(p, { recursive: true });
|
|
373
|
+
},
|
|
374
|
+
now: () => Date.now(),
|
|
375
|
+
percentSeenAt: observedAtMs === undefined ? defaultPercentSeenAt : () => observedAtMs,
|
|
376
|
+
loginFingerprint: getUsageLoginFingerprint,
|
|
377
|
+
cachePath: path3.join(os2.homedir(), ".cache", "ccstatusline", "session-usage-history.json")
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function isReading(value) {
|
|
381
|
+
return Array.isArray(value) && value.length === 3 && value.every((part) => typeof part === "number" && Number.isFinite(part));
|
|
382
|
+
}
|
|
383
|
+
function isUsageWindow(value) {
|
|
384
|
+
if (typeof value !== "object" || value === null) {
|
|
385
|
+
return false;
|
|
386
|
+
}
|
|
387
|
+
const usageWindow = value;
|
|
388
|
+
return typeof usageWindow.resetAt === "number" && Array.isArray(usageWindow.readings) && usageWindow.readings.every(isReading);
|
|
389
|
+
}
|
|
390
|
+
function readHistory(deps) {
|
|
391
|
+
const empty = { version: HISTORY_SCHEMA_VERSION, profiles: {} };
|
|
392
|
+
try {
|
|
393
|
+
const parsed = JSON.parse(deps.readFileSync(deps.cachePath));
|
|
394
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
395
|
+
return empty;
|
|
396
|
+
}
|
|
397
|
+
const data = parsed;
|
|
398
|
+
if (data.version !== HISTORY_SCHEMA_VERSION || typeof data.profiles !== "object" || data.profiles === null) {
|
|
399
|
+
return empty;
|
|
400
|
+
}
|
|
401
|
+
const profiles = {};
|
|
402
|
+
for (const [key, windows] of Object.entries(data.profiles)) {
|
|
403
|
+
if (Array.isArray(windows)) {
|
|
404
|
+
profiles[key] = windows.filter(isUsageWindow);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return { version: HISTORY_SCHEMA_VERSION, profiles };
|
|
408
|
+
} catch {
|
|
409
|
+
return empty;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
function pruneWindows(windows, nowMs) {
|
|
413
|
+
const lookbackStartMs = nowMs - LOOKBACK_MS;
|
|
414
|
+
return windows.filter((usageWindow) => usageWindow.resetAt > nowMs).map((usageWindow) => {
|
|
415
|
+
const readings = usageWindow.readings.filter(([firstSeenMs]) => firstSeenMs <= nowMs + FUTURE_TOLERANCE_MS);
|
|
416
|
+
let keepFrom = 0;
|
|
417
|
+
for (let index = 0;index < readings.length; index++) {
|
|
418
|
+
if ((readings[index]?.[0] ?? Number.POSITIVE_INFINITY) <= lookbackStartMs) {
|
|
419
|
+
keepFrom = index;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return { resetAt: usageWindow.resetAt, readings: readings.slice(keepFrom) };
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
function getSeenAtLookup(deps, nowMs) {
|
|
426
|
+
let looked = false;
|
|
427
|
+
let seenAtMs;
|
|
428
|
+
return () => {
|
|
429
|
+
if (!looked) {
|
|
430
|
+
looked = true;
|
|
431
|
+
seenAtMs = deps.percentSeenAt ? deps.percentSeenAt() : nowMs;
|
|
432
|
+
seenAtMs = seenAtMs !== undefined && Number.isFinite(seenAtMs) ? Math.min(nowMs, seenAtMs) : undefined;
|
|
433
|
+
}
|
|
434
|
+
return seenAtMs;
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
function removeOrphanedTempFiles(deps, nowMs) {
|
|
438
|
+
const dir = path3.dirname(deps.cachePath);
|
|
439
|
+
const prefix = `${path3.basename(deps.cachePath)}.`;
|
|
440
|
+
let names;
|
|
441
|
+
try {
|
|
442
|
+
names = deps.readdirSync(dir);
|
|
443
|
+
} catch {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
for (const name of names) {
|
|
447
|
+
if (!name.startsWith(prefix) || !/^\d+\.tmp$/.test(name.slice(prefix.length))) {
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
const tempPath = path3.join(dir, name);
|
|
451
|
+
try {
|
|
452
|
+
if (nowMs - deps.statSync(tempPath).mtimeMs >= ORPHANED_TEMP_FILE_AGE_MS) {
|
|
453
|
+
deps.unlinkSync(tempPath);
|
|
454
|
+
}
|
|
455
|
+
} catch {}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function addReading(history, profileKey, resetAtMs, percent, nowMs, seenAt) {
|
|
459
|
+
const profiles = {};
|
|
460
|
+
for (const [key, windows] of Object.entries(history.profiles)) {
|
|
461
|
+
const kept = pruneWindows(windows, nowMs);
|
|
462
|
+
if (kept.length > 0) {
|
|
463
|
+
profiles[key] = kept;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const windows = profiles[profileKey] ?? [];
|
|
467
|
+
let usageWindow = windows.find((candidate) => Math.abs(candidate.resetAt - resetAtMs) <= WINDOW_MATCH_MS);
|
|
468
|
+
if (!usageWindow) {
|
|
469
|
+
usageWindow = { resetAt: resetAtMs, readings: [] };
|
|
470
|
+
windows.push(usageWindow);
|
|
471
|
+
}
|
|
472
|
+
profiles[profileKey] = windows;
|
|
473
|
+
const readings = usageWindow.readings;
|
|
474
|
+
const last = readings[readings.length - 1];
|
|
475
|
+
if (last !== undefined && percent < last[2]) {
|
|
476
|
+
return { profiles, readings, changed: false };
|
|
477
|
+
}
|
|
478
|
+
if (last?.[2] !== percent) {
|
|
479
|
+
const firstSeenMs = Math.max(seenAt() ?? nowMs, last?.[1] ?? Number.NEGATIVE_INFINITY);
|
|
480
|
+
readings.push([firstSeenMs, firstSeenMs, percent]);
|
|
481
|
+
return { profiles, readings, changed: true };
|
|
482
|
+
}
|
|
483
|
+
if (nowMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
|
|
484
|
+
return { profiles, readings, changed: false };
|
|
485
|
+
}
|
|
486
|
+
const lastSeenMs = seenAt() ?? last[1];
|
|
487
|
+
if (lastSeenMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
|
|
488
|
+
return { profiles, readings, changed: false };
|
|
489
|
+
}
|
|
490
|
+
last[1] = lastSeenMs;
|
|
491
|
+
return { profiles, readings, changed: true };
|
|
492
|
+
}
|
|
493
|
+
function lockHistory(deps, nowMs) {
|
|
494
|
+
const lockPath = `${deps.cachePath}.lock`;
|
|
495
|
+
try {
|
|
496
|
+
deps.mkdirSync(path3.dirname(deps.cachePath));
|
|
497
|
+
deps.createFileExclusiveSync(lockPath);
|
|
498
|
+
return true;
|
|
499
|
+
} catch {}
|
|
500
|
+
try {
|
|
501
|
+
if (Math.abs(nowMs - deps.statSync(lockPath).mtimeMs) < STALE_LOCK_AGE_MS) {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
deps.unlinkSync(lockPath);
|
|
505
|
+
deps.createFileExclusiveSync(lockPath);
|
|
506
|
+
return true;
|
|
507
|
+
} catch {
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
function unlockHistory(deps) {
|
|
512
|
+
try {
|
|
513
|
+
deps.unlinkSync(`${deps.cachePath}.lock`);
|
|
514
|
+
} catch {}
|
|
515
|
+
}
|
|
516
|
+
function writeHistory(deps, profiles) {
|
|
517
|
+
const tempPath = `${deps.cachePath}.${process.pid}.tmp`;
|
|
518
|
+
try {
|
|
519
|
+
const history = { version: HISTORY_SCHEMA_VERSION, profiles };
|
|
520
|
+
deps.writeFileSync(tempPath, JSON.stringify(history));
|
|
521
|
+
deps.renameSync(tempPath, deps.cachePath);
|
|
522
|
+
} catch {
|
|
523
|
+
try {
|
|
524
|
+
deps.unlinkSync(tempPath);
|
|
525
|
+
} catch {}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
function recordSessionUsageReading(profileKey, resetAtMs, percent, deps = getDefaultSessionUsageHistoryDeps()) {
|
|
529
|
+
const nowMs = deps.now();
|
|
530
|
+
const clampedPercent = Math.max(0, Math.min(100, percent));
|
|
531
|
+
const seenAt = getSeenAtLookup(deps, nowMs);
|
|
532
|
+
const unlocked = addReading(readHistory(deps), profileKey, resetAtMs, clampedPercent, nowMs, seenAt);
|
|
533
|
+
if (!unlocked.changed || !lockHistory(deps, nowMs)) {
|
|
534
|
+
return unlocked.readings;
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
const locked = addReading(readHistory(deps), profileKey, resetAtMs, clampedPercent, nowMs, seenAt);
|
|
538
|
+
if (locked.changed) {
|
|
539
|
+
writeHistory(deps, locked.profiles);
|
|
540
|
+
removeOrphanedTempFiles(deps, nowMs);
|
|
541
|
+
}
|
|
542
|
+
return locked.readings;
|
|
543
|
+
} finally {
|
|
544
|
+
unlockHistory(deps);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/utils/session-forecast-prefetch.ts
|
|
549
|
+
var SESSION_FORECAST_WIDGET_TYPES = new Set(["block-forecast", "block-limit-timer"]);
|
|
550
|
+
function computeSessionForecastIfNeeded(lines, usageData, deps = getDefaultSessionUsageHistoryDeps()) {
|
|
551
|
+
if (!lines.some((line) => line.some((item) => SESSION_FORECAST_WIDGET_TYPES.has(item.type)))) {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
const percent = usageData?.sessionUsage;
|
|
555
|
+
const resetAtMs = usageData?.sessionResetAt === undefined ? Number.NaN : Date.parse(usageData.sessionResetAt);
|
|
556
|
+
const nowMs = deps.now();
|
|
557
|
+
if (percent === undefined || !Number.isFinite(resetAtMs) || resetAtMs <= nowMs) {
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
const clampedPercent = Math.max(0, Math.min(100, percent));
|
|
561
|
+
const login = deps.loginFingerprint?.() ?? null;
|
|
562
|
+
const profileKey = login === null ? getClaudeConfigDir() : `${getClaudeConfigDir()}#${login}`;
|
|
563
|
+
const readings = recordSessionUsageReading(profileKey, resetAtMs, clampedPercent, deps);
|
|
564
|
+
if (isAtSessionLimit({ usageData })) {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
return forecastSessionUsage({ readings, nowMs, resetAtMs, percent: clampedPercent });
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/utils/daily-state.ts
|
|
571
|
+
import * as fs4 from "node:fs";
|
|
572
|
+
import * as os3 from "node:os";
|
|
573
|
+
import * as path4 from "node:path";
|
|
574
|
+
var STATE_VERSION = 1;
|
|
575
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
576
|
+
var defaultDeps = {
|
|
577
|
+
readFileSync: (p) => fs4.readFileSync(p, "utf-8"),
|
|
578
|
+
writeFileSync: (p, data) => {
|
|
579
|
+
fs4.writeFileSync(p, data, "utf-8");
|
|
580
|
+
},
|
|
581
|
+
renameSync: (from, to) => {
|
|
582
|
+
fs4.renameSync(from, to);
|
|
583
|
+
},
|
|
584
|
+
unlinkSync: (p) => {
|
|
585
|
+
fs4.unlinkSync(p);
|
|
586
|
+
},
|
|
587
|
+
readdirSync: (p) => fs4.readdirSync(p),
|
|
588
|
+
statSync: (p) => fs4.statSync(p),
|
|
589
|
+
mkdirSync: (p) => {
|
|
590
|
+
fs4.mkdirSync(p, { recursive: true });
|
|
591
|
+
},
|
|
592
|
+
now: () => Date.now(),
|
|
593
|
+
statePath: path4.join(os3.homedir(), ".cache", "ccstatusline", "daily.json")
|
|
594
|
+
};
|
|
595
|
+
function utcDayKey(nowMs) {
|
|
596
|
+
return new Date(nowMs).toISOString().slice(0, 10);
|
|
597
|
+
}
|
|
598
|
+
function previousUtcDayKey(nowMs) {
|
|
599
|
+
return utcDayKey(nowMs - DAY_MS);
|
|
600
|
+
}
|
|
601
|
+
function isFiniteNumber(value) {
|
|
602
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
603
|
+
}
|
|
604
|
+
function isSpendDayRecord(value) {
|
|
605
|
+
if (typeof value !== "object" || value === null) {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
const entry = value;
|
|
609
|
+
return typeof entry.day === "string" && isFiniteNumber(entry.baselineUsed) && typeof entry.lastSeenDay === "string" && isFiniteNumber(entry.lastSeenUsed) && isFiniteNumber(entry.lastSeenAt);
|
|
610
|
+
}
|
|
611
|
+
function emptyState() {
|
|
612
|
+
return { version: STATE_VERSION, spend: {} };
|
|
613
|
+
}
|
|
614
|
+
function readDailyState(deps = defaultDeps) {
|
|
615
|
+
try {
|
|
616
|
+
const parsed = JSON.parse(deps.readFileSync(deps.statePath));
|
|
617
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
618
|
+
return emptyState();
|
|
619
|
+
}
|
|
620
|
+
const data = parsed;
|
|
621
|
+
if (data.version !== STATE_VERSION || typeof data.spend !== "object" || data.spend === null) {
|
|
622
|
+
return emptyState();
|
|
623
|
+
}
|
|
624
|
+
const spend = {};
|
|
625
|
+
for (const [key, value] of Object.entries(data.spend)) {
|
|
626
|
+
if (isSpendDayRecord(value)) {
|
|
627
|
+
spend[key] = value;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return { version: STATE_VERSION, spend };
|
|
631
|
+
} catch {
|
|
632
|
+
return emptyState();
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function prune(state, nowMs) {
|
|
636
|
+
const oldestKept = previousUtcDayKey(nowMs);
|
|
637
|
+
const spend = Object.fromEntries(Object.entries(state.spend).filter(([, entry]) => entry.lastSeenDay >= oldestKept));
|
|
638
|
+
return { ...state, spend };
|
|
639
|
+
}
|
|
640
|
+
var ORPHANED_TEMP_FILE_AGE_MS2 = 60 * 1000;
|
|
641
|
+
function removeOrphanedTempFiles2(deps, nowMs) {
|
|
642
|
+
const { readdirSync, statSync, unlinkSync } = deps;
|
|
643
|
+
if (!readdirSync || !statSync || !unlinkSync) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const dir = path4.dirname(deps.statePath);
|
|
647
|
+
const prefix = `${path4.basename(deps.statePath)}.`;
|
|
648
|
+
let names;
|
|
649
|
+
try {
|
|
650
|
+
names = readdirSync(dir);
|
|
651
|
+
} catch {
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
for (const name of names) {
|
|
655
|
+
if (!name.startsWith(prefix) || !/^\d+\.tmp$/.test(name.slice(prefix.length))) {
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
const tempPath = path4.join(dir, name);
|
|
659
|
+
try {
|
|
660
|
+
if (nowMs - statSync(tempPath).mtimeMs >= ORPHANED_TEMP_FILE_AGE_MS2) {
|
|
661
|
+
unlinkSync(tempPath);
|
|
662
|
+
}
|
|
663
|
+
} catch {}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function updateDailyState(update, deps = defaultDeps) {
|
|
667
|
+
let ran = false;
|
|
668
|
+
try {
|
|
669
|
+
deps.mkdirSync(path4.dirname(deps.statePath));
|
|
670
|
+
withCacheLock(deps.statePath, () => {
|
|
671
|
+
ran = true;
|
|
672
|
+
const next = update(readDailyState(deps));
|
|
673
|
+
if (next === null) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
const tempPath = `${deps.statePath}.${process.pid}.tmp`;
|
|
677
|
+
try {
|
|
678
|
+
deps.writeFileSync(tempPath, JSON.stringify(prune(next, deps.now())));
|
|
679
|
+
deps.renameSync(tempPath, deps.statePath);
|
|
680
|
+
} catch {
|
|
681
|
+
try {
|
|
682
|
+
deps.unlinkSync?.(tempPath);
|
|
683
|
+
} catch {}
|
|
684
|
+
}
|
|
685
|
+
removeOrphanedTempFiles2(deps, deps.now());
|
|
686
|
+
});
|
|
687
|
+
} catch {}
|
|
688
|
+
return ran;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// src/utils/daily-spend.ts
|
|
692
|
+
function advanceSpendRecord(record, used, fetchedAtMs) {
|
|
693
|
+
if (record && fetchedAtMs < record.lastSeenAt) {
|
|
694
|
+
return record;
|
|
695
|
+
}
|
|
696
|
+
const day = utcDayKey(fetchedAtMs);
|
|
697
|
+
const seen = { lastSeenDay: day, lastSeenUsed: used, lastSeenAt: fetchedAtMs };
|
|
698
|
+
if (record?.day === day) {
|
|
699
|
+
return { ...record, ...seen, baselineUsed: Math.min(record.baselineUsed, used) };
|
|
700
|
+
}
|
|
701
|
+
let baselineUsed = used;
|
|
702
|
+
const seenDayBeforeThisMonth = record?.lastSeenDay === previousUtcDayKey(fetchedAtMs) && record.lastSeenDay.slice(0, 7) === day.slice(0, 7);
|
|
703
|
+
if (seenDayBeforeThisMonth) {
|
|
704
|
+
baselineUsed = Math.min(record.lastSeenUsed, used);
|
|
705
|
+
} else if (day.endsWith("-01")) {
|
|
706
|
+
baselineUsed = 0;
|
|
707
|
+
}
|
|
708
|
+
return { day, baselineUsed, ...seen };
|
|
709
|
+
}
|
|
710
|
+
function getSpentToday(record, nowMs) {
|
|
711
|
+
if (record?.day !== utcDayKey(nowMs)) {
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
return Math.max(0, record.lastSeenUsed - record.baselineUsed);
|
|
715
|
+
}
|
|
716
|
+
var CLOCK_SKEW_TOLERANCE_MS = 60 * 1000;
|
|
717
|
+
function advanceAsOf(record, used, fetchedAtMs, nowMs) {
|
|
718
|
+
const latestTrusted = nowMs + CLOCK_SKEW_TOLERANCE_MS;
|
|
719
|
+
const trusted = record !== undefined && record.lastSeenAt <= latestTrusted ? record : undefined;
|
|
720
|
+
return fetchedAtMs > latestTrusted ? trusted : advanceSpendRecord(trusted, used, fetchedAtMs);
|
|
721
|
+
}
|
|
722
|
+
function isSameRecord(a, b) {
|
|
723
|
+
return a.day === b.day && a.baselineUsed === b.baselineUsed && a.lastSeenDay === b.lastSeenDay && a.lastSeenUsed === b.lastSeenUsed && a.lastSeenAt === b.lastSeenAt;
|
|
724
|
+
}
|
|
725
|
+
function mergeSpendRecord(merged, record) {
|
|
726
|
+
if (!merged) {
|
|
727
|
+
return record;
|
|
728
|
+
}
|
|
729
|
+
const next = advanceSpendRecord(merged, record.lastSeenUsed, record.lastSeenAt);
|
|
730
|
+
return next.day === record.day ? { ...next, baselineUsed: Math.min(next.baselineUsed, record.baselineUsed) } : next;
|
|
731
|
+
}
|
|
732
|
+
function adoptFormerRecords(state, accountKey, formerKeys, nowMs) {
|
|
733
|
+
const moved = formerKeys.filter((key) => key !== accountKey && state.spend[key] !== undefined);
|
|
734
|
+
if (moved.length === 0) {
|
|
735
|
+
return state;
|
|
736
|
+
}
|
|
737
|
+
const merged = [accountKey, ...moved].map((key) => state.spend[key]).filter((record) => record !== undefined && record.lastSeenAt <= nowMs + CLOCK_SKEW_TOLERANCE_MS).sort((a, b) => a.lastSeenAt - b.lastSeenAt).reduce((merged, record) => mergeSpendRecord(merged, record), undefined);
|
|
738
|
+
const kept = Object.fromEntries(Object.entries(state.spend).filter(([key]) => !moved.includes(key)));
|
|
739
|
+
return { ...state, spend: merged ? { ...kept, [accountKey]: merged } : kept };
|
|
740
|
+
}
|
|
741
|
+
function observeExtraUsageSpend(accountKey, used, fetchedAtMs, deps, formerKeys = []) {
|
|
742
|
+
const now = () => deps ? deps.now() : Date.now();
|
|
743
|
+
const result = {};
|
|
744
|
+
const ran = updateDailyState((stored) => {
|
|
745
|
+
const state = adoptFormerRecords(stored, accountKey, formerKeys, now());
|
|
746
|
+
const current = state.spend[accountKey];
|
|
747
|
+
const next = advanceAsOf(current, used, fetchedAtMs, now());
|
|
748
|
+
result.record = next;
|
|
749
|
+
if (state === stored && (current === next || current && next && isSameRecord(current, next))) {
|
|
750
|
+
return null;
|
|
751
|
+
}
|
|
752
|
+
if (next) {
|
|
753
|
+
return { ...state, spend: { ...state.spend, [accountKey]: next } };
|
|
754
|
+
}
|
|
755
|
+
return { ...state, spend: Object.fromEntries(Object.entries(state.spend).filter(([key]) => key !== accountKey)) };
|
|
756
|
+
}, deps);
|
|
757
|
+
if (!ran || !result.record) {
|
|
758
|
+
const stored = adoptFormerRecords(readDailyState(deps), accountKey, formerKeys, now()).spend[accountKey];
|
|
759
|
+
result.record = advanceAsOf(stored, used, fetchedAtMs, now());
|
|
760
|
+
}
|
|
761
|
+
return getSpentToday(result.record, now());
|
|
762
|
+
}
|
|
763
|
+
|
|
215
764
|
// src/utils/usage-prefetch.ts
|
|
216
765
|
var BASE_USAGE_WIDGET_TYPES = [
|
|
217
766
|
"session-usage",
|
|
767
|
+
"block-forecast",
|
|
768
|
+
"block-limit-timer",
|
|
218
769
|
"weekly-usage",
|
|
770
|
+
"weekly-limit-timer",
|
|
771
|
+
"fable-weekly-limit-timer",
|
|
219
772
|
"block-timer",
|
|
220
773
|
"reset-timer",
|
|
221
774
|
"weekly-reset-timer",
|
|
222
775
|
"extra-usage-utilization",
|
|
223
776
|
"extra-usage-remaining",
|
|
224
777
|
"extra-usage-used",
|
|
778
|
+
"extra-usage-limit",
|
|
225
779
|
"extra-usage-daily-budget",
|
|
780
|
+
"extra-usage-today",
|
|
226
781
|
"spend-limit-usage",
|
|
227
782
|
"spend-limit-amount"
|
|
228
783
|
];
|
|
@@ -248,6 +803,10 @@ var USAGE_DATA_FIELDS = [
|
|
|
248
803
|
var EMPTY_USAGE_REQUIREMENTS = [];
|
|
249
804
|
var USAGE_WIDGET_REQUIREMENTS = {
|
|
250
805
|
"session-usage": [{ field: "sessionUsage" }],
|
|
806
|
+
"block-forecast": [{ field: "sessionUsage", suppressFetchError: true }, { field: "sessionResetAt", suppressFetchError: true }],
|
|
807
|
+
"block-limit-timer": [{ field: "sessionUsage", suppressFetchError: true }, { field: "sessionResetAt", suppressFetchError: true }],
|
|
808
|
+
"weekly-limit-timer": [{ field: "weeklyUsage", suppressFetchError: true }, { field: "weeklyResetAt", suppressFetchError: true }],
|
|
809
|
+
"fable-weekly-limit-timer": [{ field: "fableUsage", suppressFetchError: true }, { field: "fableResetAt", alternatives: ["weeklyResetAt"], suppressFetchError: true }],
|
|
251
810
|
"weekly-usage": [{ field: "weeklyUsage" }],
|
|
252
811
|
...Object.fromEntries(WEEKLY_MODEL_USAGE_BUCKETS.map((bucket) => [bucket.widgetType, [{ field: bucket.usageField }]])),
|
|
253
812
|
"block-timer": [{ field: "sessionResetAt", suppressFetchError: true }],
|
|
@@ -266,17 +825,92 @@ var USAGE_WIDGET_REQUIREMENTS = {
|
|
|
266
825
|
{ field: "extraUsageEnabled" },
|
|
267
826
|
{ field: "extraUsageUsed" }
|
|
268
827
|
],
|
|
828
|
+
"extra-usage-limit": [
|
|
829
|
+
{ field: "extraUsageEnabled" },
|
|
830
|
+
{ field: "extraUsageLimit" }
|
|
831
|
+
],
|
|
269
832
|
"extra-usage-daily-budget": [
|
|
270
833
|
{ field: "extraUsageEnabled" },
|
|
271
834
|
{ field: "extraUsageLimit" },
|
|
272
835
|
{ field: "extraUsageUsed" }
|
|
836
|
+
],
|
|
837
|
+
"extra-usage-today": [
|
|
838
|
+
{ field: "extraUsageEnabled" },
|
|
839
|
+
{ field: "extraUsageUsed" }
|
|
273
840
|
]
|
|
274
841
|
};
|
|
842
|
+
var SPEND_TODAY_WIDGET_TYPES = new Set(["extra-usage-today"]);
|
|
843
|
+
function needsSpendToday(lines) {
|
|
844
|
+
return lines.some((line) => line.some((item) => SPEND_TODAY_WIDGET_TYPES.has(item.type)));
|
|
845
|
+
}
|
|
846
|
+
async function withSpendToday(data, lines) {
|
|
847
|
+
if (!needsSpendToday(lines) || data.extraUsageUsed === undefined) {
|
|
848
|
+
return data;
|
|
849
|
+
}
|
|
850
|
+
const accountKey = getUsageAccountKey();
|
|
851
|
+
const fetchedAtMs = getUsageFetchedAtMs();
|
|
852
|
+
if (accountKey === null || fetchedAtMs === undefined) {
|
|
853
|
+
return data;
|
|
854
|
+
}
|
|
855
|
+
const account = await lookUpUsageAccount();
|
|
856
|
+
const spentToday = account ? observeExtraUsageSpend(account.key, data.extraUsageUsed, fetchedAtMs, undefined, account.fingerprints) : observeExtraUsageSpend(accountKey, data.extraUsageUsed, fetchedAtMs);
|
|
857
|
+
return spentToday === undefined ? data : { ...data, extraUsageUsedToday: spentToday };
|
|
858
|
+
}
|
|
275
859
|
var USAGE_CURSOR_REQUIREMENTS = {
|
|
276
860
|
"session-usage": { field: "sessionResetAt" },
|
|
277
861
|
"weekly-usage": { field: "weeklyResetAt" },
|
|
278
862
|
...Object.fromEntries(WEEKLY_MODEL_USAGE_BUCKETS.map((bucket) => [bucket.widgetType, { field: bucket.resetField, alternatives: ["weeklyResetAt"] }]))
|
|
279
863
|
};
|
|
864
|
+
var SESSION_LIMIT_HIDE_REQUIREMENT = { field: "sessionUsage", fromApi: true, suppressFetchError: true };
|
|
865
|
+
function readsSessionLimit(item) {
|
|
866
|
+
return item.type === "reset-timer" && isHidden(item, SESSION_UNDER_LIMIT_HIDEABLE_STATE.key) || item.type === "session-usage" && isHidden(item, SESSION_AT_LIMIT_HIDEABLE_STATE.key);
|
|
867
|
+
}
|
|
868
|
+
var PAYLOAD_USAGE_TRUSTED_MS = 3 * 60 * 1000;
|
|
869
|
+
var SAME_WINDOW_MS = 60 * 1000;
|
|
870
|
+
var PAYLOAD_USAGE_WINDOWS = [
|
|
871
|
+
{ usageField: "sessionUsage", resetField: "sessionResetAt" },
|
|
872
|
+
{ usageField: "weeklyUsage", resetField: "weeklyResetAt" },
|
|
873
|
+
...WEEKLY_MODEL_USAGE_BUCKETS.filter((bucket) => bucket.apiBucketKey).map((bucket) => ({ usageField: bucket.usageField, resetField: bucket.resetField }))
|
|
874
|
+
];
|
|
875
|
+
function getPayloadUsageFields(rateLimitsData, requirements) {
|
|
876
|
+
return PAYLOAD_USAGE_WINDOWS.map(({ usageField }) => usageField).filter((field) => rateLimitsData?.[field] !== undefined && requirements.some((requirement) => requirement.field === field));
|
|
877
|
+
}
|
|
878
|
+
function getIdlePayloadUsageTime(data, nowMs) {
|
|
879
|
+
const seenAtMs = getLastResponseAtMs(data?.transcript_path);
|
|
880
|
+
return seenAtMs !== undefined && nowMs - seenAtMs > PAYLOAD_USAGE_TRUSTED_MS ? seenAtMs : null;
|
|
881
|
+
}
|
|
882
|
+
function parseResetAtMs(value) {
|
|
883
|
+
return typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
884
|
+
}
|
|
885
|
+
function refreshIdlePayloadUsage(usageData, rateLimitsData, apiData, payloadSeenAtMs, nowMs) {
|
|
886
|
+
const fetchedAtMs = getUsageFetchedAtMs();
|
|
887
|
+
if (fetchedAtMs === undefined || fetchedAtMs <= payloadSeenAtMs) {
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
for (const { usageField, resetField } of PAYLOAD_USAGE_WINDOWS) {
|
|
891
|
+
const payloadPercent = rateLimitsData[usageField];
|
|
892
|
+
const apiPercent = apiData[usageField];
|
|
893
|
+
if (typeof payloadPercent !== "number" || typeof apiPercent !== "number") {
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
const payloadResetAtMs = parseResetAtMs(rateLimitsData[resetField]);
|
|
897
|
+
const apiResetAtMs = parseResetAtMs(apiData[resetField]);
|
|
898
|
+
const isSameWindow = Math.abs(payloadResetAtMs - apiResetAtMs) <= SAME_WINDOW_MS;
|
|
899
|
+
const isApiWindowCurrent = Number.isNaN(apiResetAtMs) || apiResetAtMs > nowMs;
|
|
900
|
+
const isPayloadWindowOver = payloadResetAtMs <= nowMs && isApiWindowCurrent;
|
|
901
|
+
if (isSameWindow ? apiPercent >= payloadPercent : isPayloadWindowOver) {
|
|
902
|
+
setUsageField(usageData, usageField, apiPercent);
|
|
903
|
+
setUsageField(usageData, resetField, apiData[resetField]);
|
|
904
|
+
if (usageField === "sessionUsage") {
|
|
905
|
+
usageData.sessionUsageObservedAtMs = fetchedAtMs;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
function isFromCurrentBlock(apiData) {
|
|
911
|
+
const resetAtMs = apiData.sessionResetAt === undefined ? Number.NaN : Date.parse(apiData.sessionResetAt);
|
|
912
|
+
return Number.isNaN(resetAtMs) || resetAtMs > Date.now();
|
|
913
|
+
}
|
|
280
914
|
function hasUsageDependentWidgets(lines) {
|
|
281
915
|
return lines.some((line) => line.some((item) => USAGE_WIDGET_TYPES.has(item.type)));
|
|
282
916
|
}
|
|
@@ -292,6 +926,9 @@ function getUsageFieldRequirements(lines) {
|
|
|
292
926
|
if (cursorRequirement && isUsageCursorEnabled(item)) {
|
|
293
927
|
requirements.push(cursorRequirement);
|
|
294
928
|
}
|
|
929
|
+
if (readsSessionLimit(item)) {
|
|
930
|
+
requirements.push(SESSION_LIMIT_HIDE_REQUIREMENT);
|
|
931
|
+
}
|
|
295
932
|
}
|
|
296
933
|
}
|
|
297
934
|
return requirements;
|
|
@@ -309,7 +946,7 @@ function getMissingFetchRequirements(data, requirements) {
|
|
|
309
946
|
const missing = new Set;
|
|
310
947
|
let hasUnsuppressedMissingRequirement = false;
|
|
311
948
|
for (const requirement of requirements) {
|
|
312
|
-
if (!isUsageRequirementSatisfied(data, requirement)) {
|
|
949
|
+
if (requirement.fromApi || !isUsageRequirementSatisfied(data, requirement)) {
|
|
313
950
|
missing.add(requirement.field);
|
|
314
951
|
if (!requirement.suppressFetchError) {
|
|
315
952
|
hasUnsuppressedMissingRequirement = true;
|
|
@@ -380,6 +1017,12 @@ async function prefetchUsageDataIfNeeded(lines, data) {
|
|
|
380
1017
|
}
|
|
381
1018
|
const rateLimitsData = extractUsageDataFromRateLimits(data?.rate_limits);
|
|
382
1019
|
const requirements = getUsageFieldRequirements(lines);
|
|
1020
|
+
const nowMs = Date.now();
|
|
1021
|
+
const payloadUsageFields = getPayloadUsageFields(rateLimitsData, requirements);
|
|
1022
|
+
const payloadSeenAtMs = payloadUsageFields.length > 0 ? getIdlePayloadUsageTime(data, nowMs) : null;
|
|
1023
|
+
if (payloadSeenAtMs !== null) {
|
|
1024
|
+
requirements.push(...payloadUsageFields.map((field) => ({ field, fromApi: true, suppressFetchError: true })));
|
|
1025
|
+
}
|
|
383
1026
|
const missingRequirements = getMissingFetchRequirements(rateLimitsData, requirements);
|
|
384
1027
|
const missingFields = missingRequirements.fields;
|
|
385
1028
|
if (missingFields.length === 0) {
|
|
@@ -387,9 +1030,16 @@ async function prefetchUsageDataIfNeeded(lines, data) {
|
|
|
387
1030
|
}
|
|
388
1031
|
const apiData = await fetchUsageData({ requiredFields: missingFields });
|
|
389
1032
|
if (apiData.error && missingRequirements.suppressFetchError) {
|
|
390
|
-
return rateLimitsData;
|
|
1033
|
+
return hasAnyUsageDataField(apiData) ? mergeUsageData(rateLimitsData, { ...apiData, error: undefined }) : rateLimitsData;
|
|
1034
|
+
}
|
|
1035
|
+
const usageData = mergeUsageData(rateLimitsData, apiData);
|
|
1036
|
+
if (payloadSeenAtMs !== null && rateLimitsData && !apiData.error) {
|
|
1037
|
+
refreshIdlePayloadUsage(usageData, rateLimitsData, apiData, payloadSeenAtMs, nowMs);
|
|
1038
|
+
}
|
|
1039
|
+
if (requirements.includes(SESSION_LIMIT_HIDE_REQUIREMENT) && apiData.sessionUsage !== undefined && isFromCurrentBlock(apiData) && !isStaleUsageFallback(apiData)) {
|
|
1040
|
+
usageData.apiSessionUsage = apiData.sessionUsage;
|
|
391
1041
|
}
|
|
392
|
-
return
|
|
1042
|
+
return withSpendToday(usageData, lines);
|
|
393
1043
|
}
|
|
394
1044
|
|
|
395
1045
|
// src/utils/windows-code-page.ts
|
|
@@ -404,10 +1054,19 @@ function ensureWindowsUtf8CodePage(platform = process.platform) {
|
|
|
404
1054
|
}
|
|
405
1055
|
|
|
406
1056
|
// src/ccstatusline.ts
|
|
1057
|
+
var LAUNCH_ARGS = process.argv.slice(2);
|
|
407
1058
|
function hasSessionDurationInStatusJson(data) {
|
|
408
1059
|
const durationMs = data.cost?.total_duration_ms;
|
|
409
1060
|
return typeof durationMs === "number" && Number.isFinite(durationMs) && durationMs >= 0;
|
|
410
1061
|
}
|
|
1062
|
+
var DISPATCHABLE_HOOK_EVENT_NAMES = new Set(["PreToolUse", "UserPromptSubmit"]);
|
|
1063
|
+
function isDispatchableHookPayload(data) {
|
|
1064
|
+
if (typeof data !== "object" || data === null) {
|
|
1065
|
+
return false;
|
|
1066
|
+
}
|
|
1067
|
+
const { hook_event_name: hookEventName, session_id: sessionId } = data;
|
|
1068
|
+
return typeof hookEventName === "string" && DISPATCHABLE_HOOK_EVENT_NAMES.has(hookEventName) && typeof sessionId === "string" && sessionId.length > 0;
|
|
1069
|
+
}
|
|
411
1070
|
async function readStdin() {
|
|
412
1071
|
if (process.stdin.isTTY) {
|
|
413
1072
|
return null;
|
|
@@ -430,7 +1089,7 @@ async function readStdin() {
|
|
|
430
1089
|
return null;
|
|
431
1090
|
}
|
|
432
1091
|
}
|
|
433
|
-
async function renderMultipleLines(data) {
|
|
1092
|
+
async function renderMultipleLines(data, rawData) {
|
|
434
1093
|
const settings = await loadSettings();
|
|
435
1094
|
const configError = getConfigLoadError();
|
|
436
1095
|
source_default.level = settings.colorLevel;
|
|
@@ -442,6 +1101,7 @@ async function renderMultipleLines(data) {
|
|
|
442
1101
|
const hasCompactionWidget = lines.some((line) => line.some((item) => item.type === "compaction-counter"));
|
|
443
1102
|
const hasThinkingEffortWidget = lines.some((line) => line.some((item) => item.type === "thinking-effort"));
|
|
444
1103
|
const hasSessionNameWidget = lines.some((line) => line.some((item) => item.type === "session-name"));
|
|
1104
|
+
const hasAccountEmailWidget = lines.some((line) => line.some((item) => item.type === "claude-account-email"));
|
|
445
1105
|
const needsTranscriptThinkingEffort = hasThinkingEffortWidget && (!data.effort || !("level" in data.effort));
|
|
446
1106
|
const requestedSpeedWindows = new Set;
|
|
447
1107
|
for (const line of lines) {
|
|
@@ -460,11 +1120,13 @@ async function renderMultipleLines(data) {
|
|
|
460
1120
|
includeThinkingEffort: needsTranscriptThinkingEffort,
|
|
461
1121
|
includeSessionName: hasSessionNameWidget
|
|
462
1122
|
}) : Promise.resolve(null);
|
|
463
|
-
const [transcriptAnalysis, usageData, claudeStatusData] = await Promise.all([
|
|
1123
|
+
const [transcriptAnalysis, usageData, claudeStatusData, accountEmail] = await Promise.all([
|
|
464
1124
|
transcriptAnalysisPromise,
|
|
465
1125
|
prefetchUsageDataIfNeeded(lines, data),
|
|
466
|
-
prefetchClaudeStatusIfNeeded(lines)
|
|
1126
|
+
prefetchClaudeStatusIfNeeded(lines),
|
|
1127
|
+
hasAccountEmailWidget ? fetchAccountEmail() : Promise.resolve(undefined)
|
|
467
1128
|
]);
|
|
1129
|
+
const sessionForecast = computeSessionForecastIfNeeded(lines, usageData, getDefaultSessionUsageHistoryDeps(data, usageData));
|
|
468
1130
|
const tokenMetrics = transcriptAnalysis?.tokenMetrics ?? null;
|
|
469
1131
|
const sessionDuration = transcriptAnalysis?.sessionDuration ?? null;
|
|
470
1132
|
const speedMetrics = transcriptAnalysis?.speedMetricsCollection?.sessionAverage ?? null;
|
|
@@ -476,11 +1138,14 @@ async function renderMultipleLines(data) {
|
|
|
476
1138
|
const compactionData = hasCompactionWidget ? transcriptAnalysis?.compactionData ?? ZERO_COMPACTION_STATS : null;
|
|
477
1139
|
const context = {
|
|
478
1140
|
data,
|
|
1141
|
+
rawData,
|
|
479
1142
|
tokenMetrics,
|
|
480
1143
|
speedMetrics,
|
|
481
1144
|
windowedSpeedMetrics,
|
|
482
1145
|
usageData,
|
|
1146
|
+
sessionForecast,
|
|
483
1147
|
claudeStatusData,
|
|
1148
|
+
accountEmail,
|
|
484
1149
|
sessionDuration,
|
|
485
1150
|
transcriptSessionName: hasSessionNameWidget ? transcriptAnalysis?.sessionName ?? null : undefined,
|
|
486
1151
|
transcriptThinkingEffort: needsTranscriptThinkingEffort ? transcriptAnalysis?.thinkingEffort ?? null : undefined,
|
|
@@ -520,7 +1185,7 @@ async function renderMultipleLines(data) {
|
|
|
520
1185
|
line = `${buildConfigWarningBadge(settings.colorLevel)} | ${line}`;
|
|
521
1186
|
configBadgePrepended = true;
|
|
522
1187
|
}
|
|
523
|
-
let outputLine = sanitizeTerminalText(line)
|
|
1188
|
+
let outputLine = replaceSpacesForOutput(sanitizeTerminalText(line));
|
|
524
1189
|
outputLine = "\x1B[0m" + outputLine;
|
|
525
1190
|
console.log(outputLine);
|
|
526
1191
|
globalSeparatorIndex = advanceGlobalSeparatorIndex(globalSeparatorIndex, lineItems, preRenderedWidgets);
|
|
@@ -534,7 +1199,7 @@ async function renderMultipleLines(data) {
|
|
|
534
1199
|
}
|
|
535
1200
|
}
|
|
536
1201
|
if (configError && !configBadgePrepended) {
|
|
537
|
-
console.log("\x1B[0m" + buildConfigWarningBadge(settings.colorLevel)
|
|
1202
|
+
console.log("\x1B[0m" + replaceSpacesForOutput(buildConfigWarningBadge(settings.colorLevel)));
|
|
538
1203
|
}
|
|
539
1204
|
if (settings.updatemessage?.message && settings.updatemessage.message.trim() !== "" && settings.updatemessage.remaining && settings.updatemessage.remaining > 0) {
|
|
540
1205
|
console.log(sanitizeTerminalText(settings.updatemessage.message));
|
|
@@ -601,12 +1266,18 @@ async function main() {
|
|
|
601
1266
|
const input = await readStdin();
|
|
602
1267
|
if (input && input.trim() !== "") {
|
|
603
1268
|
try {
|
|
604
|
-
const
|
|
1269
|
+
const parsed = JSON.parse(input);
|
|
1270
|
+
if (isDispatchableHookPayload(parsed)) {
|
|
1271
|
+
handleHookInput(input);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
const rawData = parsed;
|
|
1275
|
+
const result = StatusJSONSchema.safeParse(rawData);
|
|
605
1276
|
if (!result.success) {
|
|
606
1277
|
console.error("Invalid status JSON format:", result.error.message);
|
|
607
1278
|
process.exit(1);
|
|
608
1279
|
}
|
|
609
|
-
await renderMultipleLines(result.data);
|
|
1280
|
+
await renderMultipleLines(result.data, rawData);
|
|
610
1281
|
} catch (error) {
|
|
611
1282
|
console.error("Error parsing JSON:", error);
|
|
612
1283
|
process.exit(1);
|
|
@@ -616,12 +1287,18 @@ async function main() {
|
|
|
616
1287
|
process.exit(1);
|
|
617
1288
|
}
|
|
618
1289
|
} else {
|
|
1290
|
+
if (process.env.CCSTATUSLINE_DEV_RELOAD === "1") {
|
|
1291
|
+
const { getDevReloadMode, superviseDevReload } = await import("./dev-reload-z0a689mw.js");
|
|
1292
|
+
if (getDevReloadMode(process.env) === "supervisor") {
|
|
1293
|
+
process.exit(await superviseDevReload(LAUNCH_ARGS));
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
619
1296
|
const settings = await loadSettings();
|
|
620
1297
|
if (settings.updatemessage) {
|
|
621
1298
|
const { updatemessage, ...newSettings } = settings;
|
|
622
1299
|
await saveSettings(newSettings);
|
|
623
1300
|
}
|
|
624
|
-
const { runTUI } = await import("./index-
|
|
1301
|
+
const { runTUI } = await import("./index-48pdkn43.js");
|
|
625
1302
|
runTUI();
|
|
626
1303
|
}
|
|
627
1304
|
}
|