cc-pets 1.2.8 → 1.2.9

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.
@@ -911,6 +911,8 @@ static void TrimUpdateLog(NSString *path) {
911
911
  };
912
912
  [quotaRoot addSubview:self.quotaView];
913
913
  self.quotaPanel.contentView = quotaRoot;
914
+ // 先探测再第一次显示:否则面板会先按两张卡的高度弹出来再收缩一下。
915
+ [self refreshDetectedProviders];
914
916
 
915
917
  NSScreen *screen = NSScreen.mainScreen;
916
918
  NSRect visible = screen.visibleFrame;
@@ -1293,14 +1295,72 @@ static void TrimUpdateLog(NSString *path) {
1293
1295
  }
1294
1296
  }
1295
1297
  [self updateQuotaLiveState];
1298
+ [self refreshDetectedProviders];
1296
1299
  [self hideAgentStatusIfClientGone];
1297
1300
  // 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
1298
1301
  // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
1299
1302
  if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
1300
1303
  }
1304
+ // 面板高度取决于渲染几张额度卡。quotaRoot / 毛玻璃 / quotaView 三层都是固定 frame、
1305
+ // 没有 autoresizingMask,所以统一在这里按 contentView 的 subviews 铺一遍,避免漏掉一层。
1306
+ - (void)resizeQuotaDashboard {
1307
+ NSSize size = NSMakeSize(QuotaLogicalWidth * QuotaScale,
1308
+ QuotaLogicalHeightForProviderCount([self.quotaView visibleProviders].count) * QuotaScale);
1309
+ if (NSEqualSizes(self.quotaPanel.frame.size, size)) return;
1310
+ // 只改 size 不动 origin:窗口 frame 的原点在左下,面板会朝上收缩,底边保持贴着宠物。
1311
+ NSRect frame = self.quotaPanel.frame;
1312
+ frame.size = size;
1313
+ [self.quotaPanel setFrame:frame display:NO];
1314
+ NSRect bounds = NSMakeRect(0, 0, size.width, size.height);
1315
+ self.quotaPanel.contentView.frame = bounds;
1316
+ for (NSView *subview in self.quotaPanel.contentView.subviews) subview.frame = bounds;
1317
+ self.quotaView.needsDisplay = YES;
1318
+ if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
1319
+ }
1320
+ // 额度字典"非空"不等于"这家真的在用"。Claude 的 reader 刻意永不返回 nil(见
1321
+ // CCPetsUsage.m 里 -[ClaudeUsageReader refresh] 的注释:Token 是本机从转录数出来的,
1322
+ // 不能被缺失的官方额度一票否决),什么都没有时照样返回
1323
+ // {fiveHour: NSNull, week: NSNull, tokenUsage: 全 0},count 恒为 3。
1324
+ // 拿 count > 0 当证据,Claude 就永远算"检测到",卡片再也去不掉。这里只认实质证据:
1325
+ // 官方额度块真实存在,或者本机统计出过非零 Token。Codex 侧同一套判据也成立。
1326
+ static BOOL UsageShowsProviderInUse(NSDictionary *usage) {
1327
+ if (usage.count == 0) return NO;
1328
+ for (NSString *key in @[@"fiveHour", @"week"]) {
1329
+ if ([usage[key] isKindOfClass:NSDictionary.class]) return YES;
1330
+ }
1331
+ NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
1332
+ ? usage[@"tokenUsage"] : nil;
1333
+ for (NSString *key in @[@"fiveHour", @"week", @"today", @"recentWeek"]) {
1334
+ NSDictionary *totals = [tokenUsage[key] isKindOfClass:NSDictionary.class]
1335
+ ? tokenUsage[key] : nil;
1336
+ if ([totals[@"total_tokens"] doubleValue] > 0) return YES;
1337
+ }
1338
+ return NO;
1339
+ }
1340
+ // "这台机器上有哪几家 CLI"。只增不减,并持久化:探测会瞬时失败(配置目录被改名、
1341
+ // 外置盘没挂上),卡片当着用户的面消失比多留一张更像 bug。
1342
+ - (void)refreshDetectedProviders {
1343
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1344
+ NSMutableSet<NSString *> *detected = [NSMutableSet setWithArray:
1345
+ [defaults arrayForKey:DetectedProvidersKey] ?: @[]];
1346
+ if (CodexCLIDetected()) [detected addObject:@"Codex"];
1347
+ if (ClaudeCLIDetected()) [detected addObject:@"Claude"];
1348
+ // 正在跑的客户端和已经拿到的额度数据都是比目录探测更硬的证据:探测漏判也不能
1349
+ // 把一个正在工作、或者明明有额度的 provider 藏起来。
1350
+ if (self.liveClientProviders.count > 0) [detected unionSet:self.liveClientProviders];
1351
+ if (UsageShowsProviderInUse(self.quotaView.codexUsage)) [detected addObject:@"Codex"];
1352
+ if (UsageShowsProviderInUse(self.quotaView.claudeUsage)) [detected addObject:@"Claude"];
1353
+ if (self.quotaView.detectedProviders &&
1354
+ [detected isEqualToSet:self.quotaView.detectedProviders]) return;
1355
+ self.quotaView.detectedProviders = detected;
1356
+ [defaults setObject:detected.allObjects forKey:DetectedProvidersKey];
1357
+ [self resizeQuotaDashboard];
1358
+ self.quotaView.needsDisplay = YES;
1359
+ }
1301
1360
  - (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
1302
1361
  self.quotaView.codexUsage = codexUsage;
1303
1362
  self.quotaView.claudeUsage = claudeUsage;
1363
+ [self refreshDetectedProviders];
1304
1364
  NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
1305
1365
  self.quotaView.claudeUsage);
1306
1366
  self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
@@ -20,6 +20,13 @@ NSString *QuotaHistoryPath(void);
20
20
  // 永远不直接扫描,只在开关打开时由 ImportCodexPets 复制进来。
21
21
  NSString *OwnPetsDirectory(void);
22
22
  NSString *CodexPetsDirectory(void);
23
+
24
+ // 这台机器上有没有这家 CLI。面板据此决定渲染几张额度卡:判据是"装没装",不是"此刻在不在线"。
25
+ // 在线信号(liveProviders)会随 CLI 退出而消失,拿它控制卡片显隐会让面板在用户眼前抖动,
26
+ // 而 CLI 刚退出恰恰是用户最想看剩余额度的时候。安装器已经不再凭空创建这两个配置目录,
27
+ // 所以"目录存在"是干净信号。参见 scripts/detect-cli.mjs 里同一套判据的 Node 实现。
28
+ BOOL CodexCLIDetected(void);
29
+ BOOL ClaudeCLIDetected(void);
23
30
  // 把 ~/.codex/pets 里的素材复制进 OwnPetsDirectory(),返回新导入的数量。
