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
|
@@ -1,2069 +0,0 @@
|
|
|
1
|
-
#import "CCPetsUsage.h"
|
|
2
|
-
#import "CCPetsPaths.h"
|
|
3
|
-
#import <sys/file.h>
|
|
4
|
-
#import <sys/stat.h>
|
|
5
|
-
#import <errno.h>
|
|
6
|
-
#import <fcntl.h>
|
|
7
|
-
#import <unistd.h>
|
|
8
|
-
|
|
9
|
-
// Claude 的 rate_limits 不带 window_minutes,窗长按官方订阅固定。既用于 Token 聚合区间,
|
|
10
|
-
// 也用于快照的合理性校验,所以定义在这里给两处共用。
|
|
11
|
-
static const double FiveHourWindowMinutes = 300;
|
|
12
|
-
static const double SevenDayWindowMinutes = 10080;
|
|
13
|
-
|
|
14
|
-
// 时钟偏差与整分对齐的余量。resets_at 本身是整分的,这点余量只是不想让几秒的偏差
|
|
15
|
-
// 把一份本来正常的快照判死。
|
|
16
|
-
static const NSTimeInterval QuotaResetSkewSeconds = 600.0;
|
|
17
|
-
|
|
18
|
-
// 一条限额错误刚发生、手上却一个可用窗口都没有时的保留时长。见 ExhaustionStillHolds。
|
|
19
|
-
static const NSTimeInterval RecentExhaustionGraceSeconds = 300.0;
|
|
20
|
-
|
|
21
|
-
// 一份快照要么描述当前窗口,要么就没有任何用处:resets_at 落在过去说明这个窗口早就翻篇,
|
|
22
|
-
// 落在一个窗长之外则根本不可能是它的重置时刻。2026-08-19 实测被顶进来的坏快照正是后者
|
|
23
|
-
// ——5 小时窗口的 resets_at 报到了十几小时之后。两种都在入口就拒绝,别让它进文件。
|
|
24
|
-
static BOOL ResetLooksCurrentAt(double reset, double windowMinutes, NSTimeInterval sampledAt) {
|
|
25
|
-
if (reset <= 0 || windowMinutes <= 0) return NO;
|
|
26
|
-
return reset > sampledAt && reset <= sampledAt + windowMinutes * 60.0 + QuotaResetSkewSeconds;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
static BOOL QuotaWindowLooksCurrentAt(NSDictionary *quota, double windowMinutes,
|
|
30
|
-
NSTimeInterval sampledAt) {
|
|
31
|
-
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
32
|
-
if (!reset) return NO;
|
|
33
|
-
return ResetLooksCurrentAt(reset.doubleValue, windowMinutes, sampledAt);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
static BOOL QuotaWindowLooksCurrent(NSDictionary *quota, double windowMinutes, NSTimeInterval now) {
|
|
37
|
-
return QuotaWindowLooksCurrentAt(quota, windowMinutes, now);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Codex 的 rate_limits 是一份会话快照,不会在窗口自然重置时自行刷新。一个快照里的
|
|
41
|
-
// 5 小时和 7 天窗口因此可能处于不同状态:例如 5 小时的 resets_at 已过去几天,但 7 天
|
|
42
|
-
// 的仍在未来。不能因为后者还活着,就把前者的旧百分比继续当成当前额度展示。
|
|
43
|
-
//
|
|
44
|
-
// 缺 resets_at 的旧版记录暂时保留,兼容历史会话和只提供百分比的上游版本;只要服务端给了
|
|
45
|
-
// 重置时间,就必须用它校验窗口。这个函数放在读取层而不是绘制层,状态栏、历史曲线和气泡
|
|
46
|
-
// 台词才能使用同一份已校正的数据。
|
|
47
|
-
static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
|
|
48
|
-
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
49
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
50
|
-
NSDictionary<NSString *, NSNumber *> *windows = @{
|
|
51
|
-
@"fiveHour": @(FiveHourWindowMinutes),
|
|
52
|
-
@"week": @(SevenDayWindowMinutes)
|
|
53
|
-
};
|
|
54
|
-
NSMutableDictionary *result = nil;
|
|
55
|
-
NSMutableDictionary *expired = nil;
|
|
56
|
-
for (NSString *key in windows) {
|
|
57
|
-
NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
|
|
58
|
-
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class]
|
|
59
|
-
? quota[@"resets_at"] : nil;
|
|
60
|
-
if (!reset || QuotaWindowLooksCurrent(quota, windows[key].doubleValue, now)) continue;
|
|
61
|
-
if (!result) result = [usage mutableCopy];
|
|
62
|
-
result[key] = NSNull.null;
|
|
63
|
-
// 百分比不再展示,但 resets_at 必须留下。窗口一旦被清空,"这个窗口已经重置过"
|
|
64
|
-
// 就再也无从得知——而缺失的窗口本来就用 NSNull 表示(官方没给),两者混在一起
|
|
65
|
-
// 分不开。ExhaustionStillHolds 要靠这份记录让受限标记按时失效,否则只剩一个
|
|
66
|
-
// 未到期的 7 天窗口时,一次限流会让卡片永久挂着"额度受限"。
|
|
67
|
-
if (!expired) expired = [NSMutableDictionary dictionary];
|
|
68
|
-
expired[key] = reset;
|
|
69
|
-
}
|
|
70
|
-
if (expired) result[@"expiredWindowResets"] = expired;
|
|
71
|
-
return result ?: usage;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage) {
|
|
75
|
-
return UsageByRemovingInactiveQuotaWindows(usage);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// 同一个账号下的每个 Claude 会话都会把自己那次响应里的 rate_limits 抄到同一个文件上,
|
|
79
|
-
// 而"响应更早、落盘更晚"在并发会话下完全正常。无条件覆盖时旧快照会盖掉新快照,面板上
|
|
80
|
-
// 的剩余额度于是来回跳(实测 99% → 94% → 又回 99%)。同一窗口内官方用量只增不减,
|
|
81
|
-
// 据此逐窗口丢弃倒退的快照。
|
|
82
|
-
//
|
|
83
|
-
// 判据刻意**不比较两份快照的 resets_at**。7 天窗口是滚动的,resets_at 随着旧用量滑出
|
|
84
|
-
// 窗口不断前移,前后两次上报差出十几个小时都算正常;原先写的"resets_at 变了就当窗口
|
|
85
|
-
// 滚动、无条件接受归零"于是对 7 天窗口几乎每次都成立,这道防线等同于从未生效——
|
|
86
|
-
// 2026-08-19 实测面板被一份 used=2% 的旧快照顶成剩余 98%,就是从这条分支进来的。
|
|
87
|
-
// 真正的窗口滚动只可能发生在旧窗口到期之后,拿 now 和 storedReset 判断就够了。
|
|
88
|
-
//
|
|
89
|
-
// 用量真的下降(官方口径调整、临时提额)时单调性不成立,只能靠"这份快照来自更新的响应"
|
|
90
|
-
// 放行。freshSince / storedSince 就是两份快照各自对应响应的时刻(见 QuotaValueSince)。
|
|
91
|
-
// 原先这里是"上次接受已过 10 分钟就无条件放行",但 statusline 配了 refreshInterval 时,
|
|
92
|
-
// 每个开着的空闲会话每分钟都会把自己最后一次响应里的旧额度重报一遍:活跃会话一关,
|
|
93
|
-
// 10 分钟后面板就被某个空闲会话的旧值顶掉(2026-09-29 实测剩余 18% → 跳回 70%)。
|
|
94
|
-
static BOOL ShouldAcceptQuotaWindow(id storedValue, NSDictionary *fresh, double windowMinutes,
|
|
95
|
-
NSTimeInterval freshSince, NSTimeInterval storedSince, NSTimeInterval now) {
|
|
96
|
-
if (!QuotaWindowLooksCurrent(fresh, windowMinutes, now)) return NO;
|
|
97
|
-
NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
|
|
98
|
-
if (!stored) return YES;
|
|
99
|
-
// 旧窗口确实到期了:新周期里用量归零是真的。
|
|
100
|
-
if (now >= [stored[@"resets_at"] doubleValue]) return YES;
|
|
101
|
-
if ([fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue]) return YES;
|
|
102
|
-
return freshSince > storedSince;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// 一份快照对应的响应是什么时候拿到的。statusline 的 payload 不带这个时刻,只能按会话推断:
|
|
106
|
-
// 同一个会话重报的值和它上次一模一样,说明它没有拿到新响应,时刻沿用上次记下的;值变了
|
|
107
|
-
// 才是新响应,记为现在。第一次见到的会话记 0(未知)——它可能是早就开着的空闲会话,
|
|
108
|
-
// 不能凭"刚被看到"就当成最新;它下一次真的变了自然会拿到时刻。
|
|
109
|
-
static NSTimeInterval QuotaValueSince(NSDictionary *previous, NSDictionary *fresh, NSTimeInterval now) {
|
|
110
|
-
if (![previous isKindOfClass:NSDictionary.class]) return 0;
|
|
111
|
-
BOOL unchanged = [previous[@"used_percentage"] isEqual:fresh[@"used_percentage"]] &&
|
|
112
|
-
[previous[@"resets_at"] isEqual:fresh[@"resets_at"]];
|
|
113
|
-
return unchanged ? [previous[@"since"] doubleValue] : now;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// 会话记录只为判断"值有没有变",一天没再上报的会话早就关了;上限防止异常情况下无限增长。
|
|
117
|
-
static const NSTimeInterval QuotaSessionRecordTTL = 24 * 60 * 60;
|
|
118
|
-
static const NSUInteger QuotaSessionRecordLimit = 64;
|
|
119
|
-
|
|
120
|
-
// 拿锁的重试上限。拿不到就放弃这次写入:并发写者手里的数据同样新鲜,跳过一次不丢信息,
|
|
121
|
-
// 而无锁写入正是要避免的读改写交错。阻塞版 flock 没有超时,一个被 SIGSTOP 或卡在慢速
|
|
122
|
-
// 卷上的写者会把之后每一次 statusline 渲染永久挂住,那是比丢一次采样糟得多的故障。
|
|
123
|
-
static const int QuotaLockAttempts = 50;
|
|
124
|
-
static const useconds_t QuotaLockRetryMicroseconds = 20 * 1000;
|
|
125
|
-
|
|
126
|
-
static int AcquireQuotaLock(NSString *lockPath) {
|
|
127
|
-
int descriptor = open(lockPath.fileSystemRepresentation, O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR);
|
|
128
|
-
if (descriptor < 0) return -1;
|
|
129
|
-
for (int attempt = 0; attempt < QuotaLockAttempts; attempt++) {
|
|
130
|
-
if (flock(descriptor, LOCK_EX | LOCK_NB) == 0) return descriptor;
|
|
131
|
-
if (errno != EWOULDBLOCK) break;
|
|
132
|
-
usleep(QuotaLockRetryMicroseconds);
|
|
133
|
-
}
|
|
134
|
-
close(descriptor);
|
|
135
|
-
return -1;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
int RecordClaudeUsage(void) {
|
|
139
|
-
NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
|
|
140
|
-
NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
|
|
141
|
-
NSDictionary *limits = [payload[@"rate_limits"] isKindOfClass:NSDictionary.class] ? payload[@"rate_limits"] : nil;
|
|
142
|
-
if (!limits) return EXIT_SUCCESS;
|
|
143
|
-
|
|
144
|
-
NSString *path = ClaudeUsagePath();
|
|
145
|
-
// 判据要先读后写,多个会话同时跑就会读改写交错,所以整段必须在锁里。
|
|
146
|
-
int lockDescriptor = AcquireQuotaLock(ClaudeUsageLockPath());
|
|
147
|
-
if (lockDescriptor < 0) return EXIT_SUCCESS;
|
|
148
|
-
|
|
149
|
-
NSData *existing = [NSData dataWithContentsOfFile:path];
|
|
150
|
-
id storedValue = existing.length > 0
|
|
151
|
-
? [NSJSONSerialization JSONObjectWithData:existing options:0 error:nil] : nil;
|
|
152
|
-
NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
|
|
153
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
154
|
-
NSDictionary *storedSinceValue = [stored[@"value_since"] isKindOfClass:NSDictionary.class]
|
|
155
|
-
? stored[@"value_since"] : @{};
|
|
156
|
-
NSMutableDictionary *sessions = [stored[@"sessions"] isKindOfClass:NSDictionary.class]
|
|
157
|
-
? [stored[@"sessions"] mutableCopy] : [NSMutableDictionary dictionary];
|
|
158
|
-
// 没有 session_id 的 payload 无法区分"空闲重报"和"新响应",只按单调性判。
|
|
159
|
-
NSString *sessionID = [payload[@"session_id"] isKindOfClass:NSString.class] &&
|
|
160
|
-
[payload[@"session_id"] length] > 0 ? payload[@"session_id"] : nil;
|
|
161
|
-
NSDictionary *previousRecord = [sessions[sessionID] isKindOfClass:NSDictionary.class]
|
|
162
|
-
? sessions[sessionID] : nil;
|
|
163
|
-
NSMutableDictionary *sessionRecord = [@{@"seen_at": @(now)} mutableCopy];
|
|
164
|
-
|
|
165
|
-
NSMutableDictionary *merged = stored ? [stored mutableCopy] : [NSMutableDictionary dictionary];
|
|
166
|
-
[merged removeObjectForKey:@"accepted_at"]; // 上一版的逃生阀字段,已不再使用。
|
|
167
|
-
NSMutableDictionary *mergedSince = [storedSinceValue mutableCopy];
|
|
168
|
-
NSDictionary *windowMinutes = @{@"five_hour": @(FiveHourWindowMinutes),
|
|
169
|
-
@"seven_day": @(SevenDayWindowMinutes)};
|
|
170
|
-
for (NSString *key in @[@"five_hour", @"seven_day"]) {
|
|
171
|
-
NSDictionary *fresh = [limits[key] isKindOfClass:NSDictionary.class] ? limits[key] : nil;
|
|
172
|
-
if (!fresh) continue; // 这次响应没带某个窗口时保留旧的:整体覆盖会让面板凭空少掉一个窗口。
|
|
173
|
-
NSTimeInterval freshSince = sessionID ? QuotaValueSince(previousRecord[key], fresh, now) : 0;
|
|
174
|
-
if (sessionID) {
|
|
175
|
-
sessionRecord[key] = @{@"used_percentage": fresh[@"used_percentage"] ?: NSNull.null,
|
|
176
|
-
@"resets_at": fresh[@"resets_at"] ?: NSNull.null,
|
|
177
|
-
@"since": @(freshSince)};
|
|
178
|
-
}
|
|
179
|
-
NSTimeInterval storedSince = [storedSinceValue[key] doubleValue];
|
|
180
|
-
if (!ShouldAcceptQuotaWindow(stored[key], fresh, [windowMinutes[key] doubleValue],
|
|
181
|
-
freshSince, storedSince, now)) continue;
|
|
182
|
-
merged[key] = fresh;
|
|
183
|
-
// 按单调性收下的旧响应不能把时刻往回拨,否则更旧的快照就能借它反超。
|
|
184
|
-
mergedSince[key] = @(fmax(freshSince, storedSince));
|
|
185
|
-
}
|
|
186
|
-
merged[@"value_since"] = mergedSince;
|
|
187
|
-
|
|
188
|
-
if (sessionID) sessions[sessionID] = sessionRecord;
|
|
189
|
-
for (NSString *key in sessions.allKeys) {
|
|
190
|
-
NSDictionary *record = [sessions[key] isKindOfClass:NSDictionary.class] ? sessions[key] : nil;
|
|
191
|
-
if (!record || now - [record[@"seen_at"] doubleValue] > QuotaSessionRecordTTL) {
|
|
192
|
-
[sessions removeObjectForKey:key];
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
if (sessions.count > QuotaSessionRecordLimit) {
|
|
196
|
-
NSArray *oldestFirst = [sessions keysSortedByValueUsingComparator:^NSComparisonResult(id left, id right) {
|
|
197
|
-
return [left[@"seen_at"] compare:right[@"seen_at"]];
|
|
198
|
-
}];
|
|
199
|
-
[sessions removeObjectsForKeys:[oldestFirst subarrayWithRange:
|
|
200
|
-
NSMakeRange(0, sessions.count - QuotaSessionRecordLimit)]];
|
|
201
|
-
}
|
|
202
|
-
merged[@"sessions"] = sessions;
|
|
203
|
-
// 最后一次写盘时间。不再参与任何判据,只留给排查用。
|
|
204
|
-
merged[@"written_at"] = @(now);
|
|
205
|
-
|
|
206
|
-
NSData *json = [NSJSONSerialization dataWithJSONObject:merged options:0 error:nil];
|
|
207
|
-
if (json && [json writeToFile:path options:NSDataWritingAtomic error:nil]) {
|
|
208
|
-
chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
209
|
-
}
|
|
210
|
-
flock(lockDescriptor, LOCK_UN);
|
|
211
|
-
close(lockDescriptor);
|
|
212
|
-
return EXIT_SUCCESS;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
NSDictionary *ClaudeRateLimits(void) {
|
|
216
|
-
// 只读主账号那一份。桌宠继承的 CLAUDE_CONFIG_DIR 属于"第一个拉起它的客户端",
|
|
217
|
-
// 拿它选文件会让面板显示另一个账号的额度。
|
|
218
|
-
NSData *data = [NSData dataWithContentsOfFile:
|
|
219
|
-
ClaudeUsagePathForConfigDirectory(DefaultClaudeConfigDirectory())];
|
|
220
|
-
NSDictionary *limits = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
221
|
-
if (![limits isKindOfClass:NSDictionary.class]) return nil;
|
|
222
|
-
id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
|
|
223
|
-
id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
|
|
224
|
-
// 快照只在有会话上报时更新。窗口到期后没人再报,旧百分比会一直挂着(实测 5 小时窗口
|
|
225
|
-
// 重置后面板仍显示剩余 0%),与 Codex 同样按 resets_at 清掉已经翻篇的窗口。
|
|
226
|
-
return UsageByRemovingInactiveQuotaWindows(@{@"fiveHour": fiveHour, @"week": week});
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
NSDictionary *LatestClaudeUsage(void) {
|
|
230
|
-
return [[ClaudeUsageReader new] refreshWithFullAggregation];
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
static BOOL AllDigits(NSString *text) {
|
|
234
|
-
if (text.length == 0) return NO;
|
|
235
|
-
static NSCharacterSet *nonDigits;
|
|
236
|
-
static dispatch_once_t once;
|
|
237
|
-
dispatch_once(&once, ^{
|
|
238
|
-
nonDigits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet;
|
|
239
|
-
});
|
|
240
|
-
return [text rangeOfCharacterFromSet:nonDigits].location == NSNotFound;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
static const NSArray<NSString *> *TokenKeys(void) {
|
|
244
|
-
static NSArray<NSString *> *keys;
|
|
245
|
-
static dispatch_once_t once;
|
|
246
|
-
dispatch_once(&once, ^{
|
|
247
|
-
keys = @[@"input_tokens", @"cached_input_tokens", @"cache_write_input_tokens",
|
|
248
|
-
@"output_tokens", @"reasoning_output_tokens", @"total_tokens"];
|
|
249
|
-
});
|
|
250
|
-
return keys;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
static NSDate *ISO8601Timestamp(NSString *value) {
|
|
254
|
-
if (![value isKindOfClass:NSString.class]) return nil;
|
|
255
|
-
static NSISO8601DateFormatter *formatter;
|
|
256
|
-
static dispatch_once_t once;
|
|
257
|
-
dispatch_once(&once, ^{
|
|
258
|
-
formatter = [NSISO8601DateFormatter new];
|
|
259
|
-
formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime |
|
|
260
|
-
NSISO8601DateFormatWithFractionalSeconds;
|
|
261
|
-
});
|
|
262
|
-
NSDate *date = [formatter dateFromString:value];
|
|
263
|
-
if (date) return date;
|
|
264
|
-
static NSISO8601DateFormatter *fallback;
|
|
265
|
-
static dispatch_once_t fallbackOnce;
|
|
266
|
-
dispatch_once(&fallbackOnce, ^{
|
|
267
|
-
fallback = [NSISO8601DateFormatter new];
|
|
268
|
-
fallback.formatOptions = NSISO8601DateFormatWithInternetDateTime;
|
|
269
|
-
});
|
|
270
|
-
return [fallback dateFromString:value];
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
static NSDictionary *TokenPayloadFromLine(NSData *lineData, NSDictionary **root) {
|
|
274
|
-
if (lineData.length == 0) return nil;
|
|
275
|
-
static NSData *marker;
|
|
276
|
-
static dispatch_once_t once;
|
|
277
|
-
dispatch_once(&once, ^{
|
|
278
|
-
marker = [@"\"type\":\"token_count\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
279
|
-
});
|
|
280
|
-
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
281
|
-
NSNotFound) return nil;
|
|
282
|
-
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
283
|
-
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
284
|
-
id payloadValue = ((NSDictionary *)rootValue)[@"payload"];
|
|
285
|
-
if (![payloadValue isKindOfClass:NSDictionary.class]) return nil;
|
|
286
|
-
NSDictionary *payload = payloadValue;
|
|
287
|
-
id typeValue = payload[@"type"];
|
|
288
|
-
if (![typeValue isKindOfClass:NSString.class] ||
|
|
289
|
-
![(NSString *)typeValue isEqualToString:@"token_count"]) return nil;
|
|
290
|
-
if (root) *root = rootValue;
|
|
291
|
-
return payload;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
static NSDictionary *SanitizedTokenCounts(id value) {
|
|
295
|
-
if (![value isKindOfClass:NSDictionary.class]) return nil;
|
|
296
|
-
NSMutableDictionary *counts = [NSMutableDictionary dictionary];
|
|
297
|
-
for (NSString *key in TokenKeys()) {
|
|
298
|
-
NSNumber *number = [value[key] isKindOfClass:NSNumber.class] ? value[key] : nil;
|
|
299
|
-
if (number) counts[key] = @([number unsignedLongLongValue]);
|
|
300
|
-
}
|
|
301
|
-
return counts.count > 0 ? counts : nil;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
static NSDictionary *TokenRecordFromLine(NSData *lineData) {
|
|
305
|
-
NSDictionary *root = nil;
|
|
306
|
-
NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
|
|
307
|
-
NSDictionary *info = [payload[@"info"] isKindOfClass:NSDictionary.class] ? payload[@"info"] : nil;
|
|
308
|
-
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
309
|
-
NSDictionary *last = SanitizedTokenCounts(info[@"last_token_usage"]);
|
|
310
|
-
NSDictionary *total = SanitizedTokenCounts(info[@"total_token_usage"]);
|
|
311
|
-
if (!date || (!last && !total)) return nil;
|
|
312
|
-
NSMutableDictionary *record = [@{@"timestamp": @([date timeIntervalSince1970])} mutableCopy];
|
|
313
|
-
if (last) record[@"last"] = last;
|
|
314
|
-
if (total) record[@"total"] = total;
|
|
315
|
-
return record;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// 会话目录是零填充的 YYYY/MM/DD,字典序等于时间序,因此倒序取名字即可,不必 stat。
|
|
319
|
-
static NSArray<NSURL *> *DescendingNumericSubdirectories(NSURL *directory) {
|
|
320
|
-
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
321
|
-
includingPropertiesForKeys:@[NSURLIsDirectoryKey]
|
|
322
|
-
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
323
|
-
NSMutableArray<NSURL *> *result = [NSMutableArray arrayWithCapacity:contents.count];
|
|
324
|
-
for (NSURL *url in contents) {
|
|
325
|
-
NSNumber *isDirectory = nil;
|
|
326
|
-
if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
|
|
327
|
-
if (!isDirectory.boolValue || !AllDigits(url.lastPathComponent)) continue;
|
|
328
|
-
[result addObject:url];
|
|
329
|
-
}
|
|
330
|
-
[result sortUsingComparator:^NSComparisonResult(NSURL *left, NSURL *right) {
|
|
331
|
-
return [right.lastPathComponent compare:left.lastPathComponent];
|
|
332
|
-
}];
|
|
333
|
-
return result;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
// 单个目录内 mtime 最新的 .jsonl。文件名格式不是契约,因此文件一律按 mtime 选,
|
|
337
|
-
// 只有日期目录名吃字典序。
|
|
338
|
-
static NSURL *NewestSessionFileInDirectory(NSURL *directory, NSDate **outDate) {
|
|
339
|
-
NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
|
|
340
|
-
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
341
|
-
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
342
|
-
NSURL *newest = nil;
|
|
343
|
-
NSDate *newestDate = NSDate.distantPast;
|
|
344
|
-
for (NSURL *url in contents) {
|
|
345
|
-
if (![url.pathExtension isEqualToString:@"jsonl"]) continue;
|
|
346
|
-
NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
|
|
347
|
-
if (![values[NSURLIsRegularFileKey] boolValue]) continue;
|
|
348
|
-
NSDate *date = values[NSURLContentModificationDateKey] ?: NSDate.distantPast;
|
|
349
|
-
if ([date compare:newestDate] == NSOrderedDescending) {
|
|
350
|
-
newest = url;
|
|
351
|
-
newestDate = date;
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
if (outDate) *outDate = newest ? newestDate : nil;
|
|
355
|
-
return newest;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
static const NSUInteger MinimumExaminedSessionDays = 3;
|
|
359
|
-
static const NSUInteger MaximumExaminedSessionDays = 40;
|
|
360
|
-
|
|
361
|
-
// 按 YYYY/MM/DD 倒序下钻,成本与历史会话总量无关,只与近期活跃度有关。
|
|
362
|
-
// 收手条件必须同时满足“看够 MinimumExaminedSessionDays 个日期目录”和“已经找到过文件”:
|
|
363
|
-
// 只写前者的话,用户闲置数天后冷启动会一无所获,比全量扫描更差。
|
|
364
|
-
static NSURL *NewestCodexSessionURL(NSURL *sessionsURL) {
|
|
365
|
-
NSURL *newest = nil;
|
|
366
|
-
NSDate *newestDate = NSDate.distantPast;
|
|
367
|
-
NSUInteger examinedDays = 0;
|
|
368
|
-
for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
|
|
369
|
-
for (NSURL *month in DescendingNumericSubdirectories(year)) {
|
|
370
|
-
for (NSURL *day in DescendingNumericSubdirectories(month)) {
|
|
371
|
-
NSDate *date = nil;
|
|
372
|
-
NSURL *candidate = NewestSessionFileInDirectory(day, &date);
|
|
373
|
-
if (candidate && [date compare:newestDate] == NSOrderedDescending) {
|
|
374
|
-
newest = candidate;
|
|
375
|
-
newestDate = date;
|
|
376
|
-
}
|
|
377
|
-
examinedDays += 1;
|
|
378
|
-
if (examinedDays >= MinimumExaminedSessionDays && newest) return newest;
|
|
379
|
-
if (examinedDays >= MaximumExaminedSessionDays) return newest;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
// 兜底:非 YYYY/MM/DD 布局(例如直接摊在 sessions/ 下)仍然能被发现。
|
|
384
|
-
return newest ?: NewestSessionFileInDirectory(sessionsURL, NULL);
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// 额度被拒时 Codex 会写一条带 error.codex_error_info = usage_limit_exceeded 的事件。
|
|
388
|
-
// 这是唯一能说明"官方额度现在不给用了"的结构化信号:同一时刻 rate_limits 里
|
|
389
|
-
// primary/secondary 全是 null,光看额度字段只能看到"这行没有数据",于是上一份百分比
|
|
390
|
-
// 会一直挂在面板上——账号被别人用完时,那个数字既过期又正好指向相反的结论。
|
|
391
|
-
static NSNumber *ExhaustionTimestampFromLine(NSData *lineData) {
|
|
392
|
-
if (lineData.length == 0) return nil;
|
|
393
|
-
static NSData *marker;
|
|
394
|
-
static dispatch_once_t once;
|
|
395
|
-
dispatch_once(&once, ^{
|
|
396
|
-
marker = [@"usage_limit_exceeded" dataUsingEncoding:NSUTF8StringEncoding];
|
|
397
|
-
});
|
|
398
|
-
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
399
|
-
NSNotFound) return nil;
|
|
400
|
-
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
401
|
-
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
402
|
-
NSDictionary *root = rootValue;
|
|
403
|
-
NSDictionary *payload = [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : nil;
|
|
404
|
-
NSDictionary *error = [payload[@"error"] isKindOfClass:NSDictionary.class] ? payload[@"error"] : nil;
|
|
405
|
-
NSString *info = [error[@"codex_error_info"] isKindOfClass:NSString.class]
|
|
406
|
-
? error[@"codex_error_info"] : nil;
|
|
407
|
-
if (![info containsString:@"usage_limit"]) return nil;
|
|
408
|
-
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
409
|
-
return date ? @(date.timeIntervalSince1970) : nil;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
static NSDictionary *UsageFromCodexLine(NSData *lineData) {
|
|
413
|
-
NSDictionary *root = nil;
|
|
414
|
-
NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
|
|
415
|
-
if (!payload) return nil;
|
|
416
|
-
id limitsValue = payload[@"rate_limits"];
|
|
417
|
-
if (![limitsValue isKindOfClass:NSDictionary.class]) return nil;
|
|
418
|
-
NSDictionary *limits = limitsValue;
|
|
419
|
-
id primaryValue = limits[@"primary"];
|
|
420
|
-
id secondaryValue = limits[@"secondary"];
|
|
421
|
-
NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
|
|
422
|
-
NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
|
|
423
|
-
NSDictionary *fiveHour = nil;
|
|
424
|
-
NSDictionary *week = nil;
|
|
425
|
-
for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
|
|
426
|
-
NSInteger minutes = [quota[@"window_minutes"] integerValue];
|
|
427
|
-
if (minutes == 300) fiveHour = quota;
|
|
428
|
-
if (minutes == 10080) week = quota;
|
|
429
|
-
}
|
|
430
|
-
// primary/secondary 全是 null 的 rate_limits(实测切到 premium/credits 计费后每条都这样)
|
|
431
|
-
// 并不表示额度消失,只是这条响应没带窗口信息。当成"这行没有额度"往前找,
|
|
432
|
-
// 否则上一份仍然有效的窗口会被它整块盖掉,面板退回 `--` + 等待数据。
|
|
433
|
-
if (!fiveHour && !week) return nil;
|
|
434
|
-
// 采样时刻用来和耗尽事件比先后:耗尽之后又拿到新的额度快照,说明额度已经恢复。
|
|
435
|
-
NSDate *sampledAt = ISO8601Timestamp(root[@"timestamp"]);
|
|
436
|
-
return @{
|
|
437
|
-
@"fiveHour": fiveHour ?: NSNull.null,
|
|
438
|
-
@"week": week ?: NSNull.null,
|
|
439
|
-
@"sampledAt": @(sampledAt ? sampledAt.timeIntervalSince1970 : 0)
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// 受限事件没有窗口归属,只能给它一个有效期:快照里最短窗口的 resets_at 一过,那个窗口
|
|
444
|
-
// 必然已经重置,再挂着"额度受限"就是在声称一件我们已经不知道的事——而受限期间官方常年
|
|
445
|
-
// 只回 primary/secondary 全 null(见 UsageFromCodexLine),等"更新的快照"来推翻可能等不到。
|
|
446
|
-
// 真正用尽的是 7 天窗口时,5 小时窗口重置后仍会被拒,届时会写下新的 usage_limit_exceeded,
|
|
447
|
-
// 标记自己会贴回来。
|
|
448
|
-
static BOOL ExhaustionStillHolds(NSDictionary *usage, NSTimeInterval exhaustedAt) {
|
|
449
|
-
if (![usage isKindOfClass:NSDictionary.class] || exhaustedAt <= 0) return NO;
|
|
450
|
-
if (exhaustedAt < [usage[@"sampledAt"] doubleValue]) return NO;
|
|
451
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
452
|
-
NSTimeInterval earliestReset = 0;
|
|
453
|
-
BOOL foundReset = NO;
|
|
454
|
-
BOOL foundQuotaWithoutReset = NO;
|
|
455
|
-
NSDictionary<NSString *, NSNumber *> *windows = @{
|
|
456
|
-
@"fiveHour": @(FiveHourWindowMinutes),
|
|
457
|
-
@"week": @(SevenDayWindowMinutes)
|
|
458
|
-
};
|
|
459
|
-
NSDictionary *expired = [usage[@"expiredWindowResets"] isKindOfClass:NSDictionary.class]
|
|
460
|
-
? usage[@"expiredWindowResets"] : nil;
|
|
461
|
-
for (NSString *key in windows) {
|
|
462
|
-
NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
|
|
463
|
-
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
464
|
-
// 关键是“限额错误发生时”这个 reset 是否还属于当前窗口,而不是它现在是否已过期。
|
|
465
|
-
// 例如错误发生后 5 小时窗口自然重置,标记应当清掉;反过来,数天前就过期的
|
|
466
|
-
// 5 小时快照不能让一条刚发生的错误立即失效。
|
|
467
|
-
if (!quota) {
|
|
468
|
-
// 窗口被 UsageByRemovingInactiveQuotaWindows 清掉了,用它留下的 resets_at 继续
|
|
469
|
-
// 判断。少了这一支,5 小时窗口重置后标记就再也没有失效的依据。
|
|
470
|
-
NSNumber *expiredReset = [expired[key] isKindOfClass:NSNumber.class] ? expired[key] : nil;
|
|
471
|
-
if (!expiredReset) continue;
|
|
472
|
-
foundReset = YES;
|
|
473
|
-
double value = expiredReset.doubleValue;
|
|
474
|
-
if (!ResetLooksCurrentAt(value, windows[key].doubleValue, exhaustedAt)) continue;
|
|
475
|
-
if (earliestReset == 0 || value < earliestReset) earliestReset = value;
|
|
476
|
-
continue;
|
|
477
|
-
}
|
|
478
|
-
if (!reset) {
|
|
479
|
-
foundQuotaWithoutReset = YES;
|
|
480
|
-
continue;
|
|
481
|
-
}
|
|
482
|
-
foundReset = YES;
|
|
483
|
-
if (!QuotaWindowLooksCurrentAt(quota, windows[key].doubleValue, exhaustedAt)) continue;
|
|
484
|
-
double value = reset.doubleValue;
|
|
485
|
-
if (earliestReset == 0 || value < earliestReset) earliestReset = value;
|
|
486
|
-
}
|
|
487
|
-
if (earliestReset > now) return YES;
|
|
488
|
-
// 有一个属于当前窗口的 reset 且它已经过去,说明额度确实重置了,标记必须清掉。
|
|
489
|
-
if (earliestReset > 0) return NO;
|
|
490
|
-
// 走到这里说明一个可用窗口都没有,推不出有效期。这恰恰是最需要受限提示的时刻——
|
|
491
|
-
// 上面注释里说的"受限期间官方常年只回 primary/secondary 全 null"就落在这个分支,
|
|
492
|
-
// app-server 也拿不到实时额度时更是如此。所以刚发生的错误先无条件保留一小段时间,
|
|
493
|
-
// 别让面板在用户正撞限额的当口显示一切正常。
|
|
494
|
-
if (now - exhaustedAt < RecentExhaustionGraceSeconds) return YES;
|
|
495
|
-
// 老版会话只给百分比、没有 resets_at 时无法推断受限状态的有效期;沿用之前的保守
|
|
496
|
-
// 行为,等更新的额度快照来清掉它。只要至少有一个明确的 reset,就以它为准。
|
|
497
|
-
return !foundReset && foundQuotaWithoutReset;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// 受限事件仍然成立时,把标记贴到 usage 上。事件本身没有窗口归属,面板只能提示"额度受限"
|
|
501
|
-
// 并把已有百分比标为快照,不能据此把 5 小时和 7 天窗口都判成 0。
|
|
502
|
-
static NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterval exhaustedAt) {
|
|
503
|
-
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
504
|
-
if (!ExhaustionStillHolds(usage, exhaustedAt)) return usage;
|
|
505
|
-
NSMutableDictionary *result = [usage mutableCopy];
|
|
506
|
-
result[@"exhaustedAt"] = @(exhaustedAt);
|
|
507
|
-
return result;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
// 多个会话里的额度是同一个账号的快照,只允许采样时刻向前推进。FSEvents 既可能把
|
|
511
|
-
// 多个文件合在一批里,也可能把“响应更早、落盘更晚”的旧文件单独送来;仅在批量候选
|
|
512
|
-
// 之间比较不够,最终写入 self.usage 的每个入口都必须经过这一层。
|
|
513
|
-
static NSDictionary *NewerUsageSnapshot(NSDictionary *current, NSDictionary *candidate) {
|
|
514
|
-
if (![candidate isKindOfClass:NSDictionary.class]) return current;
|
|
515
|
-
if (![current isKindOfClass:NSDictionary.class]) return candidate;
|
|
516
|
-
return [candidate[@"sampledAt"] doubleValue] >= [current[@"sampledAt"] doubleValue]
|
|
517
|
-
? candidate : current;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
// token_count 行几乎总在文件末尾,因此从尾部反向按 \n 切片逐行试,命中即停。
|
|
521
|
-
// 原实现会把整段(最多 2MB)解码成 NSString、再切成全部行、再把每行编码回 NSData、
|
|
522
|
-
// 又解码回 NSString 查子串,等于来回往返两遍。
|
|
523
|
-
static NSDictionary *LatestUsageInData(NSData *data, NSNumber **outExhaustedAt) {
|
|
524
|
-
const uint8_t *bytes = data.bytes;
|
|
525
|
-
NSUInteger end = data.length;
|
|
526
|
-
NSDictionary *usage = nil;
|
|
527
|
-
NSNumber *exhaustedAt = nil;
|
|
528
|
-
while (end > 0) {
|
|
529
|
-
NSUInteger start = end;
|
|
530
|
-
while (start > 0 && bytes[start - 1] != '\n') start -= 1;
|
|
531
|
-
if (end > start) {
|
|
532
|
-
NSData *line = [data subdataWithRange:NSMakeRange(start, end - start)];
|
|
533
|
-
if (!exhaustedAt) exhaustedAt = ExhaustionTimestampFromLine(line);
|
|
534
|
-
if (!usage) usage = UsageFromCodexLine(line);
|
|
535
|
-
if (usage && exhaustedAt) break;
|
|
536
|
-
}
|
|
537
|
-
end = start > 0 ? start - 1 : 0;
|
|
538
|
-
}
|
|
539
|
-
if (outExhaustedAt) *outExhaustedAt = exhaustedAt;
|
|
540
|
-
return usage;
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
// 「本月 / 上月同期」只有 API 展示模式要用。让默认的订阅视图也回溯到上月月初,等于把上个月
|
|
544
|
-
// 的全部会话白解析一遍:本机实测冷启动 7s vs 0.7s,扫描的文件数 327 vs 61。因此按每家自己的
|
|
545
|
-
// 展示模式决定回溯多远,两家的读取窗口互不牵连。
|
|
546
|
-
static BOOL ProviderShowsAPIUsage(NSString *preferenceKey) {
|
|
547
|
-
return [[NSUserDefaults.standardUserDefaults stringForKey:preferenceKey] isEqualToString:@"api"];
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
// resets_at 恒在未来,因此 7 天窗口的起点不可能早于 now - 7d;再留一天覆盖时区和跨日边界。
|
|
551
|
-
// 这是所有模式的下限:订阅视图只要这么多,API 视图的月窗口在月初也可能比它还窄。
|
|
552
|
-
static NSTimeInterval RollingTokenWindowFloor(void) {
|
|
553
|
-
return NSDate.date.timeIntervalSince1970 - 8 * 86400.0;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// 本月 1 日 00:00。
|
|
557
|
-
static NSDate *CurrentMonthStartDate(void) {
|
|
558
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
559
|
-
NSDate *now = NSDate.date;
|
|
560
|
-
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth
|
|
561
|
-
fromDate:now];
|
|
562
|
-
components.day = 1;
|
|
563
|
-
return [calendar dateFromComponents:components] ?: [calendar startOfDayForDate:now];
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// 归档的键:本机时区的 YYYY-MM。
|
|
567
|
-
static NSString *MonthArchiveKey(NSTimeInterval monthStart) {
|
|
568
|
-
NSDateComponents *components = [NSCalendar.currentCalendar
|
|
569
|
-
components:NSCalendarUnitYear | NSCalendarUnitMonth
|
|
570
|
-
fromDate:[NSDate dateWithTimeIntervalSince1970:monthStart]];
|
|
571
|
-
return [NSString stringWithFormat:@"%04ld-%02ld", (long)components.year, (long)components.month];
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
// 目录名是本机时区的 YYYY/MM/DD。解析不出日期时返回 0,调用方据此放弃剪枝而不是误删。
|
|
575
|
-
static NSTimeInterval DayDirectoryEnd(NSURL *year, NSURL *month, NSURL *day) {
|
|
576
|
-
NSDateComponents *components = [NSDateComponents new];
|
|
577
|
-
components.year = year.lastPathComponent.integerValue;
|
|
578
|
-
components.month = month.lastPathComponent.integerValue;
|
|
579
|
-
components.day = day.lastPathComponent.integerValue;
|
|
580
|
-
NSDate *date = [NSCalendar.currentCalendar dateFromComponents:components];
|
|
581
|
-
return date ? date.timeIntervalSince1970 + 86400.0 : 0;
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// 目录名只说明"会话是哪天建的",不说明"会话哪天还在被写":`codex resume` 会一直往
|
|
585
|
-
// 建会话那天的目录里追加,实测有用户近 8 天的全部 token_count 都写在 15 天前的
|
|
586
|
-
// sessions/2026/08/06/ 里。原实现在这里按目录名直接 return,那台机器上 urls 恒为空,
|
|
587
|
-
// 今日 / 最近 7 天的 Token 于是恒为 0(额度却正常——它走 NewestCodexSessionURL,按 mtime)。
|
|
588
|
-
// 所以窗口之前的目录不再收手,而是继续扫、只收 mtime 落在窗口内的文件。
|
|
589
|
-
// mtime 也是 Claude 侧 AppendRecentTranscriptsInDirectory 用的判据,两边口径就此一致。
|
|
590
|
-
static const NSUInteger ResumeLookbackDays = 60;
|
|
591
|
-
|
|
592
|
-
// earliest 由调用方按当前口径算好:订阅视图是 8 天,API 视图是本月 1 日(上月已归档)或
|
|
593
|
-
// 上月 1 日(还没归档,要扫一次把归档建出来),三者都不会早于 8 天下限。
|
|
594
|
-
static NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL, NSTimeInterval earliest) {
|
|
595
|
-
NSMutableArray<NSURL *> *urls = [NSMutableArray array];
|
|
596
|
-
NSUInteger examinedDays = 0;
|
|
597
|
-
// 连续多少个"整天落在窗口之前、且一个活跃文件都没有"的目录。成本上界与历史长度无关:
|
|
598
|
-
// 续写旧会话的用户在这个计数清零之前就被捞到,闲置多年的历史最多多读 60 次目录项。
|
|
599
|
-
NSUInteger staleDays = 0;
|
|
600
|
-
// 目录个数的上限跟着时间窗口走,再多留几天处理时区边界和异常目录。
|
|
601
|
-
const NSUInteger maximumTokenDays =
|
|
602
|
-
(NSUInteger)ceil((NSDate.date.timeIntervalSince1970 - earliest) / 86400.0) + 3;
|
|
603
|
-
NSArray<NSURLResourceKey> *keys = @[NSURLIsRegularFileKey, NSURLContentModificationDateKey];
|
|
604
|
-
for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
|
|
605
|
-
for (NSURL *month in DescendingNumericSubdirectories(year)) {
|
|
606
|
-
for (NSURL *day in DescendingNumericSubdirectories(month)) {
|
|
607
|
-
// 天数上限用完之后不是收手,而是降级成同一套 mtime 过滤:直接 return 会
|
|
608
|
-
// 把上限之外那个仍在续写的旧会话又一次切掉。目录名解析不出日期(dayEnd 为 0)
|
|
609
|
-
// 时按窗口内处理,交给天数上限收手,不误删。
|
|
610
|
-
NSTimeInterval dayEnd = DayDirectoryEnd(year, month, day);
|
|
611
|
-
BOOL beforeWindow = (dayEnd > 0 && dayEnd < earliest) ||
|
|
612
|
-
examinedDays >= maximumTokenDays;
|
|
613
|
-
if (beforeWindow && staleDays >= ResumeLookbackDays) return urls;
|
|
614
|
-
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:day
|
|
615
|
-
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
616
|
-
BOOL matched = NO;
|
|
617
|
-
for (NSURL *url in contents) {
|
|
618
|
-
if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
|
|
619
|
-
NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
|
|
620
|
-
if (![values[NSURLIsRegularFileKey] boolValue]) continue;
|
|
621
|
-
// 窗口内的目录整目录都要(文件本身可能刚建、mtime 还没落后),窗口之前的
|
|
622
|
-
// 目录只认最近被写过的文件——判据是 mtime,不是文件里的时间戳:伪造/回填
|
|
623
|
-
// 的时间戳不该把一份三个月前的会话拉回今天。
|
|
624
|
-
if (beforeWindow) {
|
|
625
|
-
NSDate *modified = values[NSURLContentModificationDateKey];
|
|
626
|
-
if (!modified || modified.timeIntervalSince1970 < earliest) continue;
|
|
627
|
-
}
|
|
628
|
-
[urls addObject:url];
|
|
629
|
-
matched = YES;
|
|
630
|
-
}
|
|
631
|
-
if (beforeWindow) staleDays = matched ? 0 : staleDays + 1;
|
|
632
|
-
else examinedDays += 1;
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
return urls;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
// 目录扫描之外再兜一层:当前正在被增量读取的会话、以及 FSEvents 这一轮点名的会话文件,
|
|
640
|
-
// 无条件参与 Token 聚合。内核已经确认它们刚被写过,这个结论比任何按路径名或 mtime 的
|
|
641
|
-
// 推断都可靠。多喂进来的文件不会让数字虚高——窗口过滤在 TokenTotalsInWindow 里按行内
|
|
642
|
-
// 时间戳做,这里只是保证文件有机会被读到。
|
|
643
|
-
static NSArray<NSURL *> *TokenAggregationURLs(NSURL *sessionsURL, NSTimeInterval earliest,
|
|
644
|
-
NSArray<NSURL *> *pinnedURLs) {
|
|
645
|
-
NSMutableArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL, earliest) mutableCopy];
|
|
646
|
-
if (pinnedURLs.count == 0) return urls;
|
|
647
|
-
NSMutableSet<NSString *> *paths = [NSMutableSet setWithCapacity:urls.count];
|
|
648
|
-
for (NSURL *url in urls) [paths addObject:url.path];
|
|
649
|
-
for (NSURL *url in pinnedURLs) {
|
|
650
|
-
if (!url.path.length || [paths containsObject:url.path]) continue;
|
|
651
|
-
// 会话文件可能已经被删/被轮转,PruneTokenCache 拿这份列表当保留集,塞不存在的
|
|
652
|
-
// 路径进去会让缓存条目永远清不掉。
|
|
653
|
-
if (![NSFileManager.defaultManager fileExistsAtPath:url.path]) continue;
|
|
654
|
-
[paths addObject:url.path];
|
|
655
|
-
[urls addObject:url];
|
|
656
|
-
}
|
|
657
|
-
return urls;
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
static NSData *SessionTailData(NSURL *url) {
|
|
661
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
662
|
-
if (!handle) return nil;
|
|
663
|
-
unsigned long long size = [handle seekToEndOfFile];
|
|
664
|
-
[handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
|
|
665
|
-
NSData *tail = [handle readDataToEndOfFile];
|
|
666
|
-
[handle closeFile];
|
|
667
|
-
return tail;
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
static BOOL UsageHasLiveWindow(NSDictionary *usage) {
|
|
671
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
672
|
-
NSDictionary<NSString *, NSNumber *> *windows = @{
|
|
673
|
-
@"fiveHour": @(FiveHourWindowMinutes),
|
|
674
|
-
@"week": @(SevenDayWindowMinutes)
|
|
675
|
-
};
|
|
676
|
-
for (NSString *key in windows) {
|
|
677
|
-
NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
|
|
678
|
-
if (QuotaWindowLooksCurrent(quota, windows[key].doubleValue, now)) return YES;
|
|
679
|
-
}
|
|
680
|
-
return NO;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
// 最新会话整篇都没有额度时往前找。rate_limits 是账号级的,写在哪个会话里都一样;
|
|
684
|
-
// 而新会话在第一次拿到限流响应之前一条都不写,冷启动正好撞上就会整块空白。
|
|
685
|
-
// 只接受 resets_at 还没到的窗口,免得把过期的百分比当成当前值。
|
|
686
|
-
static NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL) {
|
|
687
|
-
// 找的是"最近一次额度快照",按 mtime 排完只看前 8 个文件,没有必要把上个月的会话
|
|
688
|
-
// 也列出来再排一遍序,因此这里固定用窄窗口。
|
|
689
|
-
NSArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL, RollingTokenWindowFloor())
|
|
690
|
-
sortedArrayUsingComparator:
|
|
691
|
-
^NSComparisonResult(NSURL *left, NSURL *right) {
|
|
692
|
-
NSDate *leftDate = nil, *rightDate = nil;
|
|
693
|
-
[left getResourceValue:&leftDate forKey:NSURLContentModificationDateKey error:nil];
|
|
694
|
-
[right getResourceValue:&rightDate forKey:NSURLContentModificationDateKey error:nil];
|
|
695
|
-
return [(rightDate ?: NSDate.distantPast) compare:(leftDate ?: NSDate.distantPast)];
|
|
696
|
-
}];
|
|
697
|
-
NSUInteger examined = 0;
|
|
698
|
-
NSDictionary *newest = nil;
|
|
699
|
-
for (NSURL *url in urls) {
|
|
700
|
-
if (skipURL && [url.path isEqualToString:skipURL.path]) continue;
|
|
701
|
-
if (++examined > 8) break;
|
|
702
|
-
NSDictionary *usage = LatestUsageInData(SessionTailData(url), NULL);
|
|
703
|
-
if (!usage || !UsageHasLiveWindow(usage)) continue;
|
|
704
|
-
// mtime 只够用来挑候选:会话在拿到额度之后还会继续追加别的行,文件的新旧顺序和
|
|
705
|
-
// 额度采样的先后并不一致。命中即返回会拿到偏旧的百分比,改成按采样时刻取最新。
|
|
706
|
-
if (!newest || [usage[@"sampledAt"] doubleValue] > [newest[@"sampledAt"] doubleValue]) {
|
|
707
|
-
newest = usage;
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
return newest;
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
static NSTimeInterval LineTimestamp(NSData *line) {
|
|
714
|
-
if (line.length == 0) return 0;
|
|
715
|
-
id root = [NSJSONSerialization JSONObjectWithData:line options:0 error:nil];
|
|
716
|
-
if (![root isKindOfClass:NSDictionary.class]) return 0;
|
|
717
|
-
NSDate *date = ISO8601Timestamp(((NSDictionary *)root)[@"timestamp"]);
|
|
718
|
-
return date ? date.timeIntervalSince1970 : 0;
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
// 按块切行喂给 consume,返回消费掉的字节数(截止最后一个换行)。返回值就是下一次可以
|
|
722
|
-
// 安全续读的偏移:结尾那半行还没写完,不能算进去。includeTail=YES 时残行照样交给
|
|
723
|
-
// consume(一次性整篇扫描的调用方要它,最后一行未必有换行结尾)。
|
|
724
|
-
static unsigned long long EnumerateLines(NSFileHandle *handle, BOOL includeTail,
|
|
725
|
-
void (^consume)(NSData *)) {
|
|
726
|
-
NSMutableData *pending = [NSMutableData data];
|
|
727
|
-
unsigned long long consumed = 0;
|
|
728
|
-
while (YES) {
|
|
729
|
-
NSData *chunk = [handle readDataOfLength:256 * 1024];
|
|
730
|
-
if (chunk.length == 0) break;
|
|
731
|
-
[pending appendData:chunk];
|
|
732
|
-
const uint8_t *bytes = pending.bytes;
|
|
733
|
-
NSUInteger lineStart = 0;
|
|
734
|
-
for (NSUInteger index = 0; index < pending.length; index++) {
|
|
735
|
-
if (bytes[index] != '\n') continue;
|
|
736
|
-
if (index > lineStart) {
|
|
737
|
-
consume([pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
|
|
738
|
-
}
|
|
739
|
-
lineStart = index + 1;
|
|
740
|
-
}
|
|
741
|
-
if (lineStart > 0) {
|
|
742
|
-
consumed += lineStart;
|
|
743
|
-
pending = [[pending subdataWithRange:NSMakeRange(
|
|
744
|
-
lineStart, pending.length - lineStart)] mutableCopy];
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
if (includeTail && pending.length > 0) consume(pending);
|
|
748
|
-
return consumed;
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
752
|
-
for (NSString *key in TokenKeys()) {
|
|
753
|
-
unsigned long long current = [target[key] unsignedLongLongValue];
|
|
754
|
-
unsigned long long addition = [counts[key] unsignedLongLongValue];
|
|
755
|
-
if (counts[key]) target[key] = @(current + addition);
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
// total_token_usage 是会话内累计值,但同一个 rollout 文件里它会中途归零重来:resume 或
|
|
760
|
-
// 上下文压缩之后进程从头开始计数。本机近 14 天 106 个会话里 3 个如此,最狠的一个从
|
|
761
|
-
// 1098 万掉回 11 万——只认末行 total 的话,归零之前那一整段全被吞掉(该会话真实用量
|
|
762
|
-
// 约 1146 万,末行只有 47 万,漏掉 96%)。因此把会话按归零点切成若干段:段内仍然用
|
|
763
|
-
// 累计值(对重复写入的 token_count 幂等),段与段之间相加。
|
|
764
|
-
static BOOL TokenTotalsDidReset(NSDictionary *totals, NSDictionary *previous) {
|
|
765
|
-
for (NSString *key in TokenKeys()) {
|
|
766
|
-
if (!totals[key] || !previous[key]) continue;
|
|
767
|
-
if ([totals[key] unsignedLongLongValue] < [previous[key] unsignedLongLongValue]) return YES;
|
|
768
|
-
}
|
|
769
|
-
return NO;
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
static NSDictionary *SummedSegmentTotals(NSArray<NSDictionary *> *segments) {
|
|
773
|
-
NSMutableDictionary *total = [NSMutableDictionary dictionary];
|
|
774
|
-
for (NSDictionary *segment in segments) AddTokenCounts(total, segment);
|
|
775
|
-
return total;
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
// 日桶除 Token 字段外还带 request_count,合并时要一起累加。
|
|
779
|
-
static void AddDailyTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
780
|
-
AddTokenCounts(target, counts);
|
|
781
|
-
if (!counts[@"request_count"]) return;
|
|
782
|
-
target[@"request_count"] = @([target[@"request_count"] unsignedLongLongValue] +
|
|
783
|
-
[counts[@"request_count"] unsignedLongLongValue]);
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
static NSString *DayBucketKey(NSTimeInterval dayStart) {
|
|
787
|
-
return [NSString stringWithFormat:@"%.0f", dayStart];
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline);
|
|
791
|
-
|
|
792
|
-
// 分段必须整篇扫描(末行 total 不再够用),因此改成按偏移增量追读:活跃会话每轮只解析
|
|
793
|
-
// 新增的那几行,段状态(各段末尾的累计值)留在缓存里续接。
|
|
794
|
-
//
|
|
795
|
-
// 解析时顺手把每条记录的增量摊到它所属的自然日(summary[@"days"])。API 视图要画一个月的
|
|
796
|
-
// 日曲线,如果改成按天各扫一遍窗口,跨天会话会被 PartialTokenTotals 整篇重读 31 次——
|
|
797
|
-
// 实测本机每次刷新要多花 130ms,全落在主线程上,悬停时连拖动都会卡住。
|
|
798
|
-
static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache) {
|
|
799
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path error:nil];
|
|
800
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
801
|
-
NSDictionary *cached = cache[url.path];
|
|
802
|
-
// 没有 token_count 的会话(旧格式、被截断、刚创建)也会留下缓存条目,否则每一轮都要
|
|
803
|
-
// 把整篇重读一遍。文件长大后 size 变化自然会让缓存失效。
|
|
804
|
-
if (cached && [cached[@"size"] unsignedLongLongValue] == size) {
|
|
805
|
-
return (cached[@"start"] && cached[@"total"]) ? cached : nil;
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
unsigned long long offset = 0;
|
|
809
|
-
NSMutableArray<NSDictionary *> *segments = [NSMutableArray array];
|
|
810
|
-
NSMutableArray<NSNumber *> *requestTimestamps = [NSMutableArray array];
|
|
811
|
-
NSMutableDictionary<NSString *, NSMutableDictionary *> *days = [NSMutableDictionary dictionary];
|
|
812
|
-
__block NSNumber *start = nil;
|
|
813
|
-
__block NSTimeInterval last = 0;
|
|
814
|
-
__block NSDictionary *lastRequestTotal = nil;
|
|
815
|
-
if (cached) {
|
|
816
|
-
unsigned long long cachedOffset = [cached[@"offset"] unsignedLongLongValue];
|
|
817
|
-
// offset > size 只可能是文件被改写(截断/重建),旧的段全部作废,整篇重来。
|
|
818
|
-
if (cachedOffset <= size) {
|
|
819
|
-
offset = cachedOffset;
|
|
820
|
-
start = [cached[@"start"] isKindOfClass:NSNumber.class] ? cached[@"start"] : nil;
|
|
821
|
-
last = [cached[@"end"] doubleValue];
|
|
822
|
-
if ([cached[@"segments"] isKindOfClass:NSArray.class]) {
|
|
823
|
-
[segments addObjectsFromArray:cached[@"segments"]];
|
|
824
|
-
}
|
|
825
|
-
if ([cached[@"requestTimestamps"] isKindOfClass:NSArray.class]) {
|
|
826
|
-
[requestTimestamps addObjectsFromArray:cached[@"requestTimestamps"]];
|
|
827
|
-
}
|
|
828
|
-
if ([cached[@"days"] isKindOfClass:NSDictionary.class]) {
|
|
829
|
-
for (NSString *key in (NSDictionary *)cached[@"days"]) {
|
|
830
|
-
days[key] = [cached[@"days"][key] mutableCopy];
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
lastRequestTotal = [cached[@"lastRequestTotal"] isKindOfClass:NSDictionary.class]
|
|
834
|
-
? cached[@"lastRequestTotal"] : nil;
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
839
|
-
// 会话内记录是按时间递增写入的,日边界只在跨天那一条上重算,不必每条都问日历。
|
|
840
|
-
__block NSTimeInterval bucketStart = 0;
|
|
841
|
-
__block NSTimeInterval bucketEnd = 0;
|
|
842
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
843
|
-
if (!handle) return nil;
|
|
844
|
-
if (offset > 0) [handle seekToFileOffset:offset];
|
|
845
|
-
unsigned long long consumed = EnumerateLines(handle, NO, ^(NSData *line) {
|
|
846
|
-
// 会话起点取文件第一条带 timestamp 的行,不限于 token_count:它决定这个会话算不算
|
|
847
|
-
// 整段落在窗口内。找到之后就不再对普通行做 JSON 解析。
|
|
848
|
-
if (!start) {
|
|
849
|
-
NSTimeInterval timestamp = LineTimestamp(line);
|
|
850
|
-
if (timestamp > 0) start = @(timestamp);
|
|
851
|
-
}
|
|
852
|
-
NSDictionary *record = TokenRecordFromLine(line);
|
|
853
|
-
NSDictionary *total = record[@"total"];
|
|
854
|
-
if (!total) return;
|
|
855
|
-
last = [record[@"timestamp"] doubleValue];
|
|
856
|
-
// Codex 会重复写同一份累计快照,事件行数不能直接当调用次数。累计值发生变化才代表
|
|
857
|
-
// 一次新的模型响应;上下文压缩导致累计值归零时同样会被识别为新响应。
|
|
858
|
-
BOOL newRequest = !lastRequestTotal || ![total isEqualToDictionary:lastRequestTotal];
|
|
859
|
-
if (newRequest) [requestTimestamps addObject:record[@"timestamp"]];
|
|
860
|
-
// 段内用累计值相减、归零时整份计入,与 TokenSessionSummary 的分段口径一致:
|
|
861
|
-
// 逐条增量相加会收敛回段末的累计值,因此日桶之和等于 summary[@"total"]。
|
|
862
|
-
NSDictionary *increment = TokenCountsBySubtracting(total, lastRequestTotal);
|
|
863
|
-
if (last < bucketStart || last >= bucketEnd) {
|
|
864
|
-
NSDate *dayStart = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:last]];
|
|
865
|
-
NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:dayStart
|
|
866
|
-
options:0];
|
|
867
|
-
bucketStart = dayStart.timeIntervalSince1970;
|
|
868
|
-
bucketEnd = (next ?: [dayStart dateByAddingTimeInterval:86400]).timeIntervalSince1970;
|
|
869
|
-
}
|
|
870
|
-
NSString *dayKey = DayBucketKey(bucketStart);
|
|
871
|
-
NSMutableDictionary *bucket = days[dayKey];
|
|
872
|
-
if (!bucket) {
|
|
873
|
-
bucket = [NSMutableDictionary dictionary];
|
|
874
|
-
days[dayKey] = bucket;
|
|
875
|
-
}
|
|
876
|
-
AddTokenCounts(bucket, increment);
|
|
877
|
-
if (newRequest) {
|
|
878
|
-
bucket[@"request_count"] = @([bucket[@"request_count"] unsignedLongLongValue] + 1);
|
|
879
|
-
}
|
|
880
|
-
lastRequestTotal = total;
|
|
881
|
-
NSDictionary *previous = segments.lastObject;
|
|
882
|
-
if (!previous || TokenTotalsDidReset(total, previous)) [segments addObject:total];
|
|
883
|
-
else segments[segments.count - 1] = total;
|
|
884
|
-
});
|
|
885
|
-
[handle closeFile];
|
|
886
|
-
|
|
887
|
-
NSMutableDictionary *summary = [@{@"size": @(size), @"offset": @(offset + consumed)} mutableCopy];
|
|
888
|
-
if (start) summary[@"start"] = start;
|
|
889
|
-
if (segments.count > 0) {
|
|
890
|
-
summary[@"segments"] = [segments copy];
|
|
891
|
-
summary[@"end"] = @(last);
|
|
892
|
-
summary[@"total"] = SummedSegmentTotals(segments);
|
|
893
|
-
summary[@"requestTimestamps"] = [requestTimestamps copy];
|
|
894
|
-
// 冻结成不可变,避免下一轮增量追读时改到已经交给调用方的那份。
|
|
895
|
-
NSMutableDictionary *frozenDays = [NSMutableDictionary dictionaryWithCapacity:days.count];
|
|
896
|
-
for (NSString *key in days) frozenDays[key] = [days[key] copy];
|
|
897
|
-
summary[@"days"] = [frozenDays copy];
|
|
898
|
-
if (lastRequestTotal) summary[@"lastRequestTotal"] = lastRequestTotal;
|
|
899
|
-
}
|
|
900
|
-
cache[url.path] = summary;
|
|
901
|
-
return (start && summary[@"total"]) ? summary : nil;
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
// 累计值相减,而不是累加窗口内的 last_token_usage:Codex 会把同一份 token_count
|
|
905
|
-
// 重复写进会话(本机近期 68 个会话里 14 个如此,sum(last) 整体比末行 total 高 1.1%,
|
|
906
|
-
// 最差的单个会话高 7.7%),累加就把重复的那次算了两遍。累计值对重复事件是幂等的。
|
|
907
|
-
// total_token_usage 罕见地回退(会话内重置)时,窗口前的基线已经失效,直接取窗口内的值。
|
|
908
|
-
static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline) {
|
|
909
|
-
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
|
910
|
-
for (NSString *key in TokenKeys()) {
|
|
911
|
-
if (!totals[key]) continue;
|
|
912
|
-
unsigned long long current = [totals[key] unsignedLongLongValue];
|
|
913
|
-
unsigned long long previous = [baseline[key] unsignedLongLongValue];
|
|
914
|
-
result[key] = @(current >= previous ? current - previous : current);
|
|
915
|
-
}
|
|
916
|
-
return result;
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
// 跨窗口起点的会话只算窗口内的增量。分段规则与 TokenSessionSummary 一致:累计值一旦
|
|
920
|
-
// 归零,窗口起点之前取到的基线就作废了,后面那一段要从 0 起算,段与段的增量再相加。
|
|
921
|
-
static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTimeInterval end) {
|
|
922
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
923
|
-
if (!handle) return nil;
|
|
924
|
-
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
|
925
|
-
__block NSDictionary *previous = nil;
|
|
926
|
-
__block NSDictionary *baseline = nil;
|
|
927
|
-
__block NSDictionary *inside = nil;
|
|
928
|
-
// 窗口内一条 token_count 都没有的段不贡献任何用量。
|
|
929
|
-
void (^flush)(void) = ^{
|
|
930
|
-
if (inside) AddTokenCounts(result, TokenCountsBySubtracting(inside, baseline));
|
|
931
|
-
baseline = nil;
|
|
932
|
-
inside = nil;
|
|
933
|
-
};
|
|
934
|
-
EnumerateLines(handle, YES, ^(NSData *line) {
|
|
935
|
-
NSDictionary *record = TokenRecordFromLine(line);
|
|
936
|
-
NSDictionary *total = record[@"total"];
|
|
937
|
-
if (!total) return;
|
|
938
|
-
if (previous && TokenTotalsDidReset(total, previous)) flush();
|
|
939
|
-
previous = total;
|
|
940
|
-
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
941
|
-
if (timestamp < start) baseline = total;
|
|
942
|
-
else if (timestamp < end) inside = total;
|
|
943
|
-
});
|
|
944
|
-
flush();
|
|
945
|
-
[handle closeFile];
|
|
946
|
-
return result;
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
// 聚合区间对齐官方重置时间:[resets_at - 窗长, resets_at)。
|
|
950
|
-
// Codex 的 rate_limits 自带 window_minutes;Claude 没有这个字段,由调用方给出订阅
|
|
951
|
-
// 固定的 300 / 10080 分钟作为兜底。返回 NO 表示窗口当前不可用(缺 resets_at 或已过期),
|
|
952
|
-
// 此时不做任何 Token 统计,避免拿过期窗口冒充当前值。
|
|
953
|
-
static BOOL TokenWindowForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
954
|
-
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
955
|
-
NSNumber *minutes = [quota[@"window_minutes"] isKindOfClass:NSNumber.class]
|
|
956
|
-
? quota[@"window_minutes"] : nil;
|
|
957
|
-
double windowMinutes = minutes ? minutes.doubleValue : fallbackMinutes;
|
|
958
|
-
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
959
|
-
if (windowMinutes <= 0 || !reset) return NO;
|
|
960
|
-
NSTimeInterval end = reset.doubleValue;
|
|
961
|
-
if (NSDate.date.timeIntervalSince1970 >= end) return NO;
|
|
962
|
-
if (outStart) *outStart = end - windowMinutes * 60.0;
|
|
963
|
-
if (outEnd) *outEnd = end;
|
|
964
|
-
return YES;
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
// 官方窗口拿不到时(账号根本没有这个窗口、缺 resets_at、或窗口已过期),Token 依然是
|
|
968
|
-
// 本机自己数出来的,没有理由跟着变成 `--`。退化成按本机时钟往回推的滚动窗口。
|
|
969
|
-
// 终点向上对齐到 10 分钟:起点每秒都在动的话,分片缓存的键每轮都变,跨界会话会被整篇重扫。
|
|
970
|
-
static const NSTimeInterval TokenFallbackGranularity = 600;
|
|
971
|
-
static void RollingWindowForMinutes(double minutes, NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
972
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
973
|
-
NSTimeInterval end = (floor(now / TokenFallbackGranularity) + 1) * TokenFallbackGranularity;
|
|
974
|
-
if (outStart) *outStart = end - minutes * 60.0;
|
|
975
|
-
if (outEnd) *outEnd = end;
|
|
976
|
-
}
|
|
977
|
-
static BOOL TokenWindowOrFallback(NSDictionary *quota, double fallbackMinutes,
|
|
978
|
-
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
979
|
-
if (TokenWindowForQuota(quota, fallbackMinutes, outStart, outEnd)) return YES;
|
|
980
|
-
if (fallbackMinutes <= 0) return NO;
|
|
981
|
-
RollingWindowForMinutes(fallbackMinutes, outStart, outEnd);
|
|
982
|
-
return YES;
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
// 面板要并列展示两家数据,而两家的 resets_at 并不一致(实测能差 2 天以上),
|
|
986
|
-
// 所以汇总另用一组与订阅完全脱钩的自然日窗口,保证两家的时间口径一致。
|
|
987
|
-
//
|
|
988
|
-
// 取自然日边界而不是"从现在往回推 N 秒",是因为分片缓存的键里含窗口起点:起点每秒
|
|
989
|
-
// 都在动的话,跨界会话每一轮都要整篇重扫;对齐到零点后起点一天之内不变,缓存才能命中。
|
|
990
|
-
static void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *weekStart,
|
|
991
|
-
NSTimeInterval *end) {
|
|
992
|
-
NSDate *now = NSDate.date;
|
|
993
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
994
|
-
NSDate *midnight = [calendar startOfDayForDate:now];
|
|
995
|
-
if (todayStart) *todayStart = midnight.timeIntervalSince1970;
|
|
996
|
-
if (weekStart) {
|
|
997
|
-
NSDate *start = [calendar dateByAddingUnit:NSCalendarUnitDay value:-6 toDate:midnight
|
|
998
|
-
options:0];
|
|
999
|
-
*weekStart = (start ?: midnight).timeIntervalSince1970;
|
|
1000
|
-
}
|
|
1001
|
-
// 时钟轻微前后跳动时,不要把刚落盘的记录挡在窗口外,因此终点先留出 60 秒余量。
|
|
1002
|
-
// 之后再向上对齐到 10 分钟:分片缓存的键里同时含起点和终点,终点每秒都在动的话,
|
|
1003
|
-
// 键每一轮都是新的,起点对齐到零点省下的那次命中会被它整个抵消——跨界会话照样
|
|
1004
|
-
// 每轮重扫,而且上一轮写下的分片还会被 PruneTokenCache 当成过期窗口清掉。
|
|
1005
|
-
if (end) {
|
|
1006
|
-
*end = ceil((now.timeIntervalSince1970 + 60) / TokenFallbackGranularity) *
|
|
1007
|
-
TokenFallbackGranularity;
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
// 自然月窗口。本月是 1 日 00:00 起算,展示区间到"此刻",曲线区间到月底。
|
|
1012
|
-
//
|
|
1013
|
-
// 同比区间两边都只数到"最后一个完整的自然日":本月 1 日至今日 00:00,对比上月 1 日至上月
|
|
1014
|
-
// 第 N 日 00:00(N = 本月已过完的整日数)。刻意不做到同一时刻——上月的数据来自日粒度的
|
|
1015
|
-
// 归档,切不出"14 日 15:30"这种半天;而月度同比本来就是趋势判断,差半天换来"上月的会话
|
|
1016
|
-
// 文件一次都不用再打开",这笔账是划算的。上月天数不够时(3 月 31 日对比 2 月)封顶到上月末。
|
|
1017
|
-
static NSDictionary *CalendarMonthWindows(NSTimeInterval alignedEnd) {
|
|
1018
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
1019
|
-
NSDate *now = NSDate.date;
|
|
1020
|
-
NSDate *monthStart = CurrentMonthStartDate();
|
|
1021
|
-
NSDate *nextMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:1
|
|
1022
|
-
toDate:monthStart options:0] ?: now;
|
|
1023
|
-
NSDate *previousMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-1
|
|
1024
|
-
toDate:monthStart options:0] ?: monthStart;
|
|
1025
|
-
NSDate *todayStart = [calendar startOfDayForDate:now];
|
|
1026
|
-
NSInteger elapsedDays = [calendar components:NSCalendarUnitDay fromDate:monthStart
|
|
1027
|
-
toDate:todayStart options:0].day;
|
|
1028
|
-
if (elapsedDays < 0) elapsedDays = 0;
|
|
1029
|
-
NSDate *previousComparableEnd = [calendar dateByAddingUnit:NSCalendarUnitDay
|
|
1030
|
-
value:(int)elapsedDays toDate:previousMonthStart options:0] ?: previousMonthStart;
|
|
1031
|
-
NSTimeInterval currentStart = monthStart.timeIntervalSince1970;
|
|
1032
|
-
return @{ @"monthStart": @(currentStart),
|
|
1033
|
-
@"monthEnd": @(fmin(alignedEnd, nextMonthStart.timeIntervalSince1970)),
|
|
1034
|
-
@"monthCurveEnd": @(nextMonthStart.timeIntervalSince1970),
|
|
1035
|
-
// 每月 1 号这一天 todayStart == monthStart,同比区间两边都是空的,比出来是"持平"。
|
|
1036
|
-
@"monthComparableEnd": @(todayStart.timeIntervalSince1970),
|
|
1037
|
-
@"previousMonthStart": @(previousMonthStart.timeIntervalSince1970),
|
|
1038
|
-
@"previousMonthEnd": @(fmin(currentStart,
|
|
1039
|
-
previousComparableEnd.timeIntervalSince1970)) };
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
static NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end) {
|
|
1043
|
-
return [NSString stringWithFormat:@"partial-%.0f-%.0f", start, end];
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
// requestTimestamps 按写入顺序递增,取区间计数用二分即可:逐条比较要在每个窗口上把
|
|
1047
|
-
// 所有会话的时间戳全走一遍,窗口一多就成了主线程上的固定开销。
|
|
1048
|
-
static NSUInteger TimestampLowerBound(NSArray<NSNumber *> *timestamps, NSTimeInterval value) {
|
|
1049
|
-
NSUInteger low = 0;
|
|
1050
|
-
NSUInteger high = timestamps.count;
|
|
1051
|
-
while (low < high) {
|
|
1052
|
-
NSUInteger middle = low + (high - low) / 2;
|
|
1053
|
-
if (timestamps[middle].doubleValue < value) low = middle + 1;
|
|
1054
|
-
else high = middle;
|
|
1055
|
-
}
|
|
1056
|
-
return low;
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval end,
|
|
1060
|
-
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
1061
|
-
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
1062
|
-
BOOL hasTokenSchema = NO;
|
|
1063
|
-
unsigned long long requestCount = 0;
|
|
1064
|
-
for (NSURL *url in urls) {
|
|
1065
|
-
NSMutableDictionary *summary = [(NSDictionary *)TokenSessionSummary(url, cache) mutableCopy];
|
|
1066
|
-
if (!summary) continue;
|
|
1067
|
-
hasTokenSchema = YES;
|
|
1068
|
-
NSTimeInterval sessionStart = [summary[@"start"] doubleValue];
|
|
1069
|
-
NSTimeInterval sessionEnd = [summary[@"end"] doubleValue];
|
|
1070
|
-
if (sessionEnd < start || sessionStart >= end) continue;
|
|
1071
|
-
NSArray<NSNumber *> *timestamps = [summary[@"requestTimestamps"] isKindOfClass:NSArray.class]
|
|
1072
|
-
? summary[@"requestTimestamps"] : @[];
|
|
1073
|
-
requestCount += TimestampLowerBound(timestamps, end) -
|
|
1074
|
-
TimestampLowerBound(timestamps, start);
|
|
1075
|
-
if (sessionStart >= start) {
|
|
1076
|
-
AddTokenCounts(totals, summary[@"total"]);
|
|
1077
|
-
continue;
|
|
1078
|
-
}
|
|
1079
|
-
NSString *partialKey = PartialTokenKey(start, end);
|
|
1080
|
-
NSDictionary *partial = summary[partialKey];
|
|
1081
|
-
if (!partial) {
|
|
1082
|
-
partial = PartialTokenTotals(url, start, end) ?: @{};
|
|
1083
|
-
summary[partialKey] = partial;
|
|
1084
|
-
cache[url.path] = summary;
|
|
1085
|
-
}
|
|
1086
|
-
AddTokenCounts(totals, partial);
|
|
1087
|
-
}
|
|
1088
|
-
if (!hasTokenSchema) return nil;
|
|
1089
|
-
// 有会话但没有一条落在窗口内时,真实用量就是 0,不能退化成"无数据"的 `--`。
|
|
1090
|
-
if (totals.count == 0) {
|
|
1091
|
-
for (NSString *key in TokenKeys()) totals[key] = @0;
|
|
1092
|
-
}
|
|
1093
|
-
totals[@"request_count"] = @(requestCount);
|
|
1094
|
-
return totals;
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
static NSDictionary *TokenTotalsForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
1098
|
-
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
1099
|
-
NSTimeInterval start = 0;
|
|
1100
|
-
NSTimeInterval end = 0;
|
|
1101
|
-
if (!TokenWindowOrFallback(quota, fallbackMinutes, &start, &end)) return nil;
|
|
1102
|
-
return TokenTotalsInWindow(start, end, urls, cache);
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
// 日曲线直接汇总各会话解析时就分好的日桶:一天一次窗口聚合会让跨天会话被整篇重读,
|
|
1106
|
-
// 而日桶只是遍历一遍缓存里的小字典。
|
|
1107
|
-
static NSArray<NSDictionary *> *CodexDailyTokenSeries(NSTimeInterval start, NSTimeInterval end,
|
|
1108
|
-
NSArray<NSURL *> *urls, NSMutableDictionary *cache, BOOL *outHasTokenSchema) {
|
|
1109
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
1110
|
-
NSMutableArray<NSNumber *> *dayStarts = [NSMutableArray array];
|
|
1111
|
-
NSMutableDictionary<NSString *, NSMutableDictionary *> *buckets = [NSMutableDictionary dictionary];
|
|
1112
|
-
NSDate *cursor = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:start]];
|
|
1113
|
-
while (cursor.timeIntervalSince1970 < end) {
|
|
1114
|
-
NSTimeInterval dayStart = cursor.timeIntervalSince1970;
|
|
1115
|
-
if (dayStart >= start) {
|
|
1116
|
-
[dayStarts addObject:@(dayStart)];
|
|
1117
|
-
buckets[DayBucketKey(dayStart)] = [NSMutableDictionary dictionary];
|
|
1118
|
-
}
|
|
1119
|
-
NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
|
|
1120
|
-
if (!next) break;
|
|
1121
|
-
cursor = next;
|
|
1122
|
-
}
|
|
1123
|
-
for (NSURL *url in urls) {
|
|
1124
|
-
NSDictionary *summary = TokenSessionSummary(url, cache);
|
|
1125
|
-
NSDictionary *days = [summary[@"days"] isKindOfClass:NSDictionary.class]
|
|
1126
|
-
? summary[@"days"] : nil;
|
|
1127
|
-
if (days && outHasTokenSchema) *outHasTokenSchema = YES;
|
|
1128
|
-
for (NSString *key in days) {
|
|
1129
|
-
NSMutableDictionary *bucket = buckets[key];
|
|
1130
|
-
if (bucket) AddDailyTokenCounts(bucket, days[key]);
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
NSMutableArray<NSDictionary *> *series = [NSMutableArray arrayWithCapacity:dayStarts.count];
|
|
1134
|
-
for (NSNumber *dayStart in dayStarts) {
|
|
1135
|
-
NSMutableDictionary *bucket = buckets[DayBucketKey(dayStart.doubleValue)];
|
|
1136
|
-
// 没有任何记录的那天是真实的 0,不能留成空字典让调用方当"无数据"。
|
|
1137
|
-
for (NSString *key in TokenKeys()) if (!bucket[key]) bucket[key] = @0;
|
|
1138
|
-
if (!bucket[@"request_count"]) bucket[@"request_count"] = @0;
|
|
1139
|
-
[series addObject:@{ @"timestamp": dayStart, @"totals": [bucket copy] }];
|
|
1140
|
-
}
|
|
1141
|
-
return series;
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// 本月至今的窗口起点是自然日零点、终点在未来(对齐到 10 分钟的"现在"),窗口内不可能有
|
|
1145
|
-
// 半天,所以日桶之和与按窗口聚合逐字节等价——省掉一遍对全部会话的窗口扫描。
|
|
1146
|
-
// 上月同期的终点落在某天中间,仍然要走 TokenTotalsInWindow。
|
|
1147
|
-
static NSDictionary *SummedDailyTokenSeries(NSArray<NSDictionary *> *series) {
|
|
1148
|
-
NSMutableDictionary *totals = [NSMutableDictionary dictionary];
|
|
1149
|
-
for (NSDictionary *day in series) AddDailyTokenCounts(totals, day[@"totals"]);
|
|
1150
|
-
for (NSString *key in TokenKeys()) if (!totals[key]) totals[key] = @0;
|
|
1151
|
-
if (!totals[@"request_count"]) totals[@"request_count"] = @0;
|
|
1152
|
-
return totals;
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
// 日序列里 [start, end) 之间那几天的合计。同比两侧都靠它切出"到最后一个完整自然日为止"。
|
|
1156
|
-
static NSDictionary *SummedDailyTokenSeriesInRange(NSArray<NSDictionary *> *series,
|
|
1157
|
-
NSTimeInterval start, NSTimeInterval end) {
|
|
1158
|
-
NSMutableArray<NSDictionary *> *slice = [NSMutableArray array];
|
|
1159
|
-
for (NSDictionary *day in series) {
|
|
1160
|
-
NSTimeInterval timestamp = [day[@"timestamp"] doubleValue];
|
|
1161
|
-
if (timestamp >= start && timestamp < end) [slice addObject:day];
|
|
1162
|
-
}
|
|
1163
|
-
return SummedDailyTokenSeries(slice);
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
// 会话滚出 7 天窗口、额度窗口滚动之后,缓存里对应的条目和 partial-* 分片再也不会被读到。
|
|
1167
|
-
// 常驻进程不清理就是只增不减。
|
|
1168
|
-
static void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
|
|
1169
|
-
NSSet<NSString *> *liveWindowKeys) {
|
|
1170
|
-
NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
|
|
1171
|
-
for (NSURL *url in urls) [livePaths addObject:url.path];
|
|
1172
|
-
for (NSString *path in cache.allKeys) {
|
|
1173
|
-
if (![livePaths containsObject:path]) {
|
|
1174
|
-
[cache removeObjectForKey:path];
|
|
1175
|
-
continue;
|
|
1176
|
-
}
|
|
1177
|
-
NSDictionary *summary = cache[path];
|
|
1178
|
-
NSMutableDictionary *trimmed = nil;
|
|
1179
|
-
for (NSString *key in summary.allKeys) {
|
|
1180
|
-
if (![key hasPrefix:@"partial-"] || [liveWindowKeys containsObject:key]) continue;
|
|
1181
|
-
if (!trimmed) trimmed = [summary mutableCopy];
|
|
1182
|
-
[trimmed removeObjectForKey:key];
|
|
1183
|
-
}
|
|
1184
|
-
if (trimmed) cache[path] = trimmed;
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
|
|
1188
|
-
// 摘要缓存落盘/读回。二进制 plist:内容全是 NSNumber / NSString / NSData / 容器,
|
|
1189
|
-
// 写入走临时文件 + 替换,中途崩溃不会留下半个文件。缓存丢失或格式不对只意味着重新解析一遍,
|
|
1190
|
-
// 因此所有失败路径都是静默降级。
|
|
1191
|
-
static NSMutableDictionary *LoadTokenSummaryCache(NSString *path) {
|
|
1192
|
-
NSData *data = [NSData dataWithContentsOfFile:path];
|
|
1193
|
-
if (!data) return [NSMutableDictionary dictionary];
|
|
1194
|
-
id root = [NSPropertyListSerialization propertyListWithData:data
|
|
1195
|
-
options:NSPropertyListMutableContainers format:NULL error:NULL];
|
|
1196
|
-
if (![root isKindOfClass:NSMutableDictionary.class]) return [NSMutableDictionary dictionary];
|
|
1197
|
-
// 条目形如 路径 -> 摘要字典。别的形状一律丢掉,后面的代码不必再防一遍。
|
|
1198
|
-
NSMutableDictionary *cache = root;
|
|
1199
|
-
for (NSString *key in cache.allKeys) {
|
|
1200
|
-
if (![key isKindOfClass:NSString.class] ||
|
|
1201
|
-
![cache[key] isKindOfClass:NSDictionary.class]) {
|
|
1202
|
-
[cache removeObjectForKey:key];
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
return cache;
|
|
1206
|
-
}
|
|
1207
|
-
|
|
1208
|
-
// Codex 归档是"上月已经算完"的物化结果,一旦落盘就再也不重算(见 UsageByAddingTokenTotals
|
|
1209
|
-
// 里的 buildsArchive)。旧版本按日期目录名剪枝,长期续写旧会话的机器归出来的档本身就是缺数的,
|
|
1210
|
-
// 光换扫描口径不会自愈。版本号对不上就整份丢掉,让下一轮重新归一次。
|
|
1211
|
-
static NSString *const MonthlyArchiveSchemaKey = @"schema";
|
|
1212
|
-
static const NSInteger MonthlyArchiveSchemaVersion = 2;
|
|
1213
|
-
|
|
1214
|
-
static NSMutableDictionary *LoadMonthlyUsageArchive(NSString *path) {
|
|
1215
|
-
NSMutableDictionary *archive = LoadTokenSummaryCache(path);
|
|
1216
|
-
NSDictionary *schema = [archive[MonthlyArchiveSchemaKey] isKindOfClass:NSDictionary.class]
|
|
1217
|
-
? archive[MonthlyArchiveSchemaKey] : nil;
|
|
1218
|
-
if ([schema[@"version"] integerValue] != MonthlyArchiveSchemaVersion) [archive removeAllObjects];
|
|
1219
|
-
// PruneMonthlyArchive 按 YYYY-MM 的字典序裁剪,"schema" 排在所有月份键之后,不会被裁掉。
|
|
1220
|
-
archive[MonthlyArchiveSchemaKey] = @{@"version": @(MonthlyArchiveSchemaVersion)};
|
|
1221
|
-
return archive;
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
// NSData 是类簇,可变性判断不能靠 isKindOfClass:二进制 plist 解析出来的**不可变**
|
|
1225
|
-
// __NSCFData 对 isKindOfClass:NSMutableData 同样返回 YES。据此把只读缓冲区当成可变的
|
|
1226
|
-
// 原地 appendBytes,就会写到它末尾之外——ASan 抓到的正是这一下:
|
|
1227
|
-
// heap-buffer-overflow, WRITE of size 48, 0 bytes after 6640-byte region
|
|
1228
|
-
// 分配点 __CFBinaryPlistCreateObjectFiltered <- LoadTokenSummaryCache
|
|
1229
|
-
// 越界写破坏堆之后进程不会当场死,而是在之后任意一次内存操作上倒下,因此崩溃点看起来
|
|
1230
|
-
// 和这里毫无关系(实际报告里落在 EnumerateLines 和 SaveTokenSummaryCache 上)。
|
|
1231
|
-
//
|
|
1232
|
-
// 可靠的做法只有一条:落盘缓存一读回来就把 records 换成本进程创建的可变副本,
|
|
1233
|
-
// 之后 ClaudeRecordsForFile 的原地追加才成立。只替换 records,其余字段原样保留——
|
|
1234
|
-
// Codex 侧的条目形状不同(start/total/segments/days…),整条重建会把它们抹掉。
|
|
1235
|
-
static void MakeCachedRecordsMutable(NSMutableDictionary *cache) {
|
|
1236
|
-
for (NSString *path in cache.allKeys) {
|
|
1237
|
-
NSDictionary *entry = cache[path];
|
|
1238
|
-
if (![entry isKindOfClass:NSDictionary.class]) continue;
|
|
1239
|
-
NSData *records = [entry[@"records"] isKindOfClass:NSData.class] ? entry[@"records"] : nil;
|
|
1240
|
-
if (!records) continue;
|
|
1241
|
-
NSMutableDictionary *updated = [entry mutableCopy];
|
|
1242
|
-
updated[@"records"] = [records mutableCopy];
|
|
1243
|
-
cache[path] = updated;
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
static void SaveTokenSummaryCache(NSDictionary *cache, NSString *path) {
|
|
1248
|
-
if (!path.length) return;
|
|
1249
|
-
NSData *data = [NSPropertyListSerialization dataWithPropertyList:cache
|
|
1250
|
-
format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL];
|
|
1251
|
-
if (!data) return;
|
|
1252
|
-
NSString *temporary = [path stringByAppendingPathExtension:@"tmp"];
|
|
1253
|
-
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
1254
|
-
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
1255
|
-
if (![data writeToFile:temporary atomically:NO]) return;
|
|
1256
|
-
NSURL *destination = [NSURL fileURLWithPath:path];
|
|
1257
|
-
if (![NSFileManager.defaultManager replaceItemAtURL:destination
|
|
1258
|
-
withItemAtURL:[NSURL fileURLWithPath:temporary] backupItemName:nil options:0
|
|
1259
|
-
resultingItemURL:NULL error:NULL]) {
|
|
1260
|
-
// 目标还不存在时 replaceItemAtURL 会失败,这时直接搬过去。
|
|
1261
|
-
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
1262
|
-
if (![NSFileManager.defaultManager moveItemAtPath:temporary toPath:path error:nil]) {
|
|
1263
|
-
[NSFileManager.defaultManager removeItemAtPath:temporary error:nil];
|
|
1264
|
-
}
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
// 归档只用来做"上月同期"对比,留着更早的月份没有意义。保留 3 个月是给跨月那一下留余量,
|
|
1269
|
-
// 顺带在时区/系统时间被改回去时还能命中。
|
|
1270
|
-
static void PruneMonthlyArchive(NSMutableDictionary *archive) {
|
|
1271
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
1272
|
-
NSDate *monthStart = CurrentMonthStartDate();
|
|
1273
|
-
NSDate *oldest = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-3 toDate:monthStart
|
|
1274
|
-
options:0] ?: monthStart;
|
|
1275
|
-
NSString *oldestKey = MonthArchiveKey(oldest.timeIntervalSince1970);
|
|
1276
|
-
for (NSString *key in archive.allKeys) {
|
|
1277
|
-
if ([key compare:oldestKey] == NSOrderedAscending) [archive removeObjectForKey:key];
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
// 一份额度都没拿到时也照样统计 Token:Token 是本机数出来的,不该因为官方额度缺失就空着。
|
|
1282
|
-
//
|
|
1283
|
-
// archive 是"已结束自然月"的归档(见 MonthlyUsageArchivePath)。上月一旦归档,扫描范围就
|
|
1284
|
-
// 收窄到本月,上月的会话文件再也不会被打开;archiveChanged 置位表示这一轮新写了归档,
|
|
1285
|
-
// 调用方据此落盘。
|
|
1286
|
-
static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessionsURL,
|
|
1287
|
-
NSArray<NSURL *> *pinnedURLs, NSMutableDictionary *cache, NSMutableDictionary *archive,
|
|
1288
|
-
BOOL *archiveChanged) {
|
|
1289
|
-
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
1290
|
-
BOOL apiMode = ProviderShowsAPIUsage(CodexUsageDisplayModeKey);
|
|
1291
|
-
NSTimeInterval rollingFloor = RollingTokenWindowFloor();
|
|
1292
|
-
NSDictionary *monthWindows = CalendarMonthWindows(0);
|
|
1293
|
-
NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
|
|
1294
|
-
NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
|
|
1295
|
-
NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
|
|
1296
|
-
NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
|
|
1297
|
-
NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
|
|
1298
|
-
NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
|
|
1299
|
-
NSArray<NSDictionary *> *archivedDaily = apiMode &&
|
|
1300
|
-
[archive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
|
|
1301
|
-
? archive[previousMonthKey][@"daily"] : nil;
|
|
1302
|
-
// 上月还没归档时才把扫描范围放宽到上月月初,而且只放宽这一次。
|
|
1303
|
-
BOOL buildsArchive = apiMode && !archivedDaily;
|
|
1304
|
-
NSTimeInterval earliest = buildsArchive ? previousMonthStart
|
|
1305
|
-
: (apiMode ? fmin(monthStart, rollingFloor) : rollingFloor);
|
|
1306
|
-
NSArray<NSURL *> *urls = TokenAggregationURLs(sessionsURL, earliest, pinnedURLs);
|
|
1307
|
-
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
1308
|
-
? usage[@"fiveHour"] : nil;
|
|
1309
|
-
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
1310
|
-
NSDictionary *fiveTokens = TokenTotalsForQuota(five, FiveHourWindowMinutes, urls, cache);
|
|
1311
|
-
NSDictionary *weekTokens = TokenTotalsForQuota(week, SevenDayWindowMinutes, urls, cache);
|
|
1312
|
-
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
1313
|
-
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
1314
|
-
NSDictionary *todayTokens = TokenTotalsInWindow(todayStart, rollingEnd, urls, cache);
|
|
1315
|
-
NSDictionary *recentTokens = TokenTotalsInWindow(rollingWeekStart, rollingEnd, urls, cache);
|
|
1316
|
-
// 订阅视图不看月度数据,连算都不必算:会话列表本来就只回溯 8 天,月窗口只会得到
|
|
1317
|
-
// 一段被截断的假数据,而代价是每次刷新多遍历一遍全部会话。
|
|
1318
|
-
BOOL hasDailySchema = NO;
|
|
1319
|
-
// 曲线铺满整个自然月:末尾这些还没到的日子是货真价实的 0,读者能一眼看出月份过了多少。
|
|
1320
|
-
NSArray *monthDaily = apiMode
|
|
1321
|
-
? CodexDailyTokenSeries(monthStart, monthCurveEnd, urls, cache, &hasDailySchema) : @[];
|
|
1322
|
-
NSDictionary *monthTokens = hasDailySchema ? SummedDailyTokenSeries(monthDaily) : nil;
|
|
1323
|
-
NSDictionary *monthComparable = hasDailySchema
|
|
1324
|
-
? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd) : nil;
|
|
1325
|
-
if (buildsArchive) {
|
|
1326
|
-
NSArray *previousDaily = CodexDailyTokenSeries(previousMonthStart, monthStart,
|
|
1327
|
-
urls, cache, NULL);
|
|
1328
|
-
archive[previousMonthKey] = @{ @"daily": previousDaily,
|
|
1329
|
-
@"totals": SummedDailyTokenSeries(previousDaily) };
|
|
1330
|
-
archivedDaily = previousDaily;
|
|
1331
|
-
if (archiveChanged) *archiveChanged = YES;
|
|
1332
|
-
}
|
|
1333
|
-
NSDictionary *previousMonthTokens = archivedDaily
|
|
1334
|
-
? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd) : nil;
|
|
1335
|
-
NSMutableSet<NSString *> *liveWindowKeys = [NSMutableSet setWithArray:@[
|
|
1336
|
-
PartialTokenKey(todayStart, rollingEnd), PartialTokenKey(rollingWeekStart, rollingEnd)]];
|
|
1337
|
-
NSArray<NSDictionary *> *windows = @[
|
|
1338
|
-
@{@"quota": five ?: @{}, @"minutes": @(FiveHourWindowMinutes)},
|
|
1339
|
-
@{@"quota": week ?: @{}, @"minutes": @(SevenDayWindowMinutes)}];
|
|
1340
|
-
for (NSDictionary *window in windows) {
|
|
1341
|
-
NSTimeInterval start = 0;
|
|
1342
|
-
NSTimeInterval end = 0;
|
|
1343
|
-
if (TokenWindowOrFallback(window[@"quota"], [window[@"minutes"] doubleValue], &start, &end)) {
|
|
1344
|
-
[liveWindowKeys addObject:PartialTokenKey(start, end)];
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
PruneTokenCache(cache, urls, liveWindowKeys);
|
|
1348
|
-
NSMutableDictionary *result = [usage mutableCopy];
|
|
1349
|
-
result[@"tokenUsage"] = @{
|
|
1350
|
-
@"fiveHour": fiveTokens ?: NSNull.null,
|
|
1351
|
-
@"week": weekTokens ?: NSNull.null,
|
|
1352
|
-
@"today": todayTokens ?: NSNull.null,
|
|
1353
|
-
@"recentWeek": recentTokens ?: NSNull.null,
|
|
1354
|
-
@"recentWeekStartsAt": @(rollingWeekStart),
|
|
1355
|
-
@"month": monthTokens ?: NSNull.null,
|
|
1356
|
-
// 同比用的是"到最后一个完整自然日为止"的两段,与展示用的 month(含今天)不是一回事。
|
|
1357
|
-
@"monthComparable": monthComparable ?: NSNull.null,
|
|
1358
|
-
@"previousMonthToDate": previousMonthTokens ?: NSNull.null,
|
|
1359
|
-
@"monthDaily": monthDaily,
|
|
1360
|
-
@"monthStartsAt": @(monthStart),
|
|
1361
|
-
@"monthComparableEndsAt": @(monthComparableEnd),
|
|
1362
|
-
@"previousMonthComparableEndsAt": @(previousMonthEnd),
|
|
1363
|
-
@"source": @"local"
|
|
1364
|
-
};
|
|
1365
|
-
return result;
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
static NSURL *CodexSessionsURL(void) {
|
|
1369
|
-
return [NSURL fileURLWithPath:
|
|
1370
|
-
[DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"sessions"]];
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
NSDictionary *LatestUsage(void) {
|
|
1374
|
-
NSURL *sessions = CodexSessionsURL();
|
|
1375
|
-
NSURL *newest = NewestCodexSessionURL(sessions);
|
|
1376
|
-
if (!newest) return nil;
|
|
1377
|
-
|
|
1378
|
-
NSData *tail = SessionTailData(newest);
|
|
1379
|
-
if (!tail) return nil;
|
|
1380
|
-
NSNumber *exhaustedAt = nil;
|
|
1381
|
-
NSDictionary *usage = LatestUsageInData(tail, &exhaustedAt)
|
|
1382
|
-
?: LatestQuotaInRecentSessions(sessions, newest);
|
|
1383
|
-
usage = UsageByRemovingInactiveQuotaWindows(usage);
|
|
1384
|
-
// --status 这类一次性调用不带缓存也不写归档:它只需要当下这一份数字。
|
|
1385
|
-
usage = UsageByAddingTokenTotals(usage, sessions, newest ? @[newest] : nil,
|
|
1386
|
-
[NSMutableDictionary dictionary],
|
|
1387
|
-
LoadMonthlyUsageArchive(MonthlyUsageArchivePath(@"codex", sessions.path)), NULL);
|
|
1388
|
-
return UsageByMarkingExhaustion(usage, exhaustedAt.doubleValue);
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
// Token 聚合要遍历近 7 天的会话文件,而 refresh 由 FSEvents 驱动、会话写盘时约 0.5 秒
|
|
1392
|
-
// 一次。按额度窗口节流,窗口滚动或手动刷新时立刻重算。
|
|
1393
|
-
static const NSTimeInterval TokenAggregationInterval = 5.0;
|
|
1394
|
-
|
|
1395
|
-
// 额度窗口的身份:两个 resets_at 一变就说明窗口滚动了,缓存必须作废。
|
|
1396
|
-
static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
1397
|
-
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
1398
|
-
? usage[@"fiveHour"] : nil;
|
|
1399
|
-
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
1400
|
-
return [NSString stringWithFormat:@"%.0f/%.0f",
|
|
1401
|
-
[five[@"resets_at"] doubleValue], [week[@"resets_at"] doubleValue]];
|
|
1402
|
-
}
|
|
1403
|
-
|
|
1404
|
-
// 落盘节流:聚合本身最快 5 秒一次,缓存写盘没必要跟得那么紧。进程被 kill 而没来得及写,
|
|
1405
|
-
// 代价也只是下次启动多解析一段。
|
|
1406
|
-
static const NSTimeInterval TokenCacheSaveInterval = 60.0;
|
|
1407
|
-
|
|
1408
|
-
@interface CodexUsageReader ()
|
|
1409
|
-
@property NSMutableDictionary *tokenSummaryCache;
|
|
1410
|
-
@property NSString *tokenSummaryCachePath;
|
|
1411
|
-
@property NSTimeInterval tokenCacheSavedAt;
|
|
1412
|
-
@property NSMutableDictionary *monthlyArchive;
|
|
1413
|
-
@property NSString *monthlyArchivePath;
|
|
1414
|
-
@property NSDictionary *tokenUsage;
|
|
1415
|
-
@property NSString *tokenWindowIdentity;
|
|
1416
|
-
@property NSTimeInterval tokenComputedAt;
|
|
1417
|
-
@property NSTimeInterval exhaustedAt;
|
|
1418
|
-
@property BOOL forcesTokenAggregation;
|
|
1419
|
-
// 内核已经点名"刚被写过"的会话文件:当前正在增量读取的这个,以及最近几批 FSEvents 报上来的
|
|
1420
|
-
// 并发会话。它们无条件参与 Token 聚合,不受日期目录扫描的取舍影响。
|
|
1421
|
-
@property NSMutableArray<NSURL *> *pinnedSessionURLs;
|
|
1422
|
-
@end
|
|
1423
|
-
|
|
1424
|
-
@implementation CodexUsageReader
|
|
1425
|
-
- (instancetype)init {
|
|
1426
|
-
if ((self = [super init])) {
|
|
1427
|
-
_sessionsURL = CodexSessionsURL();
|
|
1428
|
-
_partialLine = [NSMutableData data];
|
|
1429
|
-
_tokenSummaryCachePath = TokenSummaryCachePath(@"codex", _sessionsURL.path);
|
|
1430
|
-
_tokenSummaryCache = LoadTokenSummaryCache(_tokenSummaryCachePath);
|
|
1431
|
-
_monthlyArchivePath = MonthlyUsageArchivePath(@"codex", _sessionsURL.path);
|
|
1432
|
-
_monthlyArchive = LoadMonthlyUsageArchive(_monthlyArchivePath);
|
|
1433
|
-
_pinnedSessionURLs = [NSMutableArray array];
|
|
1434
|
-
}
|
|
1435
|
-
return self;
|
|
1436
|
-
}
|
|
1437
|
-
// 缓存里过期的条目由 PruneTokenCache 在每次聚合里清掉,所以落盘的那份不会只增不减。
|
|
1438
|
-
- (void)persistTokenSummaryCacheThrottled:(BOOL)throttled {
|
|
1439
|
-
if (!self.persistsCache) return;
|
|
1440
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
1441
|
-
if (throttled && now - self.tokenCacheSavedAt < TokenCacheSaveInterval) return;
|
|
1442
|
-
self.tokenCacheSavedAt = now;
|
|
1443
|
-
SaveTokenSummaryCache(self.tokenSummaryCache, self.tokenSummaryCachePath);
|
|
1444
|
-
}
|
|
1445
|
-
- (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
|
|
1446
|
-
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
1447
|
-
usage = UsageByRemovingInactiveQuotaWindows(usage);
|
|
1448
|
-
NSString *identity = TokenWindowIdentity(usage);
|
|
1449
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
1450
|
-
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
1451
|
-
[identity isEqualToString:self.tokenWindowIdentity] &&
|
|
1452
|
-
now - self.tokenComputedAt < TokenAggregationInterval;
|
|
1453
|
-
if (reusable) {
|
|
1454
|
-
NSMutableDictionary *result = [usage mutableCopy];
|
|
1455
|
-
result[@"tokenUsage"] = self.tokenUsage;
|
|
1456
|
-
return [self usageByApplyingExhaustion:result];
|
|
1457
|
-
}
|
|
1458
|
-
BOOL archiveChanged = NO;
|
|
1459
|
-
// 正在增量读取的会话永远排在钉住列表最前面:它是最不该被漏掉的那一个,而漏掉它
|
|
1460
|
-
// 恰恰是"额度读得出、今日 Token 却是 0"的成因。
|
|
1461
|
-
[self notePinnedSessionURL:self.sessionURL];
|
|
1462
|
-
NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL,
|
|
1463
|
-
self.pinnedSessionURLs, self.tokenSummaryCache, self.monthlyArchive, &archiveChanged);
|
|
1464
|
-
if (archiveChanged) {
|
|
1465
|
-
PruneMonthlyArchive(self.monthlyArchive);
|
|
1466
|
-
if (self.persistsCache) SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
|
|
1467
|
-
}
|
|
1468
|
-
[self persistTokenSummaryCacheThrottled:YES];
|
|
1469
|
-
id tokens = result[@"tokenUsage"];
|
|
1470
|
-
self.tokenUsage = [tokens isKindOfClass:NSDictionary.class] ? tokens : nil;
|
|
1471
|
-
self.tokenWindowIdentity = identity;
|
|
1472
|
-
self.tokenComputedAt = now;
|
|
1473
|
-
self.forcesTokenAggregation = NO;
|
|
1474
|
-
return [self usageByApplyingExhaustion:result];
|
|
1475
|
-
}
|
|
1476
|
-
// 耗尽事件只往前走:额度恢复由"更新的额度快照"或窗口重置表达(见 ExhaustionStillHolds)。
|
|
1477
|
-
- (void)noteExhaustion:(NSNumber *)timestamp {
|
|
1478
|
-
if (timestamp.doubleValue > self.exhaustedAt) self.exhaustedAt = timestamp.doubleValue;
|
|
1479
|
-
}
|
|
1480
|
-
// 标记失效时把记下的时刻一并清掉:留着它只会在下一轮再比一次同样的大小,而窗口一旦重置,
|
|
1481
|
-
// 这个时刻就永远不该再让任何快照被判成受限了。
|
|
1482
|
-
- (NSDictionary *)usageByApplyingExhaustion:(NSDictionary *)usage {
|
|
1483
|
-
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
1484
|
-
if (!ExhaustionStillHolds(usage, self.exhaustedAt)) {
|
|
1485
|
-
// 快照只会向前走(NewerUsageSnapshot),所以失效一次就是永久失效;真再撞上限流,
|
|
1486
|
-
// noteExhaustion: 会记下新的时刻。
|
|
1487
|
-
self.exhaustedAt = 0;
|
|
1488
|
-
return usage;
|
|
1489
|
-
}
|
|
1490
|
-
return UsageByMarkingExhaustion(usage, self.exhaustedAt);
|
|
1491
|
-
}
|
|
1492
|
-
// 最近被写过的会话,最新的排在前面。并发会话不会太多,留 8 个足够覆盖一批 FSEvents;
|
|
1493
|
-
// 更早的那些反正也会被目录扫描按 mtime 捞回来,钉住它们只是白读文件。
|
|
1494
|
-
static const NSUInteger MaximumPinnedSessions = 8;
|
|
1495
|
-
|
|
1496
|
-
- (void)notePinnedSessionURL:(NSURL *)url {
|
|
1497
|
-
if (!url.path.length) return;
|
|
1498
|
-
NSMutableArray<NSURL *> *pinned = self.pinnedSessionURLs;
|
|
1499
|
-
if (!pinned) {
|
|
1500
|
-
pinned = [NSMutableArray array];
|
|
1501
|
-
self.pinnedSessionURLs = pinned;
|
|
1502
|
-
}
|
|
1503
|
-
for (NSUInteger index = 0; index < pinned.count; index++) {
|
|
1504
|
-
if ([pinned[index].path isEqualToString:url.path]) {
|
|
1505
|
-
[pinned removeObjectAtIndex:index];
|
|
1506
|
-
break;
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1509
|
-
[pinned insertObject:url atIndex:0];
|
|
1510
|
-
while (pinned.count > MaximumPinnedSessions) [pinned removeLastObject];
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
- (void)selectSessionURL:(NSURL *)url {
|
|
1514
|
-
self.sessionURL = url;
|
|
1515
|
-
self.offset = 0;
|
|
1516
|
-
[self.partialLine setLength:0];
|
|
1517
|
-
if (!url) {
|
|
1518
|
-
self.usage = nil;
|
|
1519
|
-
return;
|
|
1520
|
-
}
|
|
1521
|
-
[self notePinnedSessionURL:url];
|
|
1522
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
1523
|
-
if (!handle) return;
|
|
1524
|
-
unsigned long long size = [handle seekToEndOfFile];
|
|
1525
|
-
unsigned long long start = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
|
|
1526
|
-
[handle seekToFileOffset:start];
|
|
1527
|
-
NSData *tail = [handle readDataToEndOfFile];
|
|
1528
|
-
[handle closeFile];
|
|
1529
|
-
self.offset = start + tail.length;
|
|
1530
|
-
// 切换会话意味着数据来源变了,不受节流约束。
|
|
1531
|
-
self.forcesTokenAggregation = YES;
|
|
1532
|
-
// 额度是账号级的,不随会话切换失效。新会话在首个 token_count 落盘前没有 rate_limits,
|
|
1533
|
-
// 这时沿用上一份,否则每次开新会话面板都会整块闪空。窗口过期的判定另有 resets_at 兜底。
|
|
1534
|
-
NSNumber *exhaustedAt = nil;
|
|
1535
|
-
NSDictionary *latest = LatestUsageInData(tail, &exhaustedAt);
|
|
1536
|
-
[self noteExhaustion:exhaustedAt];
|
|
1537
|
-
NSDictionary *fallback = self.usage ?: LatestQuotaInRecentSessions(self.sessionsURL, url);
|
|
1538
|
-
self.usage = [self usageWithTokenTotals:NewerUsageSnapshot(fallback, latest)];
|
|
1539
|
-
|
|
1540
|
-
const uint8_t *bytes = tail.bytes;
|
|
1541
|
-
NSUInteger lastNewline = NSNotFound;
|
|
1542
|
-
for (NSUInteger index = tail.length; index > 0; index--) {
|
|
1543
|
-
if (bytes[index - 1] == '\n') {
|
|
1544
|
-
lastNewline = index - 1;
|
|
1545
|
-
break;
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
if (lastNewline == NSNotFound) [self.partialLine appendData:tail];
|
|
1549
|
-
else if (lastNewline + 1 < tail.length) {
|
|
1550
|
-
[self.partialLine appendData:[tail subdataWithRange:NSMakeRange(lastNewline + 1, tail.length - lastNewline - 1)]];
|
|
1551
|
-
}
|
|
1552
|
-
}
|
|
1553
|
-
- (void)consumeIncrementalData:(NSData *)data {
|
|
1554
|
-
if (data.length == 0) return;
|
|
1555
|
-
[self.partialLine appendData:data];
|
|
1556
|
-
const uint8_t *bytes = self.partialLine.bytes;
|
|
1557
|
-
NSUInteger lineStart = 0;
|
|
1558
|
-
for (NSUInteger index = 0; index < self.partialLine.length; index++) {
|
|
1559
|
-
if (bytes[index] != '\n') continue;
|
|
1560
|
-
NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
1561
|
-
[self noteExhaustion:ExhaustionTimestampFromLine(line)];
|
|
1562
|
-
NSDictionary *newUsage = UsageFromCodexLine(line);
|
|
1563
|
-
self.usage = NewerUsageSnapshot(self.usage, newUsage);
|
|
1564
|
-
lineStart = index + 1;
|
|
1565
|
-
}
|
|
1566
|
-
if (lineStart > 0) {
|
|
1567
|
-
NSData *remainder = [self.partialLine subdataWithRange:
|
|
1568
|
-
NSMakeRange(lineStart, self.partialLine.length - lineStart)];
|
|
1569
|
-
self.partialLine = [remainder mutableCopy];
|
|
1570
|
-
}
|
|
1571
|
-
if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
|
|
1572
|
-
}
|
|
1573
|
-
- (NSDictionary *)refresh {
|
|
1574
|
-
return [self refreshDiscovering:YES];
|
|
1575
|
-
}
|
|
1576
|
-
// discovering=NO 用于 FSEvents 定向路径:内核已经点名了变更的文件,再按 mtime 挑一次
|
|
1577
|
-
// 只会推翻这个结论——发现步骤两条分支(全量的 NewestCodexSessionURL 和同目录的
|
|
1578
|
-
// NewestSessionFileInDirectory)用的都是 mtime,而 mtime 顺序和额度采样先后并不一致。
|
|
1579
|
-
- (NSDictionary *)refreshDiscovering:(BOOL)discovering {
|
|
1580
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
1581
|
-
if (discovering) {
|
|
1582
|
-
BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
|
|
1583
|
-
NSURL *candidate = nil;
|
|
1584
|
-
if (needsFullDiscovery) {
|
|
1585
|
-
candidate = NewestCodexSessionURL(self.sessionsURL);
|
|
1586
|
-
self.lastFullDiscovery = now;
|
|
1587
|
-
} else {
|
|
1588
|
-
candidate = NewestSessionFileInDirectory(
|
|
1589
|
-
self.sessionURL.URLByDeletingLastPathComponent, NULL);
|
|
1590
|
-
}
|
|
1591
|
-
if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
|
|
1592
|
-
}
|
|
1593
|
-
if (!self.sessionURL) return self.usage;
|
|
1594
|
-
|
|
1595
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
|
|
1596
|
-
if (!handle) {
|
|
1597
|
-
self.lastFullDiscovery = 0;
|
|
1598
|
-
return self.usage;
|
|
1599
|
-
}
|
|
1600
|
-
unsigned long long size = [handle seekToEndOfFile];
|
|
1601
|
-
if (size < self.offset) {
|
|
1602
|
-
[handle closeFile];
|
|
1603
|
-
[self selectSessionURL:self.sessionURL];
|
|
1604
|
-
return self.usage;
|
|
1605
|
-
}
|
|
1606
|
-
if (size > self.offset) {
|
|
1607
|
-
unsigned long long start = self.offset;
|
|
1608
|
-
[handle seekToFileOffset:start];
|
|
1609
|
-
NSData *newData = [handle readDataToEndOfFile];
|
|
1610
|
-
self.offset = start + newData.length;
|
|
1611
|
-
[self consumeIncrementalData:newData];
|
|
1612
|
-
}
|
|
1613
|
-
[handle closeFile];
|
|
1614
|
-
self.usage = [self usageWithTokenTotals:self.usage];
|
|
1615
|
-
return self.usage;
|
|
1616
|
-
}
|
|
1617
|
-
- (NSDictionary *)refreshWithFullDiscovery {
|
|
1618
|
-
self.lastFullDiscovery = 0;
|
|
1619
|
-
self.forcesTokenAggregation = YES;
|
|
1620
|
-
return [self refresh];
|
|
1621
|
-
}
|
|
1622
|
-
- (BOOL)isSessionURL:(NSURL *)url {
|
|
1623
|
-
if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return NO;
|
|
1624
|
-
NSString *sessionsPath = self.sessionsURL.path.stringByResolvingSymlinksInPath;
|
|
1625
|
-
NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
|
|
1626
|
-
return [url.path.stringByResolvingSymlinksInPath hasPrefix:prefix];
|
|
1627
|
-
}
|
|
1628
|
-
// 并发会话下一批事件里会有多个会话文件同时变更,而"文件更晚被写"和"额度采样更晚"是两回事:
|
|
1629
|
-
// 会话拿到 rate_limits 之后还会继续追加别的行。取遍历到的最后一个就会切到采样偏旧的会话,
|
|
1630
|
-
// 面板上的百分比于是在两个会话之间来回跳。这里读各自的尾巴,按 sampledAt 挑,与
|
|
1631
|
-
// LatestQuotaInRecentSessions 的判据保持一致。
|
|
1632
|
-
//
|
|
1633
|
-
// 别的会话也必须读取并比较:迟到的旧响应通常会作为下一批里的唯一文件出现。
|
|
1634
|
-
// 唯一的例外是当前会话自己——那是单会话的常态热路径,追加的新行走增量读取,
|
|
1635
|
-
// consumeIncrementalData 里的 NewerUsageSnapshot 已经保证了单调性,不必为它白读一遍尾巴。
|
|
1636
|
-
- (NSDictionary *)refreshForSessionURLs:(NSArray<NSURL *> *)urls {
|
|
1637
|
-
NSURL *chosen = nil;
|
|
1638
|
-
NSURL *currentSession = nil;
|
|
1639
|
-
double chosenSampledAt = [self.usage[@"sampledAt"] doubleValue];
|
|
1640
|
-
for (NSURL *url in urls) {
|
|
1641
|
-
if (![self isSessionURL:url]) continue;
|
|
1642
|
-
// 额度竞选的输赢与 Token 聚合无关:这一批里每个会话文件都刚被写过,落选的那些
|
|
1643
|
-
// 同样带着新的 token_count。钉住它们,别再让日期目录扫描替内核做一次取舍。
|
|
1644
|
-
[self notePinnedSessionURL:url];
|
|
1645
|
-
if (self.sessionURL && [url.path isEqualToString:self.sessionURL.path]) {
|
|
1646
|
-
currentSession = url;
|
|
1647
|
-
continue;
|
|
1648
|
-
}
|
|
1649
|
-
// 耗尽事件也在这段尾巴里。反正已经读了,顺手记下来:候选因为采样更旧而落选时
|
|
1650
|
-
// 整批事件都不再走 refresh,不在这里捕获就永远丢了——而"另一个会话刚更新过额度、
|
|
1651
|
-
// 这个会话撞上限流"正是最容易发生耗尽的时刻。
|
|
1652
|
-
NSNumber *exhaustedAt = nil;
|
|
1653
|
-
NSDictionary *usage = LatestUsageInData(SessionTailData(url), &exhaustedAt);
|
|
1654
|
-
[self noteExhaustion:exhaustedAt];
|
|
1655
|
-
// 整篇都没有额度、或者采样比当前面板更旧的会话不参与竞选。
|
|
1656
|
-
if (!usage) continue;
|
|
1657
|
-
double sampledAt = [usage[@"sampledAt"] doubleValue];
|
|
1658
|
-
if (sampledAt >= chosenSampledAt) {
|
|
1659
|
-
chosen = url;
|
|
1660
|
-
chosenSampledAt = sampledAt;
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
// 没有别的会话胜出时才轮到当前会话,这样先后遍历到谁都不影响结果。
|
|
1664
|
-
if (!chosen) chosen = currentSession;
|
|
1665
|
-
// 一个候选都没选中就不会再走到 usageWithTokenTotals,刚记下的耗尽标记得在这里贴上。
|
|
1666
|
-
if (!chosen) {
|
|
1667
|
-
self.usage = [self usageByApplyingExhaustion:self.usage];
|
|
1668
|
-
return self.usage;
|
|
1669
|
-
}
|
|
1670
|
-
if (![chosen.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:chosen];
|
|
1671
|
-
return [self refreshDiscovering:NO];
|
|
1672
|
-
}
|
|
1673
|
-
@end
|
|
1674
|
-
|
|
1675
|
-
// MARK: - Claude Code 本地 Token 统计
|
|
1676
|
-
//
|
|
1677
|
-
// 数据源是 ~/.claude/projects/<编码后的 cwd>/<session-uuid>.jsonl,以及同级的
|
|
1678
|
-
// <session-uuid>/subagents/agent-*.jsonl(子 agent 的转录,见 RecentClaudeTranscriptURLs)。
|
|
1679
|
-
// 每条 type=assistant 的行带 timestamp 和 message.usage,是**单次请求的增量**,
|
|
1680
|
-
// 与 Codex 的会话累计值不同,因此必须逐条落窗口累加,不能取末行。
|
|
1681
|
-
//
|
|
1682
|
-
// 关键差异:Claude 的 --resume / fork / compact 会把旧行原样复制进新文件,本机实测
|
|
1683
|
-
// 5575 行里有 692 行重复(12%)。不去重的话 7 天用量会虚高一成以上,所以按
|
|
1684
|
-
// message.id + requestId 做全局去重(两者缺失时回退 uuid)。同一次请求还会被拆成多行、
|
|
1685
|
-
// 各带一份递增的 usage 快照,所以去重是**逐字段取最大值合并**而不是丢弃后续行,
|
|
1686
|
-
// 详见 ClaudeTokenTotals。
|
|
1687
|
-
|
|
1688
|
-
typedef struct {
|
|
1689
|
-
double timestamp;
|
|
1690
|
-
uint64_t identity;
|
|
1691
|
-
unsigned long long input;
|
|
1692
|
-
unsigned long long output;
|
|
1693
|
-
unsigned long long cacheRead;
|
|
1694
|
-
unsigned long long cacheWrite;
|
|
1695
|
-
} ClaudeTokenRecord;
|
|
1696
|
-
|
|
1697
|
-
// 去重键存 64 位散列而不是原字符串:近 7 天约 5.5k 条记录,散列后每条 48 字节、
|
|
1698
|
-
// 常驻不到 300KB;64 位空间下这个量级的碰撞概率约 1e-12,可以忽略。
|
|
1699
|
-
static uint64_t ClaudeIdentityHash(NSString *first, NSString *second) {
|
|
1700
|
-
uint64_t hash = 1469598103934665603ULL;
|
|
1701
|
-
for (NSString *part in @[first ?: @"", @"\n", second ?: @""]) {
|
|
1702
|
-
const char *bytes = part.UTF8String;
|
|
1703
|
-
for (const char *cursor = bytes; cursor && *cursor; cursor++) {
|
|
1704
|
-
hash ^= (uint64_t)(unsigned char)*cursor;
|
|
1705
|
-
hash *= 1099511628211ULL;
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
return hash;
|
|
1709
|
-
}
|
|
1710
|
-
|
|
1711
|
-
static unsigned long long ClaudeCount(NSDictionary *usage, NSString *key) {
|
|
1712
|
-
NSNumber *number = [usage[key] isKindOfClass:NSNumber.class] ? usage[key] : nil;
|
|
1713
|
-
return number.unsignedLongLongValue;
|
|
1714
|
-
}
|
|
1715
|
-
|
|
1716
|
-
// message.usage 的顶层就是该次请求的聚合值,内层 iterations 是明细,不能再加一遍。
|
|
1717
|
-
static BOOL ClaudeRecordFromLine(NSData *lineData, ClaudeTokenRecord *record) {
|
|
1718
|
-
if (lineData.length == 0) return NO;
|
|
1719
|
-
static NSData *marker;
|
|
1720
|
-
static dispatch_once_t once;
|
|
1721
|
-
dispatch_once(&once, ^{
|
|
1722
|
-
marker = [@"\"type\":\"assistant\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
1723
|
-
});
|
|
1724
|
-
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
1725
|
-
NSNotFound) return NO;
|
|
1726
|
-
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
1727
|
-
if (![rootValue isKindOfClass:NSDictionary.class]) return NO;
|
|
1728
|
-
NSDictionary *root = rootValue;
|
|
1729
|
-
if (![root[@"type"] isKindOfClass:NSString.class] ||
|
|
1730
|
-
![root[@"type"] isEqualToString:@"assistant"]) return NO;
|
|
1731
|
-
NSDictionary *message = [root[@"message"] isKindOfClass:NSDictionary.class]
|
|
1732
|
-
? root[@"message"] : nil;
|
|
1733
|
-
NSDictionary *usage = [message[@"usage"] isKindOfClass:NSDictionary.class]
|
|
1734
|
-
? message[@"usage"] : nil;
|
|
1735
|
-
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
1736
|
-
if (!usage || !date) return NO;
|
|
1737
|
-
|
|
1738
|
-
NSString *identifier = [message[@"id"] isKindOfClass:NSString.class] ? message[@"id"] : nil;
|
|
1739
|
-
NSString *requestIdentifier = [root[@"requestId"] isKindOfClass:NSString.class]
|
|
1740
|
-
? root[@"requestId"] : nil;
|
|
1741
|
-
// 本机实测 3112 行里有 17 行缺 id 或 requestId,回退到行级 uuid 保证仍能去重。
|
|
1742
|
-
NSString *fallback = [root[@"uuid"] isKindOfClass:NSString.class] ? root[@"uuid"] : nil;
|
|
1743
|
-
record->timestamp = date.timeIntervalSince1970;
|
|
1744
|
-
record->identity = (identifier && requestIdentifier)
|
|
1745
|
-
? ClaudeIdentityHash(identifier, requestIdentifier)
|
|
1746
|
-
: ClaudeIdentityHash(fallback, nil);
|
|
1747
|
-
record->input = ClaudeCount(usage, @"input_tokens");
|
|
1748
|
-
record->output = ClaudeCount(usage, @"output_tokens");
|
|
1749
|
-
record->cacheRead = ClaudeCount(usage, @"cache_read_input_tokens");
|
|
1750
|
-
record->cacheWrite = ClaudeCount(usage, @"cache_creation_input_tokens");
|
|
1751
|
-
return YES;
|
|
1752
|
-
}
|
|
1753
|
-
|
|
1754
|
-
// 桌宠只统计主账号 ~/.claude。刻意不读 CLAUDE_CONFIG_DIR:桌宠是被某个客户端 open
|
|
1755
|
-
// 起来的常驻进程,会一直带着当时的环境变量。用 claude-nw 启动过一次,桌宠就会永久
|
|
1756
|
-
// 只统计那个账号,主账号的用量一条都进不来——实测差了 26 倍(156.8M vs 5.96M)。
|
|
1757
|
-
static NSURL *ClaudeProjectsURL(void) {
|
|
1758
|
-
return [NSURL fileURLWithPath:
|
|
1759
|
-
[DefaultClaudeConfigDirectory() stringByAppendingPathComponent:@"projects"]];
|
|
1760
|
-
}
|
|
1761
|
-
|
|
1762
|
-
// 收集目录内 mtime 落在窗口内的 .jsonl;顺带把子目录交给调用方(传 nil 表示不关心),
|
|
1763
|
-
// 省一次 readdir。
|
|
1764
|
-
static void AppendRecentTranscriptsInDirectory(NSURL *directory, NSTimeInterval earliest,
|
|
1765
|
-
NSMutableArray<NSURL *> *urls, NSMutableArray<NSURL *> *outSubdirectories) {
|
|
1766
|
-
NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey,
|
|
1767
|
-
NSURLIsDirectoryKey];
|
|
1768
|
-
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
1769
|
-
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
1770
|
-
for (NSURL *url in contents) {
|
|
1771
|
-
NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
|
|
1772
|
-
if ([values[NSURLIsDirectoryKey] boolValue]) {
|
|
1773
|
-
[outSubdirectories addObject:url];
|
|
1774
|
-
continue;
|
|
1775
|
-
}
|
|
1776
|
-
if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
|
|
1777
|
-
if (![values[NSURLIsRegularFileKey] boolValue]) continue;
|
|
1778
|
-
NSDate *modified = values[NSURLContentModificationDateKey];
|
|
1779
|
-
if (modified && modified.timeIntervalSince1970 < earliest) continue;
|
|
1780
|
-
[urls addObject:url];
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
// 只看 mtime 落在窗口内的转录文件。本机 76 个文件里近 7 天只有 44 个,目录遍历约 3ms。
|
|
1785
|
-
//
|
|
1786
|
-
// 子 agent(Task/Explore)的转录不写进主会话文件,而是单独落在
|
|
1787
|
-
// <project>/<session-uuid>/subagents/agent-*.jsonl,只扫项目目录一层的话它们一条都进不来
|
|
1788
|
-
// ——本机主会话文件里 isSidechain 的行数为 0,漏掉的就是全部子 agent 用量(历史上单个
|
|
1789
|
-
// 文件到过 269 万 token)。
|
|
1790
|
-
//
|
|
1791
|
-
// 下钻哪些会话由主会话文件 <session-uuid>.jsonl 的 mtime 决定:Task 的调用和结果都会写进
|
|
1792
|
-
// 主会话文件,主文件不在窗口内,它的子 agent 也不可能在。projects/ 目录只增不减(本机
|
|
1793
|
-
// 99 个会话里近 8 天只有 27 个),无条件下钻等于给每个历史会话都白跑一次 readdir,而且
|
|
1794
|
-
// 多数子目录压根不是 subagents(本机 13 个里 7 个是 tool-results/memory)。
|
|
1795
|
-
// 不能改用 <session-uuid>/ 目录自身的 mtime 剪枝:目录 mtime 只在直接子项增删时更新,
|
|
1796
|
-
// 往已有 agent-*.jsonl 追加写不会动它,正在跑的长任务会被剪掉。
|
|
1797
|
-
// earliest 的口径与 RecentCodexSessionURLs 一致,由调用方按展示模式和归档状态算好。
|
|
1798
|
-
static NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL,
|
|
1799
|
-
NSTimeInterval earliest) {
|
|
1800
|
-
NSArray<NSURL *> *projects = [NSFileManager.defaultManager contentsOfDirectoryAtURL:projectsURL
|
|
1801
|
-
includingPropertiesForKeys:@[NSURLIsDirectoryKey]
|
|
1802
|
-
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
1803
|
-
NSMutableArray<NSURL *> *urls = [NSMutableArray array];
|
|
1804
|
-
for (NSURL *project in projects) {
|
|
1805
|
-
NSNumber *isDirectory = nil;
|
|
1806
|
-
if (![project getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
|
|
1807
|
-
if (!isDirectory.boolValue) continue;
|
|
1808
|
-
NSMutableArray<NSURL *> *sessions = [NSMutableArray array];
|
|
1809
|
-
NSUInteger firstIndex = urls.count;
|
|
1810
|
-
AppendRecentTranscriptsInDirectory(project, earliest, urls, sessions);
|
|
1811
|
-
NSMutableSet<NSString *> *activeSessions = [NSMutableSet set];
|
|
1812
|
-
for (NSUInteger index = firstIndex; index < urls.count; index++) {
|
|
1813
|
-
[activeSessions addObject:urls[index].URLByDeletingPathExtension.lastPathComponent];
|
|
1814
|
-
}
|
|
1815
|
-
for (NSURL *session in sessions) {
|
|
1816
|
-
if (![activeSessions containsObject:session.lastPathComponent]) continue;
|
|
1817
|
-
AppendRecentTranscriptsInDirectory(
|
|
1818
|
-
[session URLByAppendingPathComponent:@"subagents" isDirectory:YES],
|
|
1819
|
-
earliest, urls, nil);
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
return urls;
|
|
1823
|
-
}
|
|
1824
|
-
|
|
1825
|
-
// 转录文件只追加(fork 走新文件),因此按 offset 追读即可,活跃会话每轮只解析新增字节。
|
|
1826
|
-
static NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache) {
|
|
1827
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path
|
|
1828
|
-
error:nil];
|
|
1829
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
1830
|
-
NSDictionary *cached = cache[url.path];
|
|
1831
|
-
unsigned long long offset = [cached[@"offset"] unsignedLongLongValue];
|
|
1832
|
-
// 这里可以直接原地追加:可变性由 MakeCachedRecordsMutable 在缓存读回时统一保证。
|
|
1833
|
-
// 不要退回成 isKindOfClass:NSMutableData 判断——NSData 是类簇,落盘缓存解析出的
|
|
1834
|
-
// 不可变 __NSCFData 对它同样返回 YES,据此原地 appendBytes 会写出界。详见该函数注释。
|
|
1835
|
-
NSMutableData *records = [cached[@"records"] isKindOfClass:NSData.class]
|
|
1836
|
-
? (NSMutableData *)cached[@"records"] : nil;
|
|
1837
|
-
if (!records || offset > size) {
|
|
1838
|
-
// 首次读取,或文件被改写导致偏移失效,整篇重来。
|
|
1839
|
-
offset = 0;
|
|
1840
|
-
records = [NSMutableData data];
|
|
1841
|
-
}
|
|
1842
|
-
if (cached && offset == size) {
|
|
1843
|
-
// 正常情况下 records 就是缓存里那一份,不必回写;只有上面因偏移失效重建过
|
|
1844
|
-
// (文件被清空到 0 字节)才是新对象,这时写回去,免得下一轮又重建一遍。
|
|
1845
|
-
if (records != cached[@"records"]) {
|
|
1846
|
-
cache[url.path] = @{@"offset": @(offset), @"records": records};
|
|
1847
|
-
}
|
|
1848
|
-
return records;
|
|
1849
|
-
}
|
|
1850
|
-
|
|
1851
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
1852
|
-
if (!handle) return records;
|
|
1853
|
-
[handle seekToFileOffset:offset];
|
|
1854
|
-
NSData *fresh = [handle readDataToEndOfFile];
|
|
1855
|
-
[handle closeFile];
|
|
1856
|
-
|
|
1857
|
-
const uint8_t *bytes = fresh.bytes;
|
|
1858
|
-
NSUInteger lineStart = 0;
|
|
1859
|
-
NSUInteger consumed = 0;
|
|
1860
|
-
for (NSUInteger index = 0; index < fresh.length; index++) {
|
|
1861
|
-
if (bytes[index] != '\n') continue;
|
|
1862
|
-
ClaudeTokenRecord record = {0};
|
|
1863
|
-
if (index > lineStart && ClaudeRecordFromLine(
|
|
1864
|
-
[fresh subdataWithRange:NSMakeRange(lineStart, index - lineStart)], &record)) {
|
|
1865
|
-
[records appendBytes:&record length:sizeof(record)];
|
|
1866
|
-
}
|
|
1867
|
-
lineStart = index + 1;
|
|
1868
|
-
consumed = lineStart;
|
|
1869
|
-
}
|
|
1870
|
-
// 只推进到最后一个换行符,未写完的尾行留到下一轮,避免把半行当成坏数据丢掉。
|
|
1871
|
-
cache[url.path] = @{@"offset": @(offset + consumed), @"records": records};
|
|
1872
|
-
return records;
|
|
1873
|
-
}
|
|
1874
|
-
|
|
1875
|
-
// 同一次请求会被拆成多行写入(thinking / text / tool_use 各一行),每行都带一份 usage
|
|
1876
|
-
// 快照,而这些快照是**递增的**:本机实测有 14 组末行的 output_tokens 远大于首行
|
|
1877
|
-
// (6→235、3→1870),首行取到的是流式过程中的中间值。因此同 identity 的多行必须逐字段
|
|
1878
|
-
// 取最大值合并,只保留第一条会少算——全量口径下少算 16060 个 output token。
|
|
1879
|
-
// 取 max 而不是"取最后一行":fork/resume 会把旧行复制进新文件,跨文件的行序没有保证。
|
|
1880
|
-
static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInterval start,
|
|
1881
|
-
NSTimeInterval end) {
|
|
1882
|
-
NSMutableDictionary<NSNumber *, NSNumber *> *slots = [NSMutableDictionary dictionary];
|
|
1883
|
-
NSMutableData *merged = [NSMutableData data];
|
|
1884
|
-
for (NSData *data in recordSets) {
|
|
1885
|
-
const ClaudeTokenRecord *records = data.bytes;
|
|
1886
|
-
NSUInteger count = data.length / sizeof(ClaudeTokenRecord);
|
|
1887
|
-
for (NSUInteger index = 0; index < count; index++) {
|
|
1888
|
-
const ClaudeTokenRecord *record = &records[index];
|
|
1889
|
-
if (record->timestamp < start || record->timestamp >= end) continue;
|
|
1890
|
-
NSNumber *identity = @(record->identity);
|
|
1891
|
-
NSNumber *slot = slots[identity];
|
|
1892
|
-
if (!slot) {
|
|
1893
|
-
slots[identity] = @(merged.length / sizeof(ClaudeTokenRecord));
|
|
1894
|
-
[merged appendBytes:record length:sizeof(*record)];
|
|
1895
|
-
continue;
|
|
1896
|
-
}
|
|
1897
|
-
// append 可能搬动缓冲区,基址每次重新取。
|
|
1898
|
-
ClaudeTokenRecord *target =
|
|
1899
|
-
(ClaudeTokenRecord *)merged.mutableBytes + slot.unsignedIntegerValue;
|
|
1900
|
-
target->input = MAX(target->input, record->input);
|
|
1901
|
-
target->output = MAX(target->output, record->output);
|
|
1902
|
-
target->cacheRead = MAX(target->cacheRead, record->cacheRead);
|
|
1903
|
-
target->cacheWrite = MAX(target->cacheWrite, record->cacheWrite);
|
|
1904
|
-
}
|
|
1905
|
-
}
|
|
1906
|
-
unsigned long long input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
|
|
1907
|
-
const ClaudeTokenRecord *unique = merged.bytes;
|
|
1908
|
-
for (NSUInteger index = 0; index < merged.length / sizeof(ClaudeTokenRecord); index++) {
|
|
1909
|
-
input += unique[index].input;
|
|
1910
|
-
output += unique[index].output;
|
|
1911
|
-
cacheRead += unique[index].cacheRead;
|
|
1912
|
-
cacheWrite += unique[index].cacheWrite;
|
|
1913
|
-
}
|
|
1914
|
-
// 不输出 reasoning_output_tokens:Claude 的思考 token 已经计入 output_tokens,
|
|
1915
|
-
// 单列一个恒为 0 的字段会让人误以为没统计。
|
|
1916
|
-
return @{
|
|
1917
|
-
@"input_tokens": @(input),
|
|
1918
|
-
@"cached_input_tokens": @(cacheRead),
|
|
1919
|
-
@"cache_write_input_tokens": @(cacheWrite),
|
|
1920
|
-
@"output_tokens": @(output),
|
|
1921
|
-
@"total_tokens": @(input + output + cacheRead + cacheWrite),
|
|
1922
|
-
@"request_count": @(merged.length / sizeof(ClaudeTokenRecord))
|
|
1923
|
-
};
|
|
1924
|
-
}
|
|
1925
|
-
|
|
1926
|
-
static NSArray<NSDictionary *> *ClaudeDailyTokenSeries(NSArray<NSData *> *recordSets,
|
|
1927
|
-
NSTimeInterval start, NSTimeInterval end) {
|
|
1928
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
1929
|
-
NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
|
|
1930
|
-
NSDate *cursor = [NSDate dateWithTimeIntervalSince1970:start];
|
|
1931
|
-
while (cursor.timeIntervalSince1970 < end) {
|
|
1932
|
-
NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
|
|
1933
|
-
if (!next) break;
|
|
1934
|
-
NSTimeInterval bucketEnd = fmin(end, next.timeIntervalSince1970);
|
|
1935
|
-
[series addObject:@{ @"timestamp": @(cursor.timeIntervalSince1970),
|
|
1936
|
-
@"totals": ClaudeTokenTotals(recordSets, cursor.timeIntervalSince1970, bucketEnd) }];
|
|
1937
|
-
cursor = next;
|
|
1938
|
-
}
|
|
1939
|
-
return series;
|
|
1940
|
-
}
|
|
1941
|
-
|
|
1942
|
-
@interface ClaudeUsageReader ()
|
|
1943
|
-
@property NSMutableDictionary *recordCache;
|
|
1944
|
-
@property NSString *recordCachePath;
|
|
1945
|
-
@property NSTimeInterval recordCacheSavedAt;
|
|
1946
|
-
@property NSMutableDictionary *monthlyArchive;
|
|
1947
|
-
@property NSString *monthlyArchivePath;
|
|
1948
|
-
@property NSDictionary *tokenUsage;
|
|
1949
|
-
@property NSString *tokenWindowIdentity;
|
|
1950
|
-
@property NSTimeInterval tokenComputedAt;
|
|
1951
|
-
@property BOOL forcesTokenAggregation;
|
|
1952
|
-
@end
|
|
1953
|
-
|
|
1954
|
-
@implementation ClaudeUsageReader
|
|
1955
|
-
- (instancetype)init {
|
|
1956
|
-
if ((self = [super init])) {
|
|
1957
|
-
_projectsURL = ClaudeProjectsURL();
|
|
1958
|
-
_recordCachePath = TokenSummaryCachePath(@"claude", _projectsURL.path);
|
|
1959
|
-
_recordCache = LoadTokenSummaryCache(_recordCachePath);
|
|
1960
|
-
MakeCachedRecordsMutable(_recordCache);
|
|
1961
|
-
_monthlyArchivePath = MonthlyUsageArchivePath(@"claude", _projectsURL.path);
|
|
1962
|
-
_monthlyArchive = LoadTokenSummaryCache(_monthlyArchivePath);
|
|
1963
|
-
}
|
|
1964
|
-
return self;
|
|
1965
|
-
}
|
|
1966
|
-
- (NSDictionary *)aggregateForLimits:(NSDictionary *)limits {
|
|
1967
|
-
NSDictionary *five = [limits[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
1968
|
-
? limits[@"fiveHour"] : nil;
|
|
1969
|
-
NSDictionary *week = [limits[@"week"] isKindOfClass:NSDictionary.class] ? limits[@"week"] : nil;
|
|
1970
|
-
NSTimeInterval fiveStart = 0, fiveEnd = 0, weekStart = 0, weekEnd = 0;
|
|
1971
|
-
// Claude 的 rate_limits 没有 window_minutes,窗长按官方订阅固定为 5 小时 / 7 天。
|
|
1972
|
-
// 窗口不可用时退化成滚动窗口,Token 是本机数据,不跟着官方额度一起变成 `--`。
|
|
1973
|
-
TokenWindowOrFallback(five, FiveHourWindowMinutes, &fiveStart, &fiveEnd);
|
|
1974
|
-
TokenWindowOrFallback(week, SevenDayWindowMinutes, &weekStart, &weekEnd);
|
|
1975
|
-
// 自然日窗口和额度无关,即使两个额度窗口都不可用也照样统计。
|
|
1976
|
-
BOOL apiMode = ProviderShowsAPIUsage(ClaudeUsageDisplayModeKey);
|
|
1977
|
-
NSDictionary *monthWindows = CalendarMonthWindows(0);
|
|
1978
|
-
NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
|
|
1979
|
-
NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
|
|
1980
|
-
NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
|
|
1981
|
-
NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
|
|
1982
|
-
NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
|
|
1983
|
-
NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
|
|
1984
|
-
NSArray<NSDictionary *> *archivedDaily = apiMode &&
|
|
1985
|
-
[self.monthlyArchive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
|
|
1986
|
-
? self.monthlyArchive[previousMonthKey][@"daily"] : nil;
|
|
1987
|
-
// 与 Codex 侧同一套:上月归档好了就只读本月的转录,没归档才放宽一次把归档建出来。
|
|
1988
|
-
BOOL buildsArchive = apiMode && !archivedDaily;
|
|
1989
|
-
NSTimeInterval earliest = buildsArchive ? previousMonthStart
|
|
1990
|
-
: (apiMode ? fmin(monthStart, RollingTokenWindowFloor()) : RollingTokenWindowFloor());
|
|
1991
|
-
NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL, earliest);
|
|
1992
|
-
NSMutableArray<NSData *> *recordSets = [NSMutableArray arrayWithCapacity:urls.count];
|
|
1993
|
-
NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
|
|
1994
|
-
for (NSURL *url in urls) {
|
|
1995
|
-
[livePaths addObject:url.path];
|
|
1996
|
-
NSData *records = ClaudeRecordsForFile(url, self.recordCache);
|
|
1997
|
-
if (records.length > 0) [recordSets addObject:records];
|
|
1998
|
-
}
|
|
1999
|
-
for (NSString *path in self.recordCache.allKeys) {
|
|
2000
|
-
if (![livePaths containsObject:path]) [self.recordCache removeObjectForKey:path];
|
|
2001
|
-
}
|
|
2002
|
-
NSTimeInterval savedAt = NSDate.date.timeIntervalSince1970;
|
|
2003
|
-
if (self.persistsCache && savedAt - self.recordCacheSavedAt >= TokenCacheSaveInterval) {
|
|
2004
|
-
self.recordCacheSavedAt = savedAt;
|
|
2005
|
-
SaveTokenSummaryCache(self.recordCache, self.recordCachePath);
|
|
2006
|
-
}
|
|
2007
|
-
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
2008
|
-
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
2009
|
-
// 与 Codex 侧同理:订阅视图下转录只回溯 8 天,月度口径既算不准也没人看。
|
|
2010
|
-
// 曲线同样铺满整个自然月,末尾没到的日子是 0。
|
|
2011
|
-
NSArray<NSDictionary *> *monthDaily = apiMode
|
|
2012
|
-
? ClaudeDailyTokenSeries(recordSets, monthStart, monthCurveEnd) : @[];
|
|
2013
|
-
if (buildsArchive) {
|
|
2014
|
-
NSArray *previousDaily = ClaudeDailyTokenSeries(recordSets, previousMonthStart, monthStart);
|
|
2015
|
-
self.monthlyArchive[previousMonthKey] = @{ @"daily": previousDaily,
|
|
2016
|
-
@"totals": SummedDailyTokenSeries(previousDaily) };
|
|
2017
|
-
archivedDaily = previousDaily;
|
|
2018
|
-
PruneMonthlyArchive(self.monthlyArchive);
|
|
2019
|
-
if (self.persistsCache) {
|
|
2020
|
-
SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
|
|
2021
|
-
}
|
|
2022
|
-
}
|
|
2023
|
-
return @{
|
|
2024
|
-
@"fiveHour": ClaudeTokenTotals(recordSets, fiveStart, fiveEnd),
|
|
2025
|
-
@"week": ClaudeTokenTotals(recordSets, weekStart, weekEnd),
|
|
2026
|
-
@"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
|
|
2027
|
-
@"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
|
|
2028
|
-
@"recentWeekStartsAt": @(rollingWeekStart),
|
|
2029
|
-
@"month": apiMode ? SummedDailyTokenSeries(monthDaily) : NSNull.null,
|
|
2030
|
-
@"monthComparable": apiMode
|
|
2031
|
-
? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd)
|
|
2032
|
-
: NSNull.null,
|
|
2033
|
-
@"previousMonthToDate": archivedDaily
|
|
2034
|
-
? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd)
|
|
2035
|
-
: NSNull.null,
|
|
2036
|
-
@"monthDaily": monthDaily,
|
|
2037
|
-
@"monthStartsAt": @(monthStart),
|
|
2038
|
-
@"monthComparableEndsAt": @(monthComparableEnd),
|
|
2039
|
-
@"previousMonthComparableEndsAt": @(previousMonthEnd),
|
|
2040
|
-
@"source": @"local"
|
|
2041
|
-
};
|
|
2042
|
-
}
|
|
2043
|
-
- (NSDictionary *)refresh {
|
|
2044
|
-
// 额度快照是 statusline hook 写出来的(见 RecordClaudeUsage):第三方 statusline 注入不
|
|
2045
|
-
// 进去、或者账号本身(API key / Bedrock / Vertex)就不带 rate_limits 时,这份文件永远
|
|
2046
|
-
// 不存在。而 Token 是本机从转录里数出来的,跟官方额度没有半点关系,不能被它一票否决
|
|
2047
|
-
// ——原先这里直接 return nil,面板上 Claude 整行(百分比、已用 Token、今日输入输出)
|
|
2048
|
-
// 全是 `--`,看起来像统计坏了。缺额度时百分比照样 `--`,用量正常显示。
|
|
2049
|
-
NSDictionary *limits = ClaudeRateLimits() ?: @{@"fiveHour": NSNull.null, @"week": NSNull.null};
|
|
2050
|
-
NSString *identity = TokenWindowIdentity(limits);
|
|
2051
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2052
|
-
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
2053
|
-
[identity isEqualToString:self.tokenWindowIdentity] &&
|
|
2054
|
-
now - self.tokenComputedAt < TokenAggregationInterval;
|
|
2055
|
-
if (!reusable) {
|
|
2056
|
-
self.tokenUsage = [self aggregateForLimits:limits];
|
|
2057
|
-
self.tokenWindowIdentity = identity;
|
|
2058
|
-
self.tokenComputedAt = now;
|
|
2059
|
-
self.forcesTokenAggregation = NO;
|
|
2060
|
-
}
|
|
2061
|
-
NSMutableDictionary *usage = [limits mutableCopy];
|
|
2062
|
-
usage[@"tokenUsage"] = self.tokenUsage;
|
|
2063
|
-
return usage;
|
|
2064
|
-
}
|
|
2065
|
-
- (NSDictionary *)refreshWithFullAggregation {
|
|
2066
|
-
self.forcesTokenAggregation = YES;
|
|
2067
|
-
return [self refresh];
|
|
2068
|
-
}
|
|
2069
|
-
@end
|