cc-pets 2.0.0 → 2.0.3

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 (37) hide show
  1. package/CHANGELOG.md +73 -30
  2. package/CHANGELOG.zh-CN.md +90 -0
  3. package/CONTRIBUTING.md +18 -15
  4. package/CONTRIBUTING.zh-CN.md +22 -0
  5. package/LICENSE +1 -1
  6. package/PROVIDER_PROTOCOL.md +50 -41
  7. package/PROVIDER_PROTOCOL.zh-CN.md +58 -0
  8. package/README.md +240 -502
  9. package/README.zh-CN.md +617 -0
  10. package/Resources/Info.plist +2 -0
  11. package/Resources/phrases.default.txt +48 -49
  12. package/SECURITY.md +13 -10
  13. package/SECURITY.zh-CN.md +18 -0
  14. package/Sources/CCPets/CCPetsAppDelegate.h +12 -0
  15. package/Sources/CCPets/CCPetsAppDelegate.m +400 -37
  16. package/Sources/CCPets/CCPetsCodexRateLimits.h +13 -0
  17. package/Sources/CCPets/CCPetsCodexRateLimits.m +383 -0
  18. package/Sources/CCPets/CCPetsEvents.m +7 -2
  19. package/Sources/CCPets/CCPetsPaths.h +4 -0
  20. package/Sources/CCPets/CCPetsPaths.m +6 -0
  21. package/Sources/CCPets/CCPetsPhrases.h +1 -24
  22. package/Sources/CCPets/CCPetsPhrases.m +1 -82
  23. package/Sources/CCPets/CCPetsPhrasesEditor.m +0 -28
  24. package/Sources/CCPets/CCPetsQuotaHistory.m +12 -5
  25. package/Sources/CCPets/CCPetsTerminalFocus.h +11 -0
  26. package/Sources/CCPets/CCPetsTerminalFocus.m +150 -0
  27. package/Sources/CCPets/CCPetsUsage.m +135 -14
  28. package/Sources/CCPets/CCPetsUsageMonitor.m +41 -3
  29. package/Sources/CCPets/PetView.m +19 -11
  30. package/Sources/CCPets/QuotaDashboardView.m +38 -16
  31. package/Sources/CCPets/main.m +5 -0
  32. package/THIRD_PARTY_NOTICES.md +13 -7
  33. package/THIRD_PARTY_NOTICES.zh-CN.md +12 -0
  34. package/bin/claude-with-pet +8 -2
  35. package/bin/codex-with-pet +8 -3
  36. package/package.json +14 -5
  37. package/scripts/pet-store.mjs +1 -1
