cc-pets 1.0.4 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/PROVIDER_PROTOCOL.md +11 -0
- package/README.md +30 -3
- package/Sources/CCPets/CCPetsAppDelegate.h +4 -0
- package/Sources/CCPets/CCPetsAppDelegate.m +101 -10
- package/Sources/CCPets/CCPetsPaths.h +2 -0
- package/Sources/CCPets/CCPetsPaths.m +5 -0
- package/Sources/CCPets/CCPetsPreviews.m +20 -2
- package/Sources/CCPets/CCPetsUsage.h +8 -0
- package/Sources/CCPets/CCPetsUsage.m +681 -22
- package/Sources/CCPets/CCPetsUsageMonitor.m +12 -8
- package/Sources/CCPets/QuotaDashboardView.h +8 -0
- package/Sources/CCPets/QuotaDashboardView.m +222 -142
- package/package.json +1 -1
|
@@ -15,7 +15,7 @@ int RecordClaudeUsage(void) {
|
|
|
15
15
|
return EXIT_SUCCESS;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
NSDictionary *
|
|
18
|
+
NSDictionary *ClaudeRateLimits(void) {
|
|
19
19
|
NSData *data = [NSData dataWithContentsOfFile:ClaudeUsagePath()];
|
|
20
20
|
NSDictionary *limits = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
21
21
|
if (![limits isKindOfClass:NSDictionary.class]) return nil;
|
|
@@ -24,6 +24,10 @@ NSDictionary *LatestClaudeUsage(void) {
|
|
|
24
24
|
return @{@"fiveHour": fiveHour, @"week": week};
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
NSDictionary *LatestClaudeUsage(void) {
|
|
28
|
+
return [[ClaudeUsageReader new] refreshWithFullAggregation];
|
|
29
|
+
}
|
|
30
|
+
|
|
27
31
|
static BOOL AllDigits(NSString *text) {
|
|
28
32
|
if (text.length == 0) return NO;
|
|
29
33
|
static NSCharacterSet *nonDigits;
|
|
@@ -34,6 +38,81 @@ static BOOL AllDigits(NSString *text) {
|
|
|
34
38
|
return [text rangeOfCharacterFromSet:nonDigits].location == NSNotFound;
|
|
35
39
|
}
|
|
36
40
|
|
|
41
|
+
static const NSArray<NSString *> *TokenKeys(void) {
|
|
42
|
+
static NSArray<NSString *> *keys;
|
|
43
|
+
static dispatch_once_t once;
|
|
44
|
+
dispatch_once(&once, ^{
|
|
45
|
+
keys = @[@"input_tokens", @"cached_input_tokens", @"cache_write_input_tokens",
|
|
46
|
+
@"output_tokens", @"reasoning_output_tokens", @"total_tokens"];
|
|
47
|
+
});
|
|
48
|
+
return keys;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static NSDate *ISO8601Timestamp(NSString *value) {
|
|
52
|
+
if (![value isKindOfClass:NSString.class]) return nil;
|
|
53
|
+
static NSISO8601DateFormatter *formatter;
|
|
54
|
+
static dispatch_once_t once;
|
|
55
|
+
dispatch_once(&once, ^{
|
|
56
|
+
formatter = [NSISO8601DateFormatter new];
|
|
57
|
+
formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime |
|
|
58
|
+
NSISO8601DateFormatWithFractionalSeconds;
|
|
59
|
+
});
|
|
60
|
+
NSDate *date = [formatter dateFromString:value];
|
|
61
|
+
if (date) return date;
|
|
62
|
+
static NSISO8601DateFormatter *fallback;
|
|
63
|
+
static dispatch_once_t fallbackOnce;
|
|
64
|
+
dispatch_once(&fallbackOnce, ^{
|
|
65
|
+
fallback = [NSISO8601DateFormatter new];
|
|
66
|
+
fallback.formatOptions = NSISO8601DateFormatWithInternetDateTime;
|
|
67
|
+
});
|
|
68
|
+
return [fallback dateFromString:value];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static NSDictionary *TokenPayloadFromLine(NSData *lineData, NSDictionary **root) {
|
|
72
|
+
if (lineData.length == 0) return nil;
|
|
73
|
+
static NSData *marker;
|
|
74
|
+
static dispatch_once_t once;
|
|
75
|
+
dispatch_once(&once, ^{
|
|
76
|
+
marker = [@"\"type\":\"token_count\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
77
|
+
});
|
|
78
|
+
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
79
|
+
NSNotFound) return nil;
|
|
80
|
+
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
81
|
+
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
82
|
+
id payloadValue = ((NSDictionary *)rootValue)[@"payload"];
|
|
83
|
+
if (![payloadValue isKindOfClass:NSDictionary.class]) return nil;
|
|
84
|
+
NSDictionary *payload = payloadValue;
|
|
85
|
+
id typeValue = payload[@"type"];
|
|
86
|
+
if (![typeValue isKindOfClass:NSString.class] ||
|
|
87
|
+
![(NSString *)typeValue isEqualToString:@"token_count"]) return nil;
|
|
88
|
+
if (root) *root = rootValue;
|
|
89
|
+
return payload;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static NSDictionary *SanitizedTokenCounts(id value) {
|
|
93
|
+
if (![value isKindOfClass:NSDictionary.class]) return nil;
|
|
94
|
+
NSMutableDictionary *counts = [NSMutableDictionary dictionary];
|
|
95
|
+
for (NSString *key in TokenKeys()) {
|
|
96
|
+
NSNumber *number = [value[key] isKindOfClass:NSNumber.class] ? value[key] : nil;
|
|
97
|
+
if (number) counts[key] = @([number unsignedLongLongValue]);
|
|
98
|
+
}
|
|
99
|
+
return counts.count > 0 ? counts : nil;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
static NSDictionary *TokenRecordFromLine(NSData *lineData) {
|
|
103
|
+
NSDictionary *root = nil;
|
|
104
|
+
NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
|
|
105
|
+
NSDictionary *info = [payload[@"info"] isKindOfClass:NSDictionary.class] ? payload[@"info"] : nil;
|
|
106
|
+
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
107
|
+
NSDictionary *last = SanitizedTokenCounts(info[@"last_token_usage"]);
|
|
108
|
+
NSDictionary *total = SanitizedTokenCounts(info[@"total_token_usage"]);
|
|
109
|
+
if (!date || (!last && !total)) return nil;
|
|
110
|
+
NSMutableDictionary *record = [@{@"timestamp": @([date timeIntervalSince1970])} mutableCopy];
|
|
111
|
+
if (last) record[@"last"] = last;
|
|
112
|
+
if (total) record[@"total"] = total;
|
|
113
|
+
return record;
|
|
114
|
+
}
|
|
115
|
+
|
|
37
116
|
// 会话目录是零填充的 YYYY/MM/DD,字典序等于时间序,因此倒序取名字即可,不必 stat。
|
|
38
117
|
static NSArray<NSURL *> *DescendingNumericSubdirectories(NSURL *directory) {
|
|
39
118
|
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
@@ -104,25 +183,8 @@ static NSURL *NewestCodexSessionURL(NSURL *sessionsURL) {
|
|
|
104
183
|
}
|
|
105
184
|
|
|
106
185
|
static NSDictionary *UsageFromCodexLine(NSData *lineData) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
static NSData *marker;
|
|
110
|
-
static dispatch_once_t once;
|
|
111
|
-
dispatch_once(&once, ^{
|
|
112
|
-
marker = [@"\"type\":\"token_count\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
113
|
-
});
|
|
114
|
-
if ([lineData rangeOfData:marker options:0
|
|
115
|
-
range:NSMakeRange(0, lineData.length)].location == NSNotFound) return nil;
|
|
116
|
-
// 逐层校验类型:顶层若是数组、payload 若是字符串,下面的下标访问会抛
|
|
117
|
-
// unrecognized selector 直接崩掉桌宠。
|
|
118
|
-
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
119
|
-
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
120
|
-
id payloadValue = ((NSDictionary *)rootValue)[@"payload"];
|
|
121
|
-
if (![payloadValue isKindOfClass:NSDictionary.class]) return nil;
|
|
122
|
-
NSDictionary *payload = payloadValue;
|
|
123
|
-
id typeValue = payload[@"type"];
|
|
124
|
-
if (![typeValue isKindOfClass:NSString.class] ||
|
|
125
|
-
![(NSString *)typeValue isEqualToString:@"token_count"]) return nil;
|
|
186
|
+
NSDictionary *payload = TokenPayloadFromLine(lineData, NULL);
|
|
187
|
+
if (!payload) return nil;
|
|
126
188
|
id limitsValue = payload[@"rate_limits"];
|
|
127
189
|
if (![limitsValue isKindOfClass:NSDictionary.class]) return nil;
|
|
128
190
|
NSDictionary *limits = limitsValue;
|
|
@@ -162,6 +224,306 @@ static NSDictionary *LatestUsageInData(NSData *data) {
|
|
|
162
224
|
return nil;
|
|
163
225
|
}
|
|
164
226
|
|
|
227
|
+
// resets_at 恒在未来,因此 7 天窗口的起点不可能早于 now - 7d;再留一天覆盖时区和跨日边界。
|
|
228
|
+
static NSTimeInterval EarliestTokenWindowStart(void) {
|
|
229
|
+
return NSDate.date.timeIntervalSince1970 - 8 * 86400.0;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// 目录名是本机时区的 YYYY/MM/DD。解析不出日期时返回 0,调用方据此放弃剪枝而不是误删。
|
|
233
|
+
static NSTimeInterval DayDirectoryEnd(NSURL *year, NSURL *month, NSURL *day) {
|
|
234
|
+
NSDateComponents *components = [NSDateComponents new];
|
|
235
|
+
components.year = year.lastPathComponent.integerValue;
|
|
236
|
+
components.month = month.lastPathComponent.integerValue;
|
|
237
|
+
components.day = day.lastPathComponent.integerValue;
|
|
238
|
+
NSDate *date = [NSCalendar.currentCalendar dateFromComponents:components];
|
|
239
|
+
return date ? date.timeIntervalSince1970 + 86400.0 : 0;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
static NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL) {
|
|
243
|
+
NSMutableArray<NSURL *> *urls = [NSMutableArray array];
|
|
244
|
+
NSUInteger examinedDays = 0;
|
|
245
|
+
// 7 天窗口最多横跨 8 个自然日,多留一天处理时区边界。
|
|
246
|
+
const NSUInteger maximumTokenDays = 9;
|
|
247
|
+
const NSTimeInterval earliest = EarliestTokenWindowStart();
|
|
248
|
+
for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
|
|
249
|
+
for (NSURL *month in DescendingNumericSubdirectories(year)) {
|
|
250
|
+
for (NSURL *day in DescendingNumericSubdirectories(month)) {
|
|
251
|
+
// 只数目录个数不看日期的话,停用一段时间后会把 9 个早已过期的日期目录
|
|
252
|
+
// 整个拿去做 summary。目录是倒序的,一旦整天落在窗口之前就能直接收手。
|
|
253
|
+
NSTimeInterval dayEnd = DayDirectoryEnd(year, month, day);
|
|
254
|
+
if (dayEnd > 0 && dayEnd < earliest) return urls;
|
|
255
|
+
NSArray<NSURLResourceKey> *keys = @[NSURLIsRegularFileKey, NSURLFileSizeKey];
|
|
256
|
+
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:day
|
|
257
|
+
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
258
|
+
for (NSURL *url in contents) {
|
|
259
|
+
if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
|
|
260
|
+
NSNumber *regular = nil;
|
|
261
|
+
[url getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil];
|
|
262
|
+
if (regular.boolValue) [urls addObject:url];
|
|
263
|
+
}
|
|
264
|
+
examinedDays += 1;
|
|
265
|
+
if (examinedDays >= maximumTokenDays) return urls;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return urls;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
static NSDictionary *FirstTimestampRecordInData(NSData *data) {
|
|
273
|
+
const uint8_t *bytes = data.bytes;
|
|
274
|
+
NSUInteger start = 0;
|
|
275
|
+
for (NSUInteger index = 0; index <= data.length; index++) {
|
|
276
|
+
if (index < data.length && bytes[index] != '\n') continue;
|
|
277
|
+
if (index > start) {
|
|
278
|
+
NSData *line = [data subdataWithRange:NSMakeRange(start, index - start)];
|
|
279
|
+
id root = [NSJSONSerialization JSONObjectWithData:line options:0 error:nil];
|
|
280
|
+
NSDate *date = [root isKindOfClass:NSDictionary.class]
|
|
281
|
+
? ISO8601Timestamp(((NSDictionary *)root)[@"timestamp"]) : nil;
|
|
282
|
+
if (date) return @{@"timestamp": @([date timeIntervalSince1970])};
|
|
283
|
+
}
|
|
284
|
+
start = index + 1;
|
|
285
|
+
}
|
|
286
|
+
return nil;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
static NSDictionary *LatestTokenRecordInData(NSData *data) {
|
|
290
|
+
const uint8_t *bytes = data.bytes;
|
|
291
|
+
NSUInteger end = data.length;
|
|
292
|
+
while (end > 0) {
|
|
293
|
+
NSUInteger start = end;
|
|
294
|
+
while (start > 0 && bytes[start - 1] != '\n') start -= 1;
|
|
295
|
+
if (end > start) {
|
|
296
|
+
NSDictionary *record = TokenRecordFromLine(
|
|
297
|
+
[data subdataWithRange:NSMakeRange(start, end - start)]);
|
|
298
|
+
if (record[@"total"]) return record;
|
|
299
|
+
}
|
|
300
|
+
end = start > 0 ? start - 1 : 0;
|
|
301
|
+
}
|
|
302
|
+
return nil;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache) {
|
|
306
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path error:nil];
|
|
307
|
+
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
308
|
+
NSDictionary *cached = cache[url.path];
|
|
309
|
+
if (cached && [cached[@"size"] unsignedLongLongValue] == size) {
|
|
310
|
+
return [cached[@"invalid"] boolValue] ? nil : cached;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
314
|
+
if (!handle) return nil;
|
|
315
|
+
const unsigned long long headLength = MIN(size, 64 * 1024);
|
|
316
|
+
NSData *head = [handle readDataOfLength:(NSUInteger)headLength];
|
|
317
|
+
const unsigned long long tailStart = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
|
|
318
|
+
[handle seekToFileOffset:tailStart];
|
|
319
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
320
|
+
[handle closeFile];
|
|
321
|
+
|
|
322
|
+
NSDictionary *first = FirstTimestampRecordInData(head);
|
|
323
|
+
NSDictionary *latest = LatestTokenRecordInData(tail);
|
|
324
|
+
// 没有 token_count 的会话(旧格式、被截断、刚创建)也必须记住,否则每一轮都会
|
|
325
|
+
// 把 64KB head + 2MB tail 重读一遍。文件长大后 size 变化自然会让缓存失效。
|
|
326
|
+
if (!first || !latest[@"total"]) {
|
|
327
|
+
cache[url.path] = @{@"size": @(size), @"invalid": @YES};
|
|
328
|
+
return nil;
|
|
329
|
+
}
|
|
330
|
+
NSMutableDictionary *summary = [@{
|
|
331
|
+
@"size": @(size),
|
|
332
|
+
@"start": first[@"timestamp"],
|
|
333
|
+
@"end": latest[@"timestamp"],
|
|
334
|
+
@"total": latest[@"total"]
|
|
335
|
+
} mutableCopy];
|
|
336
|
+
cache[url.path] = summary;
|
|
337
|
+
return summary;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
341
|
+
for (NSString *key in TokenKeys()) {
|
|
342
|
+
unsigned long long current = [target[key] unsignedLongLongValue];
|
|
343
|
+
unsigned long long addition = [counts[key] unsignedLongLongValue];
|
|
344
|
+
if (counts[key]) target[key] = @(current + addition);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTimeInterval end) {
|
|
349
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
350
|
+
if (!handle) return nil;
|
|
351
|
+
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
352
|
+
NSMutableData *pending = [NSMutableData data];
|
|
353
|
+
while (YES) {
|
|
354
|
+
NSData *chunk = [handle readDataOfLength:256 * 1024];
|
|
355
|
+
if (chunk.length == 0) break;
|
|
356
|
+
[pending appendData:chunk];
|
|
357
|
+
const uint8_t *bytes = pending.bytes;
|
|
358
|
+
NSUInteger lineStart = 0;
|
|
359
|
+
for (NSUInteger index = 0; index < pending.length; index++) {
|
|
360
|
+
if (bytes[index] != '\n') continue;
|
|
361
|
+
NSDictionary *record = TokenRecordFromLine(
|
|
362
|
+
[pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
|
|
363
|
+
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
364
|
+
if (record[@"last"] && timestamp >= start && timestamp < end) {
|
|
365
|
+
AddTokenCounts(totals, record[@"last"]);
|
|
366
|
+
}
|
|
367
|
+
lineStart = index + 1;
|
|
368
|
+
}
|
|
369
|
+
if (lineStart > 0) {
|
|
370
|
+
pending = [[pending subdataWithRange:NSMakeRange(
|
|
371
|
+
lineStart, pending.length - lineStart)] mutableCopy];
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (pending.length > 0) {
|
|
375
|
+
NSDictionary *record = TokenRecordFromLine(pending);
|
|
376
|
+
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
377
|
+
if (record[@"last"] && timestamp >= start && timestamp < end) {
|
|
378
|
+
AddTokenCounts(totals, record[@"last"]);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
[handle closeFile];
|
|
382
|
+
return totals;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// 聚合区间对齐官方重置时间:[resets_at - 窗长, resets_at)。
|
|
386
|
+
// Codex 的 rate_limits 自带 window_minutes;Claude 没有这个字段,由调用方给出订阅
|
|
387
|
+
// 固定的 300 / 10080 分钟作为兜底。返回 NO 表示窗口当前不可用(缺 resets_at 或已过期),
|
|
388
|
+
// 此时不做任何 Token 统计,避免拿过期窗口冒充当前值。
|
|
389
|
+
static BOOL TokenWindowForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
390
|
+
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
391
|
+
NSNumber *minutes = [quota[@"window_minutes"] isKindOfClass:NSNumber.class]
|
|
392
|
+
? quota[@"window_minutes"] : nil;
|
|
393
|
+
double windowMinutes = minutes ? minutes.doubleValue : fallbackMinutes;
|
|
394
|
+
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
395
|
+
if (windowMinutes <= 0 || !reset) return NO;
|
|
396
|
+
NSTimeInterval end = reset.doubleValue;
|
|
397
|
+
if (NSDate.date.timeIntervalSince1970 >= end) return NO;
|
|
398
|
+
if (outStart) *outStart = end - windowMinutes * 60.0;
|
|
399
|
+
if (outEnd) *outEnd = end;
|
|
400
|
+
return YES;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
static const double FiveHourWindowMinutes = 300;
|
|
404
|
+
static const double SevenDayWindowMinutes = 10080;
|
|
405
|
+
|
|
406
|
+
// 面板汇总条要把两家相加,而两家的 resets_at 并不一致(实测能差 2 天以上),
|
|
407
|
+
// 按各自订阅窗口算出来的两个数不在同一个区间上,相加没有对应的物理量。
|
|
408
|
+
// 所以汇总另用一组与订阅完全脱钩的自然日窗口,两家共享。
|
|
409
|
+
//
|
|
410
|
+
// 取自然日边界而不是"从现在往回推 N 秒",是因为分片缓存的键里含窗口起点:起点每秒
|
|
411
|
+
// 都在动的话,跨界会话每一轮都要整篇重扫;对齐到零点后起点一天之内不变,缓存才能命中。
|
|
412
|
+
static void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *weekStart,
|
|
413
|
+
NSTimeInterval *end) {
|
|
414
|
+
NSDate *now = NSDate.date;
|
|
415
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
416
|
+
NSDate *midnight = [calendar startOfDayForDate:now];
|
|
417
|
+
if (todayStart) *todayStart = midnight.timeIntervalSince1970;
|
|
418
|
+
if (weekStart) {
|
|
419
|
+
NSDate *start = [calendar dateByAddingUnit:NSCalendarUnitDay value:-6 toDate:midnight
|
|
420
|
+
options:0];
|
|
421
|
+
*weekStart = (start ?: midnight).timeIntervalSince1970;
|
|
422
|
+
}
|
|
423
|
+
// 时钟轻微前后跳动时,不要把刚落盘的记录挡在窗口外。
|
|
424
|
+
if (end) *end = now.timeIntervalSince1970 + 60;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
static NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end) {
|
|
428
|
+
return [NSString stringWithFormat:@"partial-%.0f-%.0f", start, end];
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval end,
|
|
432
|
+
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
433
|
+
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
434
|
+
BOOL hasTokenSchema = NO;
|
|
435
|
+
for (NSURL *url in urls) {
|
|
436
|
+
NSMutableDictionary *summary = [(NSDictionary *)TokenSessionSummary(url, cache) mutableCopy];
|
|
437
|
+
if (!summary) continue;
|
|
438
|
+
hasTokenSchema = YES;
|
|
439
|
+
NSTimeInterval sessionStart = [summary[@"start"] doubleValue];
|
|
440
|
+
NSTimeInterval sessionEnd = [summary[@"end"] doubleValue];
|
|
441
|
+
if (sessionEnd < start || sessionStart >= end) continue;
|
|
442
|
+
if (sessionStart >= start) {
|
|
443
|
+
AddTokenCounts(totals, summary[@"total"]);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
NSString *partialKey = PartialTokenKey(start, end);
|
|
447
|
+
NSDictionary *partial = summary[partialKey];
|
|
448
|
+
if (!partial) {
|
|
449
|
+
partial = PartialTokenTotals(url, start, end) ?: @{};
|
|
450
|
+
summary[partialKey] = partial;
|
|
451
|
+
cache[url.path] = summary;
|
|
452
|
+
}
|
|
453
|
+
AddTokenCounts(totals, partial);
|
|
454
|
+
}
|
|
455
|
+
if (!hasTokenSchema) return nil;
|
|
456
|
+
// 有会话但没有一条落在窗口内时,真实用量就是 0,不能退化成"无数据"的 `--`。
|
|
457
|
+
if (totals.count == 0) {
|
|
458
|
+
for (NSString *key in TokenKeys()) totals[key] = @0;
|
|
459
|
+
}
|
|
460
|
+
return totals;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
static NSDictionary *TokenTotalsForQuota(NSDictionary *quota, NSArray<NSURL *> *urls,
|
|
464
|
+
NSMutableDictionary *cache) {
|
|
465
|
+
NSTimeInterval start = 0;
|
|
466
|
+
NSTimeInterval end = 0;
|
|
467
|
+
if (!TokenWindowForQuota(quota, 0, &start, &end)) return nil;
|
|
468
|
+
return TokenTotalsInWindow(start, end, urls, cache);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// 会话滚出 7 天窗口、额度窗口滚动之后,缓存里对应的条目和 partial-* 分片再也不会被读到。
|
|
472
|
+
// 常驻进程不清理就是只增不减。
|
|
473
|
+
static void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
|
|
474
|
+
NSSet<NSString *> *liveWindowKeys) {
|
|
475
|
+
NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
|
|
476
|
+
for (NSURL *url in urls) [livePaths addObject:url.path];
|
|
477
|
+
for (NSString *path in cache.allKeys) {
|
|
478
|
+
if (![livePaths containsObject:path]) {
|
|
479
|
+
[cache removeObjectForKey:path];
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
NSDictionary *summary = cache[path];
|
|
483
|
+
NSMutableDictionary *trimmed = nil;
|
|
484
|
+
for (NSString *key in summary.allKeys) {
|
|
485
|
+
if (![key hasPrefix:@"partial-"] || [liveWindowKeys containsObject:key]) continue;
|
|
486
|
+
if (!trimmed) trimmed = [summary mutableCopy];
|
|
487
|
+
[trimmed removeObjectForKey:key];
|
|
488
|
+
}
|
|
489
|
+
if (trimmed) cache[path] = trimmed;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessionsURL,
|
|
494
|
+
NSMutableDictionary *cache) {
|
|
495
|
+
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
496
|
+
NSArray<NSURL *> *urls = RecentCodexSessionURLs(sessionsURL);
|
|
497
|
+
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
498
|
+
? usage[@"fiveHour"] : nil;
|
|
499
|
+
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
500
|
+
NSDictionary *fiveTokens = five ? TokenTotalsForQuota(five, urls, cache) : nil;
|
|
501
|
+
NSDictionary *weekTokens = week ? TokenTotalsForQuota(week, urls, cache) : nil;
|
|
502
|
+
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
503
|
+
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
504
|
+
NSDictionary *todayTokens = TokenTotalsInWindow(todayStart, rollingEnd, urls, cache);
|
|
505
|
+
NSDictionary *recentTokens = TokenTotalsInWindow(rollingWeekStart, rollingEnd, urls, cache);
|
|
506
|
+
NSMutableSet<NSString *> *liveWindowKeys = [NSMutableSet setWithArray:@[
|
|
507
|
+
PartialTokenKey(todayStart, rollingEnd), PartialTokenKey(rollingWeekStart, rollingEnd)]];
|
|
508
|
+
for (NSDictionary *quota in @[five ?: @{}, week ?: @{}]) {
|
|
509
|
+
NSTimeInterval start = 0;
|
|
510
|
+
NSTimeInterval end = 0;
|
|
511
|
+
if (TokenWindowForQuota(quota, 0, &start, &end)) {
|
|
512
|
+
[liveWindowKeys addObject:PartialTokenKey(start, end)];
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
PruneTokenCache(cache, urls, liveWindowKeys);
|
|
516
|
+
NSMutableDictionary *result = [usage mutableCopy];
|
|
517
|
+
result[@"tokenUsage"] = @{
|
|
518
|
+
@"fiveHour": fiveTokens ?: NSNull.null,
|
|
519
|
+
@"week": weekTokens ?: NSNull.null,
|
|
520
|
+
@"today": todayTokens ?: NSNull.null,
|
|
521
|
+
@"recentWeek": recentTokens ?: NSNull.null,
|
|
522
|
+
@"source": @"local"
|
|
523
|
+
};
|
|
524
|
+
return result;
|
|
525
|
+
}
|
|
526
|
+
|
|
165
527
|
NSDictionary *LatestUsage(void) {
|
|
166
528
|
NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
|
|
167
529
|
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
@@ -175,9 +537,31 @@ NSDictionary *LatestUsage(void) {
|
|
|
175
537
|
[handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
|
|
176
538
|
NSData *tail = [handle readDataToEndOfFile];
|
|
177
539
|
[handle closeFile];
|
|
178
|
-
|
|
540
|
+
NSDictionary *usage = LatestUsageInData(tail);
|
|
541
|
+
return UsageByAddingTokenTotals(usage, sessions, [NSMutableDictionary dictionary]);
|
|
179
542
|
}
|
|
180
543
|
|
|
544
|
+
// Token 聚合要遍历近 7 天的会话文件,而 refresh 由 FSEvents 驱动、会话写盘时约 0.5 秒
|
|
545
|
+
// 一次。按额度窗口节流,窗口滚动或手动刷新时立刻重算。
|
|
546
|
+
static const NSTimeInterval TokenAggregationInterval = 5.0;
|
|
547
|
+
|
|
548
|
+
// 额度窗口的身份:两个 resets_at 一变就说明窗口滚动了,缓存必须作废。
|
|
549
|
+
static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
550
|
+
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
551
|
+
? usage[@"fiveHour"] : nil;
|
|
552
|
+
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
553
|
+
return [NSString stringWithFormat:@"%.0f/%.0f",
|
|
554
|
+
[five[@"resets_at"] doubleValue], [week[@"resets_at"] doubleValue]];
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
@interface CodexUsageReader ()
|
|
558
|
+
@property NSMutableDictionary *tokenSummaryCache;
|
|
559
|
+
@property NSDictionary *tokenUsage;
|
|
560
|
+
@property NSString *tokenWindowIdentity;
|
|
561
|
+
@property NSTimeInterval tokenComputedAt;
|
|
562
|
+
@property BOOL forcesTokenAggregation;
|
|
563
|
+
@end
|
|
564
|
+
|
|
181
565
|
@implementation CodexUsageReader
|
|
182
566
|
- (instancetype)init {
|
|
183
567
|
if ((self = [super init])) {
|
|
@@ -185,9 +569,30 @@ NSDictionary *LatestUsage(void) {
|
|
|
185
569
|
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
186
570
|
_sessionsURL = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
|
|
187
571
|
_partialLine = [NSMutableData data];
|
|
572
|
+
_tokenSummaryCache = [NSMutableDictionary dictionary];
|
|
188
573
|
}
|
|
189
574
|
return self;
|
|
190
575
|
}
|
|
576
|
+
- (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
|
|
577
|
+
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
578
|
+
NSString *identity = TokenWindowIdentity(usage);
|
|
579
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
580
|
+
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
581
|
+
[identity isEqualToString:self.tokenWindowIdentity] &&
|
|
582
|
+
now - self.tokenComputedAt < TokenAggregationInterval;
|
|
583
|
+
if (reusable) {
|
|
584
|
+
NSMutableDictionary *result = [usage mutableCopy];
|
|
585
|
+
result[@"tokenUsage"] = self.tokenUsage;
|
|
586
|
+
return result;
|
|
587
|
+
}
|
|
588
|
+
NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL, self.tokenSummaryCache);
|
|
589
|
+
id tokens = result[@"tokenUsage"];
|
|
590
|
+
self.tokenUsage = [tokens isKindOfClass:NSDictionary.class] ? tokens : nil;
|
|
591
|
+
self.tokenWindowIdentity = identity;
|
|
592
|
+
self.tokenComputedAt = now;
|
|
593
|
+
self.forcesTokenAggregation = NO;
|
|
594
|
+
return result;
|
|
595
|
+
}
|
|
191
596
|
- (void)selectSessionURL:(NSURL *)url {
|
|
192
597
|
self.sessionURL = url;
|
|
193
598
|
self.offset = 0;
|
|
@@ -204,7 +609,11 @@ NSDictionary *LatestUsage(void) {
|
|
|
204
609
|
NSData *tail = [handle readDataToEndOfFile];
|
|
205
610
|
[handle closeFile];
|
|
206
611
|
self.offset = start + tail.length;
|
|
207
|
-
|
|
612
|
+
// 切换会话意味着数据来源变了,不受节流约束。
|
|
613
|
+
self.forcesTokenAggregation = YES;
|
|
614
|
+
// 额度是账号级的,不随会话切换失效。新会话在首个 token_count 落盘前没有 rate_limits,
|
|
615
|
+
// 这时沿用上一份,否则每次开新会话面板都会整块闪空。窗口过期的判定另有 resets_at 兜底。
|
|
616
|
+
self.usage = [self usageWithTokenTotals:LatestUsageInData(tail) ?: self.usage];
|
|
208
617
|
|
|
209
618
|
const uint8_t *bytes = tail.bytes;
|
|
210
619
|
NSUInteger lastNewline = NSNotFound;
|
|
@@ -271,10 +680,12 @@ NSDictionary *LatestUsage(void) {
|
|
|
271
680
|
[self consumeIncrementalData:newData];
|
|
272
681
|
}
|
|
273
682
|
[handle closeFile];
|
|
683
|
+
self.usage = [self usageWithTokenTotals:self.usage];
|
|
274
684
|
return self.usage;
|
|
275
685
|
}
|
|
276
686
|
- (NSDictionary *)refreshWithFullDiscovery {
|
|
277
687
|
self.lastFullDiscovery = 0;
|
|
688
|
+
self.forcesTokenAggregation = YES;
|
|
278
689
|
return [self refresh];
|
|
279
690
|
}
|
|
280
691
|
- (NSDictionary *)refreshForSessionURL:(NSURL *)url {
|
|
@@ -287,3 +698,251 @@ NSDictionary *LatestUsage(void) {
|
|
|
287
698
|
return [self refresh];
|
|
288
699
|
}
|
|
289
700
|
@end
|
|
701
|
+
|
|
702
|
+
// MARK: - Claude Code 本地 Token 统计
|
|
703
|
+
//
|
|
704
|
+
// 数据源是 ~/.claude/projects/<编码后的 cwd>/<session-uuid>.jsonl。每条 type=assistant
|
|
705
|
+
// 的行带 timestamp 和 message.usage,是**单次请求的增量**,与 Codex 的会话累计值不同,
|
|
706
|
+
// 因此必须逐条落窗口累加,不能取末行。
|
|
707
|
+
//
|
|
708
|
+
// 关键差异:Claude 的 --resume / fork / compact 会把旧行原样复制进新文件,本机实测
|
|
709
|
+
// 5575 行里有 692 行重复(12%)。不去重的话 7 天用量会虚高一成以上,所以按
|
|
710
|
+
// message.id + requestId 做全局去重(两者缺失时回退 uuid)。
|
|
711
|
+
|
|
712
|
+
typedef struct {
|
|
713
|
+
double timestamp;
|
|
714
|
+
uint64_t identity;
|
|
715
|
+
unsigned long long input;
|
|
716
|
+
unsigned long long output;
|
|
717
|
+
unsigned long long cacheRead;
|
|
718
|
+
unsigned long long cacheWrite;
|
|
719
|
+
} ClaudeTokenRecord;
|
|
720
|
+
|
|
721
|
+
// 去重键存 64 位散列而不是原字符串:近 7 天约 5.5k 条记录,散列后每条 48 字节、
|
|
722
|
+
// 常驻不到 300KB;64 位空间下这个量级的碰撞概率约 1e-12,可以忽略。
|
|
723
|
+
static uint64_t ClaudeIdentityHash(NSString *first, NSString *second) {
|
|
724
|
+
uint64_t hash = 1469598103934665603ULL;
|
|
725
|
+
for (NSString *part in @[first ?: @"", @"\n", second ?: @""]) {
|
|
726
|
+
const char *bytes = part.UTF8String;
|
|
727
|
+
for (const char *cursor = bytes; cursor && *cursor; cursor++) {
|
|
728
|
+
hash ^= (uint64_t)(unsigned char)*cursor;
|
|
729
|
+
hash *= 1099511628211ULL;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return hash;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
static unsigned long long ClaudeCount(NSDictionary *usage, NSString *key) {
|
|
736
|
+
NSNumber *number = [usage[key] isKindOfClass:NSNumber.class] ? usage[key] : nil;
|
|
737
|
+
return number.unsignedLongLongValue;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// message.usage 的顶层就是该次请求的聚合值,内层 iterations 是明细,不能再加一遍。
|
|
741
|
+
static BOOL ClaudeRecordFromLine(NSData *lineData, ClaudeTokenRecord *record) {
|
|
742
|
+
if (lineData.length == 0) return NO;
|
|
743
|
+
static NSData *marker;
|
|
744
|
+
static dispatch_once_t once;
|
|
745
|
+
dispatch_once(&once, ^{
|
|
746
|
+
marker = [@"\"type\":\"assistant\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
747
|
+
});
|
|
748
|
+
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
749
|
+
NSNotFound) return NO;
|
|
750
|
+
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
751
|
+
if (![rootValue isKindOfClass:NSDictionary.class]) return NO;
|
|
752
|
+
NSDictionary *root = rootValue;
|
|
753
|
+
if (![root[@"type"] isKindOfClass:NSString.class] ||
|
|
754
|
+
![root[@"type"] isEqualToString:@"assistant"]) return NO;
|
|
755
|
+
NSDictionary *message = [root[@"message"] isKindOfClass:NSDictionary.class]
|
|
756
|
+
? root[@"message"] : nil;
|
|
757
|
+
NSDictionary *usage = [message[@"usage"] isKindOfClass:NSDictionary.class]
|
|
758
|
+
? message[@"usage"] : nil;
|
|
759
|
+
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
760
|
+
if (!usage || !date) return NO;
|
|
761
|
+
|
|
762
|
+
NSString *identifier = [message[@"id"] isKindOfClass:NSString.class] ? message[@"id"] : nil;
|
|
763
|
+
NSString *requestIdentifier = [root[@"requestId"] isKindOfClass:NSString.class]
|
|
764
|
+
? root[@"requestId"] : nil;
|
|
765
|
+
// 本机实测 3112 行里有 17 行缺 id 或 requestId,回退到行级 uuid 保证仍能去重。
|
|
766
|
+
NSString *fallback = [root[@"uuid"] isKindOfClass:NSString.class] ? root[@"uuid"] : nil;
|
|
767
|
+
record->timestamp = date.timeIntervalSince1970;
|
|
768
|
+
record->identity = (identifier && requestIdentifier)
|
|
769
|
+
? ClaudeIdentityHash(identifier, requestIdentifier)
|
|
770
|
+
: ClaudeIdentityHash(fallback, nil);
|
|
771
|
+
record->input = ClaudeCount(usage, @"input_tokens");
|
|
772
|
+
record->output = ClaudeCount(usage, @"output_tokens");
|
|
773
|
+
record->cacheRead = ClaudeCount(usage, @"cache_read_input_tokens");
|
|
774
|
+
record->cacheWrite = ClaudeCount(usage, @"cache_creation_input_tokens");
|
|
775
|
+
return YES;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
static NSURL *ClaudeProjectsURL(void) {
|
|
779
|
+
NSString *home = NSProcessInfo.processInfo.environment[@"CLAUDE_CONFIG_DIR"];
|
|
780
|
+
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".claude"];
|
|
781
|
+
return [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"projects"]];
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// 只看 mtime 落在窗口内的转录文件。本机 76 个文件里近 7 天只有 44 个,目录遍历约 3ms。
|
|
785
|
+
static NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL) {
|
|
786
|
+
NSTimeInterval earliest = EarliestTokenWindowStart();
|
|
787
|
+
NSArray<NSURLResourceKey> *keys = @[NSURLIsDirectoryKey];
|
|
788
|
+
NSArray<NSURL *> *projects = [NSFileManager.defaultManager contentsOfDirectoryAtURL:projectsURL
|
|
789
|
+
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
790
|
+
NSMutableArray<NSURL *> *urls = [NSMutableArray array];
|
|
791
|
+
NSArray<NSURLResourceKey> *fileKeys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
|
|
792
|
+
for (NSURL *project in projects) {
|
|
793
|
+
NSNumber *isDirectory = nil;
|
|
794
|
+
if (![project getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
|
|
795
|
+
if (!isDirectory.boolValue) continue;
|
|
796
|
+
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:project
|
|
797
|
+
includingPropertiesForKeys:fileKeys options:NSDirectoryEnumerationSkipsHiddenFiles
|
|
798
|
+
error:nil];
|
|
799
|
+
for (NSURL *url in contents) {
|
|
800
|
+
if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
|
|
801
|
+
NSDictionary *values = [url resourceValuesForKeys:fileKeys error:nil];
|
|
802
|
+
if (![values[NSURLIsRegularFileKey] boolValue]) continue;
|
|
803
|
+
NSDate *modified = values[NSURLContentModificationDateKey];
|
|
804
|
+
if (modified && modified.timeIntervalSince1970 < earliest) continue;
|
|
805
|
+
[urls addObject:url];
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return urls;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// 转录文件只追加(fork 走新文件),因此按 offset 追读即可,活跃会话每轮只解析新增字节。
|
|
812
|
+
static NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache) {
|
|
813
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path
|
|
814
|
+
error:nil];
|
|
815
|
+
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
816
|
+
NSDictionary *cached = cache[url.path];
|
|
817
|
+
unsigned long long offset = [cached[@"offset"] unsignedLongLongValue];
|
|
818
|
+
NSMutableData *records = cached[@"records"];
|
|
819
|
+
if (!records || offset > size) {
|
|
820
|
+
// 首次读取,或文件被改写导致偏移失效,整篇重来。
|
|
821
|
+
offset = 0;
|
|
822
|
+
records = [NSMutableData data];
|
|
823
|
+
}
|
|
824
|
+
if (cached && offset == size) return records;
|
|
825
|
+
|
|
826
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
827
|
+
if (!handle) return records;
|
|
828
|
+
[handle seekToFileOffset:offset];
|
|
829
|
+
NSData *fresh = [handle readDataToEndOfFile];
|
|
830
|
+
[handle closeFile];
|
|
831
|
+
|
|
832
|
+
const uint8_t *bytes = fresh.bytes;
|
|
833
|
+
NSUInteger lineStart = 0;
|
|
834
|
+
NSUInteger consumed = 0;
|
|
835
|
+
for (NSUInteger index = 0; index < fresh.length; index++) {
|
|
836
|
+
if (bytes[index] != '\n') continue;
|
|
837
|
+
ClaudeTokenRecord record = {0};
|
|
838
|
+
if (index > lineStart && ClaudeRecordFromLine(
|
|
839
|
+
[fresh subdataWithRange:NSMakeRange(lineStart, index - lineStart)], &record)) {
|
|
840
|
+
[records appendBytes:&record length:sizeof(record)];
|
|
841
|
+
}
|
|
842
|
+
lineStart = index + 1;
|
|
843
|
+
consumed = lineStart;
|
|
844
|
+
}
|
|
845
|
+
// 只推进到最后一个换行符,未写完的尾行留到下一轮,避免把半行当成坏数据丢掉。
|
|
846
|
+
cache[url.path] = @{@"offset": @(offset + consumed), @"records": records};
|
|
847
|
+
return records;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInterval start,
|
|
851
|
+
NSTimeInterval end) {
|
|
852
|
+
NSMutableSet<NSNumber *> *seen = [NSMutableSet set];
|
|
853
|
+
unsigned long long input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
|
|
854
|
+
for (NSData *data in recordSets) {
|
|
855
|
+
const ClaudeTokenRecord *records = data.bytes;
|
|
856
|
+
NSUInteger count = data.length / sizeof(ClaudeTokenRecord);
|
|
857
|
+
for (NSUInteger index = 0; index < count; index++) {
|
|
858
|
+
const ClaudeTokenRecord *record = &records[index];
|
|
859
|
+
if (record->timestamp < start || record->timestamp >= end) continue;
|
|
860
|
+
NSNumber *identity = @(record->identity);
|
|
861
|
+
if ([seen containsObject:identity]) continue;
|
|
862
|
+
[seen addObject:identity];
|
|
863
|
+
input += record->input;
|
|
864
|
+
output += record->output;
|
|
865
|
+
cacheRead += record->cacheRead;
|
|
866
|
+
cacheWrite += record->cacheWrite;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
// 不输出 reasoning_output_tokens:Claude 的思考 token 已经计入 output_tokens,
|
|
870
|
+
// 单列一个恒为 0 的字段会让人误以为没统计。
|
|
871
|
+
return @{
|
|
872
|
+
@"input_tokens": @(input),
|
|
873
|
+
@"cached_input_tokens": @(cacheRead),
|
|
874
|
+
@"cache_write_input_tokens": @(cacheWrite),
|
|
875
|
+
@"output_tokens": @(output),
|
|
876
|
+
@"total_tokens": @(input + output + cacheRead + cacheWrite)
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
@interface ClaudeUsageReader ()
|
|
881
|
+
@property NSMutableDictionary *recordCache;
|
|
882
|
+
@property NSDictionary *tokenUsage;
|
|
883
|
+
@property NSString *tokenWindowIdentity;
|
|
884
|
+
@property NSTimeInterval tokenComputedAt;
|
|
885
|
+
@property BOOL forcesTokenAggregation;
|
|
886
|
+
@end
|
|
887
|
+
|
|
888
|
+
@implementation ClaudeUsageReader
|
|
889
|
+
- (instancetype)init {
|
|
890
|
+
if ((self = [super init])) {
|
|
891
|
+
_projectsURL = ClaudeProjectsURL();
|
|
892
|
+
_recordCache = [NSMutableDictionary dictionary];
|
|
893
|
+
}
|
|
894
|
+
return self;
|
|
895
|
+
}
|
|
896
|
+
- (NSDictionary *)aggregateForLimits:(NSDictionary *)limits {
|
|
897
|
+
NSDictionary *five = [limits[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
898
|
+
? limits[@"fiveHour"] : nil;
|
|
899
|
+
NSDictionary *week = [limits[@"week"] isKindOfClass:NSDictionary.class] ? limits[@"week"] : nil;
|
|
900
|
+
NSTimeInterval fiveStart = 0, fiveEnd = 0, weekStart = 0, weekEnd = 0;
|
|
901
|
+
// Claude 的 rate_limits 没有 window_minutes,窗长按官方订阅固定为 5 小时 / 7 天。
|
|
902
|
+
BOOL hasFive = five && TokenWindowForQuota(five, FiveHourWindowMinutes, &fiveStart, &fiveEnd);
|
|
903
|
+
BOOL hasWeek = week && TokenWindowForQuota(week, SevenDayWindowMinutes, &weekStart, &weekEnd);
|
|
904
|
+
// 自然日窗口和额度无关,即使两个额度窗口都不可用也照样统计。
|
|
905
|
+
NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL);
|
|
906
|
+
NSMutableArray<NSData *> *recordSets = [NSMutableArray arrayWithCapacity:urls.count];
|
|
907
|
+
NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
|
|
908
|
+
for (NSURL *url in urls) {
|
|
909
|
+
[livePaths addObject:url.path];
|
|
910
|
+
NSData *records = ClaudeRecordsForFile(url, self.recordCache);
|
|
911
|
+
if (records.length > 0) [recordSets addObject:records];
|
|
912
|
+
}
|
|
913
|
+
for (NSString *path in self.recordCache.allKeys) {
|
|
914
|
+
if (![livePaths containsObject:path]) [self.recordCache removeObjectForKey:path];
|
|
915
|
+
}
|
|
916
|
+
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
917
|
+
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
918
|
+
return @{
|
|
919
|
+
@"fiveHour": hasFive ? ClaudeTokenTotals(recordSets, fiveStart, fiveEnd) : (id)NSNull.null,
|
|
920
|
+
@"week": hasWeek ? ClaudeTokenTotals(recordSets, weekStart, weekEnd) : (id)NSNull.null,
|
|
921
|
+
@"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
|
|
922
|
+
@"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
|
|
923
|
+
@"source": @"local"
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
- (NSDictionary *)refresh {
|
|
927
|
+
NSDictionary *limits = ClaudeRateLimits();
|
|
928
|
+
if (!limits) return nil;
|
|
929
|
+
NSString *identity = TokenWindowIdentity(limits);
|
|
930
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
931
|
+
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
932
|
+
[identity isEqualToString:self.tokenWindowIdentity] &&
|
|
933
|
+
now - self.tokenComputedAt < TokenAggregationInterval;
|
|
934
|
+
if (!reusable) {
|
|
935
|
+
self.tokenUsage = [self aggregateForLimits:limits];
|
|
936
|
+
self.tokenWindowIdentity = identity;
|
|
937
|
+
self.tokenComputedAt = now;
|
|
938
|
+
self.forcesTokenAggregation = NO;
|
|
939
|
+
}
|
|
940
|
+
NSMutableDictionary *usage = [limits mutableCopy];
|
|
941
|
+
usage[@"tokenUsage"] = self.tokenUsage;
|
|
942
|
+
return usage;
|
|
943
|
+
}
|
|
944
|
+
- (NSDictionary *)refreshWithFullAggregation {
|
|
945
|
+
self.forcesTokenAggregation = YES;
|
|
946
|
+
return [self refresh];
|
|
947
|
+
}
|
|
948
|
+
@end
|