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.
- package/CC_BRIDGE.md +5 -2
- package/CC_BRIDGE.zh-CN.md +4 -2
- package/CHANGELOG.md +60 -0
- package/CHANGELOG.zh-CN.md +60 -0
- package/CONTRIBUTING.md +13 -10
- package/CONTRIBUTING.zh-CN.md +11 -10
- package/README.md +113 -24
- package/README.zh-CN.md +89 -28
- package/Resources/zh-Hans.lproj/Localizable.strings +568 -17
- package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
- package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +82 -23
- package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
- package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
- package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
- package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
- package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
- package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
- package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
- package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
- package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
- package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
- package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
- package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
- package/Sources/CCPets/{main.m → App/main.m} +68 -1
- package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
- package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
- package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
- package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
- package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
- package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
- package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
- package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
- package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
- package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
- package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
- package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
- package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
- package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
- package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
- package/Sources/CCPets/Pet/PetView+Private.h +81 -0
- package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
- package/Sources/CCPets/Pet/PetView.m +635 -0
- package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
- package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
- package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
- package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
- package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
- package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
- package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
- package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
- package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
- package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
- package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
- package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
- package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
- package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
- package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
- package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
- package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
- package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
- package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
- package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
- package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
- package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
- package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
- package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
- package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
- package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
- package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
- package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
- package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
- package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
- package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
- package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
- package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
- package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
- package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
- package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
- package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
- package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
- package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
- package/bin/cc-pets +8 -6
- package/bin/claude-with-pet +10 -2
- package/bin/codex-with-pet +13 -5
- package/package.json +1 -1
- package/scripts/build.sh +7 -3
- package/scripts/i18n.zsh +9 -52
- package/scripts/install-app.sh +4 -0
- package/scripts/install-shell-integration.sh +17 -10
- package/scripts/uninstall-shell-integration.sh +6 -1
- package/Sources/CCPets/CCPetsEvents.h +0 -10
- package/Sources/CCPets/CCPetsUsage.h +0 -36
- package/Sources/CCPets/CCPetsUsage.m +0 -2069
- package/Sources/CCPets/PetView.m +0 -1839
- package/Sources/CCPets/QuotaDashboardView.m +0 -1145
- package/scripts/bridge/cli.mjs +0 -237
- package/scripts/bridge/core.mjs +0 -228
- package/scripts/bridge/hook.mjs +0 -150
- package/scripts/bridge/install.mjs +0 -311
- package/scripts/bridge/mcp-server.mjs +0 -308
- package/scripts/bridge/options.mjs +0 -87
- package/scripts/bridge/process.mjs +0 -151
- package/scripts/bridge/reservations.mjs +0 -248
- package/scripts/bridge/store.mjs +0 -433
- package/scripts/bridge/watch.mjs +0 -69
- package/scripts/check-l10n.mjs +0 -168
- package/scripts/configure-updater.mjs +0 -43
- package/scripts/detect-cli.mjs +0 -68
- package/scripts/doctor.mjs +0 -470
- package/scripts/i18n.mjs +0 -122
- package/scripts/install-claude-hooks.mjs +0 -253
- package/scripts/install-codex-hooks.mjs +0 -78
- package/scripts/integration-markers.mjs +0 -51
- package/scripts/locales/zh-Hans.json +0 -366
- package/scripts/pet-store.mjs +0 -415
- package/scripts/uninstall-integrations.mjs +0 -205
- /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
- /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
- /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
- /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
- /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
- /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
- /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
- /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
- /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
- /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
- /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
#import "CCPetsUsage+Internal.h"
|
|
2
|
+
|
|
3
|
+
static NSTimeInterval LineTimestamp(NSData *line) {
|
|
4
|
+
if (line.length == 0) return 0;
|
|
5
|
+
id root = [NSJSONSerialization JSONObjectWithData:line options:0 error:nil];
|
|
6
|
+
if (![root isKindOfClass:NSDictionary.class]) return 0;
|
|
7
|
+
NSDate *date = ISO8601Timestamp(((NSDictionary *)root)[@"timestamp"]);
|
|
8
|
+
return date ? date.timeIntervalSince1970 : 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// 按块切行喂给 consume,返回消费掉的字节数(截止最后一个换行)。返回值就是下一次可以
|
|
12
|
+
// 安全续读的偏移:结尾那半行还没写完,不能算进去。includeTail=YES 时残行照样交给
|
|
13
|
+
// consume(一次性整篇扫描的调用方要它,最后一行未必有换行结尾)。
|
|
14
|
+
static unsigned long long EnumerateLines(NSFileHandle *handle, BOOL includeTail,
|
|
15
|
+
void (^consume)(NSData *)) {
|
|
16
|
+
NSMutableData *pending = [NSMutableData data];
|
|
17
|
+
unsigned long long consumed = 0;
|
|
18
|
+
while (YES) {
|
|
19
|
+
NSData *chunk = [handle readDataOfLength:256 * 1024];
|
|
20
|
+
if (chunk.length == 0) break;
|
|
21
|
+
[pending appendData:chunk];
|
|
22
|
+
const uint8_t *bytes = pending.bytes;
|
|
23
|
+
NSUInteger lineStart = 0;
|
|
24
|
+
for (NSUInteger index = 0; index < pending.length; index++) {
|
|
25
|
+
if (bytes[index] != '\n') continue;
|
|
26
|
+
if (index > lineStart) {
|
|
27
|
+
consume([pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
|
|
28
|
+
}
|
|
29
|
+
lineStart = index + 1;
|
|
30
|
+
}
|
|
31
|
+
if (lineStart > 0) {
|
|
32
|
+
consumed += lineStart;
|
|
33
|
+
pending = [[pending subdataWithRange:NSMakeRange(
|
|
34
|
+
lineStart, pending.length - lineStart)] mutableCopy];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (includeTail && pending.length > 0) consume(pending);
|
|
38
|
+
return consumed;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
42
|
+
for (NSString *key in TokenKeys()) {
|
|
43
|
+
unsigned long long current = [target[key] unsignedLongLongValue];
|
|
44
|
+
unsigned long long addition = [counts[key] unsignedLongLongValue];
|
|
45
|
+
if (counts[key]) target[key] = @(current + addition);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// total_token_usage 是会话内累计值,但同一个 rollout 文件里它会中途归零重来:resume 或
|
|
50
|
+
// 上下文压缩之后进程从头开始计数。本机近 14 天 106 个会话里 3 个如此,最狠的一个从
|
|
51
|
+
// 1098 万掉回 11 万——只认末行 total 的话,归零之前那一整段全被吞掉(该会话真实用量
|
|
52
|
+
// 约 1146 万,末行只有 47 万,漏掉 96%)。因此把会话按归零点切成若干段:段内仍然用
|
|
53
|
+
// 累计值(对重复写入的 token_count 幂等),段与段之间相加。
|
|
54
|
+
static BOOL TokenTotalsDidReset(NSDictionary *totals, NSDictionary *previous) {
|
|
55
|
+
for (NSString *key in TokenKeys()) {
|
|
56
|
+
if (!totals[key] || !previous[key]) continue;
|
|
57
|
+
if ([totals[key] unsignedLongLongValue] < [previous[key] unsignedLongLongValue]) return YES;
|
|
58
|
+
}
|
|
59
|
+
return NO;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
static NSDictionary *SummedSegmentTotals(NSArray<NSDictionary *> *segments) {
|
|
63
|
+
NSMutableDictionary *total = [NSMutableDictionary dictionary];
|
|
64
|
+
for (NSDictionary *segment in segments) AddTokenCounts(total, segment);
|
|
65
|
+
return total;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 日桶除 Token 字段外还带 request_count,合并时要一起累加。
|
|
69
|
+
static void AddDailyTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
70
|
+
AddTokenCounts(target, counts);
|
|
71
|
+
if (!counts[@"request_count"]) return;
|
|
72
|
+
target[@"request_count"] = @([target[@"request_count"] unsignedLongLongValue] +
|
|
73
|
+
[counts[@"request_count"] unsignedLongLongValue]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
static NSString *DayBucketKey(NSTimeInterval dayStart) {
|
|
77
|
+
return [NSString stringWithFormat:@"%.0f", dayStart];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 带模型的摘要条目的版本。2 起会话摘要多了 modelDays / model(按模型归属的日桶)。
|
|
81
|
+
// 只有用量页(trackModels)要这两样:旧条目没法凭已有字段补出来,只能整篇重读——版本对不上就当没缓存。
|
|
82
|
+
// 悬停面板不看模型,也不检查版本,升级后它的缓存照旧可用,不会在主线程上把会话全部重读一遍。
|
|
83
|
+
static const NSInteger TokenSummaryVersion = 2;
|
|
84
|
+
|
|
85
|
+
// 不是真实模型:Claude Code 给本地注入的消息打的占位名,没有对应的用量。
|
|
86
|
+
BOOL IsPseudoModelName(NSString *model) {
|
|
87
|
+
return model.length == 0 || [model hasPrefix:@"<"];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 每个回合开头 Codex 会写一行 turn_context,model 在它的 payload 里,和 token_count 不在同一行。
|
|
91
|
+
// 这行很大(带着整份沙箱 / 权限配置),先用标记过滤,只有命中的才值得做 JSON 解析。
|
|
92
|
+
static NSString *ModelFromTurnContextLine(NSData *lineData) {
|
|
93
|
+
static NSData *marker;
|
|
94
|
+
static dispatch_once_t once;
|
|
95
|
+
dispatch_once(&once, ^{
|
|
96
|
+
marker = [@"\"type\":\"turn_context\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
97
|
+
});
|
|
98
|
+
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
99
|
+
NSNotFound) return nil;
|
|
100
|
+
id root = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
101
|
+
if (![root isKindOfClass:NSDictionary.class]) return nil;
|
|
102
|
+
if (![root[@"type"] isEqual:@"turn_context"]) return nil;
|
|
103
|
+
NSDictionary *payload = [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : nil;
|
|
104
|
+
NSString *model = [payload[@"model"] isKindOfClass:NSString.class] ? payload[@"model"] : nil;
|
|
105
|
+
return IsPseudoModelName(model) ? nil : model;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline);
|
|
109
|
+
|
|
110
|
+
// 分段必须整篇扫描(末行 total 不再够用),因此改成按偏移增量追读:活跃会话每轮只解析
|
|
111
|
+
// 新增的那几行,段状态(各段末尾的累计值)留在缓存里续接。
|
|
112
|
+
//
|
|
113
|
+
// 解析时顺手把每条记录的增量摊到它所属的自然日(summary[@"days"])。API 视图要画一个月的
|
|
114
|
+
// 日曲线,如果改成按天各扫一遍窗口,跨天会话会被 PartialTokenTotals 整篇重读 31 次——
|
|
115
|
+
// 实测本机每次刷新要多花 130ms,全落在主线程上,悬停时连拖动都会卡住。
|
|
116
|
+
//
|
|
117
|
+
// trackModels 只给用量页(后台线程)用:按 turn_context 把增量再分到模型名下。悬停面板走主线程、
|
|
118
|
+
// 用不到模型,关掉后不碰 turn_context 行,省掉逐行查标记和对大行的 JSON 解析。
|
|
119
|
+
NSDictionary *TokenSessionSummaryTracking(NSURL *url, NSMutableDictionary *cache,
|
|
120
|
+
BOOL trackModels) {
|
|
121
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path error:nil];
|
|
122
|
+
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
123
|
+
NSDictionary *cached = cache[url.path];
|
|
124
|
+
if (trackModels && cached && [cached[@"v"] integerValue] != TokenSummaryVersion) cached = nil;
|
|
125
|
+
// 没有 token_count 的会话(旧格式、被截断、刚创建)也会留下缓存条目,否则每一轮都要
|
|
126
|
+
// 把整篇重读一遍。文件长大后 size 变化自然会让缓存失效。
|
|
127
|
+
if (cached && [cached[@"size"] unsignedLongLongValue] == size) {
|
|
128
|
+
return (cached[@"start"] && cached[@"total"]) ? cached : nil;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
unsigned long long offset = 0;
|
|
132
|
+
NSMutableArray<NSDictionary *> *segments = [NSMutableArray array];
|
|
133
|
+
NSMutableArray<NSNumber *> *requestTimestamps = [NSMutableArray array];
|
|
134
|
+
NSMutableDictionary<NSString *, NSMutableDictionary *> *days = [NSMutableDictionary dictionary];
|
|
135
|
+
// 日 -> 模型 -> 用量。模型跟着"当时生效的 turn_context"走:会话中途 /model 切换后,
|
|
136
|
+
// 后面的增量归新模型。追读时 currentModel 要跟着缓存一起续上,否则从中间续读的那段没人认领。
|
|
137
|
+
NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSMutableDictionary *> *> *modelDays =
|
|
138
|
+
[NSMutableDictionary dictionary];
|
|
139
|
+
__block NSString *currentModel = nil;
|
|
140
|
+
__block NSNumber *start = nil;
|
|
141
|
+
__block NSTimeInterval last = 0;
|
|
142
|
+
__block NSDictionary *lastRequestTotal = nil;
|
|
143
|
+
if (cached) {
|
|
144
|
+
unsigned long long cachedOffset = [cached[@"offset"] unsignedLongLongValue];
|
|
145
|
+
// offset > size 只可能是文件被改写(截断/重建),旧的段全部作废,整篇重来。
|
|
146
|
+
if (cachedOffset <= size) {
|
|
147
|
+
offset = cachedOffset;
|
|
148
|
+
start = [cached[@"start"] isKindOfClass:NSNumber.class] ? cached[@"start"] : nil;
|
|
149
|
+
last = [cached[@"end"] doubleValue];
|
|
150
|
+
if ([cached[@"segments"] isKindOfClass:NSArray.class]) {
|
|
151
|
+
[segments addObjectsFromArray:cached[@"segments"]];
|
|
152
|
+
}
|
|
153
|
+
if ([cached[@"requestTimestamps"] isKindOfClass:NSArray.class]) {
|
|
154
|
+
[requestTimestamps addObjectsFromArray:cached[@"requestTimestamps"]];
|
|
155
|
+
}
|
|
156
|
+
if ([cached[@"days"] isKindOfClass:NSDictionary.class]) {
|
|
157
|
+
for (NSString *key in (NSDictionary *)cached[@"days"]) {
|
|
158
|
+
days[key] = [cached[@"days"][key] mutableCopy];
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
lastRequestTotal = [cached[@"lastRequestTotal"] isKindOfClass:NSDictionary.class]
|
|
162
|
+
? cached[@"lastRequestTotal"] : nil;
|
|
163
|
+
currentModel = trackModels && [cached[@"model"] isKindOfClass:NSString.class]
|
|
164
|
+
? cached[@"model"] : nil;
|
|
165
|
+
NSDictionary *cachedModelDays = trackModels &&
|
|
166
|
+
[cached[@"modelDays"] isKindOfClass:NSDictionary.class] ? cached[@"modelDays"] : nil;
|
|
167
|
+
for (NSString *dayKey in cachedModelDays) {
|
|
168
|
+
NSMutableDictionary *perModel = [NSMutableDictionary dictionary];
|
|
169
|
+
for (NSString *model in cachedModelDays[dayKey]) {
|
|
170
|
+
perModel[model] = [cachedModelDays[dayKey][model] mutableCopy];
|
|
171
|
+
}
|
|
172
|
+
modelDays[dayKey] = perModel;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
178
|
+
// 会话内记录是按时间递增写入的,日边界只在跨天那一条上重算,不必每条都问日历。
|
|
179
|
+
__block NSTimeInterval bucketStart = 0;
|
|
180
|
+
__block NSTimeInterval bucketEnd = 0;
|
|
181
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
182
|
+
if (!handle) return nil;
|
|
183
|
+
if (offset > 0) [handle seekToFileOffset:offset];
|
|
184
|
+
unsigned long long consumed = EnumerateLines(handle, NO, ^(NSData *line) {
|
|
185
|
+
// 会话起点取文件第一条带 timestamp 的行,不限于 token_count:它决定这个会话算不算
|
|
186
|
+
// 整段落在窗口内。找到之后就不再对普通行做 JSON 解析。
|
|
187
|
+
if (!start) {
|
|
188
|
+
NSTimeInterval timestamp = LineTimestamp(line);
|
|
189
|
+
if (timestamp > 0) start = @(timestamp);
|
|
190
|
+
}
|
|
191
|
+
NSString *turnModel = trackModels ? ModelFromTurnContextLine(line) : nil;
|
|
192
|
+
if (turnModel) {
|
|
193
|
+
currentModel = turnModel;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
NSDictionary *record = TokenRecordFromLine(line);
|
|
197
|
+
NSDictionary *total = record[@"total"];
|
|
198
|
+
if (!total) return;
|
|
199
|
+
last = [record[@"timestamp"] doubleValue];
|
|
200
|
+
// Codex 会重复写同一份累计快照,事件行数不能直接当调用次数。累计值发生变化才代表
|
|
201
|
+
// 一次新的模型响应;上下文压缩导致累计值归零时同样会被识别为新响应。
|
|
202
|
+
BOOL newRequest = !lastRequestTotal || ![total isEqualToDictionary:lastRequestTotal];
|
|
203
|
+
if (newRequest) [requestTimestamps addObject:record[@"timestamp"]];
|
|
204
|
+
// 段内用累计值相减、归零时整份计入,与 TokenSessionSummary 的分段口径一致:
|
|
205
|
+
// 逐条增量相加会收敛回段末的累计值,因此日桶之和等于 summary[@"total"]。
|
|
206
|
+
NSDictionary *increment = TokenCountsBySubtracting(total, lastRequestTotal);
|
|
207
|
+
if (last < bucketStart || last >= bucketEnd) {
|
|
208
|
+
NSDate *dayStart = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:last]];
|
|
209
|
+
NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:dayStart
|
|
210
|
+
options:0];
|
|
211
|
+
bucketStart = dayStart.timeIntervalSince1970;
|
|
212
|
+
bucketEnd = (next ?: [dayStart dateByAddingTimeInterval:86400]).timeIntervalSince1970;
|
|
213
|
+
}
|
|
214
|
+
NSString *dayKey = DayBucketKey(bucketStart);
|
|
215
|
+
NSMutableDictionary *bucket = days[dayKey];
|
|
216
|
+
if (!bucket) {
|
|
217
|
+
bucket = [NSMutableDictionary dictionary];
|
|
218
|
+
days[dayKey] = bucket;
|
|
219
|
+
}
|
|
220
|
+
AddTokenCounts(bucket, increment);
|
|
221
|
+
if (newRequest) {
|
|
222
|
+
bucket[@"request_count"] = @([bucket[@"request_count"] unsignedLongLongValue] + 1);
|
|
223
|
+
}
|
|
224
|
+
// 同一份增量再按模型记一遍。没见过 turn_context 就记在 unknown 名下,总量对得上。
|
|
225
|
+
if (trackModels) {
|
|
226
|
+
NSMutableDictionary<NSString *, NSMutableDictionary *> *perModel = modelDays[dayKey];
|
|
227
|
+
if (!perModel) {
|
|
228
|
+
perModel = [NSMutableDictionary dictionary];
|
|
229
|
+
modelDays[dayKey] = perModel;
|
|
230
|
+
}
|
|
231
|
+
NSString *modelName = currentModel ?: @"unknown";
|
|
232
|
+
NSMutableDictionary *modelBucket = perModel[modelName];
|
|
233
|
+
if (!modelBucket) {
|
|
234
|
+
modelBucket = [NSMutableDictionary dictionary];
|
|
235
|
+
perModel[modelName] = modelBucket;
|
|
236
|
+
}
|
|
237
|
+
AddTokenCounts(modelBucket, increment);
|
|
238
|
+
if (newRequest) {
|
|
239
|
+
modelBucket[@"request_count"] = @([modelBucket[@"request_count"] unsignedLongLongValue] + 1);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
lastRequestTotal = total;
|
|
243
|
+
NSDictionary *previous = segments.lastObject;
|
|
244
|
+
if (!previous || TokenTotalsDidReset(total, previous)) [segments addObject:total];
|
|
245
|
+
else segments[segments.count - 1] = total;
|
|
246
|
+
});
|
|
247
|
+
[handle closeFile];
|
|
248
|
+
|
|
249
|
+
NSMutableDictionary *summary = [@{@"size": @(size), @"offset": @(offset + consumed)} mutableCopy];
|
|
250
|
+
// 不跟踪模型的条目不打版本:它没有 modelDays,用量页读到时要当没缓存、整篇重读。
|
|
251
|
+
if (trackModels) summary[@"v"] = @(TokenSummaryVersion);
|
|
252
|
+
if (currentModel) summary[@"model"] = currentModel;
|
|
253
|
+
if (start) summary[@"start"] = start;
|
|
254
|
+
if (segments.count > 0) {
|
|
255
|
+
summary[@"segments"] = [segments copy];
|
|
256
|
+
summary[@"end"] = @(last);
|
|
257
|
+
summary[@"total"] = SummedSegmentTotals(segments);
|
|
258
|
+
summary[@"requestTimestamps"] = [requestTimestamps copy];
|
|
259
|
+
// 冻结成不可变,避免下一轮增量追读时改到已经交给调用方的那份。
|
|
260
|
+
NSMutableDictionary *frozenDays = [NSMutableDictionary dictionaryWithCapacity:days.count];
|
|
261
|
+
for (NSString *key in days) frozenDays[key] = [days[key] copy];
|
|
262
|
+
summary[@"days"] = [frozenDays copy];
|
|
263
|
+
NSMutableDictionary *frozenModelDays = [NSMutableDictionary dictionaryWithCapacity:modelDays.count];
|
|
264
|
+
for (NSString *dayKey in modelDays) {
|
|
265
|
+
NSMutableDictionary *perModel = [NSMutableDictionary dictionary];
|
|
266
|
+
for (NSString *model in modelDays[dayKey]) perModel[model] = [modelDays[dayKey][model] copy];
|
|
267
|
+
frozenModelDays[dayKey] = [perModel copy];
|
|
268
|
+
}
|
|
269
|
+
if (trackModels) summary[@"modelDays"] = [frozenModelDays copy];
|
|
270
|
+
if (lastRequestTotal) summary[@"lastRequestTotal"] = lastRequestTotal;
|
|
271
|
+
}
|
|
272
|
+
cache[url.path] = summary;
|
|
273
|
+
return (start && summary[@"total"]) ? summary : nil;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache) {
|
|
277
|
+
return TokenSessionSummaryTracking(url, cache, NO);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// 累计值相减,而不是累加窗口内的 last_token_usage:Codex 会把同一份 token_count
|
|
281
|
+
// 重复写进会话(本机近期 68 个会话里 14 个如此,sum(last) 整体比末行 total 高 1.1%,
|
|
282
|
+
// 最差的单个会话高 7.7%),累加就把重复的那次算了两遍。累计值对重复事件是幂等的。
|
|
283
|
+
// total_token_usage 罕见地回退(会话内重置)时,窗口前的基线已经失效,直接取窗口内的值。
|
|
284
|
+
static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline) {
|
|
285
|
+
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
|
286
|
+
for (NSString *key in TokenKeys()) {
|
|
287
|
+
if (!totals[key]) continue;
|
|
288
|
+
unsigned long long current = [totals[key] unsignedLongLongValue];
|
|
289
|
+
unsigned long long previous = [baseline[key] unsignedLongLongValue];
|
|
290
|
+
result[key] = @(current >= previous ? current - previous : current);
|
|
291
|
+
}
|
|
292
|
+
return result;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// 跨窗口起点的会话只算窗口内的增量。分段规则与 TokenSessionSummary 一致:累计值一旦
|
|
296
|
+
// 归零,窗口起点之前取到的基线就作废了,后面那一段要从 0 起算,段与段的增量再相加。
|
|
297
|
+
static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTimeInterval end) {
|
|
298
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
299
|
+
if (!handle) return nil;
|
|
300
|
+
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
|
301
|
+
__block NSDictionary *previous = nil;
|
|
302
|
+
__block NSDictionary *baseline = nil;
|
|
303
|
+
__block NSDictionary *inside = nil;
|
|
304
|
+
// 窗口内一条 token_count 都没有的段不贡献任何用量。
|
|
305
|
+
void (^flush)(void) = ^{
|
|
306
|
+
if (inside) AddTokenCounts(result, TokenCountsBySubtracting(inside, baseline));
|
|
307
|
+
baseline = nil;
|
|
308
|
+
inside = nil;
|
|
309
|
+
};
|
|
310
|
+
EnumerateLines(handle, YES, ^(NSData *line) {
|
|
311
|
+
NSDictionary *record = TokenRecordFromLine(line);
|
|
312
|
+
NSDictionary *total = record[@"total"];
|
|
313
|
+
if (!total) return;
|
|
314
|
+
if (previous && TokenTotalsDidReset(total, previous)) flush();
|
|
315
|
+
previous = total;
|
|
316
|
+
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
317
|
+
if (timestamp < start) baseline = total;
|
|
318
|
+
else if (timestamp < end) inside = total;
|
|
319
|
+
});
|
|
320
|
+
flush();
|
|
321
|
+
[handle closeFile];
|
|
322
|
+
return result;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// 聚合区间对齐官方重置时间:[resets_at - 窗长, resets_at)。
|
|
326
|
+
// Codex 的 rate_limits 自带 window_minutes;Claude 没有这个字段,由调用方给出订阅
|
|
327
|
+
// 固定的 300 / 10080 分钟作为兜底。返回 NO 表示窗口当前不可用(缺 resets_at 或已过期),
|
|
328
|
+
// 此时不做任何 Token 统计,避免拿过期窗口冒充当前值。
|
|
329
|
+
static BOOL TokenWindowForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
330
|
+
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
331
|
+
NSNumber *minutes = [quota[@"window_minutes"] isKindOfClass:NSNumber.class]
|
|
332
|
+
? quota[@"window_minutes"] : nil;
|
|
333
|
+
double windowMinutes = minutes ? minutes.doubleValue : fallbackMinutes;
|
|
334
|
+
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
335
|
+
if (windowMinutes <= 0 || !reset) return NO;
|
|
336
|
+
NSTimeInterval end = reset.doubleValue;
|
|
337
|
+
if (NSDate.date.timeIntervalSince1970 >= end) return NO;
|
|
338
|
+
if (outStart) *outStart = end - windowMinutes * 60.0;
|
|
339
|
+
if (outEnd) *outEnd = end;
|
|
340
|
+
return YES;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// 官方窗口拿不到时(账号根本没有这个窗口、缺 resets_at、或窗口已过期),Token 依然是
|
|
344
|
+
// 本机自己数出来的,没有理由跟着变成 `--`。退化成按本机时钟往回推的滚动窗口。
|
|
345
|
+
// 终点向上对齐到 10 分钟:起点每秒都在动的话,分片缓存的键每轮都变,跨界会话会被整篇重扫。
|
|
346
|
+
static const NSTimeInterval TokenFallbackGranularity = 600;
|
|
347
|
+
static void RollingWindowForMinutes(double minutes, NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
348
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
349
|
+
NSTimeInterval end = (floor(now / TokenFallbackGranularity) + 1) * TokenFallbackGranularity;
|
|
350
|
+
if (outStart) *outStart = end - minutes * 60.0;
|
|
351
|
+
if (outEnd) *outEnd = end;
|
|
352
|
+
}
|
|
353
|
+
BOOL TokenWindowOrFallback(NSDictionary *quota, double fallbackMinutes,
|
|
354
|
+
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
355
|
+
if (TokenWindowForQuota(quota, fallbackMinutes, outStart, outEnd)) return YES;
|
|
356
|
+
if (fallbackMinutes <= 0) return NO;
|
|
357
|
+
RollingWindowForMinutes(fallbackMinutes, outStart, outEnd);
|
|
358
|
+
return YES;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 面板要并列展示两家数据,而两家的 resets_at 并不一致(实测能差 2 天以上),
|
|
362
|
+
// 所以汇总另用一组与订阅完全脱钩的自然日窗口,保证两家的时间口径一致。
|
|
363
|
+
//
|
|
364
|
+
// 取自然日边界而不是"从现在往回推 N 秒",是因为分片缓存的键里含窗口起点:起点每秒
|
|
365
|
+
// 都在动的话,跨界会话每一轮都要整篇重扫;对齐到零点后起点一天之内不变,缓存才能命中。
|
|
366
|
+
void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *weekStart,
|
|
367
|
+
NSTimeInterval *end) {
|
|
368
|
+
NSDate *now = NSDate.date;
|
|
369
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
370
|
+
NSDate *midnight = [calendar startOfDayForDate:now];
|
|
371
|
+
if (todayStart) *todayStart = midnight.timeIntervalSince1970;
|
|
372
|
+
if (weekStart) {
|
|
373
|
+
NSDate *start = [calendar dateByAddingUnit:NSCalendarUnitDay value:-6 toDate:midnight
|
|
374
|
+
options:0];
|
|
375
|
+
*weekStart = (start ?: midnight).timeIntervalSince1970;
|
|
376
|
+
}
|
|
377
|
+
// 时钟轻微前后跳动时,不要把刚落盘的记录挡在窗口外,因此终点先留出 60 秒余量。
|
|
378
|
+
// 之后再向上对齐到 10 分钟:分片缓存的键里同时含起点和终点,终点每秒都在动的话,
|
|
379
|
+
// 键每一轮都是新的,起点对齐到零点省下的那次命中会被它整个抵消——跨界会话照样
|
|
380
|
+
// 每轮重扫,而且上一轮写下的分片还会被 PruneTokenCache 当成过期窗口清掉。
|
|
381
|
+
if (end) {
|
|
382
|
+
*end = ceil((now.timeIntervalSince1970 + 60) / TokenFallbackGranularity) *
|
|
383
|
+
TokenFallbackGranularity;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 自然月窗口。本月是 1 日 00:00 起算,展示区间到"此刻",曲线区间到月底。
|
|
388
|
+
//
|
|
389
|
+
// 同比区间两边都只数到"最后一个完整的自然日":本月 1 日至今日 00:00,对比上月 1 日至上月
|
|
390
|
+
// 第 N 日 00:00(N = 本月已过完的整日数)。刻意不做到同一时刻——上月的数据来自日粒度的
|
|
391
|
+
// 归档,切不出"14 日 15:30"这种半天;而月度同比本来就是趋势判断,差半天换来"上月的会话
|
|
392
|
+
// 文件一次都不用再打开",这笔账是划算的。上月天数不够时(3 月 31 日对比 2 月)封顶到上月末。
|
|
393
|
+
NSDictionary *CalendarMonthWindows(NSTimeInterval alignedEnd) {
|
|
394
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
395
|
+
NSDate *now = NSDate.date;
|
|
396
|
+
NSDate *monthStart = CurrentMonthStartDate();
|
|
397
|
+
NSDate *nextMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:1
|
|
398
|
+
toDate:monthStart options:0] ?: now;
|
|
399
|
+
NSDate *previousMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-1
|
|
400
|
+
toDate:monthStart options:0] ?: monthStart;
|
|
401
|
+
NSDate *todayStart = [calendar startOfDayForDate:now];
|
|
402
|
+
NSInteger elapsedDays = [calendar components:NSCalendarUnitDay fromDate:monthStart
|
|
403
|
+
toDate:todayStart options:0].day;
|
|
404
|
+
if (elapsedDays < 0) elapsedDays = 0;
|
|
405
|
+
NSDate *previousComparableEnd = [calendar dateByAddingUnit:NSCalendarUnitDay
|
|
406
|
+
value:(int)elapsedDays toDate:previousMonthStart options:0] ?: previousMonthStart;
|
|
407
|
+
NSTimeInterval currentStart = monthStart.timeIntervalSince1970;
|
|
408
|
+
return @{ @"monthStart": @(currentStart),
|
|
409
|
+
@"monthEnd": @(fmin(alignedEnd, nextMonthStart.timeIntervalSince1970)),
|
|
410
|
+
@"monthCurveEnd": @(nextMonthStart.timeIntervalSince1970),
|
|
411
|
+
// 每月 1 号这一天 todayStart == monthStart,同比区间两边都是空的,比出来是"持平"。
|
|
412
|
+
@"monthComparableEnd": @(todayStart.timeIntervalSince1970),
|
|
413
|
+
@"previousMonthStart": @(previousMonthStart.timeIntervalSince1970),
|
|
414
|
+
@"previousMonthEnd": @(fmin(currentStart,
|
|
415
|
+
previousComparableEnd.timeIntervalSince1970)) };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end) {
|
|
419
|
+
return [NSString stringWithFormat:@"partial-%.0f-%.0f", start, end];
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// requestTimestamps 按写入顺序递增,取区间计数用二分即可:逐条比较要在每个窗口上把
|
|
423
|
+
// 所有会话的时间戳全走一遍,窗口一多就成了主线程上的固定开销。
|
|
424
|
+
static NSUInteger TimestampLowerBound(NSArray<NSNumber *> *timestamps, NSTimeInterval value) {
|
|
425
|
+
NSUInteger low = 0;
|
|
426
|
+
NSUInteger high = timestamps.count;
|
|
427
|
+
while (low < high) {
|
|
428
|
+
NSUInteger middle = low + (high - low) / 2;
|
|
429
|
+
if (timestamps[middle].doubleValue < value) low = middle + 1;
|
|
430
|
+
else high = middle;
|
|
431
|
+
}
|
|
432
|
+
return low;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval end,
|
|
436
|
+
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
437
|
+
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
438
|
+
BOOL hasTokenSchema = NO;
|
|
439
|
+
unsigned long long requestCount = 0;
|
|
440
|
+
for (NSURL *url in urls) {
|
|
441
|
+
NSMutableDictionary *summary = [(NSDictionary *)TokenSessionSummary(url, cache) mutableCopy];
|
|
442
|
+
if (!summary) continue;
|
|
443
|
+
hasTokenSchema = YES;
|
|
444
|
+
NSTimeInterval sessionStart = [summary[@"start"] doubleValue];
|
|
445
|
+
NSTimeInterval sessionEnd = [summary[@"end"] doubleValue];
|
|
446
|
+
if (sessionEnd < start || sessionStart >= end) continue;
|
|
447
|
+
NSArray<NSNumber *> *timestamps = [summary[@"requestTimestamps"] isKindOfClass:NSArray.class]
|
|
448
|
+
? summary[@"requestTimestamps"] : @[];
|
|
449
|
+
requestCount += TimestampLowerBound(timestamps, end) -
|
|
450
|
+
TimestampLowerBound(timestamps, start);
|
|
451
|
+
if (sessionStart >= start) {
|
|
452
|
+
AddTokenCounts(totals, summary[@"total"]);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
NSString *partialKey = PartialTokenKey(start, end);
|
|
456
|
+
NSDictionary *partial = summary[partialKey];
|
|
457
|
+
if (!partial) {
|
|
458
|
+
partial = PartialTokenTotals(url, start, end) ?: @{};
|
|
459
|
+
summary[partialKey] = partial;
|
|
460
|
+
cache[url.path] = summary;
|
|
461
|
+
}
|
|
462
|
+
AddTokenCounts(totals, partial);
|
|
463
|
+
}
|
|
464
|
+
if (!hasTokenSchema) return nil;
|
|
465
|
+
// 有会话但没有一条落在窗口内时,真实用量就是 0,不能退化成"无数据"的 `--`。
|
|
466
|
+
if (totals.count == 0) {
|
|
467
|
+
for (NSString *key in TokenKeys()) totals[key] = @0;
|
|
468
|
+
}
|
|
469
|
+
totals[@"request_count"] = @(requestCount);
|
|
470
|
+
return totals;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
NSDictionary *TokenTotalsForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
474
|
+
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
475
|
+
NSTimeInterval start = 0;
|
|
476
|
+
NSTimeInterval end = 0;
|
|
477
|
+
if (!TokenWindowOrFallback(quota, fallbackMinutes, &start, &end)) return nil;
|
|
478
|
+
return TokenTotalsInWindow(start, end, urls, cache);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// 日曲线直接汇总各会话解析时就分好的日桶:一天一次窗口聚合会让跨天会话被整篇重读,
|
|
482
|
+
// 而日桶只是遍历一遍缓存里的小字典。
|
|
483
|
+
NSArray<NSDictionary *> *CodexDailyTokenSeries(NSTimeInterval start, NSTimeInterval end,
|
|
484
|
+
NSArray<NSURL *> *urls, NSMutableDictionary *cache, BOOL *outHasTokenSchema) {
|
|
485
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
486
|
+
NSMutableArray<NSNumber *> *dayStarts = [NSMutableArray array];
|
|
487
|
+
NSMutableDictionary<NSString *, NSMutableDictionary *> *buckets = [NSMutableDictionary dictionary];
|
|
488
|
+
NSDate *cursor = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:start]];
|
|
489
|
+
while (cursor.timeIntervalSince1970 < end) {
|
|
490
|
+
NSTimeInterval dayStart = cursor.timeIntervalSince1970;
|
|
491
|
+
if (dayStart >= start) {
|
|
492
|
+
[dayStarts addObject:@(dayStart)];
|
|
493
|
+
buckets[DayBucketKey(dayStart)] = [NSMutableDictionary dictionary];
|
|
494
|
+
}
|
|
495
|
+
NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
|
|
496
|
+
if (!next) break;
|
|
497
|
+
cursor = next;
|
|
498
|
+
}
|
|
499
|
+
for (NSURL *url in urls) {
|
|
500
|
+
NSDictionary *summary = TokenSessionSummary(url, cache);
|
|
501
|
+
NSDictionary *days = [summary[@"days"] isKindOfClass:NSDictionary.class]
|
|
502
|
+
? summary[@"days"] : nil;
|
|
503
|
+
if (days && outHasTokenSchema) *outHasTokenSchema = YES;
|
|
504
|
+
for (NSString *key in days) {
|
|
505
|
+
NSMutableDictionary *bucket = buckets[key];
|
|
506
|
+
if (bucket) AddDailyTokenCounts(bucket, days[key]);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
NSMutableArray<NSDictionary *> *series = [NSMutableArray arrayWithCapacity:dayStarts.count];
|
|
510
|
+
for (NSNumber *dayStart in dayStarts) {
|
|
511
|
+
NSMutableDictionary *bucket = buckets[DayBucketKey(dayStart.doubleValue)];
|
|
512
|
+
// 没有任何记录的那天是真实的 0,不能留成空字典让调用方当"无数据"。
|
|
513
|
+
for (NSString *key in TokenKeys()) if (!bucket[key]) bucket[key] = @0;
|
|
514
|
+
if (!bucket[@"request_count"]) bucket[@"request_count"] = @0;
|
|
515
|
+
[series addObject:@{ @"timestamp": dayStart, @"totals": [bucket copy] }];
|
|
516
|
+
}
|
|
517
|
+
return series;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// 本月至今的窗口起点是自然日零点、终点在未来(对齐到 10 分钟的"现在"),窗口内不可能有
|
|
521
|
+
// 半天,所以日桶之和与按窗口聚合逐字节等价——省掉一遍对全部会话的窗口扫描。
|
|
522
|
+
// 上月同期的终点落在某天中间,仍然要走 TokenTotalsInWindow。
|
|
523
|
+
NSDictionary *SummedDailyTokenSeries(NSArray<NSDictionary *> *series) {
|
|
524
|
+
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
525
|
+
for (NSDictionary *day in series) AddDailyTokenCounts(totals, day[@"totals"]);
|
|
526
|
+
for (NSString *key in TokenKeys()) if (!totals[key]) totals[key] = @0;
|
|
527
|
+
if (!totals[@"request_count"]) totals[@"request_count"] = @0;
|
|
528
|
+
return totals;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// 日序列里 [start, end) 之间那几天的合计。同比两侧都靠它切出"到最后一个完整自然日为止"。
|
|
532
|
+
NSDictionary *SummedDailyTokenSeriesInRange(NSArray<NSDictionary *> *series,
|
|
533
|
+
NSTimeInterval start, NSTimeInterval end) {
|
|
534
|
+
NSMutableArray<NSDictionary *> *slice = [NSMutableArray array];
|
|
535
|
+
for (NSDictionary *day in series) {
|
|
536
|
+
NSTimeInterval timestamp = [day[@"timestamp"] doubleValue];
|
|
537
|
+
if (timestamp >= start && timestamp < end) [slice addObject:day];
|
|
538
|
+
}
|
|
539
|
+
return SummedDailyTokenSeries(slice);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// 会话滚出 7 天窗口、额度窗口滚动之后,缓存里对应的条目和 partial-* 分片再也不会被读到。
|
|
543
|
+
// 常驻进程不清理就是只增不减。
|
|
544
|
+
void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
|
|
545
|
+
NSSet<NSString *> *liveWindowKeys) {
|
|
546
|
+
NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
|
|
547
|
+
for (NSURL *url in urls) [livePaths addObject:url.path];
|
|
548
|
+
for (NSString *path in cache.allKeys) {
|
|
549
|
+
if (![livePaths containsObject:path]) {
|
|
550
|
+
[cache removeObjectForKey:path];
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
NSDictionary *summary = cache[path];
|
|
554
|
+
NSMutableDictionary *trimmed = nil;
|
|
555
|
+
for (NSString *key in summary.allKeys) {
|
|
556
|
+
if (![key hasPrefix:@"partial-"] || [liveWindowKeys containsObject:key]) continue;
|
|
557
|
+
if (!trimmed) trimmed = [summary mutableCopy];
|
|
558
|
+
[trimmed removeObjectForKey:key];
|
|
559
|
+
}
|
|
560
|
+
if (trimmed) cache[path] = trimmed;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// 摘要缓存落盘/读回。二进制 plist:内容全是 NSNumber / NSString / NSData / 容器,
|
|
565
|
+
// 写入走临时文件 + 替换,中途崩溃不会留下半个文件。缓存丢失或格式不对只意味着重新解析一遍,
|
|
566
|
+
// 因此所有失败路径都是静默降级。
|
|
567
|
+
NSMutableDictionary *LoadTokenSummaryCache(NSString *path) {
|
|
568
|
+
NSData *data = [NSData dataWithContentsOfFile:path];
|
|
569
|
+
if (!data) return [NSMutableDictionary dictionary];
|
|
570
|
+
id root = [NSPropertyListSerialization propertyListWithData:data
|
|
571
|
+
options:NSPropertyListMutableContainers format:NULL error:NULL];
|
|
572
|
+
if (![root isKindOfClass:NSMutableDictionary.class]) return [NSMutableDictionary dictionary];
|
|
573
|
+
// 条目形如 路径 -> 摘要字典。别的形状一律丢掉,后面的代码不必再防一遍。
|
|
574
|
+
NSMutableDictionary *cache = root;
|
|
575
|
+
for (NSString *key in cache.allKeys) {
|
|
576
|
+
if (![key isKindOfClass:NSString.class] ||
|
|
577
|
+
![cache[key] isKindOfClass:NSDictionary.class]) {
|
|
578
|
+
[cache removeObjectForKey:key];
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return cache;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// Codex 归档是"上月已经算完"的物化结果,一旦落盘就再也不重算(见 UsageByAddingTokenTotals
|
|
585
|
+
// 里的 buildsArchive)。旧版本按日期目录名剪枝,长期续写旧会话的机器归出来的档本身就是缺数的,
|
|
586
|
+
// 光换扫描口径不会自愈。版本号对不上就整份丢掉,让下一轮重新归一次。
|
|
587
|
+
static NSString *const MonthlyArchiveSchemaKey = @"schema";
|
|
588
|
+
static const NSInteger MonthlyArchiveSchemaVersion = 2;
|
|
589
|
+
|
|
590
|
+
NSMutableDictionary *LoadMonthlyUsageArchive(NSString *path) {
|
|
591
|
+
NSMutableDictionary *archive = LoadTokenSummaryCache(path);
|
|
592
|
+
NSDictionary *schema = [archive[MonthlyArchiveSchemaKey] isKindOfClass:NSDictionary.class]
|
|
593
|
+
? archive[MonthlyArchiveSchemaKey] : nil;
|
|
594
|
+
if ([schema[@"version"] integerValue] != MonthlyArchiveSchemaVersion) [archive removeAllObjects];
|
|
595
|
+
// PruneMonthlyArchive 按 YYYY-MM 的字典序裁剪,"schema" 排在所有月份键之后,不会被裁掉。
|
|
596
|
+
archive[MonthlyArchiveSchemaKey] = @{@"version": @(MonthlyArchiveSchemaVersion)};
|
|
597
|
+
return archive;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// NSData 是类簇,可变性判断不能靠 isKindOfClass:二进制 plist 解析出来的**不可变**
|
|
601
|
+
// __NSCFData 对 isKindOfClass:NSMutableData 同样返回 YES。据此把只读缓冲区当成可变的
|
|
602
|
+
// 原地 appendBytes,就会写到它末尾之外——ASan 抓到的正是这一下:
|
|
603
|
+
// heap-buffer-overflow, WRITE of size 48, 0 bytes after 6640-byte region
|
|
604
|
+
// 分配点 __CFBinaryPlistCreateObjectFiltered <- LoadTokenSummaryCache
|
|
605
|
+
// 越界写破坏堆之后进程不会当场死,而是在之后任意一次内存操作上倒下,因此崩溃点看起来
|
|
606
|
+
// 和这里毫无关系(实际报告里落在 EnumerateLines 和 SaveTokenSummaryCache 上)。
|
|
607
|
+
//
|
|
608
|
+
// 可靠的做法只有一条:落盘缓存一读回来就把 records 换成本进程创建的可变副本,
|
|
609
|
+
// 之后 ClaudeRecordsForFile 的原地追加才成立。只替换 records,其余字段原样保留——
|
|
610
|
+
// Codex 侧的条目形状不同(start/total/segments/days…),整条重建会把它们抹掉。
|
|
611
|
+
void MakeCachedRecordsMutable(NSMutableDictionary *cache) {
|
|
612
|
+
for (NSString *path in cache.allKeys) {
|
|
613
|
+
NSDictionary *entry = cache[path];
|
|
614
|
+
if (![entry isKindOfClass:NSDictionary.class]) continue;
|
|
615
|
+
NSData *records = [entry[@"records"] isKindOfClass:NSData.class] ? entry[@"records"] : nil;
|
|
616
|
+
if (!records) continue;
|
|
617
|
+
NSMutableDictionary *updated = [entry mutableCopy];
|
|
618
|
+
updated[@"records"] = [records mutableCopy];
|
|
619
|
+
cache[path] = updated;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
void SaveTokenSummaryCache(NSDictionary *cache, NSString *path) {
|
|
624
|
+
if (!path.length) return;
|
|
625
|
+
NSData *data = [NSPropertyListSerialization dataWithPropertyList:cache
|
|
626
|
+
format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL];
|
|
627
|
+
if (!data) return;
|
|
628
|
+
NSString *temporary = [path stringByAppendingPathExtension:@"tmp"];
|
|
629
|
+
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
630
|
+
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
631
|
+
if (![data writeToFile:temporary atomically:NO]) return;
|
|
632
|
+
NSURL *destination = [NSURL fileURLWithPath:path];
|
|
633
|
+
if (![NSFileManager.defaultManager replaceItemAtURL:destination
|
|
634
|
+
withItemAtURL:[NSURL fileURLWithPath:temporary] backupItemName:nil options:0
|
|
635
|
+
resultingItemURL:NULL error:NULL]) {
|
|
636
|
+
// 目标还不存在时 replaceItemAtURL 会失败,这时直接搬过去。
|
|
637
|
+
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
638
|
+
if (![NSFileManager.defaultManager moveItemAtPath:temporary toPath:path error:nil]) {
|
|
639
|
+
[NSFileManager.defaultManager removeItemAtPath:temporary error:nil];
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// 归档只用来做"上月同期"对比,留着更早的月份没有意义。保留 3 个月是给跨月那一下留余量,
|
|
645
|
+
// 顺带在时区/系统时间被改回去时还能命中。
|
|
646
|
+
void PruneMonthlyArchive(NSMutableDictionary *archive) {
|
|
647
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
648
|
+
NSDate *monthStart = CurrentMonthStartDate();
|
|
649
|
+
NSDate *oldest = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-3 toDate:monthStart
|
|
650
|
+
options:0] ?: monthStart;
|
|
651
|
+
NSString *oldestKey = MonthArchiveKey(oldest.timeIntervalSince1970);
|
|
652
|
+
for (NSString *key in archive.allKeys) {
|
|
653
|
+
if ([key compare:oldestKey] == NSOrderedAscending) [archive removeObjectForKey:key];
|
|
654
|
+
}
|
|
655
|
+
}
|