cc-pets 1.2.0 → 1.2.2

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 CHANGED
@@ -4,6 +4,27 @@
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ - 修复面板上的剩余额度来回跳(实测 Claude 5 小时窗口 99% → 94% → 又回 99%):多个会话的
8
+ status line 各写各的额度快照到同一个文件,而"响应更早、落盘更晚"在并发下完全正常,
9
+ 无条件覆盖会让旧快照盖掉新快照。改为逐窗口按"同一 `resets_at` 内用量只增不减"取舍,
10
+ 窗口滚动(`resets_at` 变大)时无条件接受,某个窗口超过 10 分钟没有被接受过时也放行,
11
+ 免得官方口径调整(例如临时提额)后面板被钉死——这个逃生阀按窗口各记各的接受时刻,
12
+ 被拒绝的快照不会把它续期,否则只要还有会话在持续上报就永远到不了。读改写全程用独立
13
+ 锁文件加 `flock` 串行化,数据文件仍由 rename 整体替换;加锁是非阻塞加有限重试,拿不到
14
+ 就放弃这次采样,免得一个卡死的写者把之后每一次 status line 渲染永久挂住。响应缺某个
15
+ 窗口时保留旧值,不再整块覆盖。
16
+ Codex 侧同一问题一并修,判据统一成"按额度采样时刻取最新":兜底扫描近期会话时不再按
17
+ 文件 mtime 命中即返回;一批文件事件里有多个会话同时变更时,也不再取遍历到的最后一个,
18
+ 而是读各自的尾巴比采样时刻(会话拿到额度后还会追加别的行,mtime 顺序和采样顺序并不
19
+ 一致)。内核已经点名变更文件的路径不再重跑基于 mtime 的会话发现,否则刚选中的结果会
20
+ 立刻被推翻。`cc-pets --clean` / 完整卸载会一并删除额度写锁;7 天启动清理刻意放过它,
21
+ 锁文件 mtime 创建后不再更新,删掉一个正被持有的锁会让互斥失效。
22
+ - 修复敲 `Claude` / `Codex`(任意非全小写写法)时桌宠不启动:shell 集成从 alias 改为
23
+ `~/.cc-pets/shims` 下的软链加 `PATH` 前置。alias 名区分大小写,而 macOS 文件系统默认
24
+ 不区分,`Claude` 匹配不到 alias 就直接命中真二进制,绕过了包装脚本。shim 靠文件系统
25
+ 自身的大小写不敏感覆盖全部写法。包装脚本随之不再用 `whence -p` 找真二进制(会先命中
26
+ shim 自己导致无限 `exec`),改为遍历候选并跳过 shim。升级会自动把旧 alias 段迁移成
27
+ shim 段,卸载会一并删除软链和目录。
7
28
  - 新增 `cc-pets pet` 素材管理命令(`search` / `add` / `list` / `remove` / `source` / `dir`),
8
29
  把素材下载到 cc-pets 自己的目录 `~/.cc-pets/pets/`,不再写 `~/.petdex/pets/` 和
9
30
  `~/.codex/pets/`。两端都认 `CC_PETS_PETS_DIR` 覆盖。
package/README.md CHANGED
@@ -38,9 +38,10 @@
38
38
  Agent 动画分别由 Codex Hooks 和 Claude Code Hooks 驱动。首次安装或 Codex Hook 内容更新后,启动 Codex 并执行
39
39
  `/hooks`,检查并信任 CC Pets Hook;未经信任的用户级 Hook 会被 Codex 安全机制跳过。
40
40
  Claude Code Hook 会合并到 `~/.claude/settings.json`,现有的 `env`、`model`、`statusLine`
41
- 以及其他 Hooks 都会保留。Claude status line 会通过透明转发器继续执行原命令,同时将官方
42
- `rate_limits` 字段提供给桌宠。
43
- 通过 npm 安装或升级时会自动重新构建应用、安装或更新两套 Hooks,并配置 shell alias;如果旧版桌宠正在运行,
41
+ 以及其他 Hooks 都会保留。额度采集块会注入现有 status line 脚本,但配置中的 `command`
42
+ 仍保持原脚本路径,Claude Code 可以继续查找和修改该脚本;脚本输入会同时提供给原状态栏
43
+ 和桌宠,原有输出不变。
44
+ 通过 npm 安装或升级时会自动重新构建应用、安装或更新两套 Hooks,并配置 shell 集成;如果旧版桌宠正在运行,
44
45
  安装器会自动重启桌宠,使新版本生效。`cc-pets install` 保留为手动修复和重新初始化命令。
45
46
 
46
47
  ### 鼠标互动
@@ -127,7 +128,7 @@ claude
127
128
  ```
128
129
 
129
130
  `--allow-scripts=cc-pets` 用于允许新版 npm 执行 CC Pets 的 `postinstall`,完成原生应用构建、
130
- Hooks、shell alias 和 `~/Applications/CC Pets.app` 的安装;`--prefer-online` 会优先向 npm Registry
131
+ Hooks、shell 集成和 `~/Applications/CC Pets.app` 的安装;`--prefer-online` 会优先向 npm Registry
131
132
  检查 `latest`,减少刚发布新版本时命中旧元数据缓存的概率。
132
133
 
133
134
  如果已经只执行了 `npm install -g cc-pets@latest`,并看到 npm 提示安装脚本尚未获准,
@@ -141,7 +142,7 @@ cc-pets install
141
142
 
142
143
  新版 npm(12 起默认)引入了安装脚本白名单:不在白名单里的包,`postinstall` 一律不执行。
143
144
  它只打印一行 `warn install-scripts`,进程仍然以成功退出,所以**安装看起来是成功的**,
144
- 但原生应用、Hooks 和 shell alias 都不会被安装 —— 表现为敲 `codex` / `claude` 时桌宠不出现。
145
+ 但原生应用、Hooks 和 shell 集成都不会被安装 —— 表现为敲 `codex` / `claude` 时桌宠不出现。
145
146
 
146
147
  不想每次都带 `--allow-scripts` 参数的话,可以配置一次持久白名单:
147
148
 
@@ -179,8 +180,11 @@ npm 12 会把本地目录安装识别为项目范围安装,不接受命令行
179
180
  因此本地源码安装显式跳过生命周期脚本,再通过 `cc-pets install` 执行可重复的初始化流程。
180
181
 
181
182
  两种方式都会安装 `cc-pets`、`codex-with-pet` 和 `claude-with-pet`。
182
- npm 的安装后脚本会自动构建原生应用、安装两套 Agent Hooks,并向 `~/.zshrc` 追加带明确标记的
183
- `codex` 与 `claude` alias,不会覆盖真实的 CLI 二进制。首次安装需要新开终端让 alias 生效;以后升级只需执行 npm 命令。
183
+ npm 的安装后脚本会自动构建原生应用、安装两套 Agent Hooks,并在 `~/.cc-pets/shims` 下生成指向包装脚本的
184
+ `codex` 与 `claude` 软链,再向 `~/.zshrc` 追加带明确标记的一行把该目录前置到 `PATH`,不会覆盖真实的 CLI 二进制。
185
+ 用 shim 而不是 alias,是因为 alias 名区分大小写而 macOS 文件系统默认不区分:`Claude`、`CODEX` 这类写法
186
+ 匹配不到 alias,会直接命中真二进制,桌宠不会被拉起。shim 让任意大小写写法都落到同一个文件上。
187
+ 首次安装需要新开终端让 `PATH` 生效;以后升级只需执行 npm 命令。
184
188
  同时会将标准 macOS 应用安装到 `~/Applications/CC Pets.app`,可从 Finder 或 Launchpad 启动,
185
189
  不需要管理员权限。npm 升级时会同步更新该应用。
186
190
 
@@ -199,7 +203,7 @@ npm install -g cc-pets@latest \
199
203
  --prefer-online
200
204
  ```