24
31
  // 已存在的同名目录一律跳过,不覆盖。
25
32
  NSUInteger ImportCodexPets(void);
@@ -34,6 +41,9 @@ extern NSString *const ImportCodexPetsKey;
34
41
  extern NSString *const SystemCPUEnabledKey;
35
42
  extern NSString *const SystemTemperatureEnabledKey;
36
43
  extern NSString *const SystemMemoryEnabledKey;
44
+ // 曾经检测到过的 provider 集合。只增不减:探测有可能瞬时失败(配置目录被临时改名、
45
+ // 外置盘没挂上),而卡片突然消失比多显示一张空卡更像 bug。
46
+ extern NSString *const DetectedProvidersKey;
37
47
 
38
48
  extern const NSTimeInterval AgentStatusInactivityInterval;
39
49
  extern const NSTimeInterval AgentStatusOrphanInterval;
@@ -106,6 +106,30 @@ NSString *CodexPetsDirectory(void) {
106
106
  return [DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"pets"];
107
107
  }
108
108
 
109
+ static BOOL DirectoryExistsAtPath(NSString *path) {
110
+ BOOL isDirectory = NO;
111
+ return path.length > 0 &&
112
+ [NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory;
113
+ }
114
+
115
+ BOOL CodexCLIDetected(void) {
116
+ return DirectoryExistsAtPath(DefaultCodexHomeDirectory());
117
+ }
118
+
119
+ BOOL ClaudeCLIDetected(void) {
120
+ if (DirectoryExistsAtPath(DefaultClaudeConfigDirectory())) return YES;
121
+ // 把配置目录搬过家、又没设 CC_PETS_CLAUDE_CONFIG_DIR 的用户:statusline 写出的额度
122
+ // 缓存同样能证明这家在用。有额度数据却不给卡片,是比多一张卡糟糕得多的失败方式。
123
+ //
124
+ // 但只判"文件存在"不行:CCPetsUsageMonitor 为了挂 VNODE 监听,会先把这个文件
125
+ // 创建成 0 字节占位(见 CCPetsUsageMonitor.m 里 createFileAtPath: 那处)。那样桌宠
126
+ // 一启动就把自己造的占位文件当成"用过 Claude",探测永远为真——和安装器凭空创建
127
+ // ~/.claude 是同一类自证。必须要求文件真的有内容。
128
+ NSDictionary *attributes = [NSFileManager.defaultManager
129
+ attributesOfItemAtPath:ClaudeUsagePath() error:nil];
130
+ return attributes != nil && [attributes[NSFileSize] unsignedLongLongValue] > 0;
131
+ }
132
+
109
133
  // 素材目录里认哪些文件算"有图"。和 CCPetsAppDelegate 的 spritePathInDirectory 保持一致,
110
134
  // 但这里只做存在性判断,不需要读 pet.json 里的 spritesheetPath。
111
135
  static BOOL DirectoryHasSprite(NSString *directory) {
@@ -172,6 +196,7 @@ NSString *const ImportCodexPetsKey = @"CCPetsImportCodexPets";
172
196
  NSString *const SystemCPUEnabledKey = @"CCPetsSystemCPUEnabled";
173
197
  NSString *const SystemTemperatureEnabledKey = @"CCPetsSystemTemperatureEnabled";
174
198
  NSString *const SystemMemoryEnabledKey = @"CCPetsSystemMemoryEnabled";
199
+ NSString *const DetectedProvidersKey = @"CCPetsDetectedProviders";
175
200
  const NSTimeInterval AgentStatusInactivityInterval = 60.0;
176
201
  // 客户端进程已经消失、但状态气泡还停在它最后一条事件上时,多等这么久再清场。
177
202
  // 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
@@ -55,6 +55,9 @@ int RenderQuotaDashboard(NSString *path) {
55
55
  view.activeAgentCount = 1;
56
56
  // 预览里刻意只让一家在线,好把"有额度数据但客户端已退出"的离线态也画出来。
57
57
  view.liveProviders = [NSSet setWithObject:@"Claude"];
58
+ // 预览图始终画完整的两张卡:它是 README 里的样张,不该受这台机器装了几家 CLI 影响。
59
+ // 尺寸也因此固定在 QuotaLogicalHeight(tests/test.sh 断言的 441 x 343)。
60
+ view.detectedProviders = [NSSet setWithObjects:@"Codex", @"Claude", nil];
58
61
  view.lastUpdatedAt = NSDate.date.timeIntervalSince1970 - 12;
59
62
  NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
60
63
  NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
@@ -2,8 +2,10 @@
2
2
 
3
3
  // 额度面板按逻辑尺寸绘制后整体缩放,保证离屏渲染和实时显示是同一套代码。
4
4
  extern const CGFloat QuotaLogicalWidth;
5
+ // 两家 CLI 都装时的高度,也是预览图的尺寸。实际高度按检测到的 provider 数量算。
5
6
  extern const CGFloat QuotaLogicalHeight;
6
7
  extern const CGFloat QuotaScale;
8
+ CGFloat QuotaLogicalHeightForProviderCount(NSUInteger count);
7
9
 
8
10
  NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
9
11
 
@@ -18,6 +20,12 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
18
20
  @property NSSet<NSString *> *liveProviders;
19
21
  // 老版本包装脚本写出的 pid 文件没有 provider 名。有这种客户端时无法断言某一家离线。
20
22
  @property BOOL hasUnlabeledClient;
23
+ // 这台机器上检测到的 provider("Codex" / "Claude")。决定渲染几张额度卡、面板多高。
24
+ // 与 liveProviders 是两件事:那个是"此刻在不在线",只驱动徽章。nil 表示没探测过,
25
+ // 按两家都有渲染。
26
+ @property NSSet<NSString *> *detectedProviders;
27
+ - (NSArray<NSString *> *)visibleProviders;
28
+ - (CGFloat)logicalHeight;
21
29
  @property NSTimeInterval lastUpdatedAt;
22
30
  @property BOOL systemCPUEnabled;
23
31
  @property BOOL systemTemperatureEnabled;
@@ -4,6 +4,24 @@ const CGFloat QuotaLogicalWidth = 760;
4
4
  const CGFloat QuotaLogicalHeight = 590;
5
5
  const CGFloat QuotaScale = 0.58;
6
6
 
7
+ // 面板高度按"检测到几家 CLI"变化,所以纵向布局不再是一堆绝对坐标,而是自上而下的分段:
8
+ // 标题区 → 汇总条 → N × 额度卡 → 脚注区,块之间统一留 QuotaBlockGap。
9
+ // QuotaLogicalHeight 保留为两家都装时的高度(590),既是历史默认值,也是预览图尺寸。
10
+ static const CGFloat QuotaHeaderHeight = 106;
11
+ static const CGFloat QuotaSummaryHeight = 112;
12
+ static const CGFloat QuotaCardHeight = 152;
13
+ static const CGFloat QuotaBlockGap = 12;
14
+ static const CGFloat QuotaFooterHeight = 44;
15
+ // 两家都没装时的精简态:只留标题区、三行说明和脚注,汇总条和额度卡整块去掉——
16
+ // 没有 provider 的"今日用量/近 7 天"是两行 0,比不显示更让人以为是坏了。
17
+ static const CGFloat QuotaEmptyNoticeHeight = 76;
18
+
19
+ CGFloat QuotaLogicalHeightForProviderCount(NSUInteger count) {
20
+ if (count == 0) return QuotaHeaderHeight + QuotaEmptyNoticeHeight + QuotaFooterHeight;
21
+ return QuotaHeaderHeight + QuotaSummaryHeight +
22
+ count * (QuotaBlockGap + QuotaCardHeight) + QuotaFooterHeight;
23
+ }
24
+
7
25
  NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
8
26
  NSURL *appURL = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleIdentifier];
9
27
  NSMutableArray<NSString *> *paths = [NSMutableArray array];
@@ -48,14 +66,29 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
48
66
  self.needsDisplay = YES;
49
67
  if (self.hoverChanged) self.hoverChanged(NO);
50
68
  }
51
- - (NSRect)logicalRefreshRect { return NSMakeRect(QuotaLogicalWidth - 54, QuotaLogicalHeight - 52, 34, 32); }
69
+ // detectedProviders 未赋值时按"两家都有"渲染。这是刻意的兜底:探测是 App 侧的额外信号,
70
+ // 拿不到时宁可多画一张卡,也不要让有额度的用户看不到自己的卡片。
71
+ - (NSArray<NSString *> *)visibleProviders {
72
+ NSArray<NSString *> *order = @[@"Codex", @"Claude"];
73
+ if (!self.detectedProviders) return order;
74
+ NSMutableArray<NSString *> *visible = [NSMutableArray array];
75
+ for (NSString *name in order) {
76
+ if ([self.detectedProviders containsObject:name]) [visible addObject:name];
77
+ }
78
+ return visible;
79
+ }
80
+ - (CGFloat)logicalHeight {
81
+ return QuotaLogicalHeightForProviderCount([self visibleProviders].count);
82
+ }
83
+ - (NSRect)logicalRefreshRect { return NSMakeRect(QuotaLogicalWidth - 54, [self logicalHeight] - 52, 34, 32); }
52
84
  - (NSRect)refreshRect {
53
85
  NSRect logical = [self logicalRefreshRect];
54
86
  return NSMakeRect(logical.origin.x * QuotaScale, logical.origin.y * QuotaScale,
55
87
  logical.size.width * QuotaScale, logical.size.height * QuotaScale);
56
88
  }
57
89
  - (NSRect)logicalSummaryRect {
58
- return NSMakeRect(20, 372, QuotaLogicalWidth - 40, 112);
90
+ return NSMakeRect(20, [self logicalHeight] - QuotaHeaderHeight - QuotaSummaryHeight,
91
+ QuotaLogicalWidth - 40, QuotaSummaryHeight);
59
92
  }
60
93
  // 刷新时间挪去了右上角,这一版块整宽留给两个统计格,各占一半。
61
94
  - (NSRect)logicalSummaryCellRectAtIndex:(NSUInteger)index {
@@ -294,6 +327,10 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
294
327
  }
295
328
  - (NSArray<NSDictionary *> *)curvePointsFromHistory:(NSArray<NSDictionary *> *)history
296
329
  currentUsed:(NSNumber *)currentUsed {
330
+ // 历史只能补充当前快照,不能替代当前快照。当前窗口还没有采集到额度时继续画旧历史,
331
+ // 会让“等待数据”的卡片同时出现一条悬在中间的曲线;此时只保留图表底部基线。
332
+ if (!currentUsed) return @[];
333
+
297
334
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
298
335
  NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
299
336
  NSMutableArray<NSDictionary *> *points = [NSMutableArray array];
@@ -309,9 +346,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
309
346
  }
310
347
  // 终点必须和卡片上的当前官方额度同源;历史落盘最多会慢 15 分钟,不能直接拿它
311
348
  // 冒充“当前”,否则同一张卡里会出现两个不同百分比。
312
- if (currentUsed) {
313
- [points addObject:@{@"timestamp": @(now), @"used": currentUsed}];
314
- }
349
+ [points addObject:@{@"timestamp": @(now), @"used": currentUsed}];
315
350
  return points;
316
351
  }
