cc-pets 2.2.0 → 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 (173) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +85 -0
  4. package/CHANGELOG.zh-CN.md +85 -0
  5. package/CONTRIBUTING.md +28 -11
  6. package/CONTRIBUTING.zh-CN.md +23 -11
  7. package/README.md +127 -27
  8. package/README.zh-CN.md +104 -30
  9. package/Resources/zh-Hans.lproj/Localizable.strings +573 -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} +89 -31
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +18 -4
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +90 -21
  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/App/CCPetsAppDelegate+Settings.m +269 -0
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +13 -7
  19. package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +71 -47
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +16 -2
  22. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +110 -12
  23. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  24. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  25. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  26. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  27. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  37. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  39. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  43. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  44. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  45. package/Sources/CCPets/Pet/CCPetsImageLoader.h +5 -0
  46. package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +10 -2
  47. package/Sources/CCPets/Pet/CCPetsPetSize.h +10 -0
  48. package/Sources/CCPets/Pet/CCPetsPetSize.m +21 -0
  49. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  50. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  51. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +18 -2
  52. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +53 -22
  53. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +42 -2
  54. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  55. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  56. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  57. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  58. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  59. package/Sources/CCPets/Pet/PetView.m +635 -0
  60. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  61. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  62. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  63. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  64. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  65. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  67. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  68. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  69. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  70. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  71. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  72. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  73. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  74. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  75. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  76. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  77. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  78. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  79. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  80. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  81. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  82. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  83. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  84. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  85. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  86. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  87. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  88. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  89. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  90. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  91. package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +3 -0
  92. package/Sources/CCPets/UI/MenuPetSizeView.h +5 -0
  93. package/Sources/CCPets/UI/MenuPetSizeView.m +73 -0
  94. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  95. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  96. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  97. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  98. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  99. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  100. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  101. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  102. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  103. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  104. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  105. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  106. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  107. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  108. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  109. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  110. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  111. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  112. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  113. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  114. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  115. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  116. package/THIRD_PARTY_NOTICES.md +1 -1
  117. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  118. package/bin/cc-pets +8 -6
  119. package/bin/claude-with-pet +10 -2
  120. package/bin/codex-with-pet +13 -5
  121. package/package.json +1 -1
  122. package/scripts/build.sh +7 -3
  123. package/scripts/i18n.zsh +9 -52
  124. package/scripts/install-app.sh +4 -0
  125. package/scripts/install-shell-integration.sh +17 -10
  126. package/scripts/uninstall-shell-integration.sh +6 -1
  127. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +0 -226
  128. package/Sources/CCPets/CCPetsEvents.h +0 -10
  129. package/Sources/CCPets/CCPetsImageLoader.h +0 -4
  130. package/Sources/CCPets/CCPetsUsage.h +0 -36
  131. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  132. package/Sources/CCPets/PetView.m +0 -1806
  133. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  134. package/scripts/bridge/cli.mjs +0 -237
  135. package/scripts/bridge/core.mjs +0 -228
  136. package/scripts/bridge/hook.mjs +0 -150
  137. package/scripts/bridge/install.mjs +0 -311
  138. package/scripts/bridge/mcp-server.mjs +0 -308
  139. package/scripts/bridge/options.mjs +0 -87
  140. package/scripts/bridge/process.mjs +0 -151
  141. package/scripts/bridge/reservations.mjs +0 -248
  142. package/scripts/bridge/store.mjs +0 -433
  143. package/scripts/bridge/watch.mjs +0 -69
  144. package/scripts/check-l10n.mjs +0 -168
  145. package/scripts/configure-updater.mjs +0 -43
  146. package/scripts/detect-cli.mjs +0 -68
  147. package/scripts/doctor.mjs +0 -470
  148. package/scripts/i18n.mjs +0 -122
  149. package/scripts/install-claude-hooks.mjs +0 -253
  150. package/scripts/install-codex-hooks.mjs +0 -78
  151. package/scripts/integration-markers.mjs +0 -51
  152. package/scripts/locales/zh-Hans.json +0 -366
  153. package/scripts/pet-store.mjs +0 -415
  154. package/scripts/uninstall-integrations.mjs +0 -205
  155. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  156. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  157. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  159. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  161. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  162. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  163. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  164. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  165. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  166. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  167. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  168. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  169. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  170. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  171. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  172. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  173. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,484 @@
