cc-pets 0.2.7 → 0.2.8

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.
Files changed (2) hide show
  1. package/Sources/CCPets/main.m +243 -38
  2. package/package.json +1 -1
@@ -5,6 +5,7 @@
5
5
  #endif
6
6
  #import <sys/file.h>
7
7
  #import <sys/stat.h>
8
+ #import <fcntl.h>
8
9
  #import <signal.h>
9
10
 
10
11
  static NSString *PetStateDirectory(void) {
@@ -85,14 +86,12 @@ static int RecordHookEvent(void) {
85
86
  return EXIT_SUCCESS;
86
87
  }
87
88
 
88
- static NSDictionary *LatestUsage(void) {
89
- NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
90
- if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
91
- NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
89
+ static NSURL *NewestCodexSessionURL(NSURL *directory, BOOL recursive) {
90
+ NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsHiddenFiles;
91
+ if (!recursive) options |= NSDirectoryEnumerationSkipsSubdirectoryDescendants;
92
92
  NSArray *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
93
- NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:sessions
94
- includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles
95
- errorHandler:nil];
93
+ NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:directory
94
+ includingPropertiesForKeys:keys options:options errorHandler:nil];
96
95
  NSURL *newest = nil;
97
96
  NSDate *newestDate = NSDate.distantPast;
98
97
  for (NSURL *url in files) {
@@ -105,6 +104,50 @@ static NSDictionary *LatestUsage(void) {
105
104
  newestDate = date;
106
105
  }
107
106
  }
107
+ return newest;
108
+ }
109
+
110
+ static NSDictionary *UsageFromCodexLine(NSData *lineData) {
111
+ if (lineData.length == 0) return nil;
112
+ NSString *line = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
113
+ if (!line || [line rangeOfString:@"\"type\":\"token_count\""].location == NSNotFound) return nil;
114
+ NSDictionary *root = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
115
+ NSDictionary *payload = root[@"payload"];
116
+ if (![payload[@"type"] isEqualToString:@"token_count"]) return nil;
117
+ NSDictionary *limits = payload[@"rate_limits"];
118
+ id primaryValue = limits[@"primary"];
119
+ id secondaryValue = limits[@"secondary"];
120
+ NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
121
+ NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
122
+ NSDictionary *fiveHour = nil;
123
+ NSDictionary *week = nil;
124
+ for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
125
+ NSInteger minutes = [quota[@"window_minutes"] integerValue];
126
+ if (minutes == 300) fiveHour = quota;
127
+ if (minutes == 10080) week = quota;
128
+ }
129
+ return @{
130
+ @"fiveHour": fiveHour ?: NSNull.null,
131
+ @"week": week ?: NSNull.null
132
+ };
133
+ }
134
+
135
+ static NSDictionary *LatestUsageInData(NSData *data) {
136
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
137
+ if (!text) return nil;
138
+ NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
139
+ for (NSString *line in lines.reverseObjectEnumerator) {
140
+ NSDictionary *usage = UsageFromCodexLine([line dataUsingEncoding:NSUTF8StringEncoding]);
141
+ if (usage) return usage;
142
+ }
143
+ return nil;
144
+ }
145
+
146
+ static NSDictionary *LatestUsage(void) {
147
+ NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
148
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
149
+ NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
150
+ NSURL *newest = NewestCodexSessionURL(sessions, YES);
108
151
  if (!newest) return nil;
109
152
 
110
153
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:newest error:nil];
@@ -113,33 +156,114 @@ static NSDictionary *LatestUsage(void) {
113
156
  [handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
114
157
  NSData *tail = [handle readDataToEndOfFile];
115
158
  [handle closeFile];
116
- NSString *text = [[NSString alloc] initWithData:tail encoding:NSUTF8StringEncoding];
117
- NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
118
- for (NSString *line in lines.reverseObjectEnumerator) {
119
- if ([line rangeOfString:@"\"type\":\"token_count\""].location == NSNotFound) continue;
120
- NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding];
121
- NSDictionary *root = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
122
- NSDictionary *payload = root[@"payload"];
123
- if (![payload[@"type"] isEqualToString:@"token_count"]) continue;
124
- NSDictionary *limits = payload[@"rate_limits"];
125
- id primaryValue = limits[@"primary"];
126
- id secondaryValue = limits[@"secondary"];
127
- NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
128
- NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
129
- NSDictionary *fiveHour = nil;
130
- NSDictionary *week = nil;
131
- for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
132
- NSInteger minutes = [quota[@"window_minutes"] integerValue];
133
- if (minutes == 300) fiveHour = quota;
134
- if (minutes == 10080) week = quota;
159
+ return LatestUsageInData(tail);
160
+ }
161
+
162
+ @interface CodexUsageReader : NSObject
163
+ @property NSURL *sessionsURL;
164
+ @property NSURL *sessionURL;
165
+ @property NSDictionary *usage;
166
+ @property unsigned long long offset;
167
+ @property NSMutableData *partialLine;
168
+ @property NSTimeInterval lastFullDiscovery;
169
+ - (NSDictionary *)refresh;
170
+ @end
171
+
172
+ @implementation CodexUsageReader
173
+ - (instancetype)init {
174
+ if ((self = [super init])) {
175
+ NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
176
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
177
+ _sessionsURL = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
178
+ _partialLine = [NSMutableData data];
179
+ }
180
+ return self;
181
+ }
182
+ - (void)selectSessionURL:(NSURL *)url {
183
+ self.sessionURL = url;
184
+ self.offset = 0;
185
+ [self.partialLine setLength:0];
186
+ if (!url) {
187
+ self.usage = nil;
188
+ return;
189
+ }
190
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
191
+ if (!handle) return;
192
+ unsigned long long size = [handle seekToEndOfFile];
193
+ unsigned long long start = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
194
+ [handle seekToFileOffset:start];
195
+ NSData *tail = [handle readDataToEndOfFile];
196
+ [handle closeFile];
197
+ self.offset = start + tail.length;
198
+ self.usage = LatestUsageInData(tail);
199
+
200
+ const uint8_t *bytes = tail.bytes;
201
+ NSUInteger lastNewline = NSNotFound;
202
+ for (NSUInteger index = tail.length; index > 0; index--) {
203
+ if (bytes[index - 1] == '\n') {
204
+ lastNewline = index - 1;
205
+ break;
135
206
  }
136
- return @{
137
- @"fiveHour": fiveHour ?: NSNull.null,
138
- @"week": week ?: NSNull.null
139
- };
140
207
  }
141
- return nil;
208
+ if (lastNewline == NSNotFound) [self.partialLine appendData:tail];
209
+ else if (lastNewline + 1 < tail.length) {
210
+ [self.partialLine appendData:[tail subdataWithRange:NSMakeRange(lastNewline + 1, tail.length - lastNewline - 1)]];
211
+ }
212
+ }
213
+ - (void)consumeIncrementalData:(NSData *)data {
214
+ if (data.length == 0) return;
215
+ [self.partialLine appendData:data];
216
+ const uint8_t *bytes = self.partialLine.bytes;
217
+ NSUInteger lineStart = 0;
218
+ for (NSUInteger index = 0; index < self.partialLine.length; index++) {
219
+ if (bytes[index] != '\n') continue;
220
+ NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
221
+ NSDictionary *newUsage = UsageFromCodexLine(line);
222
+ if (newUsage) self.usage = newUsage;
223
+ lineStart = index + 1;
224
+ }
225
+ if (lineStart > 0) {
226
+ NSData *remainder = [self.partialLine subdataWithRange:
227
+ NSMakeRange(lineStart, self.partialLine.length - lineStart)];
228
+ self.partialLine = [remainder mutableCopy];
229
+ }
230
+ if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
231
+ }
232
+ - (NSDictionary *)refresh {
233
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
234
+ BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
235
+ NSURL *candidate = nil;
236
+ if (needsFullDiscovery) {
237
+ candidate = NewestCodexSessionURL(self.sessionsURL, YES);
238
+ self.lastFullDiscovery = now;
239
+ } else {
240
+ candidate = NewestCodexSessionURL(self.sessionURL.URLByDeletingLastPathComponent, NO);
241
+ }
242
+ if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
243
+ if (!self.sessionURL) return self.usage;
244
+
245
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
246
+ if (!handle) {
247
+ self.lastFullDiscovery = 0;
248
+ return self.usage;
249
+ }
250
+ unsigned long long size = [handle seekToEndOfFile];
251
+ if (size < self.offset) {
252
+ [handle closeFile];
253
+ [self selectSessionURL:self.sessionURL];
254
+ return self.usage;
255
+ }
256
+ if (size > self.offset) {
257
+ unsigned long long start = self.offset;
258
+ [handle seekToFileOffset:start];
259
+ NSData *newData = [handle readDataToEndOfFile];
260
+ self.offset = start + newData.length;
261
+ [self consumeIncrementalData:newData];
262
+ }
263
+ [handle closeFile];
264
+ return self.usage;
142
265
  }
266
+ @end
143
267
 
144
268
  @interface PetView : NSView
145
269
  @property NSImage *sheet;
@@ -724,7 +848,11 @@ static int RenderQuotaDashboard(NSString *path) {
724
848
  @property BOOL petDragging;
725
849
  @property NSString *binaryDirectory;
726
850
  @property PetView *petView;
851
+ @property CodexUsageReader *codexUsageReader;
727
852
  @property unsigned long long agentEventOffset;
853
+ @property NSMutableData *agentEventPartialLine;
854
+ @property dispatch_source_t agentEventSource;
855
+ @property BOOL agentEventReaderInitialized;
728
856
  - (void)showQuotaDashboard;
729
857
  - (void)positionQuotaDashboard;
730
858
  - (void)scheduleQuotaDashboardHide;
@@ -938,6 +1066,8 @@ static int RenderQuotaDashboard(NSString *path) {
938
1066
  NSRect visible = screen.visibleFrame;
939
1067
  [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
940
1068
  [self.panel orderFrontRegardless];
1069
+ self.codexUsageReader = [CodexUsageReader new];
1070
+ self.agentEventPartialLine = [NSMutableData data];
941
1071
  [self refreshUsage:nil];
942
1072
  if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
943
1073
  self.pocketHovering = YES;
@@ -946,8 +1076,9 @@ static int RenderQuotaDashboard(NSString *path) {
946
1076
  [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
947
1077
  [self refreshClientLifecycle:nil];
948
1078
  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshClientLifecycle:) userInfo:nil repeats:YES];
949
- [self prepareAgentEventReader];
950
- [NSTimer scheduledTimerWithTimeInterval:0.15 target:self selector:@selector(pollAgentEvents:) userInfo:nil repeats:YES];
1079
+ [self startAgentEventReader];
1080
+ [NSTimer scheduledTimerWithTimeInterval:5 target:self
1081
+ selector:@selector(ensureAgentEventReader:) userInfo:nil repeats:YES];
951
1082
  }
952
1083
  - (void)showQuotaDashboard {
953
1084
  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
@@ -986,6 +1117,15 @@ static int RenderQuotaDashboard(NSString *path) {
986
1117
  NSString *path = AgentEventPath();
987
1118
  NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
988
1119
  unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
1120
+ if (self.agentEventReaderInitialized) {
1121
+ if (size < self.agentEventOffset) {
1122
+ self.agentEventOffset = 0;
1123
+ [self.agentEventPartialLine setLength:0];
1124
+ }
1125
+ [self readNewAgentEvents];
1126
+ return;
1127
+ }
1128
+ self.agentEventReaderInitialized = YES;
989
1129
  self.agentEventOffset = size;
990
1130
  if (size > 0) {
991
1131
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
@@ -996,6 +1136,24 @@ static int RenderQuotaDashboard(NSString *path) {
996
1136
  [self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
997
1137
  }
998
1138
  }
1139
+ - (void)consumeAgentEventData:(NSData *)data {
1140
+ if (data.length == 0) return;
1141
+ [self.agentEventPartialLine appendData:data];
1142
+ const uint8_t *bytes = self.agentEventPartialLine.bytes;
1143
+ NSUInteger lineStart = 0;
1144
+ for (NSUInteger index = 0; index < self.agentEventPartialLine.length; index++) {
1145
+ if (bytes[index] != '\n') continue;
1146
+ NSData *lineData = [self.agentEventPartialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
1147
+ [self processAgentEventData:lineData ignoreFirstPartial:NO recentOnly:NO];
1148
+ lineStart = index + 1;
1149
+ }
1150
+ if (lineStart > 0) {
1151
+ NSData *remainder = [self.agentEventPartialLine subdataWithRange:
1152
+ NSMakeRange(lineStart, self.agentEventPartialLine.length - lineStart)];
1153
+ self.agentEventPartialLine = [remainder mutableCopy];
1154
+ }
1155
+ if (self.agentEventPartialLine.length > 1024 * 1024) [self.agentEventPartialLine setLength:0];
1156
+ }
999
1157
  - (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
1000
1158
  NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
1001
1159
  if (!text) return;
@@ -1015,7 +1173,7 @@ static int RenderQuotaDashboard(NSString *path) {
1015
1173
  }
1016
1174
  }
1017
1175
  }
1018
- - (void)pollAgentEvents:(id)sender {
1176
+ - (void)readNewAgentEvents {
1019
1177
  NSString *path = AgentEventPath();
1020
1178
  NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
1021
1179
  unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
@@ -1023,11 +1181,52 @@ static int RenderQuotaDashboard(NSString *path) {
1023
1181
  if (size == self.agentEventOffset) return;
1024
1182
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1025
1183
  if (!handle) return;
1026
- [handle seekToFileOffset:self.agentEventOffset];
1184
+ unsigned long long start = self.agentEventOffset;
1185
+ [handle seekToFileOffset:start];
1027
1186
  NSData *data = [handle readDataToEndOfFile];
1028
1187
  [handle closeFile];
1029
- self.agentEventOffset = size;
1030
- [self processAgentEventData:data ignoreFirstPartial:NO recentOnly:NO];
1188
+ self.agentEventOffset = start + data.length;
1189
+ [self consumeAgentEventData:data];
1190
+ }
1191
+ - (void)startAgentEventReader {
1192
+ if (self.agentEventSource) return;
1193
+ NSString *path = AgentEventPath();
1194
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
1195
+ withIntermediateDirectories:YES attributes:nil error:nil];
1196
+ int creator = open(path.fileSystemRepresentation, O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR);
1197
+ if (creator >= 0) close(creator);
1198
+ int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
1199
+ if (descriptor < 0) return;
1200
+ dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
1201
+ DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
1202
+ DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
1203
+ dispatch_get_main_queue());
1204
+ if (!source) {
1205
+ close(descriptor);
1206
+ return;
1207
+ }
1208
+ self.agentEventSource = source;
1209
+ __weak typeof(self) weakSelf = self;
1210
+ dispatch_source_set_event_handler(source, ^{
1211
+ typeof(self) strongSelf = weakSelf;
1212
+ if (!strongSelf) return;
1213
+ dispatch_source_t currentSource = strongSelf.agentEventSource;
1214
+ if (!currentSource) return;
1215
+ unsigned long flags = dispatch_source_get_data(currentSource);
1216
+ [strongSelf readNewAgentEvents];
1217
+ if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
1218
+ strongSelf.agentEventSource = nil;
1219
+ dispatch_source_cancel(currentSource);
1220
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
1221
+ dispatch_get_main_queue(), ^{ [weakSelf startAgentEventReader]; });
1222
+ }
1223
+ });
1224
+ dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
1225
+ dispatch_resume(source);
1226
+ [self prepareAgentEventReader];
1227
+ }
1228
+ - (void)ensureAgentEventReader:(id)sender {
1229
+ if (!self.agentEventSource) [self startAgentEventReader];
1031
1230
  }
1032
1231
  - (void)refreshClientLifecycle:(id)sender {
1033
1232
  NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
@@ -1049,10 +1248,16 @@ static int RenderQuotaDashboard(NSString *path) {
1049
1248
  if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
1050
1249
  }
1051
1250
  - (void)refreshUsage:(id)sender {
1052
- self.quotaView.codexUsage = LatestUsage();
1251
+ self.quotaView.codexUsage = [self.codexUsageReader refresh];
1053
1252
  self.quotaView.claudeUsage = LatestClaudeUsage();
1054
1253
  self.quotaView.needsDisplay = YES;
1055
1254
  }
1255
+ - (void)applicationWillTerminate:(NSNotification *)notification {
1256
+ if (self.agentEventSource) {
1257
+ dispatch_source_cancel(self.agentEventSource);
1258
+ self.agentEventSource = nil;
1259
+ }
1260
+ }
1056
1261
  @end
1057
1262
 
1058
1263
  int main(int argc, const char *argv[]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",