201
205
 
202
- 新版安装器会自动移除旧版 Hooks、恢复并重新接入 Claude status line,同时替换旧的 shell alias 标记,
206
+ 新版安装器会自动移除旧版 Hooks、恢复并重新接入 Claude status line,同时把旧的 `codex` / `claude` alias 段迁移成 shim,
203
207
  不需要先运行已经移除的 `codex-pet uninstall`。迁移仅识别 CC Pets 的完整命令签名,不会按
204
208
  `codex`、`claude` 或单个环境变量名称泛化删除其他工具配置。
205
209
 
@@ -251,10 +255,10 @@ cc-pets pet list
251
255
  printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
252
256
  | cc-pets provider-event
253
257
 
254
- # 手动修复或重新初始化 Hooks、shell alias,并让已运行桌宠加载当前版本
258
+ # 手动修复或重新初始化 Hooks、shell 集成,并让已运行桌宠加载当前版本
255
259
  cc-pets install
256
260
 
257
- # 安全移除 Hooks、恢复 Claude status line,并清理 shell alias
261
+ # 安全移除 Hooks、恢复 Claude status line,并清理 shell 集成
258
262
  cc-pets uninstall
259
263
 
260
264
  # 完整移除集成、应用和全部本地数据;执行前会再次确认
@@ -453,8 +457,8 @@ source ~/.zshrc
453
457
  npm uninstall -g cc-pets