1
+ #import "CCPetsUsage+Internal.h"
2
+ #import "CCPetsProfiles.h"
3
+ #import "CCPetsUsageMode.h"
4
+
5
+ static BOOL AllDigits(NSString *text) {
6
+ if (text.length == 0) return NO;
7
+ static NSCharacterSet *nonDigits;
8
+ static dispatch_once_t once;
9
+ dispatch_once(&once, ^{
10
+ nonDigits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet;
11
+ });
12
+ return [text rangeOfCharacterFromSet:nonDigits].location == NSNotFound;
13
+ }
14
+
15
+ const NSArray<NSString *> *TokenKeys(void) {
16
+ static NSArray<NSString *> *keys;
17
+ static dispatch_once_t once;
18
+ dispatch_once(&once, ^{
19
+ keys = @[@"input_tokens", @"cached_input_tokens", @"cache_write_input_tokens",
20
+ @"output_tokens", @"reasoning_output_tokens", @"total_tokens"];
21
+ });
22
+ return keys;
23
+ }
24
+
25
+ NSDate *ISO8601Timestamp(NSString *value) {
26
+ if (![value isKindOfClass:NSString.class]) return nil;
27
+ static NSISO8601DateFormatter *formatter;
28
+ static dispatch_once_t once;
29
+ dispatch_once(&once, ^{
30
+ formatter = [NSISO8601DateFormatter new];
31
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime |
32
+ NSISO8601DateFormatWithFractionalSeconds;
33
+ });
34
+ NSDate *date = [formatter dateFromString:value];
35
+ if (date) return date;
36
+ static NSISO8601DateFormatter *fallback;
37
+ static dispatch_once_t fallbackOnce;
38
+ dispatch_once(&fallbackOnce, ^{
39
+ fallback = [NSISO8601DateFormatter new];
40
+ fallback.formatOptions = NSISO8601DateFormatWithInternetDateTime;
41
+ });
42
+ return [fallback dateFromString:value];
43
+ }
44
+
45
+ static NSDictionary *TokenPayloadFromLine(NSData *lineData, NSDictionary **root) {
46
+ if (lineData.length == 0) return nil;
47
+ static NSData *marker;
48
+ static dispatch_once_t once;
49
+ dispatch_once(&once, ^{
50
+ marker = [@"\"type\":\"token_count\"" dataUsingEncoding:NSUTF8StringEncoding];
51
+ });
52
+ if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
53
+ NSNotFound) return nil;
54
+ id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
55
+ if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
56
+ id payloadValue = ((NSDictionary *)rootValue)[@"payload"];
57
+ if (![payloadValue isKindOfClass:NSDictionary.class]) return nil;
58
+ NSDictionary *payload = payloadValue;
59
+ id typeValue = payload[@"type"];
60
+ if (![typeValue isKindOfClass:NSString.class] ||
61
+ ![(NSString *)typeValue isEqualToString:@"token_count"]) return nil;
62
+ if (root) *root = rootValue;
63
+ return payload;
64
+ }
65
+
66
+ static NSDictionary *SanitizedTokenCounts(id value) {
67
+ if (![value isKindOfClass:NSDictionary.class]) return nil;
68
+ NSMutableDictionary *counts = [NSMutableDictionary dictionary];
69
+ for (NSString *key in TokenKeys()) {
70
+ NSNumber *number = [value[key] isKindOfClass:NSNumber.class] ? value[key] : nil;
71
+ if (number) counts[key] = @([number unsignedLongLongValue]);
72
+ }
73
+ return counts.count > 0 ? counts : nil;
74
+ }
75
+
76
+ NSDictionary *TokenRecordFromLine(NSData *lineData) {
77
+ NSDictionary *root = nil;
78
+ NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
79
+ NSDictionary *info = [payload[@"info"] isKindOfClass:NSDictionary.class] ? payload[@"info"] : nil;
80
+ NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
81
+ NSDictionary *last = SanitizedTokenCounts(info[@"last_token_usage"]);
82
+ NSDictionary *total = SanitizedTokenCounts(info[@"total_token_usage"]);
83
+ if (!date || (!last && !total)) return nil;
84
+ NSMutableDictionary *record = [@{@"timestamp": @([date timeIntervalSince1970])} mutableCopy];
85
+ if (last) record[@"last"] = last;
86
+ if (total) record[@"total"] = total;
87
+ return record;
88
+ }
89
+
90
+ // 会话目录是零填充的 YYYY/MM/DD,字典序等于时间序,因此倒序取名字即可,不必 stat。
91
+ static NSArray<NSURL *> *DescendingNumericSubdirectories(NSURL *directory) {
92
+ NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
93
+ includingPropertiesForKeys:@[NSURLIsDirectoryKey]
94
+ options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
95
+ NSMutableArray<NSURL *> *result = [NSMutableArray arrayWithCapacity:contents.count];
96
+ for (NSURL *url in contents) {
97
+ NSNumber *isDirectory = nil;
98
+ if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
99
+ if (!isDirectory.boolValue || !AllDigits(url.lastPathComponent)) continue;
100
+ [result addObject:url];
101
+ }
102
+ [result sortUsingComparator:^NSComparisonResult(NSURL *left, NSURL *right) {
103
+ return [right.lastPathComponent compare:left.lastPathComponent];
104
+ }];
105
+ return result;
106
+ }
107
+
108
+ // 单个目录内 mtime 最新的 .jsonl。文件名格式不是契约,因此文件一律按 mtime 选,
109
+ // 只有日期目录名吃字典序。
110
+ NSURL *NewestSessionFileInDirectory(NSURL *directory, NSDate **outDate) {
111
+ NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
112
+ NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
113
+ includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
114
+ NSURL *newest = nil;
115
+ NSDate *newestDate = NSDate.distantPast;
116
+ for (NSURL *url in contents) {
117
+ if (![url.pathExtension isEqualToString:@"jsonl"]) continue;
118
+ NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
119
+ if (![values[NSURLIsRegularFileKey] boolValue]) continue;
120
+ NSDate *date = values[NSURLContentModificationDateKey] ?: NSDate.distantPast;
121
+ if ([date compare:newestDate] == NSOrderedDescending) {
122
+ newest = url;
123
+ newestDate = date;
124
+ }
125
+ }
126
+ if (outDate) *outDate = newest ? newestDate : nil;
127
+ return newest;
128
+ }
129
+
130
+ static const NSUInteger MinimumExaminedSessionDays = 3;
131
+ static const NSUInteger MaximumExaminedSessionDays = 40;
132
+
133
+ // 按 YYYY/MM/DD 倒序下钻,成本与历史会话总量无关,只与近期活跃度有关。
134
+ // 收手条件必须同时满足“看够 MinimumExaminedSessionDays 个日期目录”和“已经找到过文件”:
135
+ // 只写前者的话,用户闲置数天后冷启动会一无所获,比全量扫描更差。
136
+ NSURL *NewestCodexSessionURL(NSURL *sessionsURL) {
137
+ NSURL *newest = nil;
138
+ NSDate *newestDate = NSDate.distantPast;
139
+ NSUInteger examinedDays = 0;
140
+ for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
141
+ for (NSURL *month in DescendingNumericSubdirectories(year)) {
142
+ for (NSURL *day in DescendingNumericSubdirectories(month)) {
143
+ NSDate *date = nil;
144
+ NSURL *candidate = NewestSessionFileInDirectory(day, &date);
145
+ if (candidate && [date compare:newestDate] == NSOrderedDescending) {
146
+ newest = candidate;
147
+ newestDate = date;
148
+ }
149
+ examinedDays += 1;
150
+ if (examinedDays >= MinimumExaminedSessionDays && newest) return newest;
151
+ if (examinedDays >= MaximumExaminedSessionDays) return newest;
152
+ }
153
+ }
154
+ }
155
+ // 兜底:非 YYYY/MM/DD 布局(例如直接摊在 sessions/ 下)仍然能被发现。
156
+ return newest ?: NewestSessionFileInDirectory(sessionsURL, NULL);
157
+ }
158
+
159
+ // 额度被拒时 Codex 会写一条带 error.codex_error_info = usage_limit_exceeded 的事件。
160
+ // 这是唯一能说明"官方额度现在不给用了"的结构化信号:同一时刻 rate_limits 里
161
+ // primary/secondary 全是 null,光看额度字段只能看到"这行没有数据",于是上一份百分比
162
+ // 会一直挂在面板上——账号被别人用完时,那个数字既过期又正好指向相反的结论。
163
+ NSNumber *ExhaustionTimestampFromLine(NSData *lineData) {
164
+ if (lineData.length == 0) return nil;
165
+ static NSData *marker;
166
+ static dispatch_once_t once;
167
+ dispatch_once(&once, ^{
168
+ marker = [@"usage_limit_exceeded" dataUsingEncoding:NSUTF8StringEncoding];
169
+ });
170
+ if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
171
+ NSNotFound) return nil;
172
+ id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
173
+ if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
174
+ NSDictionary *root = rootValue;
175
+ NSDictionary *payload = [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : nil;
176
+ NSDictionary *error = [payload[@"error"] isKindOfClass:NSDictionary.class] ? payload[@"error"] : nil;
177
+ NSString *info = [error[@"codex_error_info"] isKindOfClass:NSString.class]
178
+ ? error[@"codex_error_info"] : nil;
179
+ if (![info containsString:@"usage_limit"]) return nil;
180
+ NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
181
+ return date ? @(date.timeIntervalSince1970) : nil;
182
+ }
183
+
184
+ NSDictionary *UsageFromCodexLine(NSData *lineData) {
185
+ NSDictionary *root = nil;
186
+ NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
187
+ if (!payload) return nil;
188
+ id limitsValue = payload[@"rate_limits"];
189
+ if (![limitsValue isKindOfClass:NSDictionary.class]) return nil;
190
+ NSDictionary *limits = limitsValue;
191
+ id primaryValue = limits[@"primary"];
192
+ id secondaryValue = limits[@"secondary"];
193
+ NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
194
+ NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
195
+ NSDictionary *fiveHour = nil;
196
+ NSDictionary *week = nil;
197
+ for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
198
+ NSInteger minutes = [quota[@"window_minutes"] integerValue];
199
+ if (minutes == 300) fiveHour = quota;
200
+ if (minutes == 10080) week = quota;
201
+ }
202
+ // primary/secondary 全是 null 的 rate_limits(实测切到 premium/credits 计费后每条都这样)
203
+ // 并不表示额度消失,只是这条响应没带窗口信息。当成"这行没有额度"往前找,
204
+ // 否则上一份仍然有效的窗口会被它整块盖掉,面板退回 `--` + 等待数据。
205
+ if (!fiveHour && !week) return nil;
206
+ // 采样时刻用来和耗尽事件比先后:耗尽之后又拿到新的额度快照,说明额度已经恢复。
207
+ NSDate *sampledAt = ISO8601Timestamp(root[@"timestamp"]);
208
+ return @{
209
+ @"fiveHour": fiveHour ?: NSNull.null,
210
+ @"week": week ?: NSNull.null,
211
+ @"sampledAt": @(sampledAt ? sampledAt.timeIntervalSince1970 : 0)
212
+ };
213
+ }
214
+
215
+ // 受限事件没有窗口归属,只能给它一个有效期:快照里最短窗口的 resets_at 一过,那个窗口
216
+ // 必然已经重置,再挂着"额度受限"就是在声称一件我们已经不知道的事——而受限期间官方常年
217
+ // 只回 primary/secondary 全 null(见 UsageFromCodexLine),等"更新的快照"来推翻可能等不到。
218
+ // 真正用尽的是 7 天窗口时,5 小时窗口重置后仍会被拒,届时会写下新的 usage_limit_exceeded,
219
+ // 标记自己会贴回来。
220
+ BOOL ExhaustionStillHolds(NSDictionary *usage, NSTimeInterval exhaustedAt) {
221
+ if (![usage isKindOfClass:NSDictionary.class] || exhaustedAt <= 0) return NO;
222
+ if (exhaustedAt < [usage[@"sampledAt"] doubleValue]) return NO;
223
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
224
+ NSTimeInterval earliestReset = 0;
225
+ BOOL foundReset = NO;
226
+ BOOL foundQuotaWithoutReset = NO;
227
+ NSDictionary<NSString *, NSNumber *> *windows = @{
228
+ @"fiveHour": @(FiveHourWindowMinutes),
229
+ @"week": @(SevenDayWindowMinutes)
230
+ };
231
+ NSDictionary *expired = [usage[@"expiredWindowResets"] isKindOfClass:NSDictionary.class]
232
+ ? usage[@"expiredWindowResets"] : nil;
233
+ for (NSString *key in windows) {
234
+ NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
235
+ NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
236
+ // 关键是“限额错误发生时”这个 reset 是否还属于当前窗口,而不是它现在是否已过期。
237
+ // 例如错误发生后 5 小时窗口自然重置,标记应当清掉;反过来,数天前就过期的
238
+ // 5 小时快照不能让一条刚发生的错误立即失效。
239
+ if (!quota) {
240
+ // 窗口被 UsageByRemovingInactiveQuotaWindows 清掉了,用它留下的 resets_at 继续
241
+ // 判断。少了这一支,5 小时窗口重置后标记就再也没有失效的依据。
242
+ NSNumber *expiredReset = [expired[key] isKindOfClass:NSNumber.class] ? expired[key] : nil;
243
+ if (!expiredReset) continue;
244
+ foundReset = YES;
245
+ double value = expiredReset.doubleValue;
246
+ if (!ResetLooksCurrentAt(value, windows[key].doubleValue, exhaustedAt)) continue;
247
+ if (earliestReset == 0 || value < earliestReset) earliestReset = value;
248
+ continue;
249
+ }
250
+ if (!reset) {
251
+ foundQuotaWithoutReset = YES;
252
+ continue;
253
+ }
254
+ foundReset = YES;
255
+ if (!QuotaWindowLooksCurrentAt(quota, windows[key].doubleValue, exhaustedAt)) continue;
256
+ double value = reset.doubleValue;
257
+ if (earliestReset == 0 || value < earliestReset) earliestReset = value;
258
+ }
259
+ if (earliestReset > now) return YES;
260
+ // 有一个属于当前窗口的 reset 且它已经过去,说明额度确实重置了,标记必须清掉。
261
+ if (earliestReset > 0) return NO;
262
+ // 走到这里说明一个可用窗口都没有,推不出有效期。这恰恰是最需要受限提示的时刻——
263
+ // 上面注释里说的"受限期间官方常年只回 primary/secondary 全 null"就落在这个分支,
264
+ // app-server 也拿不到实时额度时更是如此。所以刚发生的错误先无条件保留一小段时间,
265
+ // 别让面板在用户正撞限额的当口显示一切正常。
266
+ if (now - exhaustedAt < RecentExhaustionGraceSeconds) return YES;
267
+ // 老版会话只给百分比、没有 resets_at 时无法推断受限状态的有效期;沿用之前的保守
268
+ // 行为,等更新的额度快照来清掉它。只要至少有一个明确的 reset,就以它为准。
269
+ return !foundReset && foundQuotaWithoutReset;
270
+ }
271
+
272
+ // 受限事件仍然成立时,把标记贴到 usage 上。事件本身没有窗口归属,面板只能提示"额度受限"
273
+ // 并把已有百分比标为快照,不能据此把 5 小时和 7 天窗口都判成 0。
274
+ NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterval exhaustedAt) {
275
+ if (![usage isKindOfClass:NSDictionary.class]) return usage;
276
+ if (!ExhaustionStillHolds(usage, exhaustedAt)) return usage;
277
+ NSMutableDictionary *result = [usage mutableCopy];
278
+ result[@"exhaustedAt"] = @(exhaustedAt);
279
+ return result;
280
+ }
281
+
282
+ // 多个会话里的额度是同一个账号的快照,只允许采样时刻向前推进。FSEvents 既可能把
283
+ // 多个文件合在一批里,也可能把“响应更早、落盘更晚”的旧文件单独送来;仅在批量候选
284
+ // 之间比较不够,最终写入 self.usage 的每个入口都必须经过这一层。
285
+ NSDictionary *NewerUsageSnapshot(NSDictionary *current, NSDictionary *candidate) {
286
+ if (![candidate isKindOfClass:NSDictionary.class]) return current;
287
+ if (![current isKindOfClass:NSDictionary.class]) return candidate;
288
+ return [candidate[@"sampledAt"] doubleValue] >= [current[@"sampledAt"] doubleValue]
289
+ ? candidate : current;
290
+ }
291
+
292
+ // token_count 行几乎总在文件末尾,因此从尾部反向按 \n 切片逐行试,命中即停。
293
+ // 原实现会把整段(最多 2MB)解码成 NSString、再切成全部行、再把每行编码回 NSData、
294
+ // 又解码回 NSString 查子串,等于来回往返两遍。
295
+ NSDictionary *LatestUsageInData(NSData *data, NSNumber **outExhaustedAt) {
296
+ const uint8_t *bytes = data.bytes;
297
+ NSUInteger end = data.length;
298
+ NSDictionary *usage = nil;
299
+ NSNumber *exhaustedAt = nil;
300
+ while (end > 0) {
301
+ NSUInteger start = end;
302
+ while (start > 0 && bytes[start - 1] != '\n') start -= 1;
303
+ if (end > start) {
304
+ NSData *line = [data subdataWithRange:NSMakeRange(start, end - start)];
305
+ if (!exhaustedAt) exhaustedAt = ExhaustionTimestampFromLine(line);
306
+ if (!usage) usage = UsageFromCodexLine(line);
307
+ if (usage && exhaustedAt) break;
308
+ }
309
+ end = start > 0 ? start - 1 : 0;
310
+ }
311
+ if (outExhaustedAt) *outExhaustedAt = exhaustedAt;
312
+ return usage;
313
+ }
314
+
315
+ // 「本月 / 上月同期」只有 API 展示模式要用。让默认的订阅视图也回溯到上月月初,等于把上个月
316
+ // 的全部会话白解析一遍:本机实测冷启动 7s vs 0.7s,扫描的文件数 327 vs 61。因此按每家自己的
317
+ // 展示模式决定回溯多远,两家的读取窗口互不牵连。
318
+ BOOL ProfileShowsAPIUsage(NSString *provider, NSString *home) {
319
+ return CCPetsProfileShowsAPIUsage(CCPetsProfileForHome(provider, home)
320
+ ?: @{@"provider": provider, @"home": home});
321
+ }
322
+
323
+ // resets_at 恒在未来,因此 7 天窗口的起点不可能早于 now - 7d;再留一天覆盖时区和跨日边界。
324
+ // 这是所有模式的下限:订阅视图只要这么多,API 视图的月窗口在月初也可能比它还窄。
325
+ NSTimeInterval RollingTokenWindowFloor(void) {
326
+ return NSDate.date.timeIntervalSince1970 - 8 * 86400.0;
327
+ }
328
+
329
+ // 本月 1 日 00:00。
330
+ NSDate *CurrentMonthStartDate(void) {
331
+ NSCalendar *calendar = NSCalendar.currentCalendar;
332
+ NSDate *now = NSDate.date;
333
+ NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth
334
+ fromDate:now];
335
+ components.day = 1;
336
+ return [calendar dateFromComponents:components] ?: [calendar startOfDayForDate:now];
337
+ }
338
+
339
+ // 归档的键:本机时区的 YYYY-MM。
340
+ NSString *MonthArchiveKey(NSTimeInterval monthStart) {
341
+ NSDateComponents *components = [NSCalendar.currentCalendar
342
+ components:NSCalendarUnitYear | NSCalendarUnitMonth
343
+ fromDate:[NSDate dateWithTimeIntervalSince1970:monthStart]];
344
+ return [NSString stringWithFormat:@"%04ld-%02ld", (long)components.year, (long)components.month];
345
+ }
346
+
347
+ // 目录名是本机时区的 YYYY/MM/DD。解析不出日期时返回 0,调用方据此放弃剪枝而不是误删。
348
+ static NSTimeInterval DayDirectoryEnd(NSURL *year, NSURL *month, NSURL *day) {
349
+ NSDateComponents *components = [NSDateComponents new];
350
+ components.year = year.lastPathComponent.integerValue;
351
+ components.month = month.lastPathComponent.integerValue;
352
+ components.day = day.lastPathComponent.integerValue;
353
+ NSDate *date = [NSCalendar.currentCalendar dateFromComponents:components];
354
+ return date ? date.timeIntervalSince1970 + 86400.0 : 0;
355
+ }
356
+
357
+ // 目录名只说明"会话是哪天建的",不说明"会话哪天还在被写":`codex resume` 会一直往
358
+ // 建会话那天的目录里追加,实测有用户近 8 天的全部 token_count 都写在 15 天前的
359
+ // sessions/2026/08/06/ 里。原实现在这里按目录名直接 return,那台机器上 urls 恒为空,
360
+ // 今日 / 最近 7 天的 Token 于是恒为 0(额度却正常——它走 NewestCodexSessionURL,按 mtime)。
361
+ // 所以窗口之前的目录不再收手,而是继续扫、只收 mtime 落在窗口内的文件。
362
+ // mtime 也是 Claude 侧 AppendRecentTranscriptsInDirectory 用的判据,两边口径就此一致。
363
+ static const NSUInteger ResumeLookbackDays = 60;
364
+
365
+ // earliest 由调用方按当前口径算好:订阅视图是 8 天,API 视图是本月 1 日(上月已归档)或
366
+ // 上月 1 日(还没归档,要扫一次把归档建出来),三者都不会早于 8 天下限。
367
+ NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL, NSTimeInterval earliest) {
368
+ NSMutableArray<NSURL *> *urls = [NSMutableArray array];
369
+ NSUInteger examinedDays = 0;
370
+ // 连续多少个"整天落在窗口之前、且一个活跃文件都没有"的目录。成本上界与历史长度无关:
371
+ // 续写旧会话的用户在这个计数清零之前就被捞到,闲置多年的历史最多多读 60 次目录项。
372
+ NSUInteger staleDays = 0;
373
+ // 目录个数的上限跟着时间窗口走,再多留几天处理时区边界和异常目录。
374
+ const NSUInteger maximumTokenDays =
375
+ (NSUInteger)ceil((NSDate.date.timeIntervalSince1970 - earliest) / 86400.0) + 3;
376
+ NSArray<NSURLResourceKey> *keys = @[NSURLIsRegularFileKey, NSURLContentModificationDateKey];
377
+ for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
378
+ for (NSURL *month in DescendingNumericSubdirectories(year)) {
379
+ for (NSURL *day in DescendingNumericSubdirectories(month)) {
380
+ // 天数上限用完之后不是收手,而是降级成同一套 mtime 过滤:直接 return 会
381
+ // 把上限之外那个仍在续写的旧会话又一次切掉。目录名解析不出日期(dayEnd 为 0)
382
+ // 时按窗口内处理,交给天数上限收手,不误删。
383
+ NSTimeInterval dayEnd = DayDirectoryEnd(year, month, day);
384
+ BOOL beforeWindow = (dayEnd > 0 && dayEnd < earliest) ||
385
+ examinedDays >= maximumTokenDays;
386
+ if (beforeWindow && staleDays >= ResumeLookbackDays) return urls;
387
+ NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:day
388
+ includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
389
+ BOOL matched = NO;
390
+ for (NSURL *url in contents) {
391
+ if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
392
+ NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
393
+ if (![values[NSURLIsRegularFileKey] boolValue]) continue;
394
+ // 窗口内的目录整目录都要(文件本身可能刚建、mtime 还没落后),窗口之前的
395
+ // 目录只认最近被写过的文件——判据是 mtime,不是文件里的时间戳:伪造/回填
396
+ // 的时间戳不该把一份三个月前的会话拉回今天。
397
+ if (beforeWindow) {
398
+ NSDate *modified = values[NSURLContentModificationDateKey];
399
+ if (!modified || modified.timeIntervalSince1970 < earliest) continue;
400
+ }
401
+ [urls addObject:url];
402
+ matched = YES;
403
+ }
404
+ if (beforeWindow) staleDays = matched ? 0 : staleDays + 1;
405
+ else examinedDays += 1;
406
+ }
407
+ }
408
+ }
409
+ return urls;
410
+ }
411
+
412
+ // 目录扫描之外再兜一层:当前正在被增量读取的会话、以及 FSEvents 这一轮点名的会话文件,
413
+ // 无条件参与 Token 聚合。内核已经确认它们刚被写过,这个结论比任何按路径名或 mtime 的
414
+ // 推断都可靠。多喂进来的文件不会让数字虚高——窗口过滤在 TokenTotalsInWindow 里按行内
415
+ // 时间戳做,这里只是保证文件有机会被读到。
416
+ NSArray<NSURL *> *TokenAggregationURLs(NSURL *sessionsURL, NSTimeInterval earliest,
417
+ NSArray<NSURL *> *pinnedURLs) {
418
+ NSMutableArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL, earliest) mutableCopy];
419
+ if (pinnedURLs.count == 0) return urls;
420
+ NSMutableSet<NSString *> *paths = [NSMutableSet setWithCapacity:urls.count];
421
+ for (NSURL *url in urls) [paths addObject:url.path];
422
+ for (NSURL *url in pinnedURLs) {
423
+ if (!url.path.length || [paths containsObject:url.path]) continue;
424
+ // 会话文件可能已经被删/被轮转,PruneTokenCache 拿这份列表当保留集,塞不存在的
425
+ // 路径进去会让缓存条目永远清不掉。
426
+ if (![NSFileManager.defaultManager fileExistsAtPath:url.path]) continue;
427
+ [paths addObject:url.path];
428
+ [urls addObject:url];
429
+ }
430
+ return urls;
431
+ }
432
+
433
+ NSData *SessionTailData(NSURL *url) {
434
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
435
+ if (!handle) return nil;
436
+ unsigned long long size = [handle seekToEndOfFile];
437
+ [handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
438
+ NSData *tail = [handle readDataToEndOfFile];
439
+ [handle closeFile];
440
+ return tail;
441
+ }
442
+
443
+ static BOOL UsageHasLiveWindow(NSDictionary *usage) {
444
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
445
+ NSDictionary<NSString *, NSNumber *> *windows = @{
446
+ @"fiveHour": @(FiveHourWindowMinutes),
447
+ @"week": @(SevenDayWindowMinutes)
448
+ };
449
+ for (NSString *key in windows) {
450
+ NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
451
+ if (QuotaWindowLooksCurrent(quota, windows[key].doubleValue, now)) return YES;
452
+ }
453
+ return NO;
454
+ }
455
+
456
+ // 最新会话整篇都没有额度时往前找。rate_limits 是账号级的,写在哪个会话里都一样;
457
+ // 而新会话在第一次拿到限流响应之前一条都不写,冷启动正好撞上就会整块空白。
458
+ // 只接受 resets_at 还没到的窗口,免得把过期的百分比当成当前值。
459
+ NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL) {
460
+ // 找的是"最近一次额度快照",按 mtime 排完只看前 8 个文件,没有必要把上个月的会话
461
+ // 也列出来再排一遍序,因此这里固定用窄窗口。
462
+ NSArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL, RollingTokenWindowFloor())
463
+ sortedArrayUsingComparator:
464
+ ^NSComparisonResult(NSURL *left, NSURL *right) {
465
+ NSDate *leftDate = nil, *rightDate = nil;
466
+ [left getResourceValue:&leftDate forKey:NSURLContentModificationDateKey error:nil];
467
+ [right getResourceValue:&rightDate forKey:NSURLContentModificationDateKey error:nil];
468
+ return [(rightDate ?: NSDate.distantPast) compare:(leftDate ?: NSDate.distantPast)];
469
+ }];
470
+ NSUInteger examined = 0;
471
+ NSDictionary *newest = nil;
472
+ for (NSURL *url in urls) {
473
+ if (skipURL && [url.path isEqualToString:skipURL.path]) continue;
474
+ if (++examined > 8) break;
475
+ NSDictionary *usage = LatestUsageInData(SessionTailData(url), NULL);
476
+ if (!usage || !UsageHasLiveWindow(usage)) continue;
477
+ // mtime 只够用来挑候选:会话在拿到额度之后还会继续追加别的行,文件的新旧顺序和
478
+ // 额度采样的先后并不一致。命中即返回会拿到偏旧的百分比,改成按采样时刻取最新。
479
+ if (!newest || [usage[@"sampledAt"] doubleValue] > [newest[@"sampledAt"] doubleValue]) {
480
+ newest = usage;
481
+ }
482
+ }
483
+ return newest;
484
+ }
@@ -0,0 +1,96 @@
1
+ // CCPetsUsage 拆成多个文件后,跨文件共用的常量、记录结构和内部函数。只给 CCPetsUsage*.m 用,
2
+ // 不对外:对外接口仍在 CCPetsUsage.h。
3
+ #import "CCPetsUsage.h"
4
+
5
+ // Claude 的 rate_limits 不带 window_minutes,窗长按官方订阅固定。既用于 Token 聚合区间,
6
+ // 也用于快照的合理性校验,所以定义在这里给两处共用。
7
+ static const double FiveHourWindowMinutes = 300;
8
+ static const double SevenDayWindowMinutes = 10080;
9
+ // 一条限额错误刚发生、手上却一个可用窗口都没有时的保留时长。见 ExhaustionStillHolds。
10
+ static const NSTimeInterval RecentExhaustionGraceSeconds = 300.0;
11
+ // Token 聚合要遍历近 7 天的会话文件,而 refresh 由 FSEvents 驱动、会话写盘时约 0.5 秒
12
+ // 一次。按额度窗口节流,窗口滚动或手动刷新时立刻重算。
13
+ static const NSTimeInterval TokenAggregationInterval = 5.0;
14
+ // 落盘节流:聚合本身最快 5 秒一次,缓存写盘没必要跟得那么紧。进程被 kill 而没来得及写,
15
+ // 代价也只是下次启动多解析一段。
16
+ static const NSTimeInterval TokenCacheSaveInterval = 60.0;
17
+
18
+ // model 是 ClaudeModelNames 里的下标,不直接存名字:记录是定长的二进制块,常驻内存、整块落盘。
19
+ typedef struct {
20
+ double timestamp;
21
+ uint64_t identity;
22
+ unsigned long long input;
23
+ unsigned long long output;
24
+ unsigned long long cacheRead;
25
+ unsigned long long cacheWrite;
26
+ uint32_t model;
27
+ uint32_t reserved;
28
+ } ClaudeTokenRecord;
29
+
30
+ // 额度窗口(CCPetsUsage.m)
31
+ BOOL ResetLooksCurrentAt(double reset, double windowMinutes, NSTimeInterval sampledAt);
32
+ BOOL QuotaWindowLooksCurrentAt(NSDictionary *quota, double windowMinutes,
33
+ NSTimeInterval sampledAt);
34
+ BOOL QuotaWindowLooksCurrent(NSDictionary *quota, double windowMinutes, NSTimeInterval now);
35
+ NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage);
36
+
37
+ // Codex 会话行解析与会话文件定位(CCPetsUsage+CodexSessions.m)
38
+ const NSArray<NSString *> *TokenKeys(void);
39
+ NSDate *ISO8601Timestamp(NSString *value);
40
+ NSDictionary *TokenRecordFromLine(NSData *lineData);
41
+ NSURL *NewestSessionFileInDirectory(NSURL *directory, NSDate **outDate);
42
+ NSURL *NewestCodexSessionURL(NSURL *sessionsURL);
43
+ NSNumber *ExhaustionTimestampFromLine(NSData *lineData);
44
+ NSDictionary *UsageFromCodexLine(NSData *lineData);
45
+ BOOL ExhaustionStillHolds(NSDictionary *usage, NSTimeInterval exhaustedAt);
46
+ NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterval exhaustedAt);
47
+ NSDictionary *NewerUsageSnapshot(NSDictionary *current, NSDictionary *candidate);
48
+ NSDictionary *LatestUsageInData(NSData *data, NSNumber **outExhaustedAt);
49
+ BOOL ProfileShowsAPIUsage(NSString *provider, NSString *home);
50
+ NSTimeInterval RollingTokenWindowFloor(void);
51
+ NSDate *CurrentMonthStartDate(void);
52
+ NSString *MonthArchiveKey(NSTimeInterval monthStart);
53
+ NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL, NSTimeInterval earliest);
54
+ NSArray<NSURL *> *TokenAggregationURLs(NSURL *sessionsURL, NSTimeInterval earliest,
55
+ NSArray<NSURL *> *pinnedURLs);
56
+ NSData *SessionTailData(NSURL *url);
57
+ NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL);
58
+
59
+ // Token 窗口聚合、摘要缓存与月度归档(CCPetsUsage+TokenTotals.m)
60
+ BOOL IsPseudoModelName(NSString *model);
61
+ NSDictionary *TokenSessionSummaryTracking(NSURL *url, NSMutableDictionary *cache,
62
+ BOOL trackModels);
63
+ BOOL TokenWindowOrFallback(NSDictionary *quota, double fallbackMinutes,
64
+ NSTimeInterval *outStart, NSTimeInterval *outEnd);
65
+ void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *weekStart,
66
+ NSTimeInterval *end);
67
+ NSDictionary *CalendarMonthWindows(NSTimeInterval alignedEnd);
68
+ NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end);
69
+ NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval end,
70
+ NSArray<NSURL *> *urls, NSMutableDictionary *cache);
71
+ NSDictionary *TokenTotalsForQuota(NSDictionary *quota, double fallbackMinutes,
72
+ NSArray<NSURL *> *urls, NSMutableDictionary *cache);
73
+ NSArray<NSDictionary *> *CodexDailyTokenSeries(NSTimeInterval start, NSTimeInterval end,
74
+ NSArray<NSURL *> *urls, NSMutableDictionary *cache, BOOL *outHasTokenSchema);
75
+ NSDictionary *SummedDailyTokenSeries(NSArray<NSDictionary *> *series);
76
+ NSDictionary *SummedDailyTokenSeriesInRange(NSArray<NSDictionary *> *series,
77
+ NSTimeInterval start, NSTimeInterval end);
78
+ void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
79
+ NSSet<NSString *> *liveWindowKeys);
80
+ NSMutableDictionary *LoadTokenSummaryCache(NSString *path);
81
+ NSMutableDictionary *LoadMonthlyUsageArchive(NSString *path);
82
+ void MakeCachedRecordsMutable(NSMutableDictionary *cache);
83
+ void SaveTokenSummaryCache(NSDictionary *cache, NSString *path);
84
+ void PruneMonthlyArchive(NSMutableDictionary *archive);
85
+
86
+ // Codex 额度与 Token 汇总、CodexUsageReader(CCPetsUsage+CodexReader.m)
87
+ NSString *TokenWindowIdentity(NSDictionary *usage);
88
+
89
+ // Claude Code 转录记录与 ClaudeUsageReader(CCPetsUsage+ClaudeReader.m)
90
+ NSArray<NSString *> *ClaudeModelNames(NSDictionary *cache);
91
+ void PruneClaudeRecordCache(NSMutableDictionary *cache, NSSet<NSString *> *livePaths);
92
+ NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL,
93
+ NSTimeInterval earliest);
94
+ NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache);
95
+ NSData *ClaudeMergedRecords(NSArray<NSData *> *recordSets, NSTimeInterval start,
96
+ NSTimeInterval end);