317
352
  - (void)appendCurveFromPoint:(NSPoint)from toPoint:(NSPoint)to path:(NSBezierPath *)path {
@@ -385,37 +420,65 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
385
420
  NSTimeInterval elapsed = now - start;
386
421
  double projectedRemaining = NAN;
387
422
  const NSTimeInterval paceObservationSeconds = 24 * 60 * 60;
423
+ // 满 24 小时就全额外推的话,放大倍数还有 7 倍:窗口第 25 小时,任何已用超过 14.3%
424
+ // 的用户都会被判成"重置前用尽"。更糟的是两家的窗口起点差几个小时,就会出现一家
425
+ // 已外推、另一家还没到门槛的断层——剩 80% 的报高风险,剩 61% 的却显示平稳。
426
+ // 因此在 24 小时到窗口 1/3(56 小时)之间按观测时长加权,从"按当前已用"平滑过渡
427
+ // 到"完全信任外推",门槛处不再有跳变。
428
+ const NSTimeInterval paceFullTrustSeconds = sevenDaySeconds / 3.0;
388
429
  if (reset && reset.doubleValue > now && elapsed >= paceObservationSeconds) {
389
- double projectedUsed = currentUsed.doubleValue * sevenDaySeconds / elapsed;
430
+ double linearUsed = currentUsed.doubleValue * sevenDaySeconds / elapsed;
431
+ double confidence = fmin(1.0, (elapsed - paceObservationSeconds) /
432
+ (paceFullTrustSeconds - paceObservationSeconds));
433
+ double projectedUsed = currentUsed.doubleValue +
434
+ (linearUsed - currentUsed.doubleValue) * confidence;
390
435
  projectedRemaining = 100.0 - projectedUsed;
391
436
  }
392
437
 
438
+ // 四个档位从轻到重排成阶梯,后面的仲裁只在这上面挪档位,不再各写一套 label/tip/color。
393
439
  double remaining = 100.0 - currentUsed.doubleValue;
394
- NSString *label = remaining >= 70 ? @"充足"
395
- : (remaining >= 40 ? @"平稳" : (remaining >= 15 ? @"需关注" : @"高风险"));
396
- NSString *tip = remaining >= 70 ? @"当前额度余量充足"
397
- : (remaining >= 40 ? @"当前额度余量平稳"
398
- : (remaining >= 15 ? @"建议关注额度余量" : @"当前额度余量较低"));
399
- NSColor *statusColor = remaining >= 70 ? NSColor.systemGreenColor
400
- : (remaining >= 40 ? providerColor
401
- : (remaining >= 15 ? NSColor.systemOrangeColor : NSColor.systemRedColor));
402
- // 当前窗口开始满 24 小时后再按消耗节奏预测。此前只看真实剩余额度,避免把
403
- // 开窗头几个小时的突发任务线性外推到整整 7 天,造成“高风险”误报。
404
- if (!isnan(projectedRemaining) &&
405
- (remaining <= 5 || projectedRemaining < 0)) {
406
- label = @"高风险";
407
- tip = @"预计重置前额度用尽";
408
- statusColor = NSColor.systemRedColor;
409
- } else if (!isnan(projectedRemaining) && projectedRemaining < 10) {
410
- label = @"需关注";
411
- tip = @"建议减少高消耗任务";
412
- statusColor = NSColor.systemOrangeColor;
413
- } else if (!isnan(projectedRemaining) && projectedRemaining >= 30) {
414
- label = @"充足";
415
- tip = @"按当前节奏额度充足";
416
- statusColor = NSColor.systemGreenColor;
440
+ NSArray<NSArray *> *ladder = @[
441
+ @[@"充足", @"当前额度余量充足", NSColor.systemGreenColor],
442
+ @[@"平稳", @"当前额度余量平稳", providerColor],
443
+ @[@"需关注", @"建议关注额度余量", NSColor.systemOrangeColor],
444
+ @[@"高风险", @"当前额度余量较低", NSColor.systemRedColor]
445
+ ];
446
+ NSUInteger baseRank = remaining >= 70 ? 0
447
+ : (remaining >= 40 ? 1 : (remaining >= 15 ? 2 : 3));
448
+
449
+ // 当前窗口开始满 24 小时后才按消耗节奏预测;此前 projectedRemaining 是 NAN,只看事实。
450
+ NSInteger projectedRank = -1;
451
+ NSString *projectedTip = nil;
452
+ if (!isnan(projectedRemaining)) {
453
+ if (remaining <= 5 || projectedRemaining < 0) {
454
+ projectedRank = 3;
455
+ projectedTip = @"预计重置前额度用尽";
456
+ } else if (projectedRemaining < 10) {
457
+ projectedRank = 2;
458
+ projectedTip = @"建议减少高消耗任务";
459
+ } else if (projectedRemaining >= 30) {
460
+ projectedRank = 0;
461
+ projectedTip = @"按当前节奏额度充足";
462
+ }
417
463
  }
418
- return @{@"label": label, @"tip": tip, @"color": statusColor};
464
+
465
+ // 仲裁:有预测就以预测为准,但事实划两条不可逾越的线。预测是关于未来的猜测,
466
+ // 剩余额度是此刻的事实;让猜测把事实盖掉,两个方向都会出错——
467
+ // 剩 80% 被外推成"高风险"是虚惊,剩 10% 被外推成"需关注"是漏报,后者更危险。
468
+ NSUInteger rank = projectedRank >= 0 ? (NSUInteger)projectedRank : baseRank;
469
+ BOOL demotedByFact = NO;
470
+ if (remaining < 15) rank = 3; // 只剩一成,再乐观的预测也压不下来
471
+ else if (remaining < 40 && rank < 1) rank = 1; // 不到四成就别标"充足"
472
+ if (remaining >= 70 && rank > 2) { // 还有七成,再难看的预测也不报"高风险"
473
+ rank = 2;
474
+ demotedByFact = YES;
475
+ }
476
+
477
+ NSString *label = ladder[rank][0];
478
+ NSString *tip = ladder[rank][1];
479
+ if (demotedByFact) tip = @"消耗偏快,注意节奏";
480
+ else if (projectedRank >= 0 && rank == (NSUInteger)projectedRank) tip = projectedTip;
481
+ return @{@"label": label, @"tip": tip, @"color": ladder[rank][2]};
419
482
  }
420
483
  - (void)drawProvider:(NSString *)name usage:(NSDictionary *)usage usedKey:(NSString *)usedKey
421
484
  color:(NSColor *)color cardRect:(NSRect)card {
@@ -556,7 +619,9 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
556
619
  NSAffineTransform *scale = [NSAffineTransform transform];
557
620
  [scale scaleBy:QuotaScale];
558
621
  [scale concat];
559
- NSRect logicalBounds = NSMakeRect(0, 0, QuotaLogicalWidth, QuotaLogicalHeight);
622
+ NSArray<NSString *> *visibleProviders = [self visibleProviders];
623
+ const CGFloat height = [self logicalHeight];
624
+ NSRect logicalBounds = NSMakeRect(0, 0, QuotaLogicalWidth, height);
560
625
  NSRect outer = NSInsetRect(logicalBounds, 1, 1);
561
626
  NSBezierPath *background = [NSBezierPath bezierPathWithRoundedRect:outer xRadius:24 yRadius:24];
562
627
  NSGradient *gradient = [[NSGradient alloc]
@@ -569,13 +634,17 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
569
634
  NSGradient *topGlow = [[NSGradient alloc]
570
635
  initWithStartingColor:[NSColor colorWithWhite:1 alpha:0.34]
571
636
  endingColor:[NSColor colorWithWhite:1 alpha:0.0]];
572
- [topGlow drawFromCenter:NSMakePoint(700, 650) radius:0
573
- toCenter:NSMakePoint(700, 650) radius:250 options:0];
637
+ // 两处光晕原本是按 H=590 定的绝对点。面板会变矮,改成跟着高度走:顶部光源始终悬在
638
+ // 面板上沿之外,冷色光晕落在内容区中段。
639
+ NSPoint topGlowCenter = NSMakePoint(700, height + 60);
640
+ [topGlow drawFromCenter:topGlowCenter radius:0
641
+ toCenter:topGlowCenter radius:250 options:0];
574
642
  NSGradient *cyanGlow = [[NSGradient alloc]
575
643
  initWithStartingColor:[NSColor colorWithRed:0.18 green:0.72 blue:1 alpha:0.11]
576
644
  endingColor:[NSColor colorWithRed:0.18 green:0.88 blue:1 alpha:0.0]];
577
- [cyanGlow drawFromCenter:NSMakePoint(660, 250) radius:0
578
- toCenter:NSMakePoint(660, 250) radius:260 options:0];
645
+ NSPoint cyanGlowCenter = NSMakePoint(660, height * 0.42);
646
+ [cyanGlow drawFromCenter:cyanGlowCenter radius:0
647
+ toCenter:cyanGlowCenter radius:260 options:0];
579
648
  [NSGraphicsContext restoreGraphicsState];
580
649
 
581
650
  [[NSColor colorWithWhite:1 alpha:0.34] setStroke];
@@ -590,18 +659,18 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
590
659
  NSColor *secondary = self.secondaryColor;
591
660
  NSColor *cyan = self.accentColor;
592
661
  NSColor *agentColor = self.agentStatusColor;
593
- [@"Agent Usage" drawInRect:NSMakeRect(28, QuotaLogicalHeight - 65, 260, 42)
662
+ [@"Agent Usage" drawInRect:NSMakeRect(28, height - 65, 260, 42)
594
663
  withAttributes:[self textAttributesWithSize:30 color:primary weight:NSFontWeightBold]];
595
- [@"实时状态与滚动用量" drawInRect:NSMakeRect(30, QuotaLogicalHeight - 94, 130, 22)
664
+ [@"实时状态与滚动用量" drawInRect:NSMakeRect(30, height - 94, 130, 22)
596
665
  withAttributes:[self textAttributesWithSize:14 color:secondary weight:NSFontWeightRegular]];
597
666
  [agentColor setFill];
598
- [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(174, QuotaLogicalHeight - 88, 9, 9)] fill];
667
+ [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(174, height - 88, 9, 9)] fill];
599
668
  NSString *agentText = self.activeAgentCount > 0
600
669
  ? [NSString stringWithFormat:@"%ld 个 Agent 在线", (long)self.activeAgentCount]
601
670
  : @"暂无 Agent 在线";
602
- [agentText drawInRect:NSMakeRect(190, QuotaLogicalHeight - 95, 160, 22)
671
+ [agentText drawInRect:NSMakeRect(190, height - 95, 160, 22)
603
672
  withAttributes:[self textAttributesWithSize:14 color:agentColor weight:NSFontWeightMedium]];
604
- [self drawSystemMetricsEndingAtX:QuotaLogicalWidth - 28 y:QuotaLogicalHeight - 95];
673
+ [self drawSystemMetricsEndingAtX:QuotaLogicalWidth - 28 y:height - 95];
605
674
 
606
675
  BOOL recentlyRefreshed = self.refreshedUntil > NSDate.date.timeIntervalSince1970;
607
676
  CGFloat buttonAlpha = self.refreshPressed ? 0.18 : (self.refreshHovered ? 0.12 : 0.06);
@@ -617,6 +686,61 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
617
686
  withAttributes:[self rightAlignedTextAttributesWithSize:11 color:secondary
618
687
  weight:NSFontWeightRegular]];
619
688
 
689
+ if (visibleProviders.count > 0) {
690
+ [self drawSummaryForProviders:visibleProviders primary:primary secondary:secondary
691
+ accent:cyan];
692
+ }
693
+ NSDictionary *cardSpecs = @{
694
+ @"Codex": @{@"usage": self.codexUsage ?: @{}, @"usedKey": @"used_percent",
695
+ @"color": cyan},
696
+ @"Claude": @{@"usage": self.claudeUsage ?: @{}, @"usedKey": @"used_percentage",
697
+ @"color": [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]}
698
+ };
699
+ // 卡片从汇总条下方依次向下排。少一家就少一张卡,脚注跟着上移;这里的分段账必须和
700
+ // QuotaLogicalHeightForProviderCount 完全一致,否则面板会多出或少掉一段空白。
701
+ CGFloat cardTop = height - QuotaHeaderHeight - QuotaSummaryHeight;
702
+ for (NSString *name in visibleProviders) {
703
+ NSDictionary *spec = cardSpecs[name];
704
+ cardTop -= QuotaBlockGap;
705
+ [self drawProvider:name usage:spec[@"usage"] usedKey:spec[@"usedKey"]
706
+ color:spec[@"color"]
707
+ cardRect:NSMakeRect(20, cardTop - QuotaCardHeight,
708
+ QuotaLogicalWidth - 40, QuotaCardHeight)];
709
+ cardTop -= QuotaCardHeight;
710
+ }
711
+ if (visibleProviders.count == 0) {
712
+ // 精简态。说清楚是"没检测到 CLI",而不是让用户对着一片空白猜面板是不是坏了。
713
+ // 两行说明刻意分开:卡片出现只取决于装没装 CLI,探测每 ClientLifecycleInterval
714
+ // 跑一次,装完几秒内自己就冒出来,既不用重装也不用重启桌宠。而 cc-pets install
715
+ // 解决的是另一件事——Agent 动画,以及 Claude 额度(statusline 是它唯一的来源)。
716
+ // 把两者写成一句会让人以为不执行 install 卡片就不出现。
717
+ CGFloat noticeTop = height - QuotaHeaderHeight;
718
+ [@"未检测到 Codex / Claude Code CLI" drawInRect:NSMakeRect(28, noticeTop - 30, 460, 26)
719
+ withAttributes:[self textAttributesWithSize:17 color:primary weight:NSFontWeightMedium]];
720
+ [@"安装 Codex 或 Claude Code 后,额度卡会自动出现"
721
+ drawInRect:NSMakeRect(28, noticeTop - 52, 560, 20)
722
+ withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
723
+ [@"重新执行 cc-pets install 可启用 Agent 动画与 Claude 额度采集"
724
+ drawInRect:NSMakeRect(28, noticeTop - 72, 560, 18)
725
+ withAttributes:[self textAttributesWithSize:11
726
+ color:[NSColor colorWithWhite:0.52 alpha:1] weight:NSFontWeightRegular]];
727
+ }
728
+ NSString *footer = visibleProviders.count > 0
729
+ ? @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量(输入含缓存读写),两者口径不同"
730
+ : @"ⓘ 桌宠与系统状态不受影响;额度卡只在检测到对应 CLI 时显示";
731
+ // 最后一块的底边距面板底 QuotaFooterHeight:脚注与其留约 8pt,底部留白 16pt,
732
+ // 和顶部标题的留白大致对称。
733
+ [footer drawInRect:NSMakeRect(28, 16, 650, 20)
734
+ withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.58 alpha:1] weight:NSFontWeightRegular]];
735
+ [NSGraphicsContext restoreGraphicsState];
736
+ }
737
+
738
+ // 今日与最近 7 天都按 Provider 分开展示。底层本来就是两套独立的自然日统计,
739
+ // 不在展示层相加,避免用户无法判断 Token 来自 Codex 还是 Claude。
740
+ // 每格内是一张 2×2 表:标题独占一行,每个 Provider 独占一行;输入/输出标签放在
741
+ // 对应数值上方。这样既能完整展示 7 天统计起期,也不会挤乱两家的数据行。
742
+ - (void)drawSummaryForProviders:(NSArray<NSString *> *)providers primary:(NSColor *)primary
743
+ secondary:(NSColor *)secondary accent:(NSColor *)cyan {
620
744
  NSRect summary = [self logicalSummaryRect];
621
745
  NSBezierPath *summaryPath = [NSBezierPath bezierPathWithRoundedRect:summary xRadius:18 yRadius:18];
622
746
  [[NSColor colorWithWhite:1 alpha:0.065] setFill];
@@ -624,23 +748,31 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
624
748
  [[NSColor colorWithWhite:1 alpha:0.16] setStroke];
625
749
  [summaryPath stroke];
626
750
 
627
- // 今日与最近 7 天都按 Provider 分开展示。底层本来就是两套独立的自然日统计,
628
- // 不在展示层相加,避免用户无法判断 Token 来自 Codex 还是 Claude。
629
- // 每格内是一张 2×2 表:标题独占一行,每个 Provider 独占一行;输入/输出标签放在
630
- // 对应数值上方。这样既能完整展示 7 天统计起期,也不会挤乱两家的数据行。
631
751
  NSArray<NSDictionary *> *cells = @[
632
752
  @{@"icon": @"◔", @"headerSymbol": @"calendar", @"key": @"today",
633
753
  @"label": @"今日用量"},
634
754
  @{@"icon": @"◉", @"headerSymbol": @"calendar.badge.clock", @"key": @"recentWeek",
635
755
  @"label": [self recentWeekUsageLabel]}
636
756
  ];
637
- NSColor *claudeColor = [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1];
638
- NSArray<NSDictionary *> *rows = @[
639
- @{@"name": @"Codex", @"usage": self.codexUsage ?: @{}, @"color": cyan,
640
- @"iconY": @43, @"nameY": @52, @"labelY": @68, @"valueY": @47},
641
- @{@"name": @"Claude", @"usage": self.claudeUsage ?: @{}, @"color": claudeColor,
642
- @"iconY": @5, @"nameY": @14, @"labelY": @30, @"valueY": @9}
643
- ];
757
+ NSDictionary *rowSpecs = @{
758
+ @"Codex": @{@"usage": self.codexUsage ?: @{}, @"color": cyan},
759
+ @"Claude": @{@"usage": self.claudeUsage ?: @{},
760
+ @"color": [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]}
761
+ };
762
+ // 两行版的槽位是写死的。只装了一家时改用居中的单行槽位,否则汇总条会空出半格,
763
+ // 看着像数据没加载出来。
764
+ NSArray<NSDictionary *> *slots = providers.count == 1
765
+ ? @[@{@"iconY": @24, @"nameY": @33, @"labelY": @49, @"valueY": @28}]
766
+ : @[@{@"iconY": @43, @"nameY": @52, @"labelY": @68, @"valueY": @47},
767
+ @{@"iconY": @5, @"nameY": @14, @"labelY": @30, @"valueY": @9}];
768
+ NSMutableArray<NSDictionary *> *rows = [NSMutableArray array];
769
+ for (NSUInteger index = 0; index < providers.count && index < slots.count; index++) {
770
+ NSMutableDictionary *row = [slots[index] mutableCopy];
771
+ [row addEntriesFromDictionary:rowSpecs[providers[index]]];
772
+ row[@"name"] = providers[index];
773
+ [rows addObject:row];
774
+ }
775
+
644
776
  [[NSColor colorWithWhite:1 alpha:0.10] setStroke];
645
777
  for (NSUInteger index = 1; index < cells.count; index++) {
646
778
  CGFloat x = NSMinX([self logicalSummaryCellRectAtIndex:index]);
@@ -704,16 +836,5 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
704
836
  }
705
837
  }
706
838
 
707
- [self drawProvider:@"Codex" usage:self.codexUsage usedKey:@"used_percent"
708
- color:cyan cardRect:NSMakeRect(20, 208, QuotaLogicalWidth - 40, 152)];
709
- [self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
710
- color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
711
- cardRect:NSMakeRect(20, 44, QuotaLogicalWidth - 40, 152)];
712
- NSString *footer = @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量(输入含缓存读写),两者口径不同";
713
- // 卡片底边在 y=44,原来 footer 顶到 44 完全没有间隙。下移到与卡片留约 8pt,
714
- // 同时底部留白 16pt,和顶部标题的留白大致对称。
715
- [footer drawInRect:NSMakeRect(28, 16, 650, 20)
716
- withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.58 alpha:1] weight:NSFontWeightRegular]];
717
- [NSGraphicsContext restoreGraphicsState];
718
839
  }