454
458
  ```
455
459
 
456
- 卸载器只删除带 CC Pets 标记的 Codex/Claude Hooks 和 shell alias,并恢复安装前的 Claude
457
- status line;其他用户配置和 Hooks 会保留。
460
+ 卸载器只删除带 CC Pets 标记的 Codex/Claude Hooks、`~/.zshrc` 里的 shim 段和 `~/.cc-pets/shims` 下由
461
+ CC Pets 建立的软链,并恢复安装前的 Claude status line;其他用户配置和 Hooks 会保留。
458
462
 
459
463
  ## 项目声明
460
464
 
@@ -24,6 +24,28 @@ static BOOL RemoveIfPresent(NSString *path) {
24
24
  return [NSFileManager.defaultManager removeItemAtPath:path error:nil];
25
25
  }
26
26
 
27
+ // statusline 写者不依赖桌宠进程存在,所以 RuntimeIsActive() 不能证明额度文件无人使用。
28
+ // 清理额度缓存前必须拿到同一把锁;锁文件本身刻意长期保留,持锁时 unlink 仍会让后来者
29
+ // 创建新 inode,导致新旧两把锁同时存在、互斥失效。
30
+ static BOOL RemoveClaudeUsageIfUnlocked(void) {
31
+ // 没有额度缓存就别碰锁:O_CREAT 会凭空造出一个锁文件,而它此后永不删除,
32
+ // 等于清理反而留下了残留。
33
+ if (![NSFileManager.defaultManager fileExistsAtPath:ClaudeUsagePath()]) return NO;
34
+ int descriptor = open(ClaudeUsageLockPath().fileSystemRepresentation,
35
+ O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
36
+ if (descriptor < 0) return NO;
37
+ if (flock(descriptor, LOCK_EX | LOCK_NB) != 0) {
38
+ // 静默跳过会让"共移除 N 项"看起来一切正常,用户不会知道额度缓存还在。
39
+ fputs("额度缓存正在被 Claude status line 写入,已跳过;稍后可重试。\n", stderr);
40
+ close(descriptor);
41
+ return NO;
42
+ }
43
+ BOOL removed = RemoveIfPresent(ClaudeUsagePath());
44
+ flock(descriptor, LOCK_UN);
45
+ close(descriptor);
46
+ return removed;
47
+ }
48
+
27
49
  static BOOL RuntimeIsActive(void) {
28
50
  NSString *lockPath = RuntimeLockPath();
29
51
  if (![NSFileManager.defaultManager fileExistsAtPath:lockPath]) return NO;
@@ -82,6 +104,8 @@ static BOOL IsSafeBuildCacheDirectory(NSString *path) {
82
104
  [standardized.stringByDeletingLastPathComponent.lastPathComponent isEqualToString:@".build"];
83
105
  }
84
106
 
107
+ // 刻意不按 mtime 清理额度写锁:锁文件创建后 mtime 就不再更新,7 天判据下它总是"过期"的,
108
+ // 而删掉一个正被持有的锁会让后来者 open 出新 inode,互斥直接失效。
85
109
  void PruneStaleRuntimeState(void) {
86
110
  NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - RuntimeStateTTL;
87
111
  RemoveExpiredFile(AgentEventPath(), cutoff);
@@ -107,7 +131,8 @@ int CleanCCPetsData(BOOL purge) {
107
131
  return 3;
108
132
  }
109
133
  NSUInteger removed = 0;
110
- for (NSString *path in @[AgentEventPath(), ClaudeUsagePath(), RuntimeLockPath(),
134
+ if (RemoveClaudeUsageIfUnlocked()) removed += 1;
135
+ for (NSString *path in @[AgentEventPath(), RuntimeLockPath(),
111
136
  ClientStateDirectory(), buildCache ?: @""]) {
112
137
  if (RemoveIfPresent(path)) removed += 1;
113
138
  }
@@ -5,6 +5,9 @@ NSString *PetStateDirectory(void);
5
5
  NSString *AgentEventPath(void);
6
6
  // 记录端用:解析当前会话的 CLAUDE_CONFIG_DIR。
7
7
  NSString *ClaudeUsagePath(void);
8
+ // 额度文件的写锁。挂在单独的文件上:数据文件本身由 rename 整体替换,
9
+ // 锁在它上面的话两个写者会锁到不同的 inode,等于没锁。
10
+ NSString *ClaudeUsageLockPath(void);
8
11
  // 桌宠端用:只看主账号,不受继承来的 CLAUDE_CONFIG_DIR 影响。
9
12
  NSString *DefaultClaudeConfigDirectory(void);
10
13
  NSString *CurrentClaudeConfigDirectory(void);
@@ -41,6 +41,16 @@ NSString *DefaultCodexHomeDirectory(void) {
41
41
  // 额度是按账号的。一台机器上可以有多个配置目录(例如 ~/.claude 和 ~/.claude-nw),
42
42
  // 各自是不同账号、不同额度周期。共用一个文件的话两边的 statusline 会互相覆盖,
43
43
  // 面板就会把 A 账号的剩余百分比配上 B 账号的用量。因此按配置目录分文件。
44
+ static uint64_t StablePathHash(NSString *path) {
45
+ uint64_t hash = 1469598103934665603ULL;
46
+ const unsigned char *bytes = (const unsigned char *)path.UTF8String;
47
+ for (const unsigned char *cursor = bytes; cursor && *cursor; cursor++) {
48
+ hash ^= (uint64_t)*cursor;
49
+ hash *= 1099511628211ULL;
50
+ }
51
+ return hash;
52
+ }
53
+
44
54
  NSString *ClaudeUsagePathForConfigDirectory(NSString *configDirectory) {
45
55
  NSString *suffix = @"";
46
56
  NSString *resolved = configDirectory.stringByStandardizingPath;
@@ -55,7 +65,11 @@ NSString *ClaudeUsagePathForConfigDirectory(NSString *configDirectory) {
55
65
  if ([allowed characterIsMember:character]) [name appendFormat:@"%C", character];
56
66
  }
57
67
  }
58
- suffix = name.length > 0 ? [@"-" stringByAppendingString:name] : @"-alt";
68
+ NSString *label = name.length > 0 ? name : @"alt";
69
+ // 末级目录名只用于可读性;完整规范化路径的稳定哈希才负责区分账号目录。
70
+ // 否则 /Users/a/.claude-work 与 /Volumes/team/.claude-work 会落到同一个缓存文件。
71
+ suffix = [NSString stringWithFormat:@"-%@-%016llx", label,
72
+ (unsigned long long)StablePathHash(resolved)];
59
73
  }
60
74
  NSString *name = [NSString stringWithFormat:@"cc-pets-%u-claude-usage%@.json",
61
75
  getuid(), suffix];
@@ -66,6 +80,10 @@ NSString *ClaudeUsagePath(void) {
66
80
  return ClaudeUsagePathForConfigDirectory(CurrentClaudeConfigDirectory());
67
81
  }
68
82
 
83
+ NSString *ClaudeUsageLockPath(void) {
84
+ return [ClaudeUsagePath() stringByAppendingPathExtension:@"lock"];
85
+ }
86
+
69
87
  NSString *ApplicationSupportDirectory(void) {
70
88
  NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_APPLICATION_SUPPORT_DIR"];
71
89
  if (override.length > 0) return override.stringByStandardizingPath;
@@ -24,4 +24,7 @@ NSDictionary *LatestUsage(void);
24
24
  - (NSDictionary *)refresh;
25
25
  - (NSDictionary *)refreshWithFullDiscovery;
26
26
  - (NSDictionary *)refreshForSessionURL:(NSURL *)url;
27
+ // 一批 FSEvents 里可能有多个会话文件同时变更(并发会话)。谁的额度采样更晚要读过才知道,
28
+ // 不能取遍历到的最后一个,详见实现处注释。
29
+ - (NSDictionary *)refreshForSessionURLs:(NSArray<NSURL *> *)urls;
27
30
  @end
@@ -1,17 +1,91 @@
1
1
  #import "CCPetsUsage.h"
2
2
  #import "CCPetsPaths.h"
3
+ #import <sys/file.h>
3
4
  #import <sys/stat.h>
5
+ #import <errno.h>
6
+ #import <fcntl.h>
4
7
  #import <unistd.h>
5
8
 
9
+ // 同一个账号下的每个 Claude 会话都会把自己那次响应里的 rate_limits 抄到同一个文件上,
10
+ // 而"响应更早、落盘更晚"在并发会话下完全正常。无条件覆盖时旧快照会盖掉新快照,面板上
11
+ // 的剩余额度于是来回跳(实测 99% → 94% → 又回 99%)。同一窗口内官方用量只增不减,
12
+ // 据此逐窗口丢弃倒退的快照。
13
+ static BOOL ShouldAcceptQuotaWindow(id storedValue, NSDictionary *fresh, BOOL stale) {
14
+ NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
15
+ if (!stored) return YES;
16
+ if (stale) return YES;
17
+ double storedReset = [stored[@"resets_at"] doubleValue];
18
+ double freshReset = [fresh[@"resets_at"] doubleValue];
19
+ // 窗口滚动了:用量归零是真的,无条件接受。反过来说明这份快照来自上一个窗口。
20
+ if (freshReset != storedReset) return freshReset > storedReset;
21
+ return [fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue];
22
+ }
23
+
24
+ // 单调性判据只在旧快照还新鲜时成立。官方口径调整(例如临时提额)会让用量真的掉下去,
25
+ // 这时旧值必须能被顶掉,否则面板会被永久钉在一个偏高的数字上。
26
+ static const NSTimeInterval StaleQuotaSnapshotSeconds = 600.0;
27
+
28
+ // 拿锁的重试上限。拿不到就放弃这次写入:并发写者手里的数据同样新鲜,跳过一次不丢信息,
29
+ // 而无锁写入正是要避免的读改写交错。阻塞版 flock 没有超时,一个被 SIGSTOP 或卡在慢速
30
+ // 卷上的写者会把之后每一次 statusline 渲染永久挂住,那是比丢一次采样糟得多的故障。
31
+ static const int QuotaLockAttempts = 50;
32
+ static const useconds_t QuotaLockRetryMicroseconds = 20 * 1000;
33
+
34
+ static int AcquireQuotaLock(NSString *lockPath) {
35
+ int descriptor = open(lockPath.fileSystemRepresentation, O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR);
36
+ if (descriptor < 0) return -1;
37
+ for (int attempt = 0; attempt < QuotaLockAttempts; attempt++) {
38
+ if (flock(descriptor, LOCK_EX | LOCK_NB) == 0) return descriptor;
39
+ if (errno != EWOULDBLOCK) break;
40
+ usleep(QuotaLockRetryMicroseconds);
41
+ }
42
+ close(descriptor);
43
+ return -1;
44
+ }
45
+
6
46
  int RecordClaudeUsage(void) {
7
47
  NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
8
48
  NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
9
49
  NSDictionary *limits = [payload[@"rate_limits"] isKindOfClass:NSDictionary.class] ? payload[@"rate_limits"] : nil;
10
50
  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);
51
+
52
+ NSString *path = ClaudeUsagePath();
53
+ // 判据要先读后写,多个会话同时跑就会读改写交错,所以整段必须在锁里。
54
+ int lockDescriptor = AcquireQuotaLock(ClaudeUsageLockPath());
55
+ if (lockDescriptor < 0) return EXIT_SUCCESS;
56
+
57
+ NSData *existing = [NSData dataWithContentsOfFile:path];
58
+ id storedValue = existing.length > 0
59
+ ? [NSJSONSerialization JSONObjectWithData:existing options:0 error:nil] : nil;
60
+ NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
61
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
62
+ // 过期判据必须逐窗口记"上一次被接受的时刻"。用整个文件的写盘时间会让逃生阀失效:
63
+ // 快照被判倒退而拒绝时文件照样被写,只要还有会话在持续上报,就永远到不了 10 分钟,
64
+ // 于是官方真的下调用量时面板被永久钉住——正是这个阀门要防的情况。
65
+ id acceptedValue = stored[@"accepted_at"];
66
+ NSDictionary *accepted = [acceptedValue isKindOfClass:NSDictionary.class] ? acceptedValue : nil;
67
+
68
+ NSMutableDictionary *merged = stored ? [stored mutableCopy] : [NSMutableDictionary dictionary];
69
+ NSMutableDictionary *mergedAccepted = accepted ? [accepted mutableCopy] : [NSMutableDictionary dictionary];
70
+ for (NSString *key in @[@"five_hour", @"seven_day"]) {
71
+ NSDictionary *fresh = [limits[key] isKindOfClass:NSDictionary.class] ? limits[key] : nil;
72
+ if (!fresh) continue; // 这次响应没带某个窗口时保留旧的:整体覆盖会让面板凭空少掉一个窗口。
73
+ // accepted_at 缺失的是上一版写的文件,当过期处理,一次就能迁移过来。
74
+ BOOL stale = now - [accepted[key] doubleValue] > StaleQuotaSnapshotSeconds;
75
+ if (!ShouldAcceptQuotaWindow(stored[key], fresh, stale)) continue;
76
+ merged[key] = fresh;
77
+ mergedAccepted[key] = @(now);
78
+ }
79
+ merged[@"accepted_at"] = mergedAccepted;
80
+ // 最后一次写盘时间。不再参与任何判据,只留给排查用。
81
+ merged[@"written_at"] = @(now);
82
+
83
+ NSData *json = [NSJSONSerialization dataWithJSONObject:merged options:0 error:nil];
84
+ if (json && [json writeToFile:path options:NSDataWritingAtomic error:nil]) {
85
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
86
+ }
87
+ flock(lockDescriptor, LOCK_UN);
88
+ close(lockDescriptor);
15
89
  return EXIT_SUCCESS;
16
90
  }
17
91
 
@@ -250,6 +324,16 @@ static NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterva
250
324
  return result;
251
325
  }
252
326
 
327
+ // 多个会话里的额度是同一个账号的快照,只允许采样时刻向前推进。FSEvents 既可能把
328
+ // 多个文件合在一批里,也可能把“响应更早、落盘更晚”的旧文件单独送来;仅在批量候选
329
+ // 之间比较不够,最终写入 self.usage 的每个入口都必须经过这一层。
330
+ static NSDictionary *NewerUsageSnapshot(NSDictionary *current, NSDictionary *candidate) {
331
+ if (![candidate isKindOfClass:NSDictionary.class]) return current;
332
+ if (![current isKindOfClass:NSDictionary.class]) return candidate;
333
+ return [candidate[@"sampledAt"] doubleValue] >= [current[@"sampledAt"] doubleValue]
334
+ ? candidate : current;
335
+ }
336
+
253
337
  // token_count 行几乎总在文件末尾,因此从尾部反向按 \n 切片逐行试,命中即停。
254
338
  // 原实现会把整段(最多 2MB)解码成 NSString、再切成全部行、再把每行编码回 NSData、
255
339
  // 又解码回 NSString 查子串,等于来回往返两遍。
@@ -350,13 +434,19 @@ static NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skip
350
434
  return [(rightDate ?: NSDate.distantPast) compare:(leftDate ?: NSDate.distantPast)];
351
435
  }];
352
436
  NSUInteger examined = 0;
437
+ NSDictionary *newest = nil;
353
438
  for (NSURL *url in urls) {
354
439
  if (skipURL && [url.path isEqualToString:skipURL.path]) continue;
355
440
  if (++examined > 8) break;
356
441
  NSDictionary *usage = LatestUsageInData(SessionTailData(url), NULL);
357
- if (usage && UsageHasLiveWindow(usage)) return usage;
442
+ if (!usage || !UsageHasLiveWindow(usage)) continue;
443
+ // mtime 只够用来挑候选:会话在拿到额度之后还会继续追加别的行,文件的新旧顺序和
444
+ // 额度采样的先后并不一致。命中即返回会拿到偏旧的百分比,改成按采样时刻取最新。
445
+ if (!newest || [usage[@"sampledAt"] doubleValue] > [newest[@"sampledAt"] doubleValue]) {
446
+ newest = usage;
447
+ }
358
448
  }
359
- return nil;
449
+ return newest;
360
450
  }
361
451
 
362
452
  static NSDictionary *FirstTimestampRecordInData(NSData *data) {
@@ -753,8 +843,8 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
753
843
  NSNumber *exhaustedAt = nil;
754
844
  NSDictionary *latest = LatestUsageInData(tail, &exhaustedAt);
755
845
  [self noteExhaustion:exhaustedAt];
756
- self.usage = [self usageWithTokenTotals:latest ?: self.usage
757
- ?: LatestQuotaInRecentSessions(self.sessionsURL, url)];
846
+ NSDictionary *fallback = self.usage ?: LatestQuotaInRecentSessions(self.sessionsURL, url);
847
+ self.usage = [self usageWithTokenTotals:NewerUsageSnapshot(fallback, latest)];
758
848
 
759
849
  const uint8_t *bytes = tail.bytes;
760
850
  NSUInteger lastNewline = NSNotFound;
@@ -779,7 +869,7 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
779
869
  NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
780
870
  [self noteExhaustion:ExhaustionTimestampFromLine(line)];
781
871
  NSDictionary *newUsage = UsageFromCodexLine(line);
782
- if (newUsage) self.usage = newUsage;
872
+ self.usage = NewerUsageSnapshot(self.usage, newUsage);
783
873
  lineStart = index + 1;
784
874
  }
785
875
  if (lineStart > 0) {
@@ -790,17 +880,25 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
790
880
  if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
791
881
  }
792
882
  - (NSDictionary *)refresh {
883
+ return [self refreshDiscovering:YES];
884
+ }
885
+ // discovering=NO 用于 FSEvents 定向路径:内核已经点名了变更的文件,再按 mtime 挑一次
886
+ // 只会推翻这个结论——发现步骤两条分支(全量的 NewestCodexSessionURL 和同目录的
887
+ // NewestSessionFileInDirectory)用的都是 mtime,而 mtime 顺序和额度采样先后并不一致。
888
+ - (NSDictionary *)refreshDiscovering:(BOOL)discovering {
793
889
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
794
- BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
795
- NSURL *candidate = nil;
796
- if (needsFullDiscovery) {
797
- candidate = NewestCodexSessionURL(self.sessionsURL);
798
- self.lastFullDiscovery = now;
799
- } else {
800
- candidate = NewestSessionFileInDirectory(
801
- self.sessionURL.URLByDeletingLastPathComponent, NULL);
890
+ if (discovering) {
891
+ BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
892
+ NSURL *candidate = nil;
893
+ if (needsFullDiscovery) {
894
+ candidate = NewestCodexSessionURL(self.sessionsURL);
895
+ self.lastFullDiscovery = now;
896
+ } else {
897
+ candidate = NewestSessionFileInDirectory(
898
+ self.sessionURL.URLByDeletingLastPathComponent, NULL);
899
+ }
900
+ if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
802
901
  }
803
- if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
804
902
  if (!self.sessionURL) return self.usage;
805
903
 
806
904
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
@@ -830,14 +928,56 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
830
928
  self.forcesTokenAggregation = YES;
831
929
  return [self refresh];
832
930
  }
833
- - (NSDictionary *)refreshForSessionURL:(NSURL *)url {
834
- if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return self.usage;
931
+ - (BOOL)isSessionURL:(NSURL *)url {
932
+ if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return NO;
835
933
  NSString *sessionsPath = self.sessionsURL.path.stringByResolvingSymlinksInPath;
836
- NSString *candidatePath = url.path.stringByResolvingSymlinksInPath;
837
934
  NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
838
- if (![candidatePath hasPrefix:prefix]) return self.usage;
839
- if (![candidatePath isEqualToString:self.sessionURL.path]) [self selectSessionURL:url];
840
- return [self refresh];
935
+ return [url.path.stringByResolvingSymlinksInPath hasPrefix:prefix];
936
+ }
937
+ - (NSDictionary *)refreshForSessionURL:(NSURL *)url {
938
+ return [self refreshForSessionURLs:url ? @[url] : @[]];
939
+ }
940
+ // 并发会话下一批事件里会有多个会话文件同时变更,而"文件更晚被写"和"额度采样更晚"是两回事:
941
+ // 会话拿到 rate_limits 之后还会继续追加别的行。取遍历到的最后一个就会切到采样偏旧的会话,
942
+ // 面板上的百分比于是在两个会话之间来回跳。这里读各自的尾巴,按 sampledAt 挑,与
943
+ // LatestQuotaInRecentSessions 的判据保持一致。
944
+ //
945
+ // 别的会话也必须读取并比较:迟到的旧响应通常会作为下一批里的唯一文件出现。
946
+ // 唯一的例外是当前会话自己——那是单会话的常态热路径,追加的新行走增量读取,
947
+ // consumeIncrementalData 里的 NewerUsageSnapshot 已经保证了单调性,不必为它白读一遍尾巴。
948
+ - (NSDictionary *)refreshForSessionURLs:(NSArray<NSURL *> *)urls {
949
+ NSURL *chosen = nil;
950
+ NSURL *currentSession = nil;
951
+ double chosenSampledAt = [self.usage[@"sampledAt"] doubleValue];
952
+ for (NSURL *url in urls) {
953
+ if (![self isSessionURL:url]) continue;
954
+ if (self.sessionURL && [url.path isEqualToString:self.sessionURL.path]) {
955
+ currentSession = url;
956
+ continue;
957
+ }
958
+ // 耗尽事件也在这段尾巴里。反正已经读了,顺手记下来:候选因为采样更旧而落选时
959
+ // 整批事件都不再走 refresh,不在这里捕获就永远丢了——而"另一个会话刚更新过额度、
960
+ // 这个会话撞上限流"正是最容易发生耗尽的时刻。
961
+ NSNumber *exhaustedAt = nil;
962
+ NSDictionary *usage = LatestUsageInData(SessionTailData(url), &exhaustedAt);
963
+ [self noteExhaustion:exhaustedAt];
964
+ // 整篇都没有额度、或者采样比当前面板更旧的会话不参与竞选。
965
+ if (!usage) continue;
966
+ double sampledAt = [usage[@"sampledAt"] doubleValue];
967
+ if (sampledAt >= chosenSampledAt) {
968
+ chosen = url;
969
+ chosenSampledAt = sampledAt;
970
+ }
971
+ }
972
+ // 没有别的会话胜出时才轮到当前会话,这样先后遍历到谁都不影响结果。
973
+ if (!chosen) chosen = currentSession;
974
+ // 一个候选都没选中就不会再走到 usageWithTokenTotals,刚记下的耗尽标记得在这里贴上。
975
+ if (!chosen) {
976
+ self.usage = UsageByMarkingExhaustion(self.usage, self.exhaustedAt);
977
+ return self.usage;
978
+ }
979
+ if (![chosen.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:chosen];
980
+ return [self refreshDiscovering:NO];
841
981
  }
842
982
  @end
843
983
 
@@ -26,7 +26,9 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
26
26
  CCPetsUsageMonitor *monitor = (__bridge CCPetsUsageMonitor *)clientCallBackInfo;
27
27
  NSArray<NSString *> *paths = (__bridge NSArray<NSString *> *)eventPaths;
28
28
  BOOL requiresFullDiscovery = NO;
29
- NSURL *latestSession = nil;
29
+ // 一批里同一个文件可能出现多次;并发会话时则是多个不同文件。全都收下来交给 reader
30
+ // 按额度采样时刻挑,这里不做"最后一个胜出"的判断——文件写入顺序不代表采样顺序。
31
+ NSMutableOrderedSet<NSString *> *changedSessions = [NSMutableOrderedSet orderedSet];
30
32
  for (size_t index = 0; index < numEvents; index++) {
31
33
  FSEventStreamEventFlags flags = eventFlags[index];
32
34
  if (flags & (kFSEventStreamEventFlagMustScanSubDirs |
@@ -41,13 +43,17 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
41
43
  [path.stringByResolvingSymlinksInPath hasPrefix:
42
44
  [monitor.codexReader.sessionsURL.path.stringByResolvingSymlinksInPath
43
45
  stringByAppendingString:@"/"]]) {
44
- latestSession = [NSURL fileURLWithPath:path];
46
+ [changedSessions addObject:path];
45
47
  }
46
48
  }
47
- monitor.codexUsage = requiresFullDiscovery
48
- ? [monitor.codexReader refreshWithFullDiscovery]
49
- : (latestSession ? [monitor.codexReader refreshForSessionURL:latestSession] : monitor.codexUsage);
50
- if (requiresFullDiscovery || latestSession) [monitor publishChange];
49
+ if (requiresFullDiscovery) {
50
+ monitor.codexUsage = [monitor.codexReader refreshWithFullDiscovery];
51
+ } else if (changedSessions.count > 0) {
52
+ NSMutableArray<NSURL *> *urls = [NSMutableArray arrayWithCapacity:changedSessions.count];
53
+ for (NSString *path in changedSessions) [urls addObject:[NSURL fileURLWithPath:path]];
54
+ monitor.codexUsage = [monitor.codexReader refreshForSessionURLs:urls];
55
+ }
56
+ if (requiresFullDiscovery || changedSessions.count > 0) [monitor publishChange];
51
57
  }
52
58
 
53
59
  @implementation CCPetsUsageMonitor
@@ -7,11 +7,25 @@ PET_BIN="${PROJECT_DIR}/.build/release/cc-pets"
7
7
  BUILD_APP="${PROJECT_DIR}/.build/release/CC Pets.app"
8
8
  INSTALLED_APP="${CC_PETS_APPLICATIONS_DIR:-${HOME}/Applications}/CC Pets.app"
9
9
  REAL_CLAUDE="${CLAUDE_REAL_BIN:-}"
10
+ SELF="${0:A}"
11
+ SHIM_DIR="${CC_PETS_SHIM_DIR:-${HOME}/.cc-pets/shims}"
10
12
  CLIENT_DIR="${${TMPDIR:-/tmp/}%/}/cc-pets-$(id -u)-clients"
11
13
  CLIENT_FILE="${CLIENT_DIR}/$$"
12
14
 
15
+ # PATH 里有一个名为 claude 的 shim(软链到本脚本)。alias 区分大小写而 macOS 文件系统
16
+ # 不区分,所以 Claude / CLAUDE 这些写法只有 shim 拦得住。代价是不能再用 whence -p:
17
+ # 它拿回来的第一个 claude 就是 shim 自己,exec 下去就是无限递归。这里遍历全部候选,
18
+ # 跳过解析后指向本脚本的、以及落在 shim 目录里的(复制而非软链安装时的兜底)。
13
19
  if [[ -z "${REAL_CLAUDE}" ]]; then
14
- REAL_CLAUDE="$(whence -p claude 2>/dev/null || true)"
20
+ typeset -a CANDIDATES
21
+ CANDIDATES=(${(f)"$(whence -ap claude 2>/dev/null || true)"})
22
+ for candidate in "${CANDIDATES[@]}"; do
23
+ [[ -n "${candidate}" && -x "${candidate}" ]] || continue
24
+ [[ "${candidate:A}" == "${SELF}" ]] && continue
25
+ [[ "${candidate:A:h}" == "${SHIM_DIR:A}" ]] && continue
26
+ REAL_CLAUDE="${candidate}"
27
+ break
28
+ done
15
29
  fi
16
30
  if [[ -z "${REAL_CLAUDE}" || ! -x "${REAL_CLAUDE}" ]]; then
17
31
  print -u2 "未找到可执行的 Claude Code CLI。请先安装 claude,或通过 CLAUDE_REAL_BIN 指定真实路径。"
@@ -7,11 +7,23 @@ PET_BIN="${PROJECT_DIR}/.build/release/cc-pets"
7
7
  BUILD_APP="${PROJECT_DIR}/.build/release/CC Pets.app"
8
8
  INSTALLED_APP="${CC_PETS_APPLICATIONS_DIR:-${HOME}/Applications}/CC Pets.app"
9
9
  REAL_CODEX="${CODEX_REAL_BIN:-}"
10
+ SELF="${0:A}"
11
+ SHIM_DIR="${CC_PETS_SHIM_DIR:-${HOME}/.cc-pets/shims}"
10
12
  CLIENT_DIR="${${TMPDIR:-/tmp/}%/}/cc-pets-$(id -u)-clients"
11
13
  CLIENT_FILE="${CLIENT_DIR}/$$"
12
14
 
15
+ # 见 claude-with-pet 同处注释:PATH 里的 codex 是指向本脚本的 shim,
16
+ # whence -p 会先命中它,直接 exec 就是无限递归。
13
17
  if [[ -z "${REAL_CODEX}" ]]; then
14
- REAL_CODEX="$(whence -p codex 2>/dev/null || true)"
18
+ typeset -a CANDIDATES
19
+ CANDIDATES=(${(f)"$(whence -ap codex 2>/dev/null || true)"})
20
+ for candidate in "${CANDIDATES[@]}"; do
21
+ [[ -n "${candidate}" && -x "${candidate}" ]] || continue
22
+ [[ "${candidate:A}" == "${SELF}" ]] && continue
23
+ [[ "${candidate:A:h}" == "${SHIM_DIR:A}" ]] && continue
24
+ REAL_CODEX="${candidate}"
25
+ break
26
+ done
15
27
  fi
16
28
  if [[ -z "${REAL_CODEX}" || ! -x "${REAL_CODEX}" ]]; then
17
29
  print -u2 "未找到可执行的 Codex CLI。请先安装 codex,或通过 CODEX_REAL_BIN 指定真实路径。"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
@@ -5,9 +5,8 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
 
7
7
  const binary = process.argv[2];
8
- const statusLineProxy = process.argv[3];
9
- if (!binary || !statusLineProxy) {
10
- console.error("用法: install-claude-hooks.mjs /absolute/path/to/cc-pets /absolute/path/to/claude-statusline-with-pet");
8
+ if (!binary) {
9
+ console.error("用法: install-claude-hooks.mjs /absolute/path/to/cc-pets");
11
10
  process.exit(2);
12
11
  }
13
12
 
@@ -20,6 +19,9 @@ const managedHookSignatures = [
20
19
  { marker: "CLAUDE_PET_AGENT_HOOK=1", executable: "codex-pet" }
21
20
  ];
22
21
  const managedStatusLineMarkers = [statusLineMarker, "CLAUDE_PET_STATUS_LINE=1"];
22
+ const statusLineStartMarker = "# >>> cc-pets-statusline >>>";
23
+ const statusLineEndMarker = "# <<< cc-pets-statusline <<<";
24
+ const createdStatusLineMarker = "# CC Pets created this status line script";
23
25
  const isManagedHookCommand = (value, signature) =>
24
26
  typeof value === "string" &&
25
27
  value.startsWith(`${signature.marker} `) &&
@@ -29,6 +31,67 @@ const isManagedStatusLine = (value, candidateMarker) =>
29
31
  value.startsWith(`${candidateMarker} `) &&
30
32
  /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
31
33
  const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
34
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35
+ const statusLineBlockPattern = new RegExp(
36
+ `(?:^|\\n)${escapeRegExp(statusLineStartMarker)}\\n[\\s\\S]*?\\n${escapeRegExp(statusLineEndMarker)}(?=\\n|$)`,
37
+ "g"
38
+ );
39
+ const removeStatusLineBlock = (value) => value
40
+ .replace(statusLineBlockPattern, "")
41
+ .replace(/^\n+/, "")
42
+ .replace(/\n{3,}/g, "\n\n");
43
+ const resolveStatusLineScript = (value) => {
44
+ if (typeof value !== "string") return null;
45
+ let candidate = value.trim();
46
+ const quoted = candidate.match(/^(['"])(.*)\1$/s);
47
+ if (quoted) candidate = quoted[2];
48
+ if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
49
+ if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
50
+ return path.resolve(candidate);
51
+ };
52
+ const statusLinePrelude = [
53
+ statusLineStartMarker,
54
+ `CC_PETS_STATUSLINE_INPUT="$(/usr/bin/mktemp "\${TMPDIR:-/tmp}/cc-pets-statusline.XXXXXX")" || exit 1`,
55
+ `/bin/cat > "\${CC_PETS_STATUSLINE_INPUT}"`,
56
+ `if [ -x ${shellQuote(path.resolve(binary))} ]; then`,
57
+ ` ${shellQuote(path.resolve(binary))} --claude-usage < "\${CC_PETS_STATUSLINE_INPUT}" >/dev/null 2>&1 || true`,
58
+ "fi",
59
+ `exec 0< "\${CC_PETS_STATUSLINE_INPUT}"`,
60
+ `/bin/rm -f "\${CC_PETS_STATUSLINE_INPUT}"`,
61
+ "unset CC_PETS_STATUSLINE_INPUT",
62
+ statusLineEndMarker
63
+ ].join("\n");
64
+ const installStatusLinePrelude = (scriptPath, createIfMissing = false) => {
65
+ let original = "";
66
+ let mode = 0o700;
67
+ if (fs.existsSync(scriptPath)) {
68
+ const stats = fs.statSync(scriptPath);
69
+ if (!stats.isFile()) return false;
70
+ original = fs.readFileSync(scriptPath, "utf8");
71
+ mode = stats.mode;
72
+ } else if (createIfMissing) {
73
+ fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
74
+ original = `#!/bin/zsh\n${createdStatusLineMarker}\n`;
75
+ } else {
76
+ return false;
77
+ }
78
+
79
+ const cleaned = removeStatusLineBlock(original);
80
+ const firstNewline = cleaned.indexOf("\n");
81
+ const hasShebang = cleaned.startsWith("#!");
82
+ const shebang = hasShebang
83
+ ? cleaned.slice(0, firstNewline === -1 ? cleaned.length : firstNewline)
84
+ : "#!/bin/zsh";
85
+ const body = hasShebang
86
+ ? (firstNewline === -1 ? "" : cleaned.slice(firstNewline + 1))
87
+ : cleaned;
88
+ const updated = `${shebang}\n${statusLinePrelude}\n${body}`.replace(/\n*$/, "\n");
89
+ const temporaryPath = `${scriptPath}.cc-pets.tmp`;
90
+ fs.writeFileSync(temporaryPath, updated, { mode });
91
+ fs.renameSync(temporaryPath, scriptPath);
92
+ fs.chmodSync(scriptPath, mode | 0o100);
93
+ return true;
94
+ };
32
95
  const command = `${marker} ${shellQuote(path.resolve(binary))} --hook`;
