ccstatusline-zh 2.2.35 → 2.2.37

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.
@@ -2,9 +2,11 @@
2
2
  import {
3
3
  source_default,
4
4
  getVisibleText,
5
+ replaceSpacesForOutput,
5
6
  updateColorMap,
6
7
  prefetchClaudeStatusIfNeeded,
7
8
  ZERO_COMPACTION_STATS,
9
+ withCacheLock,
8
10
  getPackageVersion,
9
11
  getTerminalWidth,
10
12
  isHidden,
@@ -19,13 +21,16 @@ import {
19
21
  renderStatusLine,
20
22
  SESSION_UNDER_LIMIT_HIDEABLE_STATE,
21
23
  SESSION_AT_LIMIT_HIDEABLE_STATE,
24
+ isAtSessionLimit,
22
25
  getClaudeConfigDir,
23
26
  setUsageField,
24
27
  WEEKLY_MODEL_USAGE_BUCKETS,
25
28
  isStaleUsageFallback,
26
29
  getUsageFetchedAtMs,
27
30
  getUsageLoginFingerprint,
31
+ getUsageAccountKey,
28
32
  fetchUsageData,
33
+ lookUpUsageAccount,
29
34
  fetchAccountEmail,
30
35
  iterateJsonlLinesReverseSync,
31
36
  parseJsonlLine,
@@ -36,16 +41,18 @@ import {
36
41
  initConfigPath,
37
42
  loadSettings,
38
43
  saveSettings
39
- } from "./ccstatusline-98magj3t.js";
44
+ } from "./ccstatusline-ss57aydk.js";
40
45
  import {
41
46
  string,
42
47
  number,
43
48
  boolean,
49
+ array,
44
50
  object,
45
51
  looseObject,
46
52
  union,
53
+ record,
47
54
  preprocess
48
- } from "./ccstatusline-88bs860s.js";
55
+ } from "./ccstatusline-er9fa25f.js";
49
56
  import {
50
57
  advanceGlobalPowerlineThemeIndex,
51
58
  advanceGlobalSeparatorIndex
@@ -72,6 +79,31 @@ var SpendLimitSchema = RateLimitPeriodSchema.extend({
72
79
  limit_usd: CoercedNumberSchema.nullable().optional(),
73
80
  period: string().nullable().optional()
74
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
+ });
75
107
  var StatusJSONSchema = looseObject({
76
108
  hook_event_name: string().optional(),
77
109
  session_id: string().optional(),
@@ -123,14 +155,7 @@ var StatusJSONSchema = looseObject({
123
155
  original_cwd: string().optional(),
124
156
  original_branch: string().optional()
125
157
  }).nullable().optional(),
126
- prompt_cache: object({
127
- warm: boolean().nullable().optional(),
128
- caching_observed: boolean().nullable().optional(),
129
- ttl: string().nullable().optional(),
130
- expires_at: CoercedNumberSchema.nullable().optional(),
131
- hit_ratio: CoercedNumberSchema.nullable().optional(),
132
- recache_tokens_if_cold: CoercedNumberSchema.nullable().optional()
133
- }).nullable().optional(),
158
+ prompt_cache: tolerant(PromptCacheSchema),
134
159
  rate_limits: object({
135
160
  five_hour: RateLimitPeriodSchema.optional(),
136
161
  seven_day: RateLimitPeriodSchema.optional(),
@@ -324,8 +349,9 @@ function getLastResponseAtMs(transcriptPath) {
324
349
  }
325
350
  return;
326
351
  }
327
- function getDefaultSessionUsageHistoryDeps(payload) {
328
- const isPayloadPercent = typeof payload?.rate_limits?.five_hour?.used_percentage === "number";
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;
329
355
  return {
330
356
  readFileSync: (p) => fs3.readFileSync(p, "utf-8"),
331
357
  writeFileSync: (p, data) => {
@@ -346,7 +372,7 @@ function getDefaultSessionUsageHistoryDeps(payload) {
346
372
  fs3.mkdirSync(p, { recursive: true });
347
373
  },
348
374
  now: () => Date.now(),
349
- percentSeenAt: isPayloadPercent ? () => getLastResponseAtMs(payload.transcript_path) : getUsageFetchedAtMs,
375
+ percentSeenAt: observedAtMs === undefined ? defaultPercentSeenAt : () => observedAtMs,
350
376
  loginFingerprint: getUsageLoginFingerprint,
351
377
  cachePath: path3.join(os2.homedir(), ".cache", "ccstatusline", "session-usage-history.json")
352
378
  };
@@ -535,15 +561,214 @@ function computeSessionForecastIfNeeded(lines, usageData, deps = getDefaultSessi
535
561
  const login = deps.loginFingerprint?.() ?? null;
536
562
  const profileKey = login === null ? getClaudeConfigDir() : `${getClaudeConfigDir()}#${login}`;
537
563
  const readings = recordSessionUsageReading(profileKey, resetAtMs, clampedPercent, deps);
564
+ if (isAtSessionLimit({ usageData })) {
565
+ return null;
566
+ }
538
567
  return forecastSessionUsage({ readings, nowMs, resetAtMs, percent: clampedPercent });
539
568
  }
540
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
+
541
764
  // src/utils/usage-prefetch.ts
542
765
  var BASE_USAGE_WIDGET_TYPES = [
543
766
  "session-usage",
544
767
  "block-forecast",
545
768
  "block-limit-timer",
546
769
  "weekly-usage",
770
+ "weekly-limit-timer",
771
+ "fable-weekly-limit-timer",
547
772
  "block-timer",
548
773
  "reset-timer",
549
774
  "weekly-reset-timer",
@@ -552,6 +777,7 @@ var BASE_USAGE_WIDGET_TYPES = [
552
777
  "extra-usage-used",
553
778
  "extra-usage-limit",
554
779
  "extra-usage-daily-budget",
780
+ "extra-usage-today",
555
781
  "spend-limit-usage",
556
782
  "spend-limit-amount"
557
783
  ];
@@ -579,6 +805,8 @@ var USAGE_WIDGET_REQUIREMENTS = {
579
805
  "session-usage": [{ field: "sessionUsage" }],
580
806
  "block-forecast": [{ field: "sessionUsage", suppressFetchError: true }, { field: "sessionResetAt", suppressFetchError: true }],
581
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 }],
582
810
  "weekly-usage": [{ field: "weeklyUsage" }],
583
811
  ...Object.fromEntries(WEEKLY_MODEL_USAGE_BUCKETS.map((bucket) => [bucket.widgetType, [{ field: bucket.usageField }]])),
584
812
  "block-timer": [{ field: "sessionResetAt", suppressFetchError: true }],
@@ -605,8 +833,29 @@ var USAGE_WIDGET_REQUIREMENTS = {
605
833
  { field: "extraUsageEnabled" },
606
834
  { field: "extraUsageLimit" },
607
835
  { field: "extraUsageUsed" }
836
+ ],
837
+ "extra-usage-today": [
838
+ { field: "extraUsageEnabled" },
839
+ { field: "extraUsageUsed" }
608
840
  ]
609
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
+ }
610
859
  var USAGE_CURSOR_REQUIREMENTS = {
611
860
  "session-usage": { field: "sessionResetAt" },
612
861
  "weekly-usage": { field: "weeklyResetAt" },
@@ -616,6 +865,48 @@ var SESSION_LIMIT_HIDE_REQUIREMENT = { field: "sessionUsage", fromApi: true, sup
616
865
  function readsSessionLimit(item) {
617
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);
618
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
+ }
619
910
  function isFromCurrentBlock(apiData) {
620
911
  const resetAtMs = apiData.sessionResetAt === undefined ? Number.NaN : Date.parse(apiData.sessionResetAt);
621
912
  return Number.isNaN(resetAtMs) || resetAtMs > Date.now();
@@ -726,6 +1017,12 @@ async function prefetchUsageDataIfNeeded(lines, data) {
726
1017
  }
727
1018
  const rateLimitsData = extractUsageDataFromRateLimits(data?.rate_limits);
728
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
+ }
729
1026
  const missingRequirements = getMissingFetchRequirements(rateLimitsData, requirements);
730
1027
  const missingFields = missingRequirements.fields;
731
1028
  if (missingFields.length === 0) {
@@ -736,10 +1033,13 @@ async function prefetchUsageDataIfNeeded(lines, data) {
736
1033
  return hasAnyUsageDataField(apiData) ? mergeUsageData(rateLimitsData, { ...apiData, error: undefined }) : rateLimitsData;
737
1034
  }
738
1035
  const usageData = mergeUsageData(rateLimitsData, apiData);
1036
+ if (payloadSeenAtMs !== null && rateLimitsData && !apiData.error) {
1037
+ refreshIdlePayloadUsage(usageData, rateLimitsData, apiData, payloadSeenAtMs, nowMs);
1038
+ }
739
1039
  if (requirements.includes(SESSION_LIMIT_HIDE_REQUIREMENT) && apiData.sessionUsage !== undefined && isFromCurrentBlock(apiData) && !isStaleUsageFallback(apiData)) {
740
1040
  usageData.apiSessionUsage = apiData.sessionUsage;
741
1041
  }
742
- return usageData;
1042
+ return withSpendToday(usageData, lines);
743
1043
  }
744
1044
 
745
1045
  // src/utils/windows-code-page.ts
@@ -789,7 +1089,7 @@ async function readStdin() {
789
1089
  return null;
790
1090
  }
791
1091
  }
792
- async function renderMultipleLines(data) {
1092
+ async function renderMultipleLines(data, rawData) {
793
1093
  const settings = await loadSettings();
794
1094
  const configError = getConfigLoadError();
795
1095
  source_default.level = settings.colorLevel;
@@ -826,7 +1126,7 @@ async function renderMultipleLines(data) {
826
1126
  prefetchClaudeStatusIfNeeded(lines),
827
1127
  hasAccountEmailWidget ? fetchAccountEmail() : Promise.resolve(undefined)
828
1128
  ]);
829
- const sessionForecast = computeSessionForecastIfNeeded(lines, usageData, getDefaultSessionUsageHistoryDeps(data));
1129
+ const sessionForecast = computeSessionForecastIfNeeded(lines, usageData, getDefaultSessionUsageHistoryDeps(data, usageData));
830
1130
  const tokenMetrics = transcriptAnalysis?.tokenMetrics ?? null;
831
1131
  const sessionDuration = transcriptAnalysis?.sessionDuration ?? null;
832
1132
  const speedMetrics = transcriptAnalysis?.speedMetricsCollection?.sessionAverage ?? null;
@@ -838,6 +1138,7 @@ async function renderMultipleLines(data) {
838
1138
  const compactionData = hasCompactionWidget ? transcriptAnalysis?.compactionData ?? ZERO_COMPACTION_STATS : null;
839
1139
  const context = {
840
1140
  data,
1141
+ rawData,
841
1142
  tokenMetrics,
842
1143
  speedMetrics,
843
1144
  windowedSpeedMetrics,
@@ -884,7 +1185,7 @@ async function renderMultipleLines(data) {
884
1185
  line = `${buildConfigWarningBadge(settings.colorLevel)} | ${line}`;
885
1186
  configBadgePrepended = true;
886
1187
  }
887
- let outputLine = sanitizeTerminalText(line).replace(/ /g, " ");
1188
+ let outputLine = replaceSpacesForOutput(sanitizeTerminalText(line));
888
1189
  outputLine = "\x1B[0m" + outputLine;
889
1190
  console.log(outputLine);
890
1191
  globalSeparatorIndex = advanceGlobalSeparatorIndex(globalSeparatorIndex, lineItems, preRenderedWidgets);
@@ -898,7 +1199,7 @@ async function renderMultipleLines(data) {
898
1199
  }
899
1200
  }
900
1201
  if (configError && !configBadgePrepended) {
901
- console.log("\x1B[0m" + buildConfigWarningBadge(settings.colorLevel).replace(/ /g, " "));
1202
+ console.log("\x1B[0m" + replaceSpacesForOutput(buildConfigWarningBadge(settings.colorLevel)));
902
1203
  }
903
1204
  if (settings.updatemessage?.message && settings.updatemessage.message.trim() !== "" && settings.updatemessage.remaining && settings.updatemessage.remaining > 0) {
904
1205
  console.log(sanitizeTerminalText(settings.updatemessage.message));
@@ -970,12 +1271,13 @@ async function main() {
970
1271
  handleHookInput(input);
971
1272
  return;
972
1273
  }
973
- const result = StatusJSONSchema.safeParse(parsed);
1274
+ const rawData = parsed;
1275
+ const result = StatusJSONSchema.safeParse(rawData);
974
1276
  if (!result.success) {
975
1277
  console.error("Invalid status JSON format:", result.error.message);
976
1278
  process.exit(1);
977
1279
  }
978
- await renderMultipleLines(result.data);
1280
+ await renderMultipleLines(result.data, rawData);
979
1281
  } catch (error) {
980
1282
  console.error("Error parsing JSON:", error);
981
1283
  process.exit(1);
@@ -986,7 +1288,7 @@ async function main() {
986
1288
  }
987
1289
  } else {
988
1290
  if (process.env.CCSTATUSLINE_DEV_RELOAD === "1") {
989
- const { getDevReloadMode, superviseDevReload } = await import("./dev-reload-egdx2kp5.js");
1291
+ const { getDevReloadMode, superviseDevReload } = await import("./dev-reload-z0a689mw.js");
990
1292
  if (getDevReloadMode(process.env) === "supervisor") {
991
1293
  process.exit(await superviseDevReload(LAUNCH_ARGS));
992
1294
  }
@@ -996,7 +1298,7 @@ async function main() {
996
1298
  const { updatemessage, ...newSettings } = settings;
997
1299
  await saveSettings(newSettings);
998
1300
  }
999
- const { runTUI } = await import("./index-7sf5nvak.js");
1301
+ const { runTUI } = await import("./index-1az9bg18.js");
1000
1302
  runTUI();
1001
1303
  }
1002
1304
  }
@@ -8,8 +8,8 @@ import {
8
8
  requestDevReload2,
9
9
  isDevReloadRequested2,
10
10
  superviseDevReload2
11
- } from "./ccstatusline-j1gdxtq4.js";
12
- import"./ccstatusline-88bs860s.js";
11
+ } from "./ccstatusline-mkma8vq8.js";
12
+ import"./ccstatusline-er9fa25f.js";
13
13
  export {
14
14
  DEV_RELOAD_EXIT_CODE2 as DEV_RELOAD_EXIT_CODE,
15
15
  discardDevReloadSnapshot2 as discardDevReloadSnapshot,
@@ -1,12 +1,15 @@
1
- import"./ccstatusline-88bs860s.js";
1
+ import"./ccstatusline-er9fa25f.js";
2
2
  import {
3
3
  loadClaudeSettings,
4
4
  saveClaudeSettings,
5
+ getStatusLineConfigPath,
5
6
  getExistingStatusLine,
6
- getWidget
7
- } from "./ccstatusline-98magj3t.js";
7
+ getWidget,
8
+ getConfigPath
9
+ } from "./ccstatusline-ss57aydk.js";
8
10
 
9
11
  // src/utils/hooks.ts
12
+ import * as fs from "node:fs";
10
13
  var HOOK_TAG = "ccstatusline-managed";
11
14
  var CCSTATUSLINE_HOOK_PATTERN = /ccstatusline.* --hook(?:\s|$)/;
12
15
  function hasWidgetHooks(widget) {
@@ -16,13 +19,16 @@ function isCcstatuslineManagedEntry(entry) {
16
19
  return entry._tag === HOOK_TAG;
17
20
  }
18
21
  function isLegacyCcstatuslineHookCommand(hook) {
19
- return CCSTATUSLINE_HOOK_PATTERN.test(hook.command);
22
+ return typeof hook === "object" && hook !== null && "command" in hook && typeof hook.command === "string" && CCSTATUSLINE_HOOK_PATTERN.test(hook.command);
23
+ }
24
+ function isHookEntry(entry) {
25
+ return typeof entry === "object" && entry !== null;
20
26
  }
21
27
  function stripManagedHookEntry(entry) {
22
28
  if (isCcstatuslineManagedEntry(entry)) {
23
29
  return null;
24
30
  }
25
- if (!entry.hooks) {
31
+ if (!Array.isArray(entry.hooks)) {
26
32
  return entry;
27
33
  }
28
34
  const remainingHooks = entry.hooks.filter((hook) => !isLegacyCcstatuslineHookCommand(hook));
@@ -39,12 +45,33 @@ function stripManagedHookEntry(entry) {
39
45
  }
40
46
  function stripManagedHooks(hooks) {
41
47
  for (const event of Object.keys(hooks)) {
42
- hooks[event] = (hooks[event] ?? []).map(stripManagedHookEntry).filter((entry) => entry !== null);
43
- if (hooks[event].length === 0) {
48
+ const entries = hooks[event];
49
+ if (!Array.isArray(entries)) {
50
+ continue;
51
+ }
52
+ const remaining = [];
53
+ for (const entry of entries) {
54
+ if (!isHookEntry(entry)) {
55
+ remaining.push(entry);
56
+ continue;
57
+ }
58
+ const stripped = stripManagedHookEntry(entry);
59
+ if (stripped) {
60
+ remaining.push(stripped);
61
+ }
62
+ }
63
+ hooks[event] = remaining;
64
+ if (remaining.length === 0) {
44
65
  Reflect.deleteProperty(hooks, event);
45
66
  }
46
67
  }
47
68
  }
69
+ function hasManagedHooks(hooks) {
70
+ return Object.keys(hooks).some((event) => {
71
+ const entries = hooks[event];
72
+ return Array.isArray(entries) && entries.some((entry) => isHookEntry(entry) && stripManagedHookEntry(entry) !== entry);
73
+ });
74
+ }
48
75
  function getHookWidgets(settings) {
49
76
  const widgets = new Set;
50
77
  for (const line of settings.lines) {
@@ -71,6 +98,13 @@ function getActiveHookDefs(widgets) {
71
98
  }
72
99
  return defs;
73
100
  }
101
+ async function resolveHookConfigPath(configPath) {
102
+ try {
103
+ return await fs.promises.realpath(configPath);
104
+ } catch {
105
+ return configPath;
106
+ }
107
+ }
74
108
  async function syncWidgetHooks(settings) {
75
109
  const hookWidgets = getHookWidgets(settings);
76
110
  const needed = getActiveHookDefs(hookWidgets);
@@ -83,6 +117,17 @@ async function syncWidgetHooks(settings) {
83
117
  await saveClaudeSettings(claudeSettings);
84
118
  return statusCommand && needed.length > 0 ? { statusCommand, widgetNames: hookWidgets.map((widget) => widget.getDisplayName()) } : null;
85
119
  }
120
+ const statusConfigPath = getStatusLineConfigPath(statusCommand);
121
+ if (statusConfigPath === null) {
122
+ return null;
123
+ }
124
+ const [statusTarget, editedTarget] = await Promise.all([
125
+ resolveHookConfigPath(statusConfigPath),
126
+ resolveHookConfigPath(getConfigPath())
127
+ ]);
128
+ if (statusTarget !== editedTarget) {
129
+ return null;
130
+ }
86
131
  const hookCommand = `${statusCommand} --hook`;
87
132
  for (const def of needed) {
88
133
  const entry = {
@@ -99,14 +144,16 @@ async function syncWidgetHooks(settings) {
99
144
  await saveClaudeSettings(claudeSettings);
100
145
  return null;
101
146
  }
102
- async function removeManagedHooks() {
103
- const claudeSettings = await loadClaudeSettings({ logErrors: false });
147
+ function stripManagedHooksFromSettings(claudeSettings) {
104
148
  const hooks = claudeSettings.hooks ?? {};
149
+ if (!hasManagedHooks(hooks)) {
150
+ return false;
151
+ }
105
152
  stripManagedHooks(hooks);
106
153
  claudeSettings.hooks = Object.keys(hooks).length > 0 ? hooks : undefined;
107
- await saveClaudeSettings(claudeSettings);
154
+ return true;
108
155
  }
109
156
  export {
110
- removeManagedHooks,
157
+ stripManagedHooksFromSettings,
111
158
  syncWidgetHooks
112
159
  };