cc-pets 2.2.1 → 2.4.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 +24 -2
- package/CC_BRIDGE.zh-CN.md +19 -2
- package/CHANGELOG.md +111 -0
- package/CHANGELOG.zh-CN.md +111 -0
- package/CONTRIBUTING.md +35 -10
- package/CONTRIBUTING.zh-CN.md +28 -10
- package/README.md +212 -32
- package/README.zh-CN.md +167 -36
- package/Resources/AgentIcons/claude.png +0 -0
- package/Resources/AgentIcons/codex.icns +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
- package/Resources/zh-Hans.lproj/Localizable.strings +699 -20
- package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
- package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +90 -25
- 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} +71 -23
- 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} +87 -102
- package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +121 -51
- package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
- package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +17 -2
- 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} +74 -1
- package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
- package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +43 -23
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +832 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +59 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +576 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +507 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +106 -0
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +897 -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/CCPetsIDEIntegration.h +21 -0
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
- package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
- package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
- package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +2 -1
- package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +148 -36
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
- 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 +646 -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 +33 -0
- package/Sources/CCPets/Support/CCPetsPreferences.m +117 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
- package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.h +44 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.m +279 -0
- package/Sources/CCPets/UI/CCPetsGlassView.h +57 -0
- package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +60 -11
- package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
- package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.h +64 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.m +1412 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.h +135 -0
- package/Sources/CCPets/UI/CCPetsUIStyle.m +865 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
- package/Sources/CCPets/UI/CCPetsUsageChartView.m +288 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.m +712 -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+CodexBackground.m +193 -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 +97 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Models.m +323 -0
- package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
- package/Sources/CCPets/Usage/CCPetsUsage.h +58 -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} +174 -19
- 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 +598 -0
- package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
- package/Sources/CCPets/Usage/QuotaDashboardView.m +713 -0
- package/THIRD_PARTY_NOTICES.md +8 -4
- package/THIRD_PARTY_NOTICES.zh-CN.md +6 -2
- package/bin/cc-pets +8 -6
- package/bin/claude-with-pet +12 -2
- package/bin/codex-with-pet +15 -5
- package/package.json +5 -1
- package/plugins/jetbrains/README.md +62 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
- package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
- package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
- package/plugins/vscode/README.md +63 -0
- package/plugins/vscode/extension.js +210 -0
- package/plugins/vscode/package.json +18 -0
- package/scripts/build-idea-plugin.sh +101 -0
- package/scripts/build-vscode-extension.sh +112 -0
- package/scripts/build.sh +31 -5
- package/scripts/compile-cached.zsh +133 -0
- 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/CCPetsGlassView.h +0 -31
- 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/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
- /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
- /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
- /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
- /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
- /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
- /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
- /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
- /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
- /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
- /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
- /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
- /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
- /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
- /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#import "CCPetsUsage+Internal.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sqlite3.h>
|
|
4
|
+
|
|
5
|
+
// 只补没有持久化会话的线程。不能把运行日志和 rollout 相加:同一次响应会同时出现
|
|
6
|
+
// 在两处,而且后台日志只给累计总量,没有可靠的输入、输出拆分。
|
|
7
|
+
static NSString *BackgroundMatch(NSString *text, NSString *pattern) {
|
|
8
|
+
static NSMutableDictionary<NSString *, NSRegularExpression *> *patterns;
|
|
9
|
+
static dispatch_once_t once;
|
|
10
|
+
dispatch_once(&once, ^{ patterns = [NSMutableDictionary dictionary]; });
|
|
11
|
+
NSRegularExpression *regex;
|
|
12
|
+
@synchronized (patterns) {
|
|
13
|
+
regex = patterns[pattern];
|
|
14
|
+
if (!regex) {
|
|
15
|
+
regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
|
|
16
|
+
if (regex) patterns[pattern] = regex;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
NSTextCheckingResult *match = [regex firstMatchInString:text options:0
|
|
20
|
+
range:NSMakeRange(0, text.length)];
|
|
21
|
+
return match ? [text substringWithRange:[match rangeAtIndex:1]] : nil;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
static NSString *BackgroundColumn(sqlite3_stmt *statement, int column) {
|
|
25
|
+
const unsigned char *text = sqlite3_column_text(statement, column);
|
|
26
|
+
return text ? [NSString stringWithUTF8String:(const char *)text] : nil;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
static sqlite3 *BackgroundOpen(NSString *path) {
|
|
30
|
+
sqlite3 *db = NULL;
|
|
31
|
+
// 不创建数据库、不设置 journal_mode,也不执行任何写 SQL。
|
|
32
|
+
if (sqlite3_open_v2(path.fileSystemRepresentation, &db,
|
|
33
|
+
SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
|
|
34
|
+
if (db) sqlite3_close(db);
|
|
35
|
+
return NULL;
|
|
36
|
+
}
|
|
37
|
+
sqlite3_busy_timeout(db, 100);
|
|
38
|
+
return db;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static void BackgroundCoveredThreads(NSString *home, NSMutableDictionary *covered, double now) {
|
|
42
|
+
// state 索引能在 rollout 尚未写完时排除主会话;归档/旧版本还要从文件名补齐。
|
|
43
|
+
sqlite3 *db = BackgroundOpen([home stringByAppendingPathComponent:@"state_5.sqlite"]);
|
|
44
|
+
sqlite3_stmt *statement = NULL;
|
|
45
|
+
if (db && sqlite3_prepare_v2(db, "SELECT id FROM threads", -1, &statement, NULL) == SQLITE_OK) {
|
|
46
|
+
while (sqlite3_step(statement) == SQLITE_ROW) {
|
|
47
|
+
NSString *thread = BackgroundColumn(statement, 0);
|
|
48
|
+
if (thread.length) covered[thread] = @(now);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
sqlite3_finalize(statement);
|
|
52
|
+
if (db) sqlite3_close(db);
|
|
53
|
+
for (NSString *directory in @[@"sessions", @"archived_sessions"]) {
|
|
54
|
+
NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:
|
|
55
|
+
[NSURL fileURLWithPath:[home stringByAppendingPathComponent:directory]]
|
|
56
|
+
includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil];
|
|
57
|
+
for (NSURL *file in files) {
|
|
58
|
+
if (![file.pathExtension isEqualToString:@"jsonl"]) continue;
|
|
59
|
+
NSString *thread = BackgroundMatch(file.lastPathComponent,
|
|
60
|
+
@"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\\.jsonl$");
|
|
61
|
+
if (thread) covered[thread.lowercaseString] = @(now);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
NSDictionary *CodexBackgroundModelDays(NSString *home, NSTimeInterval start, NSTimeInterval end) {
|
|
67
|
+
NSString *path = TokenSummaryCachePath(@"codex-background", home);
|
|
68
|
+
NSMutableDictionary *cache = LoadTokenSummaryCache(path);
|
|
69
|
+
NSMutableDictionary *events = [cache[@"events"] mutableCopy] ?: [NSMutableDictionary dictionary];
|
|
70
|
+
NSMutableDictionary *covered = [cache[@"covered"] mutableCopy] ?: [NSMutableDictionary dictionary];
|
|
71
|
+
NSDictionary *cursor = cache[@"cursor"] ?: @{};
|
|
72
|
+
double now = NSDate.date.timeIntervalSince1970;
|
|
73
|
+
// 与用量页 90 天窗口一致,留 10 天余量;先采集所有仍保留的记录,再做日桶切片。
|
|
74
|
+
double retentionStart = now - 100 * 86400.0;
|
|
75
|
+
BackgroundCoveredThreads(home, covered, now);
|
|
76
|
+
NSString *dbPath = [home stringByAppendingPathComponent:@"logs_2.sqlite"];
|
|
77
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:dbPath error:nil];
|
|
78
|
+
NSString *identity = [NSString stringWithFormat:@"%@/%@", attributes[NSFileSystemNumber],
|
|
79
|
+
attributes[NSFileSystemFileNumber]];
|
|
80
|
+
sqlite3 *db = BackgroundOpen(dbPath);
|
|
81
|
+
if (db) {
|
|
82
|
+
sqlite3_stmt *statement = NULL;
|
|
83
|
+
sqlite3_int64 maximum = 0;
|
|
84
|
+
BOOL hasMaximum = NO;
|
|
85
|
+
if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM logs", -1, &statement, NULL) == SQLITE_OK &&
|
|
86
|
+
sqlite3_step(statement) == SQLITE_ROW) {
|
|
87
|
+
maximum = sqlite3_column_int64(statement, 0);
|
|
88
|
+
hasMaximum = YES;
|
|
89
|
+
}
|
|
90
|
+
sqlite3_finalize(statement);
|
|
91
|
+
statement = NULL;
|
|
92
|
+
sqlite3_int64 lastID = [cursor[@"id"] longLongValue];
|
|
93
|
+
if (![cursor[@"identity"] isEqual:identity] || maximum < lastID) lastID = 0;
|
|
94
|
+
// MAX(id) 给这一批固定上界。按主键推进,不为每次刷新扫描全部运行日志。
|
|
95
|
+
// 首次扫描虽有时间过滤,但不假设 ts 有索引。
|
|
96
|
+
const char *sql = "SELECT id, ts, ts_nanos, feedback_log_body, thread_id FROM logs "
|
|
97
|
+
"WHERE id > ? AND id <= ? AND ts >= ? "
|
|
98
|
+
"AND feedback_log_body LIKE '%post sampling token usage%' ORDER BY id";
|
|
99
|
+
if (hasMaximum && sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK) {
|
|
100
|
+
sqlite3_bind_int64(statement, 1, lastID);
|
|
101
|
+
sqlite3_bind_int64(statement, 2, maximum);
|
|
102
|
+
sqlite3_bind_double(statement, 3, retentionStart);
|
|
103
|
+
int status;
|
|
104
|
+
while ((status = sqlite3_step(statement)) == SQLITE_ROW) {
|
|
105
|
+
@autoreleasepool {
|
|
106
|
+
NSString *body = BackgroundColumn(statement, 3) ?: @"";
|
|
107
|
+
NSString *thread = BackgroundMatch(body, @"thread_id=\"?([0-9a-fA-F-]{36})")
|
|
108
|
+
?: BackgroundColumn(statement, 4);
|
|
109
|
+
NSString *turn = BackgroundMatch(body, @"turn_id=\"?([0-9a-fA-F-]{36})");
|
|
110
|
+
NSString *total = BackgroundMatch(body, @"total_usage_tokens=([0-9]+)");
|
|
111
|
+
NSString *model = BackgroundMatch(body, @"\\bmodel=\"?([^\\s\"}]+)");
|
|
112
|
+
if (!thread.length || !turn.length || !total.length) continue;
|
|
113
|
+
thread = thread.lowercaseString;
|
|
114
|
+
if (covered[thread]) continue;
|
|
115
|
+
// 同一轮可多次采样,甚至重置后回到相同累计值,不能只用 turn/total 去重。
|
|
116
|
+
// 时间戳标识一次采样;重复累计快照稍后求差为 0,不增加请求数。
|
|
117
|
+
NSString *key = [NSString stringWithFormat:@"%@/%@/%lld/%lld/%@", thread, turn,
|
|
118
|
+
sqlite3_column_int64(statement, 1), sqlite3_column_int64(statement, 2), total];
|
|
119
|
+
if (events[key]) continue;
|
|
120
|
+
events[key] = @{@"thread": thread, @"turn": turn,
|
|
121
|
+
@"model": model ?: @"unknown", @"total": @([total longLongValue]),
|
|
122
|
+
@"timestamp": @(sqlite3_column_double(statement, 1) +
|
|
123
|
+
sqlite3_column_double(statement, 2) / 1e9),
|
|
124
|
+
@"id": @(sqlite3_column_int64(statement, 0))};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// 锁冲突/读取失败时不推进游标;已经读到的事件有稳定标识,重读不会重复计算。
|
|
128
|
+
if (status == SQLITE_DONE) cache[@"cursor"] = @{@"id": @(maximum), @"identity": identity};
|
|
129
|
+
}
|
|
130
|
+
sqlite3_finalize(statement);
|
|
131
|
+
sqlite3_close(db);
|
|
132
|
+
}
|
|
133
|
+
for (NSString *key in covered.allKeys) {
|
|
134
|
+
if ([covered[key] doubleValue] < retentionStart) [covered removeObjectForKey:key];
|
|
135
|
+
}
|
|
136
|
+
// 长期运行的临时线程跨越保留边界时,保留边界前最后一个快照作基线,
|
|
137
|
+
// 否则删掉旧快照会把新窗口首条累计值误当成全部新增量。
|
|
138
|
+
NSMutableSet *recentThreads = [NSMutableSet set];
|
|
139
|
+
NSMutableDictionary *baselineKeys = [NSMutableDictionary dictionary];
|
|
140
|
+
for (NSString *key in events.allKeys) {
|
|
141
|
+
NSDictionary *event = events[key];
|
|
142
|
+
NSString *thread = event[@"thread"];
|
|
143
|
+
if (covered[thread]) { [events removeObjectForKey:key]; continue; }
|
|
144
|
+
if ([event[@"timestamp"] doubleValue] >= retentionStart) [recentThreads addObject:thread];
|
|
145
|
+
else {
|
|
146
|
+
NSString *oldKey = baselineKeys[thread];
|
|
147
|
+
if (!oldKey || [event[@"timestamp"] doubleValue] > [events[oldKey][@"timestamp"] doubleValue]) {
|
|
148
|
+
baselineKeys[thread] = key;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (NSString *key in events.allKeys) {
|
|
153
|
+
NSDictionary *event = events[key];
|
|
154
|
+
NSString *thread = event[@"thread"];
|
|
155
|
+
if ([event[@"timestamp"] doubleValue] < retentionStart &&
|
|
156
|
+
!([recentThreads containsObject:thread] && [baselineKeys[thread] isEqual:key])) {
|
|
157
|
+
[events removeObjectForKey:key];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
cache[@"events"] = events;
|
|
161
|
+
cache[@"covered"] = covered;
|
|
162
|
+
SaveTokenSummaryCache(cache, path);
|
|
163
|
+
|
|
164
|
+
NSArray *ordered = [events.allValues sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
|
|
165
|
+
NSComparisonResult order = [a[@"timestamp"] compare:b[@"timestamp"]];
|
|
166
|
+
return order == NSOrderedSame ? [a[@"id"] compare:b[@"id"]] : order;
|
|
167
|
+
}];
|
|
168
|
+
NSMutableDictionary *previous = [NSMutableDictionary dictionary];
|
|
169
|
+
NSMutableDictionary *days = [NSMutableDictionary dictionary];
|
|
170
|
+
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
171
|
+
for (NSDictionary *event in ordered) {
|
|
172
|
+
NSString *thread = event[@"thread"];
|
|
173
|
+
if (covered[thread]) continue;
|
|
174
|
+
unsigned long long total = [event[@"total"] unsignedLongLongValue];
|
|
175
|
+
unsigned long long baseline = [previous[thread] unsignedLongLongValue];
|
|
176
|
+
previous[thread] = @(total);
|
|
177
|
+
unsigned long long delta = total >= baseline ? total - baseline : total;
|
|
178
|
+
double timestamp = [event[@"timestamp"] doubleValue];
|
|
179
|
+
// 留 10 秒等主会话文件/索引落盘,下一轮刷新再展示,不提前把它冒充后台用量。
|
|
180
|
+
if (!delta || timestamp < start || timestamp >= end || timestamp > now - 10) continue;
|
|
181
|
+
NSDateComponents *date = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
|
|
182
|
+
fromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
|
|
183
|
+
NSString *day = [NSString stringWithFormat:@"%04ld-%02ld-%02ld", (long)date.year, (long)date.month, (long)date.day];
|
|
184
|
+
NSMutableDictionary *models = days[day];
|
|
185
|
+
if (!models) { models = [NSMutableDictionary dictionary]; days[day] = models; }
|
|
186
|
+
NSString *model = event[@"model"];
|
|
187
|
+
NSMutableDictionary *counts = models[model];
|
|
188
|
+
if (!counts) { counts = [NSMutableDictionary dictionary]; models[model] = counts; }
|
|
189
|
+
counts[@"background"] = @([counts[@"background"] unsignedLongLongValue] + delta);
|
|
190
|
+
counts[@"requests"] = @([counts[@"requests"] unsignedLongLongValue] + 1);
|
|
191
|
+
}
|
|
192
|
+
return days;
|
|
193
|
+
}
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
#import "CCPetsUsage+Internal.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
|
|
4
|
+
// 一份额度都没拿到时也照样统计 Token:Token 是本机数出来的,不该因为官方额度缺失就空着。
|
|
5
|
+
//
|
|
6
|
+
// archive 是"已结束自然月"的归档(见 MonthlyUsageArchivePath)。上月一旦归档,扫描范围就
|
|
7
|
+
// 收窄到本月,上月的会话文件再也不会被打开;archiveChanged 置位表示这一轮新写了归档,
|
|
8
|
+
// 调用方据此落盘。
|
|
9
|
+
static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessionsURL,
|
|
10
|
+
NSArray<NSURL *> *pinnedURLs, NSMutableDictionary *cache, NSMutableDictionary *archive,
|
|
11
|
+
BOOL *archiveChanged) {
|
|
12
|
+
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
13
|
+
BOOL apiMode = ProfileShowsAPIUsage(@"codex", sessionsURL.path.stringByDeletingLastPathComponent);
|
|
14
|
+
NSTimeInterval rollingFloor = RollingTokenWindowFloor();
|
|
15
|
+
NSDictionary *monthWindows = CalendarMonthWindows(0);
|
|
16
|
+
NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
|
|
17
|
+
NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
|
|
18
|
+
NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
|
|
19
|
+
NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
|
|
20
|
+
NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
|
|
21
|
+
NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
|
|
22
|
+
NSArray<NSDictionary *> *archivedDaily = apiMode &&
|
|
23
|
+
[archive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
|
|
24
|
+
? archive[previousMonthKey][@"daily"] : nil;
|
|
25
|
+
// 上月还没归档时才把扫描范围放宽到上月月初,而且只放宽这一次。
|
|
26
|
+
BOOL buildsArchive = apiMode && !archivedDaily;
|
|
27
|
+
NSTimeInterval earliest = buildsArchive ? previousMonthStart
|
|
28
|
+
: (apiMode ? fmin(monthStart, rollingFloor) : rollingFloor);
|
|
29
|
+
NSArray<NSURL *> *urls = TokenAggregationURLs(sessionsURL, earliest, pinnedURLs);
|
|
30
|
+
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
31
|
+
? usage[@"fiveHour"] : nil;
|
|
32
|
+
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
33
|
+
NSDictionary *fiveTokens = TokenTotalsForQuota(five, FiveHourWindowMinutes, urls, cache);
|
|
34
|
+
NSDictionary *weekTokens = TokenTotalsForQuota(week, SevenDayWindowMinutes, urls, cache);
|
|
35
|
+
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
36
|
+
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
37
|
+
NSDictionary *todayTokens = TokenTotalsInWindow(todayStart, rollingEnd, urls, cache);
|
|
38
|
+
NSDictionary *recentTokens = TokenTotalsInWindow(rollingWeekStart, rollingEnd, urls, cache);
|
|
39
|
+
// 订阅视图不看月度数据,连算都不必算:会话列表本来就只回溯 8 天,月窗口只会得到
|
|
40
|
+
// 一段被截断的假数据,而代价是每次刷新多遍历一遍全部会话。
|
|
41
|
+
BOOL hasDailySchema = NO;
|
|
42
|
+
// 曲线铺满整个自然月:末尾这些还没到的日子是货真价实的 0,读者能一眼看出月份过了多少。
|
|
43
|
+
NSArray *monthDaily = apiMode
|
|
44
|
+
? CodexDailyTokenSeries(monthStart, monthCurveEnd, urls, cache, &hasDailySchema) : @[];
|
|
45
|
+
NSDictionary *monthTokens = hasDailySchema ? SummedDailyTokenSeries(monthDaily) : nil;
|
|
46
|
+
NSDictionary *monthComparable = hasDailySchema
|
|
47
|
+
? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd) : nil;
|
|
48
|
+
if (buildsArchive) {
|
|
49
|
+
NSArray *previousDaily = CodexDailyTokenSeries(previousMonthStart, monthStart,
|
|
50
|
+
urls, cache, NULL);
|
|
51
|
+
archive[previousMonthKey] = @{ @"daily": previousDaily,
|
|
52
|
+
@"totals": SummedDailyTokenSeries(previousDaily) };
|
|
53
|
+
archivedDaily = previousDaily;
|
|
54
|
+
if (archiveChanged) *archiveChanged = YES;
|
|
55
|
+
}
|
|
56
|
+
NSDictionary *previousMonthTokens = archivedDaily
|
|
57
|
+
? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd) : nil;
|
|
58
|
+
NSMutableSet<NSString *> *liveWindowKeys = [NSMutableSet setWithArray:@[
|
|
59
|
+
PartialTokenKey(todayStart, rollingEnd), PartialTokenKey(rollingWeekStart, rollingEnd)]];
|
|
60
|
+
NSArray<NSDictionary *> *windows = @[
|
|
61
|
+
@{@"quota": five ?: @{}, @"minutes": @(FiveHourWindowMinutes)},
|
|
62
|
+
@{@"quota": week ?: @{}, @"minutes": @(SevenDayWindowMinutes)}];
|
|
63
|
+
for (NSDictionary *window in windows) {
|
|
64
|
+
NSTimeInterval start = 0;
|
|
65
|
+
NSTimeInterval end = 0;
|
|
66
|
+
if (TokenWindowOrFallback(window[@"quota"], [window[@"minutes"] doubleValue], &start, &end)) {
|
|
67
|
+
[liveWindowKeys addObject:PartialTokenKey(start, end)];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
PruneTokenCache(cache, urls, liveWindowKeys);
|
|
71
|
+
NSMutableDictionary *result = [usage mutableCopy];
|
|
72
|
+
result[@"tokenUsage"] = @{
|
|
73
|
+
@"fiveHour": fiveTokens ?: NSNull.null,
|
|
74
|
+
@"week": weekTokens ?: NSNull.null,
|
|
75
|
+
@"today": todayTokens ?: NSNull.null,
|
|
76
|
+
@"recentWeek": recentTokens ?: NSNull.null,
|
|
77
|
+
@"recentWeekStartsAt": @(rollingWeekStart),
|
|
78
|
+
@"month": monthTokens ?: NSNull.null,
|
|
79
|
+
// 同比用的是"到最后一个完整自然日为止"的两段,与展示用的 month(含今天)不是一回事。
|
|
80
|
+
@"monthComparable": monthComparable ?: NSNull.null,
|
|
81
|
+
@"previousMonthToDate": previousMonthTokens ?: NSNull.null,
|
|
82
|
+
@"monthDaily": monthDaily,
|
|
83
|
+
@"monthStartsAt": @(monthStart),
|
|
84
|
+
@"monthComparableEndsAt": @(monthComparableEnd),
|
|
85
|
+
@"previousMonthComparableEndsAt": @(previousMonthEnd),
|
|
86
|
+
@"source": @"local"
|
|
87
|
+
};
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
static NSURL *CodexSessionsURL(void) {
|
|
92
|
+
return [NSURL fileURLWithPath:
|
|
93
|
+
[DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"sessions"]];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
NSDictionary *LatestUsage(void) {
|
|
97
|
+
NSURL *sessions = CodexSessionsURL();
|
|
98
|
+
NSURL *newest = NewestCodexSessionURL(sessions);
|
|
99
|
+
if (!newest) return nil;
|
|
100
|
+
|
|
101
|
+
NSData *tail = SessionTailData(newest);
|
|
102
|
+
if (!tail) return nil;
|
|
103
|
+
NSNumber *exhaustedAt = nil;
|
|
104
|
+
NSDictionary *usage = LatestUsageInData(tail, &exhaustedAt)
|
|
105
|
+
?: LatestQuotaInRecentSessions(sessions, newest);
|
|
106
|
+
usage = UsageByRemovingInactiveQuotaWindows(usage);
|
|
107
|
+
// --status 这类一次性调用不带缓存也不写归档:它只需要当下这一份数字。
|
|
108
|
+
usage = UsageByAddingTokenTotals(usage, sessions, newest ? @[newest] : nil,
|
|
109
|
+
[NSMutableDictionary dictionary],
|
|
110
|
+
LoadMonthlyUsageArchive(MonthlyUsageArchivePath(@"codex", sessions.path)), NULL);
|
|
111
|
+
return UsageByMarkingExhaustion(usage, exhaustedAt.doubleValue);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 额度窗口的身份:两个 resets_at 一变就说明窗口滚动了,缓存必须作废。
|
|
115
|
+
NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
116
|
+
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
117
|
+
? usage[@"fiveHour"] : nil;
|
|
118
|
+
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
119
|
+
return [NSString stringWithFormat:@"%.0f/%.0f",
|
|
120
|
+
[five[@"resets_at"] doubleValue], [week[@"resets_at"] doubleValue]];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
@interface CodexUsageReader ()
|
|
124
|
+
@property NSMutableDictionary *tokenSummaryCache;
|
|
125
|
+
@property NSString *tokenSummaryCachePath;
|
|
126
|
+
@property NSTimeInterval tokenCacheSavedAt;
|
|
127
|
+
@property NSMutableDictionary *monthlyArchive;
|
|
128
|
+
@property NSString *monthlyArchivePath;
|
|
129
|
+
@property NSDictionary *tokenUsage;
|
|
130
|
+
@property NSString *tokenWindowIdentity;
|
|
131
|
+
@property NSTimeInterval tokenComputedAt;
|
|
132
|
+
@property NSTimeInterval exhaustedAt;
|
|
133
|
+
@property BOOL forcesTokenAggregation;
|
|
134
|
+
// 内核已经点名"刚被写过"的会话文件:当前正在增量读取的这个,以及最近几批 FSEvents 报上来的
|
|
135
|
+
// 并发会话。它们无条件参与 Token 聚合,不受日期目录扫描的取舍影响。
|
|
136
|
+
@property NSMutableArray<NSURL *> *pinnedSessionURLs;
|
|
137
|
+
@end
|
|
138
|
+
|
|
139
|
+
@implementation CodexUsageReader
|
|
140
|
+
- (instancetype)init {
|
|
141
|
+
return [self initWithCodexHome:DefaultCodexHomeDirectory()];
|
|
142
|
+
}
|
|
143
|
+
- (instancetype)initWithCodexHome:(NSString *)codexHome {
|
|
144
|
+
if ((self = [super init])) {
|
|
145
|
+
_sessionsURL = [NSURL fileURLWithPath:[codexHome stringByAppendingPathComponent:@"sessions"]];
|
|
146
|
+
_partialLine = [NSMutableData data];
|
|
147
|
+
_tokenSummaryCachePath = TokenSummaryCachePath(@"codex", _sessionsURL.path);
|
|
148
|
+
_tokenSummaryCache = LoadTokenSummaryCache(_tokenSummaryCachePath);
|
|
149
|
+
_monthlyArchivePath = MonthlyUsageArchivePath(@"codex", _sessionsURL.path);
|
|
150
|
+
_monthlyArchive = LoadMonthlyUsageArchive(_monthlyArchivePath);
|
|
151
|
+
_pinnedSessionURLs = [NSMutableArray array];
|
|
152
|
+
}
|
|
153
|
+
return self;
|
|
154
|
+
}
|
|
155
|
+
// 缓存里过期的条目由 PruneTokenCache 在每次聚合里清掉,所以落盘的那份不会只增不减。
|
|
156
|
+
- (void)persistTokenSummaryCacheThrottled:(BOOL)throttled {
|
|
157
|
+
if (!self.persistsCache) return;
|
|
158
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
159
|
+
if (throttled && now - self.tokenCacheSavedAt < TokenCacheSaveInterval) return;
|
|
160
|
+
self.tokenCacheSavedAt = now;
|
|
161
|
+
SaveTokenSummaryCache(self.tokenSummaryCache, self.tokenSummaryCachePath);
|
|
162
|
+
}
|
|
163
|
+
- (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
|
|
164
|
+
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
165
|
+
usage = UsageByRemovingInactiveQuotaWindows(usage);
|
|
166
|
+
NSString *identity = [NSString stringWithFormat:@"%@:%d", TokenWindowIdentity(usage),
|
|
167
|
+
ProfileShowsAPIUsage(@"codex", self.sessionsURL.path.stringByDeletingLastPathComponent)];
|
|
168
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
169
|
+
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
170
|
+
[identity isEqualToString:self.tokenWindowIdentity] &&
|
|
171
|
+
now - self.tokenComputedAt < TokenAggregationInterval;
|
|
172
|
+
if (reusable) {
|
|
173
|
+
NSMutableDictionary *result = [usage mutableCopy];
|
|
174
|
+
result[@"tokenUsage"] = self.tokenUsage;
|
|
175
|
+
return [self usageByApplyingExhaustion:result];
|
|
176
|
+
}
|
|
177
|
+
BOOL archiveChanged = NO;
|
|
178
|
+
// 正在增量读取的会话永远排在钉住列表最前面:它是最不该被漏掉的那一个,而漏掉它
|
|
179
|
+
// 恰恰是"额度读得出、今日 Token 却是 0"的成因。
|
|
180
|
+
[self notePinnedSessionURL:self.sessionURL];
|
|
181
|
+
NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL,
|
|
182
|
+
self.pinnedSessionURLs, self.tokenSummaryCache, self.monthlyArchive, &archiveChanged);
|
|
183
|
+
if (archiveChanged) {
|
|
184
|
+
PruneMonthlyArchive(self.monthlyArchive);
|
|
185
|
+
if (self.persistsCache) SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
|
|
186
|
+
}
|
|
187
|
+
[self persistTokenSummaryCacheThrottled:YES];
|
|
188
|
+
id tokens = result[@"tokenUsage"];
|
|
189
|
+
self.tokenUsage = [tokens isKindOfClass:NSDictionary.class] ? tokens : nil;
|
|
190
|
+
self.tokenWindowIdentity = identity;
|
|
191
|
+
self.tokenComputedAt = now;
|
|
192
|
+
self.forcesTokenAggregation = NO;
|
|
193
|
+
return [self usageByApplyingExhaustion:result];
|
|
194
|
+
}
|
|
195
|
+
// 耗尽事件只往前走:额度恢复由"更新的额度快照"或窗口重置表达(见 ExhaustionStillHolds)。
|
|
196
|
+
- (void)noteExhaustion:(NSNumber *)timestamp {
|
|
197
|
+
if (timestamp.doubleValue > self.exhaustedAt) self.exhaustedAt = timestamp.doubleValue;
|
|
198
|
+
}
|
|
199
|
+
// 标记失效时把记下的时刻一并清掉:留着它只会在下一轮再比一次同样的大小,而窗口一旦重置,
|
|
200
|
+
// 这个时刻就永远不该再让任何快照被判成受限了。
|
|
201
|
+
- (NSDictionary *)usageByApplyingExhaustion:(NSDictionary *)usage {
|
|
202
|
+
if (![usage isKindOfClass:NSDictionary.class]) return usage;
|
|
203
|
+
if (!ExhaustionStillHolds(usage, self.exhaustedAt)) {
|
|
204
|
+
// 快照只会向前走(NewerUsageSnapshot),所以失效一次就是永久失效;真再撞上限流,
|
|
205
|
+
// noteExhaustion: 会记下新的时刻。
|
|
206
|
+
self.exhaustedAt = 0;
|
|
207
|
+
return usage;
|
|
208
|
+
}
|
|
209
|
+
return UsageByMarkingExhaustion(usage, self.exhaustedAt);
|
|
210
|
+
}
|
|
211
|
+
// 最近被写过的会话,最新的排在前面。并发会话不会太多,留 8 个足够覆盖一批 FSEvents;
|
|
212
|
+
// 更早的那些反正也会被目录扫描按 mtime 捞回来,钉住它们只是白读文件。
|
|
213
|
+
static const NSUInteger MaximumPinnedSessions = 8;
|
|
214
|
+
|
|
215
|
+
- (void)notePinnedSessionURL:(NSURL *)url {
|
|
216
|
+
if (!url.path.length) return;
|
|
217
|
+
NSMutableArray<NSURL *> *pinned = self.pinnedSessionURLs;
|
|
218
|
+
if (!pinned) {
|
|
219
|
+
pinned = [NSMutableArray array];
|
|
220
|
+
self.pinnedSessionURLs = pinned;
|
|
221
|
+
}
|
|
222
|
+
for (NSUInteger index = 0; index < pinned.count; index++) {
|
|
223
|
+
if ([pinned[index].path isEqualToString:url.path]) {
|
|
224
|
+
[pinned removeObjectAtIndex:index];
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
[pinned insertObject:url atIndex:0];
|
|
229
|
+
while (pinned.count > MaximumPinnedSessions) [pinned removeLastObject];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
- (void)selectSessionURL:(NSURL *)url {
|
|
233
|
+
self.sessionURL = url;
|
|
234
|
+
self.offset = 0;
|
|
235
|
+
[self.partialLine setLength:0];
|
|
236
|
+
if (!url) {
|
|
237
|
+
self.usage = nil;
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
[self notePinnedSessionURL:url];
|
|
241
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
242
|
+
if (!handle) return;
|
|
243
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
244
|
+
unsigned long long start = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
|
|
245
|
+
[handle seekToFileOffset:start];
|
|
246
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
247
|
+
[handle closeFile];
|
|
248
|
+
self.offset = start + tail.length;
|
|
249
|
+
// 切换会话意味着数据来源变了,不受节流约束。
|
|
250
|
+
self.forcesTokenAggregation = YES;
|
|
251
|
+
// 额度是账号级的,不随会话切换失效。新会话在首个 token_count 落盘前没有 rate_limits,
|
|
252
|
+
// 这时沿用上一份,否则每次开新会话面板都会整块闪空。窗口过期的判定另有 resets_at 兜底。
|
|
253
|
+
NSNumber *exhaustedAt = nil;
|
|
254
|
+
NSDictionary *latest = LatestUsageInData(tail, &exhaustedAt);
|
|
255
|
+
[self noteExhaustion:exhaustedAt];
|
|
256
|
+
NSDictionary *fallback = self.usage ?: LatestQuotaInRecentSessions(self.sessionsURL, url);
|
|
257
|
+
self.usage = [self usageWithTokenTotals:NewerUsageSnapshot(fallback, latest)];
|
|
258
|
+
|
|
259
|
+
const uint8_t *bytes = tail.bytes;
|
|
260
|
+
NSUInteger lastNewline = NSNotFound;
|
|
261
|
+
for (NSUInteger index = tail.length; index > 0; index--) {
|
|
262
|
+
if (bytes[index - 1] == '\n') {
|
|
263
|
+
lastNewline = index - 1;
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (lastNewline == NSNotFound) [self.partialLine appendData:tail];
|
|
268
|
+
else if (lastNewline + 1 < tail.length) {
|
|
269
|
+
[self.partialLine appendData:[tail subdataWithRange:NSMakeRange(lastNewline + 1, tail.length - lastNewline - 1)]];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
- (void)consumeIncrementalData:(NSData *)data {
|
|
273
|
+
if (data.length == 0) return;
|
|
274
|
+
[self.partialLine appendData:data];
|
|
275
|
+
const uint8_t *bytes = self.partialLine.bytes;
|
|
276
|
+
NSUInteger lineStart = 0;
|
|
277
|
+
for (NSUInteger index = 0; index < self.partialLine.length; index++) {
|
|
278
|
+
if (bytes[index] != '\n') continue;
|
|
279
|
+
NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
280
|
+
[self noteExhaustion:ExhaustionTimestampFromLine(line)];
|
|
281
|
+
NSDictionary *newUsage = UsageFromCodexLine(line);
|
|
282
|
+
self.usage = NewerUsageSnapshot(self.usage, newUsage);
|
|
283
|
+
lineStart = index + 1;
|
|
284
|
+
}
|
|
285
|
+
if (lineStart > 0) {
|
|
286
|
+
NSData *remainder = [self.partialLine subdataWithRange:
|
|
287
|
+
NSMakeRange(lineStart, self.partialLine.length - lineStart)];
|
|
288
|
+
self.partialLine = [remainder mutableCopy];
|
|
289
|
+
}
|
|
290
|
+
if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
|
|
291
|
+
}
|
|
292
|
+
- (NSDictionary *)refresh {
|
|
293
|
+
return [self refreshDiscovering:YES];
|
|
294
|
+
}
|
|
295
|
+
// discovering=NO 用于 FSEvents 定向路径:内核已经点名了变更的文件,再按 mtime 挑一次
|
|
296
|
+
// 只会推翻这个结论——发现步骤两条分支(全量的 NewestCodexSessionURL 和同目录的
|
|
297
|
+
// NewestSessionFileInDirectory)用的都是 mtime,而 mtime 顺序和额度采样先后并不一致。
|
|
298
|
+
- (NSDictionary *)refreshDiscovering:(BOOL)discovering {
|
|
299
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
300
|
+
if (discovering) {
|
|
301
|
+
BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
|
|
302
|
+
NSURL *candidate = nil;
|
|
303
|
+
if (needsFullDiscovery) {
|
|
304
|
+
candidate = NewestCodexSessionURL(self.sessionsURL);
|
|
305
|
+
self.lastFullDiscovery = now;
|
|
306
|
+
} else {
|
|
307
|
+
candidate = NewestSessionFileInDirectory(
|
|
308
|
+
self.sessionURL.URLByDeletingLastPathComponent, NULL);
|
|
309
|
+
}
|
|
310
|
+
if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
|
|
311
|
+
}
|
|
312
|
+
if (!self.sessionURL) return self.usage;
|
|
313
|
+
|
|
314
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
|
|
315
|
+
if (!handle) {
|
|
316
|
+
self.lastFullDiscovery = 0;
|
|
317
|
+
return self.usage;
|
|
318
|
+
}
|
|
319
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
320
|
+
if (size < self.offset) {
|
|
321
|
+
[handle closeFile];
|
|
322
|
+
[self selectSessionURL:self.sessionURL];
|
|
323
|
+
return self.usage;
|
|
324
|
+
}
|
|
325
|
+
if (size > self.offset) {
|
|
326
|
+
unsigned long long start = self.offset;
|
|
327
|
+
[handle seekToFileOffset:start];
|
|
328
|
+
NSData *newData = [handle readDataToEndOfFile];
|
|
329
|
+
self.offset = start + newData.length;
|
|
330
|
+
[self consumeIncrementalData:newData];
|
|
331
|
+
}
|
|
332
|
+
[handle closeFile];
|
|
333
|
+
self.usage = [self usageWithTokenTotals:self.usage];
|
|
334
|
+
return self.usage;
|
|
335
|
+
}
|
|
336
|
+
- (NSDictionary *)refreshWithFullDiscovery {
|
|
337
|
+
self.lastFullDiscovery = 0;
|
|
338
|
+
self.forcesTokenAggregation = YES;
|
|
339
|
+
return [self refresh];
|
|
340
|
+
}
|
|
341
|
+
- (BOOL)isSessionURL:(NSURL *)url {
|
|
342
|
+
if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return NO;
|
|
343
|
+
NSString *sessionsPath = self.sessionsURL.path.stringByResolvingSymlinksInPath;
|
|
344
|
+
NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
|
|
345
|
+
return [url.path.stringByResolvingSymlinksInPath hasPrefix:prefix];
|
|
346
|
+
}
|
|
347
|
+
// 并发会话下一批事件里会有多个会话文件同时变更,而"文件更晚被写"和"额度采样更晚"是两回事:
|
|
348
|
+
// 会话拿到 rate_limits 之后还会继续追加别的行。取遍历到的最后一个就会切到采样偏旧的会话,
|
|
349
|
+
// 面板上的百分比于是在两个会话之间来回跳。这里读各自的尾巴,按 sampledAt 挑,与
|
|
350
|
+
// LatestQuotaInRecentSessions 的判据保持一致。
|
|
351
|
+
//
|
|
352
|
+
// 别的会话也必须读取并比较:迟到的旧响应通常会作为下一批里的唯一文件出现。
|
|
353
|
+
// 唯一的例外是当前会话自己——那是单会话的常态热路径,追加的新行走增量读取,
|
|
354
|
+
// consumeIncrementalData 里的 NewerUsageSnapshot 已经保证了单调性,不必为它白读一遍尾巴。
|
|
355
|
+
- (NSDictionary *)refreshForSessionURLs:(NSArray<NSURL *> *)urls {
|
|
356
|
+
NSURL *chosen = nil;
|
|
357
|
+
NSURL *currentSession = nil;
|
|
358
|
+
double chosenSampledAt = [self.usage[@"sampledAt"] doubleValue];
|
|
359
|
+
for (NSURL *url in urls) {
|
|
360
|
+
if (![self isSessionURL:url]) continue;
|
|
361
|
+
// 额度竞选的输赢与 Token 聚合无关:这一批里每个会话文件都刚被写过,落选的那些
|
|
362
|
+
// 同样带着新的 token_count。钉住它们,别再让日期目录扫描替内核做一次取舍。
|
|
363
|
+
[self notePinnedSessionURL:url];
|
|
364
|
+
if (self.sessionURL && [url.path isEqualToString:self.sessionURL.path]) {
|
|
365
|
+
currentSession = url;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
// 耗尽事件也在这段尾巴里。反正已经读了,顺手记下来:候选因为采样更旧而落选时
|
|
369
|
+
// 整批事件都不再走 refresh,不在这里捕获就永远丢了——而"另一个会话刚更新过额度、
|
|
370
|
+
// 这个会话撞上限流"正是最容易发生耗尽的时刻。
|
|
371
|
+
NSNumber *exhaustedAt = nil;
|
|
372
|
+
NSDictionary *usage = LatestUsageInData(SessionTailData(url), &exhaustedAt);
|
|
373
|
+
[self noteExhaustion:exhaustedAt];
|
|
374
|
+
// 整篇都没有额度、或者采样比当前面板更旧的会话不参与竞选。
|
|
375
|
+
if (!usage) continue;
|
|
376
|
+
double sampledAt = [usage[@"sampledAt"] doubleValue];
|
|
377
|
+
if (sampledAt >= chosenSampledAt) {
|
|
378
|
+
chosen = url;
|
|
379
|
+
chosenSampledAt = sampledAt;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
// 没有别的会话胜出时才轮到当前会话,这样先后遍历到谁都不影响结果。
|
|
383
|
+
if (!chosen) chosen = currentSession;
|
|
384
|
+
// 一个候选都没选中就不会再走到 usageWithTokenTotals,刚记下的耗尽标记得在这里贴上。
|
|
385
|
+
if (!chosen) {
|
|
386
|
+
self.usage = [self usageByApplyingExhaustion:self.usage];
|
|
387
|
+
return self.usage;
|
|
388
|
+
}
|
|
389
|
+
if (![chosen.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:chosen];
|
|
390
|
+
return [self refreshDiscovering:NO];
|
|
391
|
+
}
|
|
392
|
+
@end
|