33
96
  const events = [
34
97
  "SessionStart",
@@ -90,16 +153,28 @@ if (config.statusLine && typeof config.statusLine === "object" && !Array.isArray
90
153
  } else {
91
154
  config.statusLine = { type: "command" };
92
155
  }
93
- const encodedOriginal = Buffer.from(originalStatusLineCommand, "utf8").toString("base64");
94
- config.statusLine = {
95
- ...config.statusLine,
96
- type: "command",
97
- command: `${statusLineMarker} ${shellQuote(path.resolve(statusLineProxy))} ${shellQuote(encodedOriginal)}`
98
- };
156
+
157
+ let createdStatusLine = false;
158
+ if (!originalStatusLineCommand) {
159
+ originalStatusLineCommand = path.join(claudeHome, "statusline-command.sh");
160
+ createdStatusLine = true;
161
+ }
162
+ config.statusLine = { ...config.statusLine, type: "command", command: originalStatusLineCommand };
163
+
164
+ const statusLineScript = resolveStatusLineScript(originalStatusLineCommand);
165
+ const statusLineInstalled = Boolean(
166
+ statusLineScript && installStatusLinePrelude(statusLineScript, createdStatusLine)
167
+ );
168
+ if (!statusLineInstalled) {
169
+ console.warn(`未修改 Claude status line:command 不是可直接编辑的脚本路径:${originalStatusLineCommand}`);
170
+ console.warn("Claude Hooks 仍会正常工作,但 CC Pets 暂时无法采集 Claude 额度。");
171
+ }
99
172
 
100
173
  const temporaryPath = `${settingsPath}.cc-pets.tmp`;
101
174
  fs.writeFileSync(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
102
175
  fs.renameSync(temporaryPath, settingsPath);
103
176
  fs.chmodSync(settingsPath, 0o600);
104
177
  console.log(`Claude Code Hooks 已安装到 ${settingsPath}`);
105
- console.log("Claude 额度采集已接入现有 status line。首次 API 响应后桌宠会显示额度。");
178
+ if (statusLineInstalled) {
179
+ console.log("Claude 额度采集已接入现有 status line。首次 API 响应后桌宠会显示额度。");
180
+ }
@@ -6,10 +6,9 @@ PROJECT_DIR="${SCRIPT_DIR:h}"
6
6
  LAUNCHER="${PROJECT_DIR}/bin/codex-with-pet"
7
7
  CLAUDE_LAUNCHER="${PROJECT_DIR}/bin/claude-with-pet"
8
8
  SHELL_RC="${ZDOTDIR:-${HOME}}/.zshrc"
9
- START_MARKER="# >>> cc-pets-codex >>>"
10
- END_MARKER="# <<< cc-pets-codex <<<"
11
- CLAUDE_START_MARKER="# >>> cc-pets-claude >>>"
12
- CLAUDE_END_MARKER="# <<< cc-pets-claude <<<"
9
+ SHIM_DIR="${CC_PETS_SHIM_DIR:-${HOME}/.cc-pets/shims}"
10
+ SHIM_START_MARKER="# >>> cc-pets-shims >>>"
11
+ SHIM_END_MARKER="# <<< cc-pets-shims <<<"
13
12
 
14
13
  NODE_EXECUTABLE="${npm_node_execpath:-}"
15
14
  if [[ -z "${NODE_EXECUTABLE}" || ! -x "${NODE_EXECUTABLE}" ]]; then
@@ -26,8 +25,7 @@ export PATH="${NODE_EXECUTABLE:h}:${PATH:-/usr/bin:/bin:/usr/sbin:/sbin}"
26
25
  "${PROJECT_DIR}/scripts/install-app.sh"
27
26
  "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/install-codex-hooks.mjs" "${PROJECT_DIR}/.build/release/cc-pets"
28
27
  "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/install-claude-hooks.mjs" \
29
- "${PROJECT_DIR}/.build/release/cc-pets" \
30
- "${PROJECT_DIR}/bin/claude-statusline-with-pet"
28
+ "${PROJECT_DIR}/.build/release/cc-pets"
31
29
  "${NODE_EXECUTABLE}" "${PROJECT_DIR}/scripts/configure-updater.mjs"
32
30
 
33
31
  PET_APP="${PROJECT_DIR}/.build/release/CC Pets.app"
@@ -55,23 +53,23 @@ if (( PET_WAS_RUNNING )); then
55
53
  print "已重启正在运行的桌宠,使新版本立即生效。"
56
54
  fi
57
55
 
58
- if ! grep -Fq "${START_MARKER}" "${SHELL_RC}" 2>/dev/null; then
59
- {
60
- print ""
61
- print "${START_MARKER}"
62
- print "alias codex=${(q)LAUNCHER}"
63
- print "${END_MARKER}"
64
- } >> "${SHELL_RC}"
65
- fi
56
+ # 早期版本用 alias 接管 codex / claude。alias 名区分大小写,而 macOS 文件系统默认不区分:
57
+ # 用户敲 Claude / CODEX 时 zsh 找不到同名 alias,就直接从 PATH 里命中真二进制,
58
+ # 桌宠不会被拉起。改成 PATH 前置的 shim 目录后,任意大小写写法都会命中同一个文件。
59
+ mkdir -p "${SHIM_DIR}"
60
+ ln -sfn "${LAUNCHER}" "${SHIM_DIR}/codex"
61
+ ln -sfn "${CLAUDE_LAUNCHER}" "${SHIM_DIR}/claude"
66
62
 
67
- if ! grep -Fq "${CLAUDE_START_MARKER}" "${SHELL_RC}" 2>/dev/null; then
63
+ if ! grep -Fq "${SHIM_START_MARKER}" "${SHELL_RC}" 2>/dev/null; then
68
64
  {
69
65
  print ""
70
- print "${CLAUDE_START_MARKER}"
71
- print "alias claude=${(q)CLAUDE_LAUNCHER}"
72
- print "${CLAUDE_END_MARKER}"
66
+ print "${SHIM_START_MARKER}"
67
+ # 追加在 .zshrc 末尾,保证排在 nvm 之类会前置 PATH 的初始化之后;
68
+ # 含入判断让重复 source .zshrc 不会把同一个目录堆进 PATH。
69
+ print "[[ \":\${PATH}:\" == *\":${SHIM_DIR}:\"* ]] || export PATH=${(q)SHIM_DIR}\":\${PATH}\""
70
+ print "${SHIM_END_MARKER}"
73
71
  } >> "${SHELL_RC}"
74
72
  fi
75
73
 
76
- print "安装完成。CC Pets 已加入 ${(q)INSTALLED_PET_APP};执行 source ${(q)SHELL_RC},之后运行 codex 或 claude 会自动启动桌宠。"
74
+ print "安装完成。CC Pets 已加入 ${(q)INSTALLED_PET_APP};执行 source ${(q)SHELL_RC},之后运行 codex 或 claude(含 Codex / Claude 等任意大小写写法)会自动启动桌宠。"
77
75
  print "首次启动后执行 /hooks,信任 CC Pets Hooks 以启用 Agent 工作动画。"
@@ -15,6 +15,9 @@ const currentClaudeHook = { marker: "CC_PETS_CLAUDE_AGENT_HOOK=1", executable: "
15
15
  const legacyClaudeHook = { marker: "CLAUDE_PET_AGENT_HOOK=1", executable: "codex-pet" };
16
16
  const currentStatusLineMarker = "CC_PETS_CLAUDE_STATUS_LINE=1";
17
17
  const legacyStatusLineMarker = "CLAUDE_PET_STATUS_LINE=1";
18
+ const statusLineStartMarker = "# >>> cc-pets-statusline >>>";
19
+ const statusLineEndMarker = "# <<< cc-pets-statusline <<<";
20
+ const createdStatusLineMarker = "# CC Pets created this status line script";
18
21
 
19
22
  function isManagedHookCommand(value, signature) {
20
23
  return typeof value === "string" &&
@@ -28,6 +31,43 @@ function isManagedStatusLine(value, marker) {
28
31
  /\/bin\/claude-statusline-with-pet' '[A-Za-z0-9+/=]*'$/.test(value);
29
32
  }
30
33
 
34
+ function resolveStatusLineScript(value) {
35
+ if (typeof value !== "string") return null;
36
+ let candidate = value.trim();
37
+ const quoted = candidate.match(/^(['"])(.*)\1$/s);
38
+ if (quoted) candidate = quoted[2];
39
+ if (candidate.startsWith("~/")) candidate = path.join(os.homedir(), candidate.slice(2));
40
+ if (!path.isAbsolute(candidate) || /[\s;&|<>`$()]/.test(candidate)) return null;
41
+ return path.resolve(candidate);
42
+ }
43
+
44
+ function removeStatusLinePrelude(scriptPath) {
45
+ if (!scriptPath || !fs.existsSync(scriptPath)) return { changed: false, created: false };
46
+ const stats = fs.statSync(scriptPath);
47
+ if (!stats.isFile()) return { changed: false, created: false };
48
+ const original = fs.readFileSync(scriptPath, "utf8");
49
+ const expression = new RegExp(
50
+ `(?:^|\\n)${escapeRegExp(statusLineStartMarker)}\\n[\\s\\S]*?\\n${escapeRegExp(statusLineEndMarker)}(?=\\n|$)`,
51
+ "g"
52
+ );
53
+ const updated = original
54
+ .replace(expression, "")
55
+ .replace(/^\n+/, "")
56
+ .replace(/\n{3,}/g, "\n\n")
57
+ .replace(/\n*$/, "\n");
58
+ if (updated === original) return { changed: false, created: false };
59
+ const created = updated === `#!/bin/zsh\n${createdStatusLineMarker}\n`;
60
+ if (created) {
61
+ fs.unlinkSync(scriptPath);
62
+ } else {
63
+ const temporaryPath = `${scriptPath}.cc-pets.tmp`;
64
+ fs.writeFileSync(temporaryPath, updated, { mode: stats.mode });
65
+ fs.renameSync(temporaryPath, scriptPath);
66
+ fs.chmodSync(scriptPath, stats.mode);
67
+ }
68
+ return { changed: true, created };
69
+ }
70
+
31
71
  function writeJSON(filePath, value) {
32
72
  const temporaryPath = `${filePath}.cc-pets.tmp`;
33
73
  fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
@@ -96,6 +136,12 @@ const claudeChanged = updateJSON(claudeSettingsPath, (config) => {
96
136
  else delete config.statusLine;
97
137
  changed = true;
98
138
  }
139
+ if (!preparingInstall) {
140
+ const scriptPath = resolveStatusLineScript(config.statusLine?.command);
141
+ const statusLineResult = removeStatusLinePrelude(scriptPath);
142
+ if (statusLineResult.created) delete config.statusLine;
143
+ if (statusLineResult.changed) changed = true;
144
+ }
99
145
  return changed;
100
146
  });
101
147
 
@@ -114,7 +160,11 @@ function removeMarkedBlock(text, startMarker, endMarker) {
114
160
  let shellChanged = false;
115
161
  if (shellRC && fs.existsSync(shellRC)) {
116
162
  const original = fs.readFileSync(shellRC, "utf8");
117
- let updated = removeMarkedBlock(original, "# >>> cc-pets-codex >>>", "# <<< cc-pets-codex <<<");
163
+ // cc-pets-codex / cc-pets-claude 是 alias 时代的段落。alias 区分大小写,挡不住
164
+ // Claude / CODEX 这类写法,已被 cc-pets-shims 的 PATH shim 取代;安装前的
165
+ // --prepare-install 会走到这里,顺带把老段落迁移掉。
166
+ let updated = removeMarkedBlock(original, "# >>> cc-pets-shims >>>", "# <<< cc-pets-shims <<<");
167
+ updated = removeMarkedBlock(updated, "# >>> cc-pets-codex >>>", "# <<< cc-pets-codex <<<");
118
168
  updated = removeMarkedBlock(updated, "# >>> cc-pets-claude >>>", "# <<< cc-pets-claude <<<");
119
169
  updated = removeMarkedBlock(updated, "# >>> codex-pet >>>", "# <<< codex-pet <<<");
120
170
  updated = removeMarkedBlock(updated, "# >>> claude-pet >>>", "# <<< claude-pet <<<");
@@ -128,10 +178,33 @@ if (shellRC && fs.existsSync(shellRC)) {
128
178
  }
129
179
  }
130
180
 
181
+ // shim 只在真正卸载时删:--prepare-install 之后紧接着就是重建,删了反而在
182
+ // 重建失败时留下一个没有 codex / claude 的 PATH 目录。
183
+ let shimChanged = false;
184
+ const shimDirectory = process.env.CC_PETS_SHIM_DIR || path.join(os.homedir(), ".cc-pets", "shims");
185
+ if (!preparingInstall && fs.existsSync(shimDirectory)) {
186
+ for (const name of ["codex", "claude"]) {
187
+ const shimPath = path.join(shimDirectory, name);
188
+ // lstat:shim 是软链,目标包被 npm uninstall 删掉后 existsSync 会是 false。
189
+ let stats = null;
190
+ try {
191
+ stats = fs.lstatSync(shimPath);
192
+ } catch {
193
+ continue;
194
+ }
195
+ if (!stats.isSymbolicLink()) continue;
196
+ if (!fs.readlinkSync(shimPath).endsWith(`/bin/${name}-with-pet`)) continue;
197
+ fs.rmSync(shimPath, { force: true });
198
+ shimChanged = true;
199
+ }
200
+ if (fs.readdirSync(shimDirectory).length === 0) fs.rmdirSync(shimDirectory);
201
+ }
202
+
131
203
  const action = preparingInstall ? "已迁移" : "已移除";
132
204
  if (codexChanged) console.log(`${action} ${codexHooksPath} 中的 CC Pets Hooks。`);
133
205
  if (claudeChanged) console.log(`${action} ${claudeSettingsPath} 中的 CC Pets Hooks,并恢复原 status line。`);
134
- if (shellChanged) console.log(`${action} ${shellRC} 中的 CC Pets aliases。`);
135
- if (!codexChanged && !claudeChanged && !shellChanged && !preparingInstall) {
206
+ if (shellChanged) console.log(`${action} ${shellRC} 中的 CC Pets shell 集成。`);
207
+ if (shimChanged) console.log(`${action} ${shimDirectory} 中的 codex / claude shim。`);
208
+ if (!codexChanged && !claudeChanged && !shellChanged && !shimChanged && !preparingInstall) {
136
209
  console.log("未发现需要移除的 CC Pets 集成。 ");
137
210
  }