719
840
  @end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.2.8",
3
+ "version": "1.2.9",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
@@ -0,0 +1,68 @@
1
+ // "这台机器上到底装没装 Codex / Claude Code CLI"。安装器据此决定是否写它们的配置:
2
+ // 以前无条件 mkdir + 写 hooks.json / settings.json,没装的用户会被凭空造出 ~/.codex、
3
+ // ~/.claude,甚至被接管一个他还没有的 status line。
4
+ //
5
+ // 判据是"配置目录已存在"或"PATH 里有真二进制",两者取或:
6
+ // - 装了但从没跑过 → 没有配置目录,靠 PATH 认出来;
7
+ // - 装在非标准位置或用别的启动方式 → PATH 里找不到,靠配置目录认出来。
8
+ // 安装器自己不再创建这两个目录,所以"目录存在"是一个干净的信号,不会自证。
9
+
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+
14
+ const shimDirectory = () => path.resolve(
15
+ process.env.CC_PETS_SHIM_DIR || path.join(os.homedir(), ".cc-pets/shims"));
16
+
17
+ const isDirectory = (target) => {
18
+ try {
19
+ return fs.statSync(target).isDirectory();
20
+ } catch {
21
+ return false;
22
+ }
23
+ };
24
+
25
+ // 不能直接用 `which codex`:安装完成后 shim 目录就排在 PATH 最前面,命中的是我们自己的
26
+ // 包装器,等于自己证明自己。这里跳过 shim 目录,并且对解析后落在包装器上的候选再兜一层
27
+ // (复制而非软链安装时,shim 可能不在 CC_PETS_SHIM_DIR 里)。
28
+ const hasRealExecutable = (name) => {
29
+ const shim = shimDirectory();
30
+ const wrapperNames = new Set([`${name}-with-pet`, "codex-with-pet", "claude-with-pet"]);
31
+ for (const entry of (process.env.PATH || "").split(path.delimiter)) {
32
+ if (!entry) continue;
33
+ let resolvedEntry;
34
+ try {
35
+ resolvedEntry = fs.realpathSync(entry);
36
+ } catch {
37
+ resolvedEntry = path.resolve(entry);
38
+ }
39
+ if (resolvedEntry === shim) continue;
40
+ const candidate = path.join(entry, name);
41
+ try {
42
+ const stats = fs.statSync(candidate);
43
+ if (!stats.isFile() || (stats.mode & 0o111) === 0) continue;
44
+ const real = fs.realpathSync(candidate);
45
+ if (path.dirname(real) === shim) continue;
46
+ if (wrapperNames.has(path.basename(real))) continue;
47
+ return true;
48
+ } catch {
49
+ // 断链或没权限的候选直接跳过,继续看 PATH 里的下一个。
50
+ }
51
+ }
52
+ return false;
53
+ };
54
+
55
+ // 逃生舱:探测漏判时(装在容器里、PATH 被裁剪过、CI 造假环境)用户可以强制安装。
56
+ // CODEX_REAL_BIN / CLAUDE_REAL_BIN 沿用 bin/*-with-pet 已有的约定。
57
+ const forced = (realBinVariable) =>
58
+ process.env.CC_PETS_ASSUME_CLI === "1" || (process.env[realBinVariable] || "").length > 0;
59
+
60
+ export const detectCodexCLI = () =>
61
+ forced("CODEX_REAL_BIN") ||
62
+ isDirectory(process.env.CODEX_HOME || path.join(os.homedir(), ".codex")) ||
63
+ hasRealExecutable("codex");
64
+
65
+ export const detectClaudeCLI = () =>
66
+ forced("CLAUDE_REAL_BIN") ||
67
+ isDirectory(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude")) ||
68
+ hasRealExecutable("claude");
@@ -4,6 +4,7 @@ import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { detectClaudeCLI } from "./detect-cli.mjs";
7
8
 
8
9
  const binary = process.argv[2];
9
10
  if (!binary) {
@@ -11,6 +12,15 @@ if (!binary) {
11
12
  process.exit(2);
12
13
  }
13
14
 
15
+ // 没装 Claude Code 就什么都不写。这里尤其重要:下面的 createStatusLine 分支会创建
16
+ // ~/.claude/statusline-command.sh 并把 settings.json 的 statusLine 指过去,
17
+ // 对还没装 Claude 的用户等于提前替他决定了状态栏。exit 0 的理由见 install-codex-hooks.mjs。
18
+ if (!detectClaudeCLI()) {
19
+ console.log("未检测到 Claude Code CLI,跳过 Claude Hooks 与 status line 接入。");
20
+ console.log("之后安装了 Claude Code,执行 cc-pets install 即可补装。");
21
+ process.exit(0);
22
+ }
23
+
14
24
  const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
15
25
  const settingsPath = path.join(claudeHome, "settings.json");
16
26
  const marker = "CC_PETS_CLAUDE_AGENT_HOOK=1";
@@ -41,15 +51,35 @@ const removeStatusLineBlock = (value) => value
41
51
  .replace(statusLineBlockPattern, "")
42
52
  .replace(/^\n+/, "")
43
53
  .replace(/\n{3,}/g, "\n\n");
44
- const resolveStatusLineScript = (value) => {
54
+ // `bash ~/.claude/statusline-command.sh` 指向的仍是一个能就地注入的脚本,只是多了解释器
55
+ // 前缀和 `~/`。不剥掉就会被下面的"绝对路径 + 无空格"两条拒掉,白白退化成 base64 包装器,
56
+ // 而包装器形态对改 settings.json 的 agent 是黑盒(读不出原命令,容易整条覆盖掉)。
57
+ // 带 -c 的形式除外:`-c` 后面是命令串而非脚本路径,不能当路径注入。
58
+ const interpreterPattern =
59
+ /^(?:\/usr\/bin\/env\s+)?(?:[^\s'"]*\/)?(?:ba|z|k|da)?sh((?:\s+-[A-Za-z]+)*)\s+(.+)$/s;
60
+ const unquote = (value) => {
61
+ const quoted = value.match(/^(['"])(.*)\1$/s);
62
+ return quoted ? quoted[2] : value;
63
+ };
64
+ // target 保留用户原来的写法(含 `~/`),script 才是展开后用于读写文件的绝对路径。
65
+ // 官方形态就是 `~/.claude/statusline.sh`,`~` 是刻意的可移植写法,不能展开后写回配置。
66
+ const parseStatusLineCommand = (value) => {
45
67
  if (typeof value !== "string") return null;
46
- let candidate = value.trim();
47
- const quoted = candidate.match(/^(['"])(.*)\1$/s);
48
- if (quoted) candidate = quoted[2];
49
- if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
50
- if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
51
- return path.resolve(candidate);
68
+ let candidate = unquote(value.trim());
69
+ let hasInterpreter = false;
70
+ let flags = "";
71
+ const interpreted = candidate.match(interpreterPattern);
72
+ if (interpreted && !/-[A-Za-z]*c(?=\s|$)/.test(interpreted[1])) {
73
+ hasInterpreter = true;
74
+ flags = interpreted[1].trim();
75
+ candidate = unquote(interpreted[2].trim());
76
+ }
77
+ let resolved = candidate;
78
+ if (resolved.startsWith("~/")) resolved = path.join(os.homedir(), resolved.slice(2));
79
+ if (!path.isAbsolute(resolved) || /[\s;&|<>`$()]/.test(resolved)) return null;
80
+ return { script: path.resolve(resolved), target: candidate, hasInterpreter, flags };
52
81
  };
82
+ const resolveStatusLineScript = (value) => parseStatusLineCommand(value)?.script ?? null;
53
83
  const statusLinePrelude = [
54
84
  statusLineStartMarker,
55
85
  `CC_PETS_STATUSLINE_INPUT="$(/usr/bin/mktemp "\${TMPDIR:-/tmp}/cc-pets-statusline.XXXXXX")" || exit 1`,
@@ -67,14 +97,14 @@ const installStatusLinePrelude = (scriptPath, createIfMissing = false) => {
67
97
  let mode = 0o700;
68
98
  if (fs.existsSync(scriptPath)) {
69
99
  const stats = fs.statSync(scriptPath);
70
- if (!stats.isFile()) return false;
100
+ if (!stats.isFile()) return { installed: false, hadShebang: false };
71
101
  original = fs.readFileSync(scriptPath, "utf8");
72
102
  mode = stats.mode;
73
103
  } else if (createIfMissing) {
74
104
  fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
75
105
  original = `#!/bin/zsh\n${createdStatusLineMarker}\n`;
76
106
  } else {
77
- return false;
107
+ return { installed: false, hadShebang: false };
78
108
  }
79
109
 
80
110
  const cleaned = removeStatusLineBlock(original);
@@ -91,7 +121,7 @@ const installStatusLinePrelude = (scriptPath, createIfMissing = false) => {
91
121
  fs.writeFileSync(temporaryPath, updated, { mode });
92
122
  fs.renameSync(temporaryPath, scriptPath);
93
123
  fs.chmodSync(scriptPath, mode | 0o100);
94
- return true;
124
+ return { installed: true, hadShebang: hasShebang };
95
125
  };
96
126
  const command = `${marker} ${shellQuote(path.resolve(binary))} --hook`;
97
127
  const events = [
@@ -162,14 +192,31 @@ if (!originalStatusLineCommand) {
162
192
  }
163
193
  config.statusLine = { ...config.statusLine, type: "command", command: originalStatusLineCommand };
164
194
 
165
- const statusLineScript = resolveStatusLineScript(originalStatusLineCommand);
166
- const statusLineInstalled = Boolean(
167
- statusLineScript && installStatusLinePrelude(statusLineScript, createdStatusLine)
168
- );
195
+ const parsedStatusLine = parseStatusLineCommand(originalStatusLineCommand);
196
+ const statusLineScript = parsedStatusLine?.script ?? null;
197
+ const preludeResult = statusLineScript
198
+ ? installStatusLinePrelude(statusLineScript, createdStatusLine)
199
+ : { installed: false, hadShebang: false };
200
+ const statusLineInstalled = preludeResult.installed;
201
+
202
+ // 只在原命令带解释器前缀(`bash ~/x.sh`)时才改写 command,去掉那层前缀让 agent 能直接读懂。
203
+ // 纯路径形态——包括官方默认的 `~/.claude/statusline.sh`——一个字都不动,写法原样保留。
204
+ // 两条额外的闸门,都是为了不改变脚本的执行语义:
205
+ // * 带 flag(`sh -e ~/x.sh`)不动,否则 `-e` 这类选项会被悄悄丢掉;
206
+ // * 脚本原本没有 shebang 的不动,否则 prelude 补的 `#!/bin/zsh` 会把本来用 bash 跑的
207
+ // 脚本换成 zsh 跑。用户写 `bash ~/x.sh` 往往正是因为脚本没有 shebang。
208
+ if (
209
+ statusLineInstalled &&
210
+ parsedStatusLine?.hasInterpreter &&
211
+ !parsedStatusLine.flags &&
212
+ preludeResult.hadShebang
213
+ ) {
214
+ config.statusLine = { ...config.statusLine, command: parsedStatusLine.target };
215
+ }
169
216
 
170
- // 就地往用户脚本里插 prelude 只对"绝对路径的可编辑脚本"成立。第三方状态栏基本都不是这个
171
- // 形态(`bun x ccstatusline`、`npx …`、任何带参数或管道的命令行),resolveStatusLineScript
172
- // 一律拒绝。以前这里只打印一行警告就算了,而 statusline 是 Claude 额度的唯一来源
217
+ // 就地往用户脚本里插 prelude 只对"能解析出脚本路径的命令"成立。真·第三方状态栏不是这个
218
+ // 形态(`bun x ccstatusline`、`npx …`、任何带管道或 `sh -c` 的命令行),
219
+ // resolveStatusLineScript 一律拒绝。以前这里只打印一行警告就算了,而 statusline 是 Claude 额度的唯一来源
173
220
  // (转录 jsonl 和 stats-cache.json 里都没有 rate_limits),于是这类用户的额度永远是 `--`。
174
221
  // 回退到包装器:command 换成 claude-statusline-with-pet + base64 编码的原命令,它先把 stdin
175
222
  // 喂给 cc-pets --claude-usage,再原样转发给原命令执行。卸载侧本来就认这个形态(marker +
@@ -3,6 +3,7 @@
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { detectCodexCLI } from "./detect-cli.mjs";
6
7
 
7
8
  const binary = process.argv[2];
8
9
  if (!binary) {
@@ -10,6 +11,15 @@ if (!binary) {
10
11
  process.exit(2);
11
12
  }
12
13
 
14
+ // 没装 Codex 就什么都不写。必须 exit 0:install-shell-integration.sh 是 set -eu,
15
+ // 这里非零退出会把后面的 Claude Hooks、更新器、shim 和 .zshrc 全部带停,
16
+ // 用户会拿到一个装了一半的状态。
17
+ if (!detectCodexCLI()) {
18
+ console.log("未检测到 Codex CLI,跳过 Codex Hooks 安装。");
19
+ console.log("之后安装了 Codex,执行 cc-pets install 即可补装。");
20
+ process.exit(0);
21
+ }
22
+
13
23
  const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
14
24
  const hooksPath = path.join(codexHome, "hooks.json");
15
25
  const marker = "CC_PETS_CODEX_AGENT_HOOK=1";
@@ -31,11 +31,23 @@ function isManagedStatusLine(value, marker) {
31
31
  /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
32
32
  }
33
33
 
34
+ // 与 install-claude-hooks.mjs 保持一致:`bash ~/x.sh` 这类带解释器前缀的命令同样指向一个
35
+ // 被就地注入过的脚本,卸载时也要能解析出来,否则 prelude 会残留在脚本里。
36
+ const interpreterPattern =
37
+ /^(?:\/usr\/bin\/env\s+)?(?:[^\s'"]*\/)?(?:ba|z|k|da)?sh((?:\s+-[A-Za-z]+)*)\s+(.+)$/s;
38
+
39
+ function unquote(value) {
40
+ const quoted = value.match(/^(['"])(.*)\1$/s);
41
+ return quoted ? quoted[2] : value;
42
+ }
43
+
34
44
  function resolveStatusLineScript(value) {
35
45
  if (typeof value !== "string") return null;
36
- let candidate = value.trim();
37
- const quoted = candidate.match(/^(['"])(.*)\1$/s);
38
- if (quoted) candidate = quoted[2];
46
+ let candidate = unquote(value.trim());
47
+ const interpreted = candidate.match(interpreterPattern);
48
+ if (interpreted && !/-[A-Za-z]*c(?=\s|$)/.test(interpreted[1])) {
49
+ candidate = unquote(interpreted[2].trim());
50
+ }
39
51
  if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
40
52
  if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
41
53
  return path.resolve(candidate);