cc-pets 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +60 -0
  4. package/CHANGELOG.zh-CN.md +60 -0
  5. package/CONTRIBUTING.md +13 -10
  6. package/CONTRIBUTING.zh-CN.md +11 -10
  7. package/README.md +113 -24
  8. package/README.zh-CN.md +89 -28
  9. package/Resources/zh-Hans.lproj/Localizable.strings +568 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +82 -23
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  22. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  23. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  24. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  25. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  26. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  27. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  35. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  38. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  39. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  41. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  43. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  44. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  45. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  46. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  47. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  48. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  49. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  50. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  51. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  52. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  53. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  54. package/Sources/CCPets/Pet/PetView.m +635 -0
  55. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  56. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  57. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  58. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  59. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  60. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  61. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  62. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  63. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  64. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  65. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  66. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  67. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  68. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  69. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  70. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  71. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  72. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  73. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  74. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  75. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  76. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  77. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  78. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  79. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  81. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  82. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  83. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  84. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  85. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  86. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  87. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  88. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  89. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  90. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  92. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  93. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  94. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  95. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  96. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  97. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  98. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  99. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  100. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  101. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  102. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  103. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  104. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  105. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  106. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  107. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  108. package/THIRD_PARTY_NOTICES.md +1 -1
  109. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  110. package/bin/cc-pets +8 -6
  111. package/bin/claude-with-pet +10 -2
  112. package/bin/codex-with-pet +13 -5
  113. package/package.json +1 -1
  114. package/scripts/build.sh +7 -3
  115. package/scripts/i18n.zsh +9 -52
  116. package/scripts/install-app.sh +4 -0
  117. package/scripts/install-shell-integration.sh +17 -10
  118. package/scripts/uninstall-shell-integration.sh +6 -1
  119. package/Sources/CCPets/CCPetsEvents.h +0 -10
  120. package/Sources/CCPets/CCPetsUsage.h +0 -36
  121. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  122. package/Sources/CCPets/PetView.m +0 -1839
  123. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  124. package/scripts/bridge/cli.mjs +0 -237
  125. package/scripts/bridge/core.mjs +0 -228
  126. package/scripts/bridge/hook.mjs +0 -150
  127. package/scripts/bridge/install.mjs +0 -311
  128. package/scripts/bridge/mcp-server.mjs +0 -308
  129. package/scripts/bridge/options.mjs +0 -87
  130. package/scripts/bridge/process.mjs +0 -151
  131. package/scripts/bridge/reservations.mjs +0 -248
  132. package/scripts/bridge/store.mjs +0 -433
  133. package/scripts/bridge/watch.mjs +0 -69
  134. package/scripts/check-l10n.mjs +0 -168
  135. package/scripts/configure-updater.mjs +0 -43
  136. package/scripts/detect-cli.mjs +0 -68
  137. package/scripts/doctor.mjs +0 -470
  138. package/scripts/i18n.mjs +0 -122
  139. package/scripts/install-claude-hooks.mjs +0 -253
  140. package/scripts/install-codex-hooks.mjs +0 -78
  141. package/scripts/integration-markers.mjs +0 -51
  142. package/scripts/locales/zh-Hans.json +0 -366
  143. package/scripts/pet-store.mjs +0 -415
  144. package/scripts/uninstall-integrations.mjs +0 -205
  145. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  146. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  147. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  148. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  149. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  150. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  151. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  152. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  153. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  154. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  155. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  156. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  157. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  159. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  161. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  162. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  163. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  164. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  165. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  166. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  167. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  168. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  169. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  170. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  171. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -73,6 +73,7 @@
73
73
  NSColor *pillColor = usesAPI
74
74
  ? [NSColor colorWithRed:0.12 green:0.52 blue:0.96 alpha:self.highlighted ? 0.78 : 0.96]
75
75
  : [NSColor colorWithRed:0.20 green:0.68 blue:0.36 alpha:self.highlighted ? 0.78 : 0.96];
76
+ if (!self.enabled) pillColor = [pillColor colorWithAlphaComponent:0.45];
76
77
  [pillColor setFill];
77
78
  NSBezierPath *pillPath = [NSBezierPath bezierPathWithRoundedRect:pill
78
79
  xRadius:NSHeight(pill) / 2.0 yRadius:NSHeight(pill) / 2.0];
@@ -4,6 +4,7 @@
4
4
  // rate_limits 只是一份历史快照,不能作为当前窗口的唯一事实来源。
5
5
  @interface CCPetsCodexRateLimitsReader : NSObject
6
6
  @property(copy) void (^liveUsageHandler)(NSDictionary *liveUsage);
7
+ - (instancetype)initWithCodexHome:(NSString *)codexHome;
7
8
  - (void)refresh;
8
9
  - (void)stop;
9
10
  @end
@@ -138,7 +138,8 @@ static NSString *CodexAppServerExecutablePath(void) {
138
138
  return nil;
139
139
  }
140
140
 
141
- static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString *executablePath) {
141
+ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString *executablePath,
142
+ NSString *codexHome) {
142
143
  NSMutableDictionary<NSString *, NSString *> *environment =
143
144
  [NSProcessInfo.processInfo.environment mutableCopy];
144
145
  NSMutableOrderedSet<NSString *> *paths = [NSMutableOrderedSet orderedSet];
@@ -151,7 +152,7 @@ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString
151
152
  }
152
153
  environment[@"PATH"] = [paths.array componentsJoinedByString:@":"];
153
154
  // 与会话扫描使用同一份配置目录,避免备用 CODEX_HOME 下的账号被错读成默认账号。
154
- environment[@"CODEX_HOME"] = DefaultCodexHomeDirectory();
155
+ environment[@"CODEX_HOME"] = codexHome.length > 0 ? codexHome : DefaultCodexHomeDirectory();
155
156
  return environment;
156
157
  }
157
158
 
@@ -164,17 +165,23 @@ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString
164
165
  @property NSInteger nextRequestID;
165
166
  @property NSInteger pendingRequestID;
166
167
  @property BOOL stopped;
168
+ @property(copy) NSString *codexHome;
167
169
  @end
168
170
 
169
171
  @implementation CCPetsCodexRateLimitsReader
170
172
 
171
173
  - (instancetype)init {
174
+ return [self initWithCodexHome:DefaultCodexHomeDirectory()];
175
+ }
176
+
177
+ - (instancetype)initWithCodexHome:(NSString *)codexHome {
172
178
  if ((self = [super init])) {
173
179
  _queue = dispatch_queue_create("com.universewang.cc-pets.codex-rate-limits",
174
180
  DISPATCH_QUEUE_SERIAL);
175
181
  dispatch_queue_set_specific(_queue, &CodexRateLimitsQueueKey, (__bridge void *)self, NULL);
176
182
  _partialOutput = [NSMutableData data];
177
183
  _nextRequestID = 2; // 1 留给 initialize。
184
+ _codexHome = [codexHome.stringByStandardizingPath copy];
178
185
  }
179
186
  return self;
180
187
  }
@@ -220,7 +227,7 @@ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString
220
227
  NSPipe *outputPipe = [NSPipe pipe];
221
228
  task.executableURL = [NSURL fileURLWithPath:path];
222
229
  task.arguments = @[@"app-server", @"--stdio"];
223
- task.environment = CodexAppServerEnvironment(path);
230
+ task.environment = CodexAppServerEnvironment(path, self.codexHome);
224
231
  task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
225
232
  task.standardInput = inputPipe;
226
233
  task.standardOutput = outputPipe;
@@ -6,3 +6,6 @@ NSDictionary *QuotaHistoryDocument(void);
6
6
  NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage);
7
7
  // 每个点保留 timestamp 与 weekRemaining,绘图层才能按真实时间轴展示缺口和重置。
8
8
  NSArray<NSDictionary *> *QuotaHistorySeries(NSDictionary *document, NSString *provider);
9
+ NSDictionary *RecordProfileQuotaHistory(NSDictionary<NSString *, NSDictionary *> *profileUsages,
10
+ NSArray<NSDictionary *> *profiles);
11
+ NSArray<NSDictionary *> *QuotaHistorySeriesForProfile(NSDictionary *document, NSString *profileID);
@@ -97,3 +97,61 @@ NSArray<NSDictionary *> *QuotaHistorySeries(NSDictionary *document, NSString *pr
97
97
  }
98
98
  return series;
99
99
  }
100
+
101
+ NSDictionary *RecordProfileQuotaHistory(NSDictionary<NSString *, NSDictionary *> *profileUsages,
102
+ NSArray<NSDictionary *> *profiles) {
103
+ if (profileUsages.count == 0 || profiles.count == 0) return QuotaHistoryDocument();
104
+ NSDictionary *document = QuotaHistoryDocument();
105
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
106
+ NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
107
+ NSMutableArray *samples = [NSMutableArray array];
108
+ for (NSDictionary *sample in document[@"samples"]) {
109
+ if ([sample isKindOfClass:NSDictionary.class] && [sample[@"timestamp"] doubleValue] >= cutoff) {
110
+ [samples addObject:[sample mutableCopy]];
111
+ }
112
+ }
113
+ NSMutableDictionary *profileSamples = [NSMutableDictionary dictionary];
114
+ for (NSDictionary *profile in profiles) {
115
+ NSString *profileID = profile[@"id"];
116
+ NSDictionary *usage = profileUsages[profileID];
117
+ NSString *usedKey = [profile[@"provider"] isEqualToString:@"codex"]
118
+ ? @"used_percent" : @"used_percentage";
119
+ NSDictionary *sample = HistoryProviderSample(usage, usedKey);
120
+ if (profileID.length > 0 && sample.count > 0) profileSamples[profileID] = sample;
121
+ }
122
+ if (profileSamples.count == 0) return document;
123
+ NSMutableDictionary *last = [samples.lastObject isKindOfClass:NSDictionary.class]
124
+ ? [samples.lastObject mutableCopy] : nil;
125
+ if (last && now - [last[@"timestamp"] doubleValue] < 15 * 60) {
126
+ NSMutableDictionary *merged = [last[@"profiles"] isKindOfClass:NSDictionary.class]
127
+ ? [last[@"profiles"] mutableCopy] : [NSMutableDictionary dictionary];
128
+ [merged addEntriesFromDictionary:profileSamples];
129
+ last[@"profiles"] = merged;
130
+ samples[samples.count - 1] = last;
131
+ } else {
132
+ [samples addObject:[@{@"timestamp": @(now), @"profiles": profileSamples} mutableCopy]];
133
+ }
134
+ if (samples.count > 672) [samples removeObjectsInRange:NSMakeRange(0, samples.count - 672)];
135
+ NSDictionary *updated = @{@"schemaVersion": @1, @"samples": samples};
136
+ NSData *json = [NSJSONSerialization dataWithJSONObject:updated options:NSJSONWritingPrettyPrinted error:nil];
137
+ if ([json writeToFile:QuotaHistoryPath() options:NSDataWritingAtomic error:nil]) {
138
+ chmod(QuotaHistoryPath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
139
+ }
140
+ return updated;
141
+ }
142
+
143
+ NSArray<NSDictionary *> *QuotaHistorySeriesForProfile(NSDictionary *document, NSString *profileID) {
144
+ NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
145
+ for (NSDictionary *sample in document[@"samples"]) {
146
+ NSDictionary *profiles = [sample[@"profiles"] isKindOfClass:NSDictionary.class]
147
+ ? sample[@"profiles"] : nil;
148
+ NSDictionary *profile = [profiles[profileID] isKindOfClass:NSDictionary.class]
149
+ ? profiles[profileID] : nil;
150
+ NSNumber *timestamp = [sample[@"timestamp"] isKindOfClass:NSNumber.class]
151
+ ? sample[@"timestamp"] : nil;
152
+ NSNumber *remaining = [profile[@"weekRemaining"] isKindOfClass:NSNumber.class]
153
+ ? profile[@"weekRemaining"] : nil;
154
+ if (timestamp && remaining) [series addObject:@{@"timestamp": timestamp, @"remaining": remaining}];
155
+ }
156
+ return series;
157
+ }
@@ -0,0 +1,436 @@
1
+ #import "CCPetsUsage+Internal.h"
2
+ #import "CCPetsPaths.h"
3
+
4
+ // MARK: - Claude Code 本地 Token 统计
5
+ //
6
+ // 数据源是 ~/.claude/projects/<编码后的 cwd>/<session-uuid>.jsonl,以及同级的
7
+ // <session-uuid>/subagents/agent-*.jsonl(子 agent 的转录,见 RecentClaudeTranscriptURLs)。
8
+ // 每条 type=assistant 的行带 timestamp 和 message.usage,是**单次请求的增量**,
9
+ // 与 Codex 的会话累计值不同,因此必须逐条落窗口累加,不能取末行。
10
+ //
11
+ // 关键差异:Claude 的 --resume / fork / compact 会把旧行原样复制进新文件,本机实测
12
+ // 5575 行里有 692 行重复(12%)。不去重的话 7 天用量会虚高一成以上,所以按
13
+ // message.id + requestId 做全局去重(两者缺失时回退 uuid)。同一次请求还会被拆成多行、
14
+ // 各带一份递增的 usage 快照,所以去重是**逐字段取最大值合并**而不是丢弃后续行,
15
+ // 详见 ClaudeTokenTotals。
16
+
17
+ // 记录缓存条目的版本。2 起记录多了 model 字段,结构体变长,旧条目按旧步长存的,
18
+ // 不能当新的读——版本对不上就整篇重来。
19
+ static const NSInteger ClaudeRecordCacheVersion = 2;
20
+ // 缓存里的保留键:模型名表。键不是路径,清理失效路径时要跳过它。
21
+ static NSString *const ClaudeModelTableKey = @"~models";
22
+ static const uint32_t ClaudeUnknownModel = UINT32_MAX;
23
+
24
+ // 模型名表只增不减,下标一旦发出去就不能变(记录里存的就是下标)。
25
+ NSArray<NSString *> *ClaudeModelNames(NSDictionary *cache) {
26
+ NSDictionary *table = [cache[ClaudeModelTableKey] isKindOfClass:NSDictionary.class]
27
+ ? cache[ClaudeModelTableKey] : nil;
28
+ return [table[@"names"] isKindOfClass:NSArray.class] ? table[@"names"] : @[];
29
+ }
30
+
31
+ // 清掉已经不在扫描范围里的文件条目。模型名表不是路径,必须留着:删了它,已有记录里存的
32
+ // 下标就对不上名字了。
33
+ void PruneClaudeRecordCache(NSMutableDictionary *cache, NSSet<NSString *> *livePaths) {
34
+ for (NSString *path in cache.allKeys) {
35
+ if ([path isEqualToString:ClaudeModelTableKey]) continue;
36
+ if (![livePaths containsObject:path]) [cache removeObjectForKey:path];
37
+ }
38
+ }
39
+
40
+ static uint32_t ClaudeModelIndex(NSMutableDictionary *cache, NSString *model) {
41
+ if (model.length == 0) return ClaudeUnknownModel;
42
+ NSArray<NSString *> *names = ClaudeModelNames(cache);
43
+ NSUInteger index = [names indexOfObject:model];
44
+ if (index != NSNotFound) return (uint32_t)index;
45
+ // 换成不可变副本再存:落盘读回的容器可变性不可靠(见 MakeCachedRecordsMutable 的注释)。
46
+ cache[ClaudeModelTableKey] = @{@"names": [names arrayByAddingObject:model]};
47
+ return (uint32_t)names.count;
48
+ }
49
+
50
+ // 去重键存 64 位散列而不是原字符串:近 7 天约 5.5k 条记录,散列后每条 56 字节(含模型下标)、
51
+ // 常驻约 300KB;64 位空间下这个量级的碰撞概率约 1e-12,可以忽略。用量页另有一份 90 天的
52
+ // 记录缓存(claude-models),大小随天数大致线性增长,同量级下是这份的十几倍。
53
+ static uint64_t ClaudeIdentityHash(NSString *first, NSString *second) {
54
+ uint64_t hash = 1469598103934665603ULL;
55
+ for (NSString *part in @[first ?: @"", @"\n", second ?: @""]) {
56
+ const char *bytes = part.UTF8String;
57
+ for (const char *cursor = bytes; cursor && *cursor; cursor++) {
58
+ hash ^= (uint64_t)(unsigned char)*cursor;
59
+ hash *= 1099511628211ULL;
60
+ }
61
+ }
62
+ return hash;
63
+ }
64
+
65
+ static unsigned long long ClaudeCount(NSDictionary *usage, NSString *key) {
66
+ NSNumber *number = [usage[key] isKindOfClass:NSNumber.class] ? usage[key] : nil;
67
+ return number.unsignedLongLongValue;
68
+ }
69
+
70
+ // message.usage 的顶层就是该次请求的聚合值,内层 iterations 是明细,不能再加一遍。
71
+ static BOOL ClaudeRecordFromLine(NSData *lineData, ClaudeTokenRecord *record, NSString **outModel) {
72
+ if (lineData.length == 0) return NO;
73
+ static NSData *marker;
74
+ static dispatch_once_t once;
75
+ dispatch_once(&once, ^{
76
+ marker = [@"\"type\":\"assistant\"" dataUsingEncoding:NSUTF8StringEncoding];
77
+ });
78
+ if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
79
+ NSNotFound) return NO;
80
+ id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
81
+ if (![rootValue isKindOfClass:NSDictionary.class]) return NO;
82
+ NSDictionary *root = rootValue;
83
+ if (![root[@"type"] isKindOfClass:NSString.class] ||
84
+ ![root[@"type"] isEqualToString:@"assistant"]) return NO;
85
+ NSDictionary *message = [root[@"message"] isKindOfClass:NSDictionary.class]
86
+ ? root[@"message"] : nil;
87
+ NSDictionary *usage = [message[@"usage"] isKindOfClass:NSDictionary.class]
88
+ ? message[@"usage"] : nil;
89
+ NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
90
+ if (!usage || !date) return NO;
91
+
92
+ NSString *identifier = [message[@"id"] isKindOfClass:NSString.class] ? message[@"id"] : nil;
93
+ NSString *requestIdentifier = [root[@"requestId"] isKindOfClass:NSString.class]
94
+ ? root[@"requestId"] : nil;
95
+ // 本机实测 3112 行里有 17 行缺 id 或 requestId,回退到行级 uuid 保证仍能去重。
96
+ NSString *fallback = [root[@"uuid"] isKindOfClass:NSString.class] ? root[@"uuid"] : nil;
97
+ record->timestamp = date.timeIntervalSince1970;
98
+ record->identity = (identifier && requestIdentifier)
99
+ ? ClaudeIdentityHash(identifier, requestIdentifier)
100
+ : ClaudeIdentityHash(fallback, nil);
101
+ record->input = ClaudeCount(usage, @"input_tokens");
102
+ record->output = ClaudeCount(usage, @"output_tokens");
103
+ record->cacheRead = ClaudeCount(usage, @"cache_read_input_tokens");
104
+ record->cacheWrite = ClaudeCount(usage, @"cache_creation_input_tokens");
105
+ if (outModel) *outModel = [message[@"model"] isKindOfClass:NSString.class] ? message[@"model"] : nil;
106
+ return YES;
107
+ }
108
+
109
+ // 收集目录内 mtime 落在窗口内的 .jsonl;顺带把子目录交给调用方(传 nil 表示不关心),
110
+ // 省一次 readdir。
111
+ static void AppendRecentTranscriptsInDirectory(NSURL *directory, NSTimeInterval earliest,
112
+ NSMutableArray<NSURL *> *urls, NSMutableArray<NSURL *> *outSubdirectories) {
113
+ NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey,
114
+ NSURLIsDirectoryKey];
115
+ NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
116
+ includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
117
+ for (NSURL *url in contents) {
118
+ NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
119
+ if ([values[NSURLIsDirectoryKey] boolValue]) {
120
+ [outSubdirectories addObject:url];
121
+ continue;
122
+ }
123
+ if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
124
+ if (![values[NSURLIsRegularFileKey] boolValue]) continue;
125
+ NSDate *modified = values[NSURLContentModificationDateKey];
126
+ if (modified && modified.timeIntervalSince1970 < earliest) continue;
127
+ [urls addObject:url];
128
+ }
129
+ }
130
+
131
+ // 只看 mtime 落在窗口内的转录文件。本机 76 个文件里近 7 天只有 44 个,目录遍历约 3ms。
132
+ //
133
+ // 子 agent(Task/Explore)的转录不写进主会话文件,而是单独落在
134
+ // <project>/<session-uuid>/subagents/agent-*.jsonl,只扫项目目录一层的话它们一条都进不来
135
+ // ——本机主会话文件里 isSidechain 的行数为 0,漏掉的就是全部子 agent 用量(历史上单个
136
+ // 文件到过 269 万 token)。
137
+ //
138
+ // 下钻哪些会话由主会话文件 <session-uuid>.jsonl 的 mtime 决定:Task 的调用和结果都会写进
139
+ // 主会话文件,主文件不在窗口内,它的子 agent 也不可能在。projects/ 目录只增不减(本机
140
+ // 99 个会话里近 8 天只有 27 个),无条件下钻等于给每个历史会话都白跑一次 readdir,而且
141
+ // 多数子目录压根不是 subagents(本机 13 个里 7 个是 tool-results/memory)。
142
+ // 不能改用 <session-uuid>/ 目录自身的 mtime 剪枝:目录 mtime 只在直接子项增删时更新,
143
+ // 往已有 agent-*.jsonl 追加写不会动它,正在跑的长任务会被剪掉。
144
+ // earliest 的口径与 RecentCodexSessionURLs 一致,由调用方按展示模式和归档状态算好。
145
+ NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL,
146
+ NSTimeInterval earliest) {
147
+ NSArray<NSURL *> *projects = [NSFileManager.defaultManager contentsOfDirectoryAtURL:projectsURL
148
+ includingPropertiesForKeys:@[NSURLIsDirectoryKey]
149
+ options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
150
+ NSMutableArray<NSURL *> *urls = [NSMutableArray array];
151
+ for (NSURL *project in projects) {
152
+ NSNumber *isDirectory = nil;
153
+ if (![project getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
154
+ if (!isDirectory.boolValue) continue;
155
+ NSMutableArray<NSURL *> *sessions = [NSMutableArray array];
156
+ NSUInteger firstIndex = urls.count;
157
+ AppendRecentTranscriptsInDirectory(project, earliest, urls, sessions);
158
+ NSMutableSet<NSString *> *activeSessions = [NSMutableSet set];
159
+ for (NSUInteger index = firstIndex; index < urls.count; index++) {
160
+ [activeSessions addObject:urls[index].URLByDeletingPathExtension.lastPathComponent];
161
+ }
162
+ for (NSURL *session in sessions) {
163
+ if (![activeSessions containsObject:session.lastPathComponent]) continue;
164
+ AppendRecentTranscriptsInDirectory(
165
+ [session URLByAppendingPathComponent:@"subagents" isDirectory:YES],
166
+ earliest, urls, nil);
167
+ }
168
+ }
169
+ return urls;
170
+ }
171
+
172
+ // 转录文件只追加(fork 走新文件),因此按 offset 追读即可,活跃会话每轮只解析新增字节。
173
+ NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache) {
174
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path
175
+ error:nil];
176
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
177
+ NSDictionary *cached = cache[url.path];
178
+ if (cached && [cached[@"v"] integerValue] != ClaudeRecordCacheVersion) cached = nil;
179
+ unsigned long long offset = [cached[@"offset"] unsignedLongLongValue];
180
+ // 这里可以直接原地追加:可变性由 MakeCachedRecordsMutable 在缓存读回时统一保证。
181
+ // 不要退回成 isKindOfClass:NSMutableData 判断——NSData 是类簇,落盘缓存解析出的
182
+ // 不可变 __NSCFData 对它同样返回 YES,据此原地 appendBytes 会写出界。详见该函数注释。
183
+ NSMutableData *records = [cached[@"records"] isKindOfClass:NSData.class]
184
+ ? (NSMutableData *)cached[@"records"] : nil;
185
+ if (!records || offset > size) {
186
+ // 首次读取,或文件被改写导致偏移失效,整篇重来。
187
+ offset = 0;
188
+ records = [NSMutableData data];
189
+ }
190
+ if (cached && offset == size) {
191
+ // 正常情况下 records 就是缓存里那一份,不必回写;只有上面因偏移失效重建过
192
+ // (文件被清空到 0 字节)才是新对象,这时写回去,免得下一轮又重建一遍。
193
+ if (records != cached[@"records"]) {
194
+ cache[url.path] = @{@"offset": @(offset), @"records": records,
195
+ @"v": @(ClaudeRecordCacheVersion)};
196
+ }
197
+ return records;
198
+ }
199
+
200
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
201
+ if (!handle) return records;
202
+ [handle seekToFileOffset:offset];
203
+ NSData *fresh = [handle readDataToEndOfFile];
204
+ [handle closeFile];
205
+
206
+ const uint8_t *bytes = fresh.bytes;
207
+ NSUInteger lineStart = 0;
208
+ NSUInteger consumed = 0;
209
+ for (NSUInteger index = 0; index < fresh.length; index++) {
210
+ if (bytes[index] != '\n') continue;
211
+ ClaudeTokenRecord record = {0};
212
+ NSString *model = nil;
213
+ if (index > lineStart && ClaudeRecordFromLine(
214
+ [fresh subdataWithRange:NSMakeRange(lineStart, index - lineStart)], &record, &model) &&
215
+ // <synthetic> 之类的占位模型是本地注入的消息,没有真实用量,不进统计。
216
+ !(model.length > 0 && IsPseudoModelName(model))) {
217
+ record.model = ClaudeModelIndex(cache, model);
218
+ [records appendBytes:&record length:sizeof(record)];
219
+ }
220
+ lineStart = index + 1;
221
+ consumed = lineStart;
222
+ }
223
+ // 只推进到最后一个换行符,未写完的尾行留到下一轮,避免把半行当成坏数据丢掉。
224
+ cache[url.path] = @{@"offset": @(offset + consumed), @"records": records,
225
+ @"v": @(ClaudeRecordCacheVersion)};
226
+ return records;
227
+ }
228
+
229
+ // 同一次请求会被拆成多行写入(thinking / text / tool_use 各一行),每行都带一份 usage
230
+ // 快照,而这些快照是**递增的**:本机实测有 14 组末行的 output_tokens 远大于首行
231
+ // (6→235、3→1870),首行取到的是流式过程中的中间值。因此同 identity 的多行必须逐字段
232
+ // 取最大值合并,只保留第一条会少算——全量口径下少算 16060 个 output token。
233
+ // 取 max 而不是"取最后一行":fork/resume 会把旧行复制进新文件,跨文件的行序没有保证。
234
+ NSData *ClaudeMergedRecords(NSArray<NSData *> *recordSets, NSTimeInterval start,
235
+ NSTimeInterval end) {
236
+ NSMutableDictionary<NSNumber *, NSNumber *> *slots = [NSMutableDictionary dictionary];
237
+ NSMutableData *merged = [NSMutableData data];
238
+ for (NSData *data in recordSets) {
239
+ const ClaudeTokenRecord *records = data.bytes;
240
+ NSUInteger count = data.length / sizeof(ClaudeTokenRecord);
241
+ for (NSUInteger index = 0; index < count; index++) {
242
+ const ClaudeTokenRecord *record = &records[index];
243
+ if (record->timestamp < start || record->timestamp >= end) continue;
244
+ NSNumber *identity = @(record->identity);
245
+ NSNumber *slot = slots[identity];
246
+ if (!slot) {
247
+ slots[identity] = @(merged.length / sizeof(ClaudeTokenRecord));
248
+ [merged appendBytes:record length:sizeof(*record)];
249
+ continue;
250
+ }
251
+ // append 可能搬动缓冲区,基址每次重新取。
252
+ ClaudeTokenRecord *target =
253
+ (ClaudeTokenRecord *)merged.mutableBytes + slot.unsignedIntegerValue;
254
+ target->input = MAX(target->input, record->input);
255
+ target->output = MAX(target->output, record->output);
256
+ target->cacheRead = MAX(target->cacheRead, record->cacheRead);
257
+ target->cacheWrite = MAX(target->cacheWrite, record->cacheWrite);
258
+ // 同一次请求只可能是一个模型;先出现的行没带 model(unknown)时,用后面带的补上。
259
+ if (target->model == ClaudeUnknownModel) target->model = record->model;
260
+ }
261
+ }
262
+ return merged;
263
+ }
264
+
265
+ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInterval start,
266
+ NSTimeInterval end) {
267
+ NSData *merged = ClaudeMergedRecords(recordSets, start, end);
268
+ unsigned long long input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
269
+ const ClaudeTokenRecord *unique = merged.bytes;
270
+ for (NSUInteger index = 0; index < merged.length / sizeof(ClaudeTokenRecord); index++) {
271
+ input += unique[index].input;
272
+ output += unique[index].output;
273
+ cacheRead += unique[index].cacheRead;
274
+ cacheWrite += unique[index].cacheWrite;
275
+ }
276
+ // 不输出 reasoning_output_tokens:Claude 的思考 token 已经计入 output_tokens,
277
+ // 单列一个恒为 0 的字段会让人误以为没统计。
278
+ return @{
279
+ @"input_tokens": @(input),
280
+ @"cached_input_tokens": @(cacheRead),
281
+ @"cache_write_input_tokens": @(cacheWrite),
282
+ @"output_tokens": @(output),
283
+ @"total_tokens": @(input + output + cacheRead + cacheWrite),
284
+ @"request_count": @(merged.length / sizeof(ClaudeTokenRecord))
285
+ };
286
+ }
287
+
288
+ static NSArray<NSDictionary *> *ClaudeDailyTokenSeries(NSArray<NSData *> *recordSets,
289
+ NSTimeInterval start, NSTimeInterval end) {
290
+ NSCalendar *calendar = NSCalendar.currentCalendar;
291
+ NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
292
+ NSDate *cursor = [NSDate dateWithTimeIntervalSince1970:start];
293
+ while (cursor.timeIntervalSince1970 < end) {
294
+ NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
295
+ if (!next) break;
296
+ NSTimeInterval bucketEnd = fmin(end, next.timeIntervalSince1970);
297
+ [series addObject:@{ @"timestamp": @(cursor.timeIntervalSince1970),
298
+ @"totals": ClaudeTokenTotals(recordSets, cursor.timeIntervalSince1970, bucketEnd) }];
299
+ cursor = next;
300
+ }
301
+ return series;
302
+ }
303
+
304
+ @interface ClaudeUsageReader ()
305
+ @property NSString *configDirectory;
306
+ @property NSMutableDictionary *recordCache;
307
+ @property NSString *recordCachePath;
308
+ @property NSTimeInterval recordCacheSavedAt;
309
+ @property NSMutableDictionary *monthlyArchive;
310
+ @property NSString *monthlyArchivePath;
311
+ @property NSDictionary *tokenUsage;
312
+ @property NSString *tokenWindowIdentity;
313
+ @property NSTimeInterval tokenComputedAt;
314
+ @property BOOL forcesTokenAggregation;
315
+ @end
316
+
317
+ @implementation ClaudeUsageReader
318
+ - (instancetype)init {
319
+ return [self initWithConfigDirectory:DefaultClaudeConfigDirectory()];
320
+ }
321
+ - (instancetype)initWithConfigDirectory:(NSString *)configDirectory {
322
+ if ((self = [super init])) {
323
+ _configDirectory = configDirectory.stringByStandardizingPath;
324
+ _projectsURL = [NSURL fileURLWithPath:[_configDirectory stringByAppendingPathComponent:@"projects"]];
325
+ _recordCachePath = TokenSummaryCachePath(@"claude", _projectsURL.path);
326
+ _recordCache = LoadTokenSummaryCache(_recordCachePath);
327
+ MakeCachedRecordsMutable(_recordCache);
328
+ _monthlyArchivePath = MonthlyUsageArchivePath(@"claude", _projectsURL.path);
329
+ _monthlyArchive = LoadTokenSummaryCache(_monthlyArchivePath);
330
+ }
331
+ return self;
332
+ }
333
+ - (NSDictionary *)aggregateForLimits:(NSDictionary *)limits {
334
+ NSDictionary *five = [limits[@"fiveHour"] isKindOfClass:NSDictionary.class]
335
+ ? limits[@"fiveHour"] : nil;
336
+ NSDictionary *week = [limits[@"week"] isKindOfClass:NSDictionary.class] ? limits[@"week"] : nil;
337
+ NSTimeInterval fiveStart = 0, fiveEnd = 0, weekStart = 0, weekEnd = 0;
338
+ // Claude 的 rate_limits 没有 window_minutes,窗长按官方订阅固定为 5 小时 / 7 天。
339
+ // 窗口不可用时退化成滚动窗口,Token 是本机数据,不跟着官方额度一起变成 `--`。
340
+ TokenWindowOrFallback(five, FiveHourWindowMinutes, &fiveStart, &fiveEnd);
341
+ TokenWindowOrFallback(week, SevenDayWindowMinutes, &weekStart, &weekEnd);
342
+ // 自然日窗口和额度无关,即使两个额度窗口都不可用也照样统计。
343
+ BOOL apiMode = ProfileShowsAPIUsage(@"claude", self.configDirectory);
344
+ NSDictionary *monthWindows = CalendarMonthWindows(0);
345
+ NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
346
+ NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
347
+ NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
348
+ NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
349
+ NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
350
+ NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
351
+ NSArray<NSDictionary *> *archivedDaily = apiMode &&
352
+ [self.monthlyArchive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
353
+ ? self.monthlyArchive[previousMonthKey][@"daily"] : nil;
354
+ // 与 Codex 侧同一套:上月归档好了就只读本月的转录,没归档才放宽一次把归档建出来。
355
+ BOOL buildsArchive = apiMode && !archivedDaily;
356
+ NSTimeInterval earliest = buildsArchive ? previousMonthStart
357
+ : (apiMode ? fmin(monthStart, RollingTokenWindowFloor()) : RollingTokenWindowFloor());
358
+ NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL, earliest);
359
+ NSMutableArray<NSData *> *recordSets = [NSMutableArray arrayWithCapacity:urls.count];
360
+ NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
361
+ for (NSURL *url in urls) {
362
+ [livePaths addObject:url.path];
363
+ NSData *records = ClaudeRecordsForFile(url, self.recordCache);
364
+ if (records.length > 0) [recordSets addObject:records];
365
+ }
366
+ PruneClaudeRecordCache(self.recordCache, livePaths);
367
+ NSTimeInterval savedAt = NSDate.date.timeIntervalSince1970;
368
+ if (self.persistsCache && savedAt - self.recordCacheSavedAt >= TokenCacheSaveInterval) {
369
+ self.recordCacheSavedAt = savedAt;
370
+ SaveTokenSummaryCache(self.recordCache, self.recordCachePath);
371
+ }
372
+ NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
373
+ RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
374
+ // 与 Codex 侧同理:订阅视图下转录只回溯 8 天,月度口径既算不准也没人看。
375
+ // 曲线同样铺满整个自然月,末尾没到的日子是 0。
376
+ NSArray<NSDictionary *> *monthDaily = apiMode
377
+ ? ClaudeDailyTokenSeries(recordSets, monthStart, monthCurveEnd) : @[];
378
+ if (buildsArchive) {
379
+ NSArray *previousDaily = ClaudeDailyTokenSeries(recordSets, previousMonthStart, monthStart);
380
+ self.monthlyArchive[previousMonthKey] = @{ @"daily": previousDaily,
381
+ @"totals": SummedDailyTokenSeries(previousDaily) };
382
+ archivedDaily = previousDaily;
383
+ PruneMonthlyArchive(self.monthlyArchive);
384
+ if (self.persistsCache) {
385
+ SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
386
+ }
387
+ }
388
+ return @{
389
+ @"fiveHour": ClaudeTokenTotals(recordSets, fiveStart, fiveEnd),
390
+ @"week": ClaudeTokenTotals(recordSets, weekStart, weekEnd),
391
+ @"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
392
+ @"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
393
+ @"recentWeekStartsAt": @(rollingWeekStart),
394
+ @"month": apiMode ? SummedDailyTokenSeries(monthDaily) : NSNull.null,
395
+ @"monthComparable": apiMode
396
+ ? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd)
397
+ : NSNull.null,
398
+ @"previousMonthToDate": archivedDaily
399
+ ? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd)
400
+ : NSNull.null,
401
+ @"monthDaily": monthDaily,
402
+ @"monthStartsAt": @(monthStart),
403
+ @"monthComparableEndsAt": @(monthComparableEnd),
404
+ @"previousMonthComparableEndsAt": @(previousMonthEnd),
405
+ @"source": @"local"
406
+ };
407
+ }
408
+ - (NSDictionary *)refresh {
409
+ // 额度快照是 statusline hook 写出来的(见 RecordClaudeUsage):第三方 statusline 注入不
410
+ // 进去、或者账号本身(API key / Bedrock / Vertex)就不带 rate_limits 时,这份文件永远
411
+ // 不存在。而 Token 是本机从转录里数出来的,跟官方额度没有半点关系,不能被它一票否决
412
+ // ——原先这里直接 return nil,面板上 Claude 整行(百分比、已用 Token、今日输入输出)
413
+ // 全是 `--`,看起来像统计坏了。缺额度时百分比照样 `--`,用量正常显示。
414
+ NSDictionary *limits = ClaudeRateLimitsForConfigDirectory(self.configDirectory) ?:
415
+ @{@"fiveHour": NSNull.null, @"week": NSNull.null};
416
+ NSString *identity = [NSString stringWithFormat:@"%@:%d", TokenWindowIdentity(limits),
417
+ ProfileShowsAPIUsage(@"claude", self.configDirectory)];
418
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
419
+ BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
420
+ [identity isEqualToString:self.tokenWindowIdentity] &&
421
+ now - self.tokenComputedAt < TokenAggregationInterval;
422
+ if (!reusable) {
423
+ self.tokenUsage = [self aggregateForLimits:limits];
424
+ self.tokenWindowIdentity = identity;
425
+ self.tokenComputedAt = now;
426
+ self.forcesTokenAggregation = NO;
427
+ }
428
+ NSMutableDictionary *usage = [limits mutableCopy];
429
+ usage[@"tokenUsage"] = self.tokenUsage;
430
+ return usage;
431
+ }
432
+ - (NSDictionary *)refreshWithFullAggregation {
433
+ self.forcesTokenAggregation = YES;
434
+ return [self refresh];
435
+ }
436
+ @end