cc-pets 1.0.1 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +12 -2
- package/Sources/CCPets/CCPetsAppDelegate.h +54 -0
- package/Sources/CCPets/CCPetsAppDelegate.m +1158 -0
- package/Sources/CCPets/CCPetsCleanup.h +7 -0
- package/Sources/CCPets/CCPetsCleanup.m +126 -0
- package/Sources/CCPets/CCPetsEvents.h +10 -0
- package/Sources/CCPets/CCPetsEvents.m +232 -0
- package/Sources/CCPets/CCPetsImageLoader.h +4 -0
- package/Sources/CCPets/CCPetsImageLoader.m +36 -0
- package/Sources/CCPets/CCPetsPaths.h +23 -0
- package/Sources/CCPets/CCPetsPaths.m +48 -0
- package/Sources/CCPets/CCPetsPreviews.h +6 -0
- package/Sources/CCPets/CCPetsPreviews.m +159 -0
- package/Sources/CCPets/CCPetsQuotaHistory.h +7 -0
- package/Sources/CCPets/CCPetsQuotaHistory.m +83 -0
- package/Sources/CCPets/CCPetsUsage.h +19 -0
- package/Sources/CCPets/CCPetsUsage.m +289 -0
- package/Sources/CCPets/CCPetsUsageMonitor.h +10 -0
- package/Sources/CCPets/CCPetsUsageMonitor.m +163 -0
- package/Sources/CCPets/CCPetsVersion.h +10 -0
- package/Sources/CCPets/CCPetsVersion.m +62 -0
- package/Sources/CCPets/MenuToggleSwitch.h +5 -0
- package/Sources/CCPets/MenuToggleSwitch.m +47 -0
- package/Sources/CCPets/PetView.h +35 -0
- package/Sources/CCPets/PetView.m +511 -0
- package/Sources/CCPets/QuotaDashboardView.h +23 -0
- package/Sources/CCPets/QuotaDashboardView.m +318 -0
- package/Sources/CCPets/main.m +11 -2528
- package/bin/cc-pets +5 -0
- package/bin/claude-with-pet +2 -1
- package/bin/codex-with-pet +3 -1
- package/package.json +2 -3
- package/scripts/build.sh +20 -1
- package/scripts/install-git-hooks.sh +47 -0
- package/scripts/uninstall-app.sh +9 -0
- package/scripts/uninstall-shell-integration.sh +50 -2
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// 本地额度历史(默认关闭,由 HistoryEnabledKey 控制)。
|
|
4
|
+
// RecordQuotaHistory 返回当前文档,调用方直接复用,避免一轮刷新里重复读盘。
|
|
5
|
+
NSDictionary *QuotaHistoryDocument(void);
|
|
6
|
+
NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage);
|
|
7
|
+
NSArray<NSNumber *> *QuotaHistorySeries(NSDictionary *document, NSString *provider);
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#import "CCPetsQuotaHistory.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sys/stat.h>
|
|
4
|
+
|
|
5
|
+
static NSNumber *RemainingValue(NSDictionary *usage, NSString *quotaKey, NSString *usedKey) {
|
|
6
|
+
NSDictionary *quota = [usage[quotaKey] isKindOfClass:NSDictionary.class] ? usage[quotaKey] : nil;
|
|
7
|
+
NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
|
|
8
|
+
if (!used) return nil;
|
|
9
|
+
return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
NSDictionary *QuotaHistoryDocument(void) {
|
|
13
|
+
NSData *data = [NSData dataWithContentsOfFile:QuotaHistoryPath()];
|
|
14
|
+
NSDictionary *document = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
15
|
+
if (![document isKindOfClass:NSDictionary.class] ||
|
|
16
|
+
[document[@"schemaVersion"] integerValue] != 1 ||
|
|
17
|
+
![document[@"samples"] isKindOfClass:NSArray.class]) {
|
|
18
|
+
return @{@"schemaVersion": @1, @"samples": @[]};
|
|
19
|
+
}
|
|
20
|
+
return document;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
|
|
24
|
+
NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
|
|
25
|
+
NSNumber *week = RemainingValue(usage, @"week", usedKey);
|
|
26
|
+
NSMutableDictionary *sample = [NSMutableDictionary dictionary];
|
|
27
|
+
if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
|
|
28
|
+
if (week) sample[@"weekRemaining"] = week;
|
|
29
|
+
return sample;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 返回当前的历史文档,供调用方直接取用:原先每次刷新要读盘+解析三次
|
|
33
|
+
// (这里一次、两条曲线各一次),现在整轮只读一次。
|
|
34
|
+
NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
|
|
35
|
+
NSDictionary *document = QuotaHistoryDocument();
|
|
36
|
+
if (![NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]) return document;
|
|
37
|
+
NSDictionary *codex = HistoryProviderSample(codexUsage, @"used_percent");
|
|
38
|
+
NSDictionary *claude = HistoryProviderSample(claudeUsage, @"used_percentage");
|
|
39
|
+
if (codex.count == 0 && claude.count == 0) return document;
|
|
40
|
+
|
|
41
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
42
|
+
NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
|
|
43
|
+
NSArray *existing = document[@"samples"];
|
|
44
|
+
NSMutableArray *samples = [NSMutableArray arrayWithCapacity:existing.count + 1];
|
|
45
|
+
for (NSDictionary *sample in existing) {
|
|
46
|
+
if (![sample isKindOfClass:NSDictionary.class] || [sample[@"timestamp"] doubleValue] < cutoff) continue;
|
|
47
|
+
[samples addObject:sample];
|
|
48
|
+
}
|
|
49
|
+
NSDictionary *last = samples.lastObject;
|
|
50
|
+
if (last && now - [last[@"timestamp"] doubleValue] < 15 * 60) return document;
|
|
51
|
+
|
|
52
|
+
NSMutableDictionary *sample = [@{@"timestamp": @(now)} mutableCopy];
|
|
53
|
+
if (codex.count > 0) sample[@"codex"] = codex;
|
|
54
|
+
if (claude.count > 0) sample[@"claude"] = claude;
|
|
55
|
+
[samples addObject:sample];
|
|
56
|
+
if (samples.count > 672) {
|
|
57
|
+
[samples removeObjectsInRange:NSMakeRange(0, samples.count - 672)];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
NSString *directory = QuotaHistoryPath().stringByDeletingLastPathComponent;
|
|
61
|
+
[NSFileManager.defaultManager createDirectoryAtPath:directory
|
|
62
|
+
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
63
|
+
NSDictionary *updated = @{@"schemaVersion": @1, @"samples": samples};
|
|
64
|
+
NSData *json = [NSJSONSerialization dataWithJSONObject:updated
|
|
65
|
+
options:NSJSONWritingPrettyPrinted error:nil];
|
|
66
|
+
if ([json writeToFile:QuotaHistoryPath() options:NSDataWritingAtomic error:nil]) {
|
|
67
|
+
chmod(QuotaHistoryPath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
68
|
+
}
|
|
69
|
+
return updated;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
NSArray<NSNumber *> *QuotaHistorySeries(NSDictionary *document, NSString *provider) {
|
|
73
|
+
NSMutableArray<NSNumber *> *series = [NSMutableArray array];
|
|
74
|
+
for (NSDictionary *sample in document[@"samples"]) {
|
|
75
|
+
if (![sample isKindOfClass:NSDictionary.class]) continue;
|
|
76
|
+
NSDictionary *providerSample = [sample[provider] isKindOfClass:NSDictionary.class]
|
|
77
|
+
? sample[provider] : nil;
|
|
78
|
+
NSNumber *remaining = [providerSample[@"weekRemaining"] isKindOfClass:NSNumber.class]
|
|
79
|
+
? providerSample[@"weekRemaining"] : nil;
|
|
80
|
+
if (remaining) [series addObject:remaining];
|
|
81
|
+
}
|
|
82
|
+
return series;
|
|
83
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// Codex 与 Claude 的额度读取。
|
|
4
|
+
int RecordClaudeUsage(void);
|
|
5
|
+
NSDictionary *LatestClaudeUsage(void);
|
|
6
|
+
NSDictionary *LatestUsage(void);
|
|
7
|
+
|
|
8
|
+
// 增量跟读当前 Codex 会话文件:只在会话切换时做一次冷读,之后按偏移追读。
|
|
9
|
+
@interface CodexUsageReader : NSObject
|
|
10
|
+
@property NSURL *sessionsURL;
|
|
11
|
+
@property NSURL *sessionURL;
|
|
12
|
+
@property NSDictionary *usage;
|
|
13
|
+
@property unsigned long long offset;
|
|
14
|
+
@property NSMutableData *partialLine;
|
|
15
|
+
@property NSTimeInterval lastFullDiscovery;
|
|
16
|
+
- (NSDictionary *)refresh;
|
|
17
|
+
- (NSDictionary *)refreshWithFullDiscovery;
|
|
18
|
+
- (NSDictionary *)refreshForSessionURL:(NSURL *)url;
|
|
19
|
+
@end
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
#import "CCPetsUsage.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sys/stat.h>
|
|
4
|
+
#import <unistd.h>
|
|
5
|
+
|
|
6
|
+
int RecordClaudeUsage(void) {
|
|
7
|
+
NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
|
|
8
|
+
NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
|
|
9
|
+
NSDictionary *limits = [payload[@"rate_limits"] isKindOfClass:NSDictionary.class] ? payload[@"rate_limits"] : nil;
|
|
10
|
+
if (!limits) return EXIT_SUCCESS;
|
|
11
|
+
NSData *json = [NSJSONSerialization dataWithJSONObject:limits options:0 error:nil];
|
|
12
|
+
if (!json) return EXIT_SUCCESS;
|
|
13
|
+
if (![json writeToFile:ClaudeUsagePath() options:NSDataWritingAtomic error:nil]) return EXIT_SUCCESS;
|
|
14
|
+
chmod(ClaudeUsagePath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
15
|
+
return EXIT_SUCCESS;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
NSDictionary *LatestClaudeUsage(void) {
|
|
19
|
+
NSData *data = [NSData dataWithContentsOfFile:ClaudeUsagePath()];
|
|
20
|
+
NSDictionary *limits = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
21
|
+
if (![limits isKindOfClass:NSDictionary.class]) return nil;
|
|
22
|
+
id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
|
|
23
|
+
id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
|
|
24
|
+
return @{@"fiveHour": fiveHour, @"week": week};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static BOOL AllDigits(NSString *text) {
|
|
28
|
+
if (text.length == 0) return NO;
|
|
29
|
+
static NSCharacterSet *nonDigits;
|
|
30
|
+
static dispatch_once_t once;
|
|
31
|
+
dispatch_once(&once, ^{
|
|
32
|
+
nonDigits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet;
|
|
33
|
+
});
|
|
34
|
+
return [text rangeOfCharacterFromSet:nonDigits].location == NSNotFound;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// 会话目录是零填充的 YYYY/MM/DD,字典序等于时间序,因此倒序取名字即可,不必 stat。
|
|
38
|
+
static NSArray<NSURL *> *DescendingNumericSubdirectories(NSURL *directory) {
|
|
39
|
+
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
40
|
+
includingPropertiesForKeys:@[NSURLIsDirectoryKey]
|
|
41
|
+
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
42
|
+
NSMutableArray<NSURL *> *result = [NSMutableArray arrayWithCapacity:contents.count];
|
|
43
|
+
for (NSURL *url in contents) {
|
|
44
|
+
NSNumber *isDirectory = nil;
|
|
45
|
+
if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
|
|
46
|
+
if (!isDirectory.boolValue || !AllDigits(url.lastPathComponent)) continue;
|
|
47
|
+
[result addObject:url];
|
|
48
|
+
}
|
|
49
|
+
[result sortUsingComparator:^NSComparisonResult(NSURL *left, NSURL *right) {
|
|
50
|
+
return [right.lastPathComponent compare:left.lastPathComponent];
|
|
51
|
+
}];
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 单个目录内 mtime 最新的 .jsonl。文件名格式不是契约,因此文件一律按 mtime 选,
|
|
56
|
+
// 只有日期目录名吃字典序。
|
|
57
|
+
static NSURL *NewestSessionFileInDirectory(NSURL *directory, NSDate **outDate) {
|
|
58
|
+
NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
|
|
59
|
+
NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
|
|
60
|
+
includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
|
|
61
|
+
NSURL *newest = nil;
|
|
62
|
+
NSDate *newestDate = NSDate.distantPast;
|
|
63
|
+
for (NSURL *url in contents) {
|
|
64
|
+
if (![url.pathExtension isEqualToString:@"jsonl"]) continue;
|
|
65
|
+
NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
|
|
66
|
+
if (![values[NSURLIsRegularFileKey] boolValue]) continue;
|
|
67
|
+
NSDate *date = values[NSURLContentModificationDateKey] ?: NSDate.distantPast;
|
|
68
|
+
if ([date compare:newestDate] == NSOrderedDescending) {
|
|
69
|
+
newest = url;
|
|
70
|
+
newestDate = date;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (outDate) *outDate = newest ? newestDate : nil;
|
|
74
|
+
return newest;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
static const NSUInteger MinimumExaminedSessionDays = 3;
|
|
78
|
+
static const NSUInteger MaximumExaminedSessionDays = 40;
|
|
79
|
+
|
|
80
|
+
// 按 YYYY/MM/DD 倒序下钻,成本与历史会话总量无关,只与近期活跃度有关。
|
|
81
|
+
// 收手条件必须同时满足“看够 MinimumExaminedSessionDays 个日期目录”和“已经找到过文件”:
|
|
82
|
+
// 只写前者的话,用户闲置数天后冷启动会一无所获,比全量扫描更差。
|
|
83
|
+
static NSURL *NewestCodexSessionURL(NSURL *sessionsURL) {
|
|
84
|
+
NSURL *newest = nil;
|
|
85
|
+
NSDate *newestDate = NSDate.distantPast;
|
|
86
|
+
NSUInteger examinedDays = 0;
|
|
87
|
+
for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
|
|
88
|
+
for (NSURL *month in DescendingNumericSubdirectories(year)) {
|
|
89
|
+
for (NSURL *day in DescendingNumericSubdirectories(month)) {
|
|
90
|
+
NSDate *date = nil;
|
|
91
|
+
NSURL *candidate = NewestSessionFileInDirectory(day, &date);
|
|
92
|
+
if (candidate && [date compare:newestDate] == NSOrderedDescending) {
|
|
93
|
+
newest = candidate;
|
|
94
|
+
newestDate = date;
|
|
95
|
+
}
|
|
96
|
+
examinedDays += 1;
|
|
97
|
+
if (examinedDays >= MinimumExaminedSessionDays && newest) return newest;
|
|
98
|
+
if (examinedDays >= MaximumExaminedSessionDays) return newest;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// 兜底:非 YYYY/MM/DD 布局(例如直接摊在 sessions/ 下)仍然能被发现。
|
|
103
|
+
return newest ?: NewestSessionFileInDirectory(sessionsURL, NULL);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
static NSDictionary *UsageFromCodexLine(NSData *lineData) {
|
|
107
|
+
if (lineData.length == 0) return nil;
|
|
108
|
+
// 快速拒绝直接在字节上做,不再为每行分配 NSString。
|
|
109
|
+
static NSData *marker;
|
|
110
|
+
static dispatch_once_t once;
|
|
111
|
+
dispatch_once(&once, ^{
|
|
112
|
+
marker = [@"\"type\":\"token_count\"" dataUsingEncoding:NSUTF8StringEncoding];
|
|
113
|
+
});
|
|
114
|
+
if ([lineData rangeOfData:marker options:0
|
|
115
|
+
range:NSMakeRange(0, lineData.length)].location == NSNotFound) return nil;
|
|
116
|
+
// 逐层校验类型:顶层若是数组、payload 若是字符串,下面的下标访问会抛
|
|
117
|
+
// unrecognized selector 直接崩掉桌宠。
|
|
118
|
+
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
119
|
+
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
120
|
+
id payloadValue = ((NSDictionary *)rootValue)[@"payload"];
|
|
121
|
+
if (![payloadValue isKindOfClass:NSDictionary.class]) return nil;
|
|
122
|
+
NSDictionary *payload = payloadValue;
|
|
123
|
+
id typeValue = payload[@"type"];
|
|
124
|
+
if (![typeValue isKindOfClass:NSString.class] ||
|
|
125
|
+
![(NSString *)typeValue isEqualToString:@"token_count"]) return nil;
|
|
126
|
+
id limitsValue = payload[@"rate_limits"];
|
|
127
|
+
if (![limitsValue isKindOfClass:NSDictionary.class]) return nil;
|
|
128
|
+
NSDictionary *limits = limitsValue;
|
|
129
|
+
id primaryValue = limits[@"primary"];
|
|
130
|
+
id secondaryValue = limits[@"secondary"];
|
|
131
|
+
NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
|
|
132
|
+
NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
|
|
133
|
+
NSDictionary *fiveHour = nil;
|
|
134
|
+
NSDictionary *week = nil;
|
|
135
|
+
for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
|
|
136
|
+
NSInteger minutes = [quota[@"window_minutes"] integerValue];
|
|
137
|
+
if (minutes == 300) fiveHour = quota;
|
|
138
|
+
if (minutes == 10080) week = quota;
|
|
139
|
+
}
|
|
140
|
+
return @{
|
|
141
|
+
@"fiveHour": fiveHour ?: NSNull.null,
|
|
142
|
+
@"week": week ?: NSNull.null
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// token_count 行几乎总在文件末尾,因此从尾部反向按 \n 切片逐行试,命中即停。
|
|
147
|
+
// 原实现会把整段(最多 2MB)解码成 NSString、再切成全部行、再把每行编码回 NSData、
|
|
148
|
+
// 又解码回 NSString 查子串,等于来回往返两遍。
|
|
149
|
+
static NSDictionary *LatestUsageInData(NSData *data) {
|
|
150
|
+
const uint8_t *bytes = data.bytes;
|
|
151
|
+
NSUInteger end = data.length;
|
|
152
|
+
while (end > 0) {
|
|
153
|
+
NSUInteger start = end;
|
|
154
|
+
while (start > 0 && bytes[start - 1] != '\n') start -= 1;
|
|
155
|
+
if (end > start) {
|
|
156
|
+
NSDictionary *usage = UsageFromCodexLine(
|
|
157
|
+
[data subdataWithRange:NSMakeRange(start, end - start)]);
|
|
158
|
+
if (usage) return usage;
|
|
159
|
+
}
|
|
160
|
+
end = start > 0 ? start - 1 : 0;
|
|
161
|
+
}
|
|
162
|
+
return nil;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
NSDictionary *LatestUsage(void) {
|
|
166
|
+
NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
|
|
167
|
+
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
168
|
+
NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
|
|
169
|
+
NSURL *newest = NewestCodexSessionURL(sessions);
|
|
170
|
+
if (!newest) return nil;
|
|
171
|
+
|
|
172
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:newest error:nil];
|
|
173
|
+
if (!handle) return nil;
|
|
174
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
175
|
+
[handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
|
|
176
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
177
|
+
[handle closeFile];
|
|
178
|
+
return LatestUsageInData(tail);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
@implementation CodexUsageReader
|
|
182
|
+
- (instancetype)init {
|
|
183
|
+
if ((self = [super init])) {
|
|
184
|
+
NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
|
|
185
|
+
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
186
|
+
_sessionsURL = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
|
|
187
|
+
_partialLine = [NSMutableData data];
|
|
188
|
+
}
|
|
189
|
+
return self;
|
|
190
|
+
}
|
|
191
|
+
- (void)selectSessionURL:(NSURL *)url {
|
|
192
|
+
self.sessionURL = url;
|
|
193
|
+
self.offset = 0;
|
|
194
|
+
[self.partialLine setLength:0];
|
|
195
|
+
if (!url) {
|
|
196
|
+
self.usage = nil;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
200
|
+
if (!handle) return;
|
|
201
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
202
|
+
unsigned long long start = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
|
|
203
|
+
[handle seekToFileOffset:start];
|
|
204
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
205
|
+
[handle closeFile];
|
|
206
|
+
self.offset = start + tail.length;
|
|
207
|
+
self.usage = LatestUsageInData(tail);
|
|
208
|
+
|
|
209
|
+
const uint8_t *bytes = tail.bytes;
|
|
210
|
+
NSUInteger lastNewline = NSNotFound;
|
|
211
|
+
for (NSUInteger index = tail.length; index > 0; index--) {
|
|
212
|
+
if (bytes[index - 1] == '\n') {
|
|
213
|
+
lastNewline = index - 1;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (lastNewline == NSNotFound) [self.partialLine appendData:tail];
|
|
218
|
+
else if (lastNewline + 1 < tail.length) {
|
|
219
|
+
[self.partialLine appendData:[tail subdataWithRange:NSMakeRange(lastNewline + 1, tail.length - lastNewline - 1)]];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
- (void)consumeIncrementalData:(NSData *)data {
|
|
223
|
+
if (data.length == 0) return;
|
|
224
|
+
[self.partialLine appendData:data];
|
|
225
|
+
const uint8_t *bytes = self.partialLine.bytes;
|
|
226
|
+
NSUInteger lineStart = 0;
|
|
227
|
+
for (NSUInteger index = 0; index < self.partialLine.length; index++) {
|
|
228
|
+
if (bytes[index] != '\n') continue;
|
|
229
|
+
NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
230
|
+
NSDictionary *newUsage = UsageFromCodexLine(line);
|
|
231
|
+
if (newUsage) self.usage = newUsage;
|
|
232
|
+
lineStart = index + 1;
|
|
233
|
+
}
|
|
234
|
+
if (lineStart > 0) {
|
|
235
|
+
NSData *remainder = [self.partialLine subdataWithRange:
|
|
236
|
+
NSMakeRange(lineStart, self.partialLine.length - lineStart)];
|
|
237
|
+
self.partialLine = [remainder mutableCopy];
|
|
238
|
+
}
|
|
239
|
+
if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
|
|
240
|
+
}
|
|
241
|
+
- (NSDictionary *)refresh {
|
|
242
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
243
|
+
BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
|
|
244
|
+
NSURL *candidate = nil;
|
|
245
|
+
if (needsFullDiscovery) {
|
|
246
|
+
candidate = NewestCodexSessionURL(self.sessionsURL);
|
|
247
|
+
self.lastFullDiscovery = now;
|
|
248
|
+
} else {
|
|
249
|
+
candidate = NewestSessionFileInDirectory(
|
|
250
|
+
self.sessionURL.URLByDeletingLastPathComponent, NULL);
|
|
251
|
+
}
|
|
252
|
+
if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
|
|
253
|
+
if (!self.sessionURL) return self.usage;
|
|
254
|
+
|
|
255
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
|
|
256
|
+
if (!handle) {
|
|
257
|
+
self.lastFullDiscovery = 0;
|
|
258
|
+
return self.usage;
|
|
259
|
+
}
|
|
260
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
261
|
+
if (size < self.offset) {
|
|
262
|
+
[handle closeFile];
|
|
263
|
+
[self selectSessionURL:self.sessionURL];
|
|
264
|
+
return self.usage;
|
|
265
|
+
}
|
|
266
|
+
if (size > self.offset) {
|
|
267
|
+
unsigned long long start = self.offset;
|
|
268
|
+
[handle seekToFileOffset:start];
|
|
269
|
+
NSData *newData = [handle readDataToEndOfFile];
|
|
270
|
+
self.offset = start + newData.length;
|
|
271
|
+
[self consumeIncrementalData:newData];
|
|
272
|
+
}
|
|
273
|
+
[handle closeFile];
|
|
274
|
+
return self.usage;
|
|
275
|
+
}
|
|
276
|
+
- (NSDictionary *)refreshWithFullDiscovery {
|
|
277
|
+
self.lastFullDiscovery = 0;
|
|
278
|
+
return [self refresh];
|
|
279
|
+
}
|
|
280
|
+
- (NSDictionary *)refreshForSessionURL:(NSURL *)url {
|
|
281
|
+
if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return self.usage;
|
|
282
|
+
NSString *sessionsPath = self.sessionsURL.path.stringByResolvingSymlinksInPath;
|
|
283
|
+
NSString *candidatePath = url.path.stringByResolvingSymlinksInPath;
|
|
284
|
+
NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
|
|
285
|
+
if (![candidatePath hasPrefix:prefix]) return self.usage;
|
|
286
|
+
if (![candidatePath isEqualToString:self.sessionURL.path]) [self selectSessionURL:url];
|
|
287
|
+
return [self refresh];
|
|
288
|
+
}
|
|
289
|
+
@end
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
@interface CCPetsUsageMonitor : NSObject
|
|
4
|
+
@property(copy) void (^changeHandler)(NSDictionary *codexUsage, NSDictionary *claudeUsage);
|
|
5
|
+
@property(readonly) NSDictionary *codexUsage;
|
|
6
|
+
@property(readonly) NSDictionary *claudeUsage;
|
|
7
|
+
- (void)start;
|
|
8
|
+
- (void)refreshNow;
|
|
9
|
+
- (void)stop;
|
|
10
|
+
@end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
#import "CCPetsUsageMonitor.h"
|
|
2
|
+
#import "CCPetsUsage.h"
|
|
3
|
+
#import "CCPetsPaths.h"
|
|
4
|
+
#import <CoreServices/CoreServices.h>
|
|
5
|
+
#import <fcntl.h>
|
|
6
|
+
#import <unistd.h>
|
|
7
|
+
|
|
8
|
+
@interface CCPetsUsageMonitor ()
|
|
9
|
+
@property CodexUsageReader *codexReader;
|
|
10
|
+
@property(readwrite) NSDictionary *codexUsage;
|
|
11
|
+
@property(readwrite) NSDictionary *claudeUsage;
|
|
12
|
+
@property FSEventStreamRef codexStream;
|
|
13
|
+
@property dispatch_source_t claudeSource;
|
|
14
|
+
@property unsigned long long claudeSize;
|
|
15
|
+
@property NSTimeInterval claudeModifiedAt;
|
|
16
|
+
@property BOOL started;
|
|
17
|
+
- (void)publishChange;
|
|
18
|
+
- (void)startClaudeSource;
|
|
19
|
+
@end
|
|
20
|
+
|
|
21
|
+
static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
|
|
22
|
+
void *clientCallBackInfo, size_t numEvents, void *eventPaths,
|
|
23
|
+
const FSEventStreamEventFlags eventFlags[],
|
|
24
|
+
const FSEventStreamEventId eventIds[]) {
|
|
25
|
+
CCPetsUsageMonitor *monitor = (__bridge CCPetsUsageMonitor *)clientCallBackInfo;
|
|
26
|
+
NSArray<NSString *> *paths = (__bridge NSArray<NSString *> *)eventPaths;
|
|
27
|
+
BOOL requiresFullDiscovery = NO;
|
|
28
|
+
NSURL *latestSession = nil;
|
|
29
|
+
for (size_t index = 0; index < numEvents; index++) {
|
|
30
|
+
FSEventStreamEventFlags flags = eventFlags[index];
|
|
31
|
+
if (flags & (kFSEventStreamEventFlagMustScanSubDirs |
|
|
32
|
+
kFSEventStreamEventFlagUserDropped |
|
|
33
|
+
kFSEventStreamEventFlagKernelDropped |
|
|
34
|
+
kFSEventStreamEventFlagRootChanged)) {
|
|
35
|
+
requiresFullDiscovery = YES;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
NSString *path = paths[index];
|
|
39
|
+
if ([path.pathExtension.lowercaseString isEqualToString:@"jsonl"] &&
|
|
40
|
+
[path.stringByResolvingSymlinksInPath hasPrefix:
|
|
41
|
+
[monitor.codexReader.sessionsURL.path.stringByResolvingSymlinksInPath
|
|
42
|
+
stringByAppendingString:@"/"]]) {
|
|
43
|
+
latestSession = [NSURL fileURLWithPath:path];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
monitor.codexUsage = requiresFullDiscovery
|
|
47
|
+
? [monitor.codexReader refreshWithFullDiscovery]
|
|
48
|
+
: (latestSession ? [monitor.codexReader refreshForSessionURL:latestSession] : monitor.codexUsage);
|
|
49
|
+
if (requiresFullDiscovery || latestSession) [monitor publishChange];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
@implementation CCPetsUsageMonitor
|
|
53
|
+
- (instancetype)init {
|
|
54
|
+
if ((self = [super init])) {
|
|
55
|
+
_codexReader = [CodexUsageReader new];
|
|
56
|
+
}
|
|
57
|
+
return self;
|
|
58
|
+
}
|
|
59
|
+
- (void)publishChange {
|
|
60
|
+
if (self.changeHandler) self.changeHandler(self.codexUsage, self.claudeUsage);
|
|
61
|
+
}
|
|
62
|
+
- (NSDictionary *)readClaudeUsageIfChanged:(BOOL)force {
|
|
63
|
+
NSString *path = ClaudeUsagePath();
|
|
64
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
65
|
+
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
66
|
+
NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
|
|
67
|
+
if (!force && size == self.claudeSize && modifiedAt == self.claudeModifiedAt) {
|
|
68
|
+
return self.claudeUsage;
|
|
69
|
+
}
|
|
70
|
+
self.claudeSize = size;
|
|
71
|
+
self.claudeModifiedAt = modifiedAt;
|
|
72
|
+
return LatestClaudeUsage();
|
|
73
|
+
}
|
|
74
|
+
- (void)startCodexStream {
|
|
75
|
+
if (self.codexStream) return;
|
|
76
|
+
NSString *sessionsPath = self.codexReader.sessionsURL.path;
|
|
77
|
+
BOOL isDirectory = NO;
|
|
78
|
+
if (![NSFileManager.defaultManager fileExistsAtPath:sessionsPath isDirectory:&isDirectory] ||
|
|
79
|
+
!isDirectory) return;
|
|
80
|
+
FSEventStreamContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
|
|
81
|
+
NSArray *paths = @[sessionsPath];
|
|
82
|
+
FSEventStreamCreateFlags flags =
|
|
83
|
+
kFSEventStreamCreateFlagFileEvents |
|
|
84
|
+
kFSEventStreamCreateFlagNoDefer |
|
|
85
|
+
kFSEventStreamCreateFlagUseCFTypes;
|
|
86
|
+
self.codexStream = FSEventStreamCreate(NULL, CodexEventsCallback, &context,
|
|
87
|
+
(__bridge CFArrayRef)paths, kFSEventStreamEventIdSinceNow, 0.5, flags);
|
|
88
|
+
if (!self.codexStream) return;
|
|
89
|
+
FSEventStreamSetDispatchQueue(self.codexStream, dispatch_get_main_queue());
|
|
90
|
+
if (!FSEventStreamStart(self.codexStream)) {
|
|
91
|
+
FSEventStreamInvalidate(self.codexStream);
|
|
92
|
+
FSEventStreamRelease(self.codexStream);
|
|
93
|
+
self.codexStream = NULL;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
- (void)startClaudeSource {
|
|
97
|
+
if (self.claudeSource || !self.started) return;
|
|
98
|
+
NSString *path = ClaudeUsagePath();
|
|
99
|
+
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
100
|
+
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
101
|
+
if (![NSFileManager.defaultManager fileExistsAtPath:path]) {
|
|
102
|
+
[NSFileManager.defaultManager createFileAtPath:path contents:nil attributes:nil];
|
|
103
|
+
}
|
|
104
|
+
int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
|
|
105
|
+
if (descriptor < 0) return;
|
|
106
|
+
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
|
|
107
|
+
DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
|
|
108
|
+
DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, dispatch_get_main_queue());
|
|
109
|
+
if (!source) {
|
|
110
|
+
close(descriptor);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
self.claudeSource = source;
|
|
114
|
+
__weak typeof(self) weakSelf = self;
|
|
115
|
+
dispatch_source_set_event_handler(source, ^{
|
|
116
|
+
typeof(self) strongSelf = weakSelf;
|
|
117
|
+
if (!strongSelf) return;
|
|
118
|
+
dispatch_source_t current = strongSelf.claudeSource;
|
|
119
|
+
if (!current) return;
|
|
120
|
+
unsigned long flags = dispatch_source_get_data(current);
|
|
121
|
+
strongSelf.claudeUsage = [strongSelf readClaudeUsageIfChanged:YES];
|
|
122
|
+
[strongSelf publishChange];
|
|
123
|
+
if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
|
|
124
|
+
strongSelf.claudeSource = nil;
|
|
125
|
+
dispatch_source_cancel(current);
|
|
126
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
|
|
127
|
+
dispatch_get_main_queue(), ^{ [weakSelf startClaudeSource]; });
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
|
|
131
|
+
dispatch_resume(source);
|
|
132
|
+
}
|
|
133
|
+
- (void)start {
|
|
134
|
+
if (self.started) return;
|
|
135
|
+
self.started = YES;
|
|
136
|
+
[self refreshNow];
|
|
137
|
+
[self startCodexStream];
|
|
138
|
+
[self startClaudeSource];
|
|
139
|
+
}
|
|
140
|
+
- (void)refreshNow {
|
|
141
|
+
self.codexUsage = [self.codexReader refresh];
|
|
142
|
+
self.claudeUsage = [self readClaudeUsageIfChanged:NO];
|
|
143
|
+
if (!self.codexStream) [self startCodexStream];
|
|
144
|
+
if (!self.claudeSource) [self startClaudeSource];
|
|
145
|
+
[self publishChange];
|
|
146
|
+
}
|
|
147
|
+
- (void)stop {
|
|
148
|
+
self.started = NO;
|
|
149
|
+
if (self.codexStream) {
|
|
150
|
+
FSEventStreamStop(self.codexStream);
|
|
151
|
+
FSEventStreamInvalidate(self.codexStream);
|
|
152
|
+
FSEventStreamRelease(self.codexStream);
|
|
153
|
+
self.codexStream = NULL;
|
|
154
|
+
}
|
|
155
|
+
if (self.claudeSource) {
|
|
156
|
+
dispatch_source_cancel(self.claudeSource);
|
|
157
|
+
self.claudeSource = nil;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
- (void)dealloc {
|
|
161
|
+
[self stop];
|
|
162
|
+
}
|
|
163
|
+
@end
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
#ifndef CC_PETS_VERSION
|
|
4
|
+
#define CC_PETS_VERSION "unknown"
|
|
5
|
+
#endif
|
|
6
|
+
|
|
7
|
+
// 只接受严格的三段纯数字版本号;valid 为 NO 时返回值无意义。
|
|
8
|
+
// 自动更新会把比较结果作为是否升级的唯一依据,所以这里刻意不接受预发布号。
|
|
9
|
+
NSComparisonResult CompareStableVersions(NSString *left, NSString *right, BOOL *valid);
|
|
10
|
+
int RestartAfterPID(pid_t pid, NSString *appPath, BOOL managed);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#import "CCPetsVersion.h"
|
|
2
|
+
#import <signal.h>
|
|
3
|
+
#import <unistd.h>
|
|
4
|
+
#import <errno.h>
|
|
5
|
+
|
|
6
|
+
static NSArray<NSNumber *> *StableVersionComponents(NSString *version) {
|
|
7
|
+
if (![version isKindOfClass:NSString.class]) return nil;
|
|
8
|
+
NSArray<NSString *> *parts = [version componentsSeparatedByString:@"."];
|
|
9
|
+
if (parts.count != 3) return nil;
|
|
10
|
+
NSCharacterSet *nonDigits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet;
|
|
11
|
+
NSMutableArray<NSNumber *> *components = [NSMutableArray arrayWithCapacity:3];
|
|
12
|
+
for (NSString *part in parts) {
|
|
13
|
+
if (part.length == 0 || part.length > 9 ||
|
|
14
|
+
(part.length > 1 && [part hasPrefix:@"0"]) ||
|
|
15
|
+
[part rangeOfCharacterFromSet:nonDigits].location != NSNotFound) return nil;
|
|
16
|
+
[components addObject:@(part.longLongValue)];
|
|
17
|
+
}
|
|
18
|
+
return components;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
NSComparisonResult CompareStableVersions(NSString *left, NSString *right, BOOL *valid) {
|
|
22
|
+
NSArray<NSNumber *> *leftParts = StableVersionComponents(left);
|
|
23
|
+
NSArray<NSNumber *> *rightParts = StableVersionComponents(right);
|
|
24
|
+
if (!leftParts || !rightParts) {
|
|
25
|
+
if (valid) *valid = NO;
|
|
26
|
+
return NSOrderedSame;
|
|
27
|
+
}
|
|
28
|
+
if (valid) *valid = YES;
|
|
29
|
+
for (NSUInteger index = 0; index < 3; index++) {
|
|
30
|
+
long long leftValue = leftParts[index].longLongValue;
|
|
31
|
+
long long rightValue = rightParts[index].longLongValue;
|
|
32
|
+
if (leftValue < rightValue) return NSOrderedAscending;
|
|
33
|
+
if (leftValue > rightValue) return NSOrderedDescending;
|
|
34
|
+
}
|
|
35
|
+
return NSOrderedSame;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
int RestartAfterPID(pid_t pid, NSString *appPath, BOOL managed) {
|
|
39
|
+
for (NSUInteger attempt = 0; attempt < 300; attempt++) {
|
|
40
|
+
if (pid <= 1 || (kill(pid, 0) != 0 && errno == ESRCH)) break;
|
|
41
|
+
usleep(100000);
|
|
42
|
+
}
|
|
43
|
+
if (pid > 1 && (kill(pid, 0) == 0 || errno == EPERM)) {
|
|
44
|
+
fprintf(stderr, "等待旧版 CC Pets 退出超时。\n");
|
|
45
|
+
return EXIT_FAILURE;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
NSString *openPath = NSProcessInfo.processInfo.environment[@"CC_PETS_OPEN_PATH"];
|
|
49
|
+
if (openPath.length == 0) openPath = @"/usr/bin/open";
|
|
50
|
+
NSTask *task = [NSTask new];
|
|
51
|
+
task.executableURL = [NSURL fileURLWithPath:openPath];
|
|
52
|
+
NSMutableArray<NSString *> *arguments = [NSMutableArray arrayWithObjects:@"-g", appPath, nil];
|
|
53
|
+
if (managed) [arguments addObjectsFromArray:@[@"--args", @"--managed"]];
|
|
54
|
+
task.arguments = arguments;
|
|
55
|
+
NSError *error = nil;
|
|
56
|
+
if (![task launchAndReturnError:&error]) {
|
|
57
|
+
fprintf(stderr, "无法重新启动 CC Pets: %s\n", error.localizedDescription.UTF8String);
|
|
58
|
+
return EXIT_FAILURE;
|
|
59
|
+
}
|
|
60
|
+
[task waitUntilExit];
|
|
61
|
+
return task.terminationStatus == EXIT_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
|
|
62
|
+
}
|