@@ -0,0 +1,383 @@
1
+ #import "CCPetsCodexRateLimits.h"
2
+ #import "CCPetsPaths.h"
3
+ #import "CCPetsVersion.h"
4
+
5
+ static const NSTimeInterval CodexRateLimitRequestTimeout = 20.0;
6
+ static char CodexRateLimitsQueueKey;
7
+
8
+ static NSNumber *NumberForKeys(NSDictionary *dictionary, NSArray<NSString *> *keys) {
9
+ for (NSString *key in keys) {
10
+ id value = dictionary[key];
11
+ if ([value isKindOfClass:NSNumber.class]) return value;
12
+ }
13
+ return nil;
14
+ }
15
+
16
+ static NSDictionary *QuotaFromAppServerWindow(NSDictionary *window) {
17
+ if (![window isKindOfClass:NSDictionary.class]) return nil;
18
+ NSNumber *used = NumberForKeys(window, @[@"usedPercent", @"used_percent"]);
19
+ NSNumber *minutes = NumberForKeys(window, @[@"windowDurationMins", @"window_minutes"]);
20
+ NSNumber *reset = NumberForKeys(window, @[@"resetsAt", @"resets_at"]);
21
+ if (!used && !minutes && !reset) return nil;
22
+ NSMutableDictionary *quota = [NSMutableDictionary dictionary];
23
+ if (used) quota[@"used_percent"] = @(fmax(0, fmin(100, used.doubleValue)));
24
+ if (minutes) quota[@"window_minutes"] = minutes;
25
+ if (reset) quota[@"resets_at"] = reset;
26
+ return quota;
27
+ }
28
+
29
+ static BOOL RateLimitReached(id value) {
30
+ if (!value || value == NSNull.null) return NO;
31
+ if ([value isKindOfClass:NSNumber.class]) return [value boolValue];
32
+ if ([value isKindOfClass:NSString.class]) return ((NSString *)value).length > 0;
33
+ return YES;
34
+ }
35
+
36
+ // App Server 以 camelCase 返回额度。按 windowDurationMins 分窗而不是假设 primary/
37
+ // secondary 的位置,这样服务端将来调整字段顺序时,5 小时和 7 天也不会被画反。
38
+ //
39
+ // 分窗结果决定了要不要写 NSNull:账号确实没有某个窗口时,用 NSNull 盖掉会话里的陈旧
40
+ // 快照是对的;但一个窗口都没认出来(服务端改了窗长、或响应里缺 windowDurationMins)
41
+ // 时再盖,就等于用一次解析失败清空本来可用的数据——那比不读实时额度还糟。所以两个窗口
42
+ // 全没命中时只回传受限状态,让会话快照继续兜底。
43
+ static NSDictionary *LiveUsageFromRateLimitBucket(NSDictionary *bucket) {
44
+ if (![bucket isKindOfClass:NSDictionary.class]) return nil;
45
+ NSString *limitID = [bucket[@"limitId"] isKindOfClass:NSString.class]
46
+ ? bucket[@"limitId"] : nil;
47
+ if (limitID.length > 0 && ![limitID hasPrefix:@"codex"]) return nil;
48
+
49
+ NSDictionary *fiveHour = nil;
50
+ NSDictionary *week = nil;
51
+ for (id value in @[bucket[@"primary"] ?: NSNull.null,
52
+ bucket[@"secondary"] ?: NSNull.null]) {
53
+ NSDictionary *quota = QuotaFromAppServerWindow(value);
54
+ NSInteger minutes = [quota[@"window_minutes"] integerValue];
55
+ if (minutes == 300) fiveHour = quota;
56
+ else if (minutes == 10080) week = quota;
57
+ }
58
+
59
+ BOOL exhausted = RateLimitReached(bucket[@"rateLimitReachedType"]);
60
+ if (!fiveHour && !week && !exhausted) return nil;
61
+
62
+ NSNumber *sampledAt = @(NSDate.date.timeIntervalSince1970);
63
+ NSMutableDictionary *usage = [@{@"sampledAt": sampledAt} mutableCopy];
64
+ if (fiveHour || week) {
65
+ usage[@"fiveHour"] = fiveHour ?: NSNull.null;
66
+ usage[@"week"] = week ?: NSNull.null;
67
+ }
68
+ if (exhausted) {
69
+ // 服务端已分类为额度受限时,不能让一次成功请求留下的百分比继续显示为可用。
70
+ usage[@"exhaustedAt"] = sampledAt;
71
+ }
72
+ return usage;
73
+ }
74
+
75
+ static NSDictionary *LiveUsageFromRateLimitResponse(NSDictionary *result) {
76
+ if (![result isKindOfClass:NSDictionary.class]) return nil;
77
+ NSDictionary *byLimitID = [result[@"rateLimitsByLimitId"] isKindOfClass:NSDictionary.class]
78
+ ? result[@"rateLimitsByLimitId"] : nil;
79
+ NSDictionary *fallback = [result[@"rateLimits"] isKindOfClass:NSDictionary.class]
80
+ ? result[@"rateLimits"] : nil;
81
+ NSDictionary *codex = [byLimitID[@"codex"] isKindOfClass:NSDictionary.class]
82
+ ? byLimitID[@"codex"] : nil;
83
+ // 单桶视图由当前 Codex 客户端选择,是最接近终端 /status 的口径;多桶对象只在
84
+ // 服务端未给单桶视图时才作为兼容兜底。
85
+ return LiveUsageFromRateLimitBucket(fallback ?: codex);
86
+ }
87
+
88
+ static BOOL IsCCPetsCodexWrapper(NSString *path) {
89
+ NSString *resolved = path.stringByResolvingSymlinksInPath.stringByStandardizingPath;
90
+ if ([resolved.lastPathComponent isEqualToString:@"codex-with-pet"]) return YES;
91
+ NSString *shims = [[NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets/shims"]
92
+ stringByStandardizingPath];
93
+ return [resolved hasPrefix:[shims stringByAppendingString:@"/"]];
94
+ }
95
+
96
+ static BOOL IsUsableCodexExecutable(NSString *path) {
97
+ return path.length > 0 && [NSFileManager.defaultManager isExecutableFileAtPath:path] &&
98
+ !IsCCPetsCodexWrapper(path);
99
+ }
100
+
101
+ static NSString *CodexAppServerExecutablePath(void) {
102
+ NSDictionary *environment = NSProcessInfo.processInfo.environment;
103
+ for (NSString *key in @[@"CC_PETS_CODEX_BIN", @"CODEX_REAL_BIN"]) {
104
+ id value = environment[key];
105
+ NSString *path = [value isKindOfClass:NSString.class]
106
+ ? [value stringByStandardizingPath] : nil;
107
+ if (IsUsableCodexExecutable(path)) return path;
108
+ }
109
+
110
+ NSMutableOrderedSet<NSString *> *directories = [NSMutableOrderedSet orderedSet];
111
+ for (NSString *path in [environment[@"PATH"] componentsSeparatedByString:@":"]) {
112
+ if (path.length > 0) [directories addObject:path.stringByStandardizingPath];
113
+ }
114
+ for (NSString *path in @[
115
+ [NSHomeDirectory() stringByAppendingPathComponent:@".local/bin"],
116
+ [NSHomeDirectory() stringByAppendingPathComponent:@".npm-global/bin"],
117
+ [NSHomeDirectory() stringByAppendingPathComponent:@".npm/bin"],
118
+ @"/opt/homebrew/bin", @"/usr/local/bin", @"/usr/bin", @"/bin"
119
+ ]) [directories addObject:path.stringByStandardizingPath];
120
+
121
+ // Finder 拉起的 App 通常没有终端里的 nvm PATH。补上已安装 Node 版本的 bin 目录,
122
+ // 同时仍跳过 CC Pets 自己的 codex shim,避免 app-server 反过来再启动桌宠。
123
+ NSString *nvmVersions = [NSHomeDirectory() stringByAppendingPathComponent:@".nvm/versions/node"];
124
+ NSArray<NSString *> *versions = [[NSFileManager.defaultManager
125
+ contentsOfDirectoryAtPath:nvmVersions error:nil]
126
+ sortedArrayUsingComparator:^NSComparisonResult(NSString *left, NSString *right) {
127
+ return [right compare:left options:NSNumericSearch];
128
+ }];
129
+ for (NSString *version in versions) {
130
+ [directories addObject:[[nvmVersions stringByAppendingPathComponent:version]
131
+ stringByAppendingPathComponent:@"bin"]];
132
+ }
133
+
134
+ for (NSString *directory in directories) {
135
+ NSString *candidate = [directory stringByAppendingPathComponent:@"codex"];
136
+ if (IsUsableCodexExecutable(candidate)) return candidate;
137
+ }
138
+ return nil;
139
+ }
140
+
141
+ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString *executablePath) {
142
+ NSMutableDictionary<NSString *, NSString *> *environment =
143
+ [NSProcessInfo.processInfo.environment mutableCopy];
144
+ NSMutableOrderedSet<NSString *> *paths = [NSMutableOrderedSet orderedSet];
145
+ if (executablePath.stringByDeletingLastPathComponent.length > 0) {
146
+ [paths addObject:executablePath.stringByDeletingLastPathComponent];
147
+ }
148
+ for (NSString *path in [environment[@"PATH"] componentsSeparatedByString:@":"]) {
149
+ if (path.length == 0 || IsCCPetsCodexWrapper([path stringByAppendingPathComponent:@"codex"])) continue;
150
+ [paths addObject:path];
151
+ }
152
+ environment[@"PATH"] = [paths.array componentsJoinedByString:@":"];
153
+ // 与会话扫描使用同一份配置目录,避免备用 CODEX_HOME 下的账号被错读成默认账号。
154
+ environment[@"CODEX_HOME"] = DefaultCodexHomeDirectory();
155
+ return environment;
156
+ }
157
+
158
+ @interface CCPetsCodexRateLimitsReader ()
159
+ @property dispatch_queue_t queue;
160
+ @property NSTask *task;
161
+ @property NSFileHandle *input;
162
+ @property NSFileHandle *output;
163
+ @property NSMutableData *partialOutput;
164
+ @property NSInteger nextRequestID;
165
+ @property NSInteger pendingRequestID;
166
+ @property BOOL stopped;
167
+ @end
168
+
169
+ @implementation CCPetsCodexRateLimitsReader
170
+
171
+ - (instancetype)init {
172
+ if ((self = [super init])) {
173
+ _queue = dispatch_queue_create("com.universewang.cc-pets.codex-rate-limits",
174
+ DISPATCH_QUEUE_SERIAL);
175
+ dispatch_queue_set_specific(_queue, &CodexRateLimitsQueueKey, (__bridge void *)self, NULL);
176
+ _partialOutput = [NSMutableData data];
177
+ _nextRequestID = 2; // 1 留给 initialize。
178
+ }
179
+ return self;
180
+ }
181
+
182
+ - (void)refresh {
183
+ __weak typeof(self) weakSelf = self;
184
+ dispatch_async(self.queue, ^{ [weakSelf refreshOnQueue]; });
185
+ }
186
+
187
+ - (void)stop {
188
+ void (^stopOnQueue)(void) = ^{
189
+ self.stopped = YES;
190
+ [self stopTaskOnQueue];
191
+ };
192
+ if (dispatch_get_specific(&CodexRateLimitsQueueKey) == (__bridge void *)self) {
193
+ stopOnQueue();
194
+ } else {
195
+ dispatch_sync(self.queue, stopOnQueue);
196
+ }
197
+ }
198
+
199
+ - (BOOL)sendMessageOnQueue:(NSDictionary *)message {
200
+ if (!self.input || !message) return NO;
201
+ NSData *data = [NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
202
+ if (!data) return NO;
203
+ NSMutableData *line = [data mutableCopy];
204
+ [line appendData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];
205
+ @try {
206
+ [self.input writeData:line];
207
+ return YES;
208
+ } @catch (NSException *exception) {
209
+ return NO;
210
+ }
211
+ }
212
+
213
+ - (BOOL)ensureTaskOnQueue {
214
+ if (self.task.running) return YES;
215
+ NSString *path = CodexAppServerExecutablePath();
216
+ if (path.length == 0) return NO;
217
+
218
+ NSTask *task = [NSTask new];
219
+ NSPipe *inputPipe = [NSPipe pipe];
220
+ NSPipe *outputPipe = [NSPipe pipe];
221
+ task.executableURL = [NSURL fileURLWithPath:path];
222
+ task.arguments = @[@"app-server", @"--stdio"];
223
+ task.environment = CodexAppServerEnvironment(path);
224
+ task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
225
+ task.standardInput = inputPipe;
226
+ task.standardOutput = outputPipe;
227
+ task.standardError = [NSFileHandle fileHandleForWritingAtPath:@"/dev/null"];
228
+
229
+ __weak typeof(self) weakSelf = self;
230
+ // 两个回调都跑在后台线程,与 dealloc -> stop 清理回调之间存在竞态窗口。reader 已经
231
+ // 释放时 weakSelf.queue 是 nil,而 dispatch_async 到 NULL 队列会直接崩,所以必须先
232
+ // strongify 再判空,不能图省事写成 dispatch_async(weakSelf.queue, ...)。
233
+ outputPipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *handle) {
234
+ NSData *data = handle.availableData;
235
+ typeof(self) strongSelf = weakSelf;
236
+ if (!strongSelf) {
237
+ handle.readabilityHandler = nil;
238
+ return;
239
+ }
240
+ dispatch_async(strongSelf.queue, ^{
241
+ [weakSelf consumeOutputDataOnQueue:data fromHandle:handle];
242
+ });
243
+ };
244
+ task.terminationHandler = ^(NSTask *finishedTask) {
245
+ typeof(self) strongSelf = weakSelf;
246
+ if (!strongSelf) return;
247
+ dispatch_async(strongSelf.queue, ^{ [weakSelf taskDidTerminateOnQueue:finishedTask]; });
248
+ };
249
+
250
+ NSError *error = nil;
251
+ if (![task launchAndReturnError:&error]) {
252
+ outputPipe.fileHandleForReading.readabilityHandler = nil;
253
+ return NO;
254
+ }
255
+ self.task = task;
256
+ self.input = inputPipe.fileHandleForWriting;
257
+ self.output = outputPipe.fileHandleForReading;
258
+ [self.partialOutput setLength:0];
259
+ NSDictionary *initialize = @{
260
+ @"method": @"initialize", @"id": @1,
261
+ @"params": @{ @"clientInfo": @{
262
+ @"name": @"cc_pets", @"title": @"CC Pets", @"version": @CC_PETS_VERSION
263
+ }}
264
+ };
265
+ if (![self sendMessageOnQueue:initialize] ||
266
+ ![self sendMessageOnQueue:@{ @"method": @"initialized", @"params": @{} }]) {
267
+ [self stopTaskOnQueue];
268
+ return NO;
269
+ }
270
+ return YES;
271
+ }
272
+
273
+ - (void)refreshOnQueue {
274
+ if (self.stopped || self.pendingRequestID != 0 || ![self ensureTaskOnQueue]) return;
275
+ NSInteger requestID = self.nextRequestID++;
276
+ self.pendingRequestID = requestID;
277
+ if (![self sendMessageOnQueue:@{ @"method": @"account/rateLimits/read", @"id": @(requestID) }]) {
278
+ self.pendingRequestID = 0;
279
+ [self stopTaskOnQueue];
280
+ return;
281
+ }
282
+ __weak typeof(self) weakSelf = self;
283
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
284
+ (int64_t)(CodexRateLimitRequestTimeout * NSEC_PER_SEC)), self.queue, ^{
285
+ typeof(self) strongSelf = weakSelf;
286
+ if (!strongSelf || strongSelf.pendingRequestID != requestID) return;
287
+ strongSelf.pendingRequestID = 0;
288
+ [strongSelf stopTaskOnQueue];
289
+ });
290
+ }
291
+
292
+ - (void)deliverLiveUsageOnQueue:(NSDictionary *)usage {
293
+ if (!usage) return;
294
+ void (^handler)(NSDictionary *) = self.liveUsageHandler;
295
+ if (handler) handler(usage);
296
+ }
297
+
298
+ - (void)consumeMessageOnQueue:(NSDictionary *)message {
299
+ if (![message isKindOfClass:NSDictionary.class]) return;
300
+ NSNumber *requestID = [message[@"id"] isKindOfClass:NSNumber.class] ? message[@"id"] : nil;
301
+ if (requestID && requestID.integerValue == self.pendingRequestID) {
302
+ self.pendingRequestID = 0;
303
+ NSDictionary *usage = LiveUsageFromRateLimitResponse(message[@"result"]);
304
+ [self deliverLiveUsageOnQueue:usage];
305
+ return;
306
+ }
307
+ NSString *method = [message[@"method"] isKindOfClass:NSString.class] ? message[@"method"] : nil;
308
+ if (![method isEqualToString:@"account/rateLimits/updated"]) return;
309
+ NSDictionary *params = [message[@"params"] isKindOfClass:NSDictionary.class]
310
+ ? message[@"params"] : nil;
311
+ [self deliverLiveUsageOnQueue:LiveUsageFromRateLimitBucket(params[@"rateLimits"])];
312
+ }
313
+
314
+ - (void)consumeOutputDataOnQueue:(NSData *)data fromHandle:(NSFileHandle *)handle {
315
+ // 旧进程退出时可能还留下一次 readability 回调;不能让它把刚重连的新 stdout
316
+ // 处理器清掉,或把上一代进程的响应套到新请求上。
317
+ if (handle != self.output) return;
318
+ if (data.length == 0) {
319
+ handle.readabilityHandler = nil;
320
+ return;
321
+ }
322
+ [self.partialOutput appendData:data];
323
+ const uint8_t *bytes = self.partialOutput.bytes;
324
+ NSUInteger lineStart = 0;
325
+ for (NSUInteger index = 0; index < self.partialOutput.length; index++) {
326
+ if (bytes[index] != '\n') continue;
327
+ NSData *line = [self.partialOutput subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
328
+ NSDictionary *message = line.length > 0
329
+ ? [NSJSONSerialization JSONObjectWithData:line options:0 error:nil] : nil;
330
+ [self consumeMessageOnQueue:message];
331
+ lineStart = index + 1;
332
+ }
333
+ if (lineStart > 0) {
334
+ self.partialOutput = [[self.partialOutput subdataWithRange:
335
+ NSMakeRange(lineStart, self.partialOutput.length - lineStart)] mutableCopy];
336
+ }
337
+ if (self.partialOutput.length > 1024 * 1024) [self.partialOutput setLength:0];
338
+ }
339
+
340
+ - (void)taskDidTerminateOnQueue:(NSTask *)task {
341
+ if (task != self.task) return;
342
+ self.output.readabilityHandler = nil;
343
+ self.task = nil;
344
+ self.input = nil;
345
+ self.output = nil;
346
+ self.pendingRequestID = 0;
347
+ [self.partialOutput setLength:0];
348
+ }
349
+
350
+ - (void)stopTaskOnQueue {
351
+ NSTask *task = self.task;
352
+ self.output.readabilityHandler = nil;
353
+ self.task = nil;
354
+ self.input = nil;
355
+ self.output = nil;
356
+ self.pendingRequestID = 0;
357
+ [self.partialOutput setLength:0];
358
+ if (task.running) [task terminate];
359
+ }
360
+
361
+ - (void)dealloc {
362
+ [self stop];
363
+ }
364
+
365
+ @end
366
+
367
+ NSDictionary *CodexUsageByApplyingLiveUsage(NSDictionary *sessionUsage,
368
+ NSDictionary *liveUsage) {
369
+ if (![liveUsage isKindOfClass:NSDictionary.class]) return sessionUsage;
370
+ NSMutableDictionary *merged = [sessionUsage isKindOfClass:NSDictionary.class]
371
+ ? [sessionUsage mutableCopy] : [NSMutableDictionary dictionary];
372
+ for (NSString *key in @[@"fiveHour", @"week"]) {
373
+ id quota = liveUsage[key];
374
+ if (quota) merged[key] = quota;
375
+ }
376
+ merged[@"sampledAt"] = liveUsage[@"sampledAt"] ?: @(NSDate.date.timeIntervalSince1970);
377
+ if ([liveUsage[@"exhaustedAt"] isKindOfClass:NSNumber.class]) {
378
+ merged[@"exhaustedAt"] = liveUsage[@"exhaustedAt"];
379
+ } else {
380
+ [merged removeObjectForKey:@"exhaustedAt"];
381
+ }
382
+ return merged;
383
+ }
@@ -1,5 +1,6 @@
1
1
  #import "CCPetsEvents.h"
2
2
  #import "CCPetsPaths.h"
3
+ #import "CCPetsTerminalFocus.h"
3
4
  #import <sys/stat.h>
4
5
  #import <fcntl.h>
5
6
  #import <unistd.h>
@@ -196,6 +197,8 @@ int RecordHookEvent(void) {
196
197
  @"timestamp": @([NSDate.date timeIntervalSince1970])
197
198
  } mutableCopy];
198
199
  if (session.length > 0) record[@"session"] = session;
200
+ NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
201
+ if (terminal.count > 0) record[@"terminal"] = terminal;
199
202
  AppendAgentEventRecord(record);
200
203
  return EXIT_SUCCESS;
201
204
  }
@@ -233,14 +236,16 @@ int RecordProviderEvent(void) {
233
236
  @"failed": @"StopFailure",
234
237
  @"notification": @"Notification"
235
238
  };
236
- NSDictionary *record = @{
239
+ NSMutableDictionary *record = [@{
237
240
  @"event": events[state],
238
241
  @"tool": tool,
239
242
  @"failed": @([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]),
240
243
  @"provider": provider,
241
244
  @"state": state,
242
245
  @"timestamp": @([NSDate.date timeIntervalSince1970])
243
- };
246
+ } mutableCopy];
247
+ NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
248
+ if (terminal.count > 0) record[@"terminal"] = terminal;
244
249
  if (!AppendAgentEventRecord(record)) {
245
250
  fprintf(stderr, "无法写入 Provider 事件。\n");
246
251
  return EXIT_FAILURE;
@@ -39,6 +39,8 @@ extern NSString *const HistoryEnabledKey;
39
39
  extern NSString *const NotificationCompletionKey;
40
40
  extern NSString *const NotificationFailureKey;
41
41
  extern NSString *const NotificationApprovalKey;
42
+ // Agent 卡在审批或思考态超过阈值时的提醒开关。
43
+ extern NSString *const NotificationStallKey;
42
44
  extern NSString *const StatusBubbleExpandedKey;
43
45
  extern NSString *const StatusBubblePreferenceV2Key;
44
46
  extern NSString *const ImportCodexPetsKey;
@@ -55,6 +57,8 @@ extern NSString *const DetectedProvidersKey;
55
57
  extern const NSTimeInterval AgentStatusInactivityInterval;
56
58
  extern const NSTimeInterval AgentStatusOrphanInterval;
57
59
  extern const NSTimeInterval AgentStartingGraceInterval;
60
+ extern const NSTimeInterval AgentApprovalStallInterval;
61
+ extern const NSTimeInterval AgentThinkingStallInterval;
58
62
  extern const NSTimeInterval UpdateRetryDelay;
59
63
  extern const NSTimeInterval UsageRefreshIntervalVisible;
60
64
  extern const NSTimeInterval UsageRefreshIntervalHidden;
@@ -213,6 +213,7 @@ NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
213
213
  NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
214
214
  NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
215
215
  NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
216
+ NSString *const NotificationStallKey = @"CCPetsNotifyStall";
216
217
  NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
217
218
  NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
218
219
  NSString *const ImportCodexPetsKey = @"CCPetsImportCodexPets";
@@ -230,6 +231,11 @@ const NSTimeInterval AgentStatusOrphanInterval = 10.0;
230
231
  // "正在启动"只在会话拉起的一瞬间成立。超过这段还没有任何后续事件,说明会话已经就绪、
231
232
  // 正在等用户输入,气泡应当落到"待机中",否则启动态和空闲态看起来完全一样。
232
233
  const NSTimeInterval AgentStartingGraceInterval = 8.0;
234
+ // 审批和思考是唯二会长时间停住不动的状态:窗口切走之后没人知道 Agent 早就停在
235
+ // 那儿了。超过这两个阈值就主动提醒一次,会话有新事件后重新武装。审批是纯粹在等
236
+ // 人,给得短;思考本来就可能跑很久,给得长,免得正常的长任务被当成卡死。
237
+ const NSTimeInterval AgentApprovalStallInterval = 120.0;
238
+ const NSTimeInterval AgentThinkingStallInterval = 300.0;
233
239
  // 刚发布的版本存在 registry 传播竞态,更新失败后等这么久再自动重试一次。
234
240
  const NSTimeInterval UpdateRetryDelay = 5.0;
235
241
  // 额度变化由 FSEvents/VNODE 主动推送;定时器只保留为监听不可用时的 120 秒兜底。
@@ -83,30 +83,7 @@ NSString *PetPhrasesCurrentPetFilePath(void);
83
83
  // 默认词库路径:app bundle 里的 phrases.default.txt。
84
84
  // 可用 CC_PETS_PHRASES_DEFAULT_FILE 覆盖(测试用)。
85
85
  NSString *PetPhrasesDefaultFilePath(void);
86
- // 老版词库路径:~/.cc-pets/phrases.txt。可用 CC_PETS_PHRASES_LEGACY_FILE 覆盖(测试用)。
87
- //
88
- // 换个文件名是为了让"迁移过没有"这件事变成一个平凡的判断:新文件在就是迁移过了。
89
- // 靠猜内容特征(有没有 replace 行、缺不缺某个小节)都不可靠,用户改过之后更没法判断。
90
- NSString *PetPhrasesLegacyFilePath(void);
91
-
92
- // 老版词库还在不在。在的话说明还没提示用户删掉它。
93
- BOOL PetPhrasesLegacyFileExists(void);
94
- // 把老版词库改名成 phrases.txt.bak。用户在提示里确认之后调用。
95
- //
96
- // 改名而不是删除:内容还在原地,万一合并合错了还能翻出来对。同时 PetPhrasesLegacyFilePath
97
- // 只认 phrases.txt,改完名它既不会再被当成迁移源,也不会再弹询问——留着原名不动的话,
98
- // 哪天 speech.txt 丢了,启动时会再从它合并一遍,把用户迁移之后写的台词全冲掉。
99
- BOOL PetPhrasesArchiveLegacyFile(void);
100
-
101
- // 把老版词库合并进默认词库。纯函数,不碰磁盘,方便测。
102
- //
103
- // 合并而不是覆盖:老语义是"内置 + 用户的混着说",用户当时听到的就是两者的并集,
104
- // 直接拿用户那几句顶掉整节的话,桌宠会突然变哑。老文件里写了 replace 的除外——
105
- // 那是"只说我的",照办。
106
- // 注释一律不搬,按新模板的来。
107
- NSString *PetPhraseTextMergedFromLegacy(NSString *legacyText, NSString *defaultText);
108
-
109
- // 用户词库不存在就准备一份:有老版词库就合并过来,否则从默认词库拷。返回是否可用。
86
+ // 用户词库不存在就从默认词库拷一份出来。返回是否可用。
110
87
  //
111
88
  // 默认词库是一个随 app 打包的文本文件,不是代码里的字典:默认台词只在"生成文件"
112
89
  // 这一刻出现一次,之后运行时只认用户文件。两份词库同时存在于运行期就必然要回答
@@ -118,26 +118,6 @@ NSString *PetPhrasesCurrentPetFilePath(void) {
118
118
  return PetPhrasesFilePathForPetID(PetPhrasesCurrentPet);
119
119
  }
120
120
 
121
- NSString *PetPhrasesLegacyFilePath(void) {
122
- NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_PHRASES_LEGACY_FILE"];
123
- if (override.length > 0) return override.stringByStandardizingPath;
124
- return [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets/phrases.txt"];
125
- }
126
-
127
- BOOL PetPhrasesLegacyFileExists(void) {
128
- return [NSFileManager.defaultManager fileExistsAtPath:PetPhrasesLegacyFilePath()];
129
- }
130
-
131
- BOOL PetPhrasesArchiveLegacyFile(void) {
132
- NSFileManager *manager = NSFileManager.defaultManager;
133
- NSString *source = PetPhrasesLegacyFilePath();
134
- if (![manager fileExistsAtPath:source]) return YES;
135
- NSString *target = [source stringByAppendingPathExtension:@"bak"];
136
- // 已经有一份更早的备份就顶掉:它比这份更旧,留着只会让人分不清哪份是哪份。
137
- if ([manager fileExistsAtPath:target]) [manager removeItemAtPath:target error:nil];
138
- return [manager moveItemAtPath:source toPath:target error:nil];
139
- }
140
-
141
121
  NSString *PetPhrasesDefaultFilePath(void) {
142
122
  NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_PHRASES_DEFAULT_FILE"];
143
123
  if (override.length > 0) return override.stringByStandardizingPath;
@@ -159,17 +139,7 @@ BOOL PetPhrasesEnsureFileExists(void) {
159
139
  if (defaultText.length == 0) return NO;
160
140
  [manager createDirectoryAtPath:path.stringByDeletingLastPathComponent
161
141
  withIntermediateDirectories:YES attributes:nil error:nil];
162
-
163
- // 老用户:启动时就把老词库合并过来,不等他打开编辑器。
164
- //
165
- // 拖到编辑器里再迁移的话,从升级到他第一次打开编辑器这段时间,桌宠说的会是默认
166
- // 台词而不是他自己写的——没人会把这件事和"我该去点一下编辑台词"联系起来。
167
- // 老文件这一步不删,等编辑器里问过用户再删。
168
- NSString *legacyText = [NSString stringWithContentsOfFile:PetPhrasesLegacyFilePath()
169
- encoding:NSUTF8StringEncoding error:nil];
170
- NSString *text = legacyText.length > 0 ?
171
- PetPhraseTextMergedFromLegacy(legacyText, defaultText) : defaultText;
172
- return [text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
142
+ return [defaultText writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
173
143
  }
174
144
 
175
145
  // 标签清单。顺序就是默认模板里的顺序,校验提示按这个顺序报,
@@ -552,57 +522,6 @@ static BOOL IsDamagedHeaderLine(NSString *rawLine, NSString *tag) {
552
522
  return [comment isEqualToString:PetPhraseTagDescription(tag)];
553
523
  }
554
524
 
555
- NSString *PetPhraseTextMergedFromLegacy(NSString *legacyText, NSString *defaultText) {
556
- if (legacyText.length == 0) return defaultText;
557
-
558
- NSDictionary<NSString *, NSArray<NSString *> *> *legacy = ParsePhrasesText(legacyText, nil);
559
- // 老文件里独立成行的 replace 表示"只说我写的"。这个写法在新版里已经没有了,
560
- // 但迁移时必须认——不认的话,用过它的人升级后会突然多出一堆他当初特意关掉的话。
561
- BOOL replaceMode = NO;
562
- for (NSString *rawLine in [legacyText componentsSeparatedByCharactersInSet:
563
- NSCharacterSet.newlineCharacterSet]) {
564
- NSString *line = PetLineWithoutTrailingComment([rawLine
565
- stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]);
566
- if ([line isEqualToString:@"replace"]) { replaceMode = YES; break; }
567
- }
568
-
569
- // 拿默认模板当骨架,逐节把内容换掉。注释、分节说明全都用新模板的,
570
- // 老文件里的注释一概不搬。
571
- NSMutableArray<NSString *> *output = [NSMutableArray array];
572
- NSArray<NSString *> *lines = [defaultText componentsSeparatedByString:@"\n"];
573
- NSSet<NSString *> *known = [NSSet setWithArray:PetPhraseAllTags()];
574
- NSString *current = nil;
575
- for (NSString *rawLine in lines) {
576
- NSString *line = PetLineWithoutTrailingComment([rawLine
577
- stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]);
578
- BOOL isHeader = [line hasPrefix:@"["] && [line hasSuffix:@"]"] &&
579
- [known containsObject:[line substringWithRange:NSMakeRange(1, line.length - 2)]];
580
- if (isHeader) {
581
- current = [line substringWithRange:NSMakeRange(1, line.length - 2)];
582
- [output addObject:rawLine];
583
- NSArray<NSString *> *userLines = legacy[current];
584
- NSMutableArray<NSString *> *merged = [NSMutableArray array];
585
- // 默认在前、用户的追加在后,顺序稳定,用户一眼能看出哪几句是自己写的。
586
- //
587
- // replace 模式只覆盖用户**写过**的那些小节,没写过的仍旧用默认内容。
588
- // 照搬老语义(没写的一律清空)会让 15 个 state_ 小节全空:老版那些小节空了
589
- // 还有一层兜底文案顶着,新版把兜底删了,状态卡副行会直接残掉。
590
- if (!replaceMode || userLines.count == 0) {
591
- [merged addObjectsFromArray:ParsePhrasesText(defaultText, nil)[current] ?: @[]];
592
- }
593
- for (NSString *text in userLines) {
594
- if (![merged containsObject:text]) [merged addObject:text];
595
- }
596
- [output addObjectsFromArray:merged];
597
- continue;
598
- }
599
- // 小节内的原有台词由上面一次性写完,这里跳过;注释和空行照抄,骨架才立得住。
600
- if (current != nil && line.length > 0) continue;
601
- [output addObject:rawLine];
602
- }
603
- return [output componentsJoinedByString:@"\n"];
604
- }
605
-
606
525
  // 找 tag 的小节头在第几行,没有返回 -1。
607
526
  static NSInteger HeaderIndex(NSArray<NSString *> *lines, NSString *tag) {
608
527
  for (NSUInteger index = 0; index < lines.count; index++) {
@@ -45,34 +45,6 @@ static void (^PetPhrasesSpeakHandler)(NSString *);
45
45
  [NSApp activateIgnoringOtherApps:YES];
46
46
  [controller.window makeKeyAndOrderFront:nil];
47
47
  [controller.window makeFirstResponder:controller.textView];
48
- [controller offerToRemoveLegacyFile];
49
- }
50
-
51
- // 老词库在启动时已经合并进新文件了(见 PetPhrasesEnsureFileExists),但老文件还留着。
52
- // 在这里问一次要不要收起来:合并是我们替用户做的,动他的文件必须他自己点头。
53
- //
54
- // 他选"先留着"的话下次打开还会问。留着原名不动有两个坑:改它不会有任何效果;
55
- // 而且哪天 speech.txt 丢了,启动时会再从它合并一遍,把迁移之后写的台词全冲掉。
56
- - (void)offerToRemoveLegacyFile {
57
- if (!PetPhrasesLegacyFileExists()) return;
58
-
59
- NSString *legacy = PetPhrasesLegacyFilePath();
60
- NSAlert *alert = [NSAlert new];
61
- alert.messageText = @"旧的台词文件已更新";
62
- alert.informativeText = [NSString stringWithFormat:
63
- @"正在使用的台词全部保留并合并到 %@。\n\n"
64
- "旧文件 %@ 已经失效,后续修改不会有任何效果。"
65
- "可以把它改名成 %@.bak 收起来,内容还留在原地。",
66
- PetPhrasesFilePath(), legacy, legacy.lastPathComponent];
67
- [alert addButtonWithTitle:@"改名收起来"];
68
- [alert addButtonWithTitle:@"先留着"];
69
- if ([alert runModal] != NSAlertFirstButtonReturn) return;
70
- if (PetPhrasesArchiveLegacyFile()) {
71
- [self showStatus:[NSString stringWithFormat:@"旧文件已改名成 %@.bak。",
72
- legacy.lastPathComponent] warning:NO];
73
- } else {
74
- [self showStatus:@"旧文件改名失败,可以手动改。" warning:YES];
75
- }
76
48
  }
77
49
 
78
50
  #pragma mark - 界面
@@ -23,11 +23,18 @@ NSDictionary *QuotaHistoryDocument(void) {
23
23
  static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
24
24
  NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
25
25
  NSNumber *week = RemainingValue(usage, @"week", usedKey);
26
- // 额度被拒之后官方不再报窗口,留在手里的百分比是过期值,照抄进历史会画出一条
27
- // "一直有余额"的假曲线。
28
- if ([usage[@"exhaustedAt"] isKindOfClass:NSNumber.class]) {
29
- if (fiveHour) fiveHour = @0;
30
- if (week) week = @0;
26
+ // usage_limit_exceeded 没有窗口归属,既不能证明两个窗口都归零,也不能证明上次快照
27
+ // 仍代表当前额度。但"受限"和"没有可信百分比"是两件事:受限期间官方 rate_limits
28
+ // 照样会返回窗口百分比(见 CCPetsCodexRateLimits.m 的 LiveUsageFromRateLimitBucket,
29
+ // 受限分支之前就已经填好 fiveHour / week),那是服务端给的真实数值。一律丢掉的话,
30
+ // 长期受限的 provider 在 7 天里攒不下一个历史点,趋势曲线就只剩"当前"这一个点,
31
+ // 画不出线。所以只在快照比受限时刻更旧时才丢——判据与 CCPetsUsage.m 的
32
+ // ExhaustionStillHolds 一致:exhaustedAt < sampledAt 说明快照更新、仍然可信。
33
+ NSNumber *exhaustedAt = [usage[@"exhaustedAt"] isKindOfClass:NSNumber.class]
34
+ ? usage[@"exhaustedAt"] : nil;
35
+ if (exhaustedAt && exhaustedAt.doubleValue >= [usage[@"sampledAt"] doubleValue]) {
36
+ fiveHour = nil;
37
+ week = nil;
31
38
  }
32
39
  NSMutableDictionary *sample = [NSMutableDictionary dictionary];
33
40
  if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
@@ -0,0 +1,11 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 包装脚本在 Agent 启动时固定下来的终端身份。Hook 子进程继承这些环境变量,
4
+ // 因此任务结束时即使用户已经切到别的应用,也不会把目标错记成当前前台窗口。
5
+ NSDictionary *TerminalFocusTargetFromEnvironment(void);
6
+
7
+ // Terminal / iTerm2 按 TTY 精确选中 tab/session;其他终端在无扩展模式下激活应用。
8
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target);
9
+
10
+ // 供包装脚本在 exec Agent 之前捕获承载终端的应用。
11
+ NSString *FrontmostApplicationBundleIdentifier(void);