cc-pets 2.0.3 → 2.1.1

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 (50) hide show
  1. package/CC_BRIDGE.md +239 -0
  2. package/CC_BRIDGE.zh-CN.md +210 -0
  3. package/CHANGELOG.md +49 -0
  4. package/CHANGELOG.zh-CN.md +49 -0
  5. package/PROVIDER_PROTOCOL.md +6 -0
  6. package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
  7. package/README.md +17 -1
  8. package/README.zh-CN.md +18 -2
  9. package/Sources/CCPets/CCPetsAppDelegate.h +17 -2
  10. package/Sources/CCPets/CCPetsAppDelegate.m +478 -56
  11. package/Sources/CCPets/CCPetsBridge.h +43 -0
  12. package/Sources/CCPets/CCPetsBridge.m +198 -0
  13. package/Sources/CCPets/CCPetsCleanup.m +3 -1
  14. package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
  15. package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
  16. package/Sources/CCPets/CCPetsEvents.m +1 -1
  17. package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
  18. package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
  19. package/Sources/CCPets/CCPetsGlassView.h +31 -0
  20. package/Sources/CCPets/CCPetsGlassView.m +246 -0
  21. package/Sources/CCPets/CCPetsPaths.h +7 -0
  22. package/Sources/CCPets/CCPetsPaths.m +14 -0
  23. package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
  24. package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
  25. package/Sources/CCPets/CCPetsUsage.h +2 -0
  26. package/Sources/CCPets/CCPetsUsage.m +69 -18
  27. package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
  28. package/Sources/CCPets/MenuChoiceRow.h +19 -0
  29. package/Sources/CCPets/MenuChoiceRow.m +96 -0
  30. package/Sources/CCPets/MenuHintView.h +15 -0
  31. package/Sources/CCPets/MenuHintView.m +128 -0
  32. package/Sources/CCPets/PetView.m +143 -3
  33. package/Sources/CCPets/QuotaDashboardView.h +3 -4
  34. package/Sources/CCPets/QuotaDashboardView.m +222 -143
  35. package/Sources/CCPets/main.m +16 -0
  36. package/bin/cc-pets +38 -1
  37. package/bin/codex-with-pet +2 -0
  38. package/package.json +3 -1
  39. package/scripts/bridge/cli.mjs +229 -0
  40. package/scripts/bridge/core.mjs +227 -0
  41. package/scripts/bridge/hook.mjs +149 -0
  42. package/scripts/bridge/install.mjs +288 -0
  43. package/scripts/bridge/mcp-server.mjs +300 -0
  44. package/scripts/bridge/options.mjs +86 -0
  45. package/scripts/bridge/process.mjs +129 -0
  46. package/scripts/bridge/reservations.mjs +247 -0
  47. package/scripts/bridge/store.mjs +432 -0
  48. package/scripts/bridge/watch.mjs +69 -0
  49. package/scripts/install-shell-integration.sh +3 -0
  50. package/scripts/uninstall-integrations.mjs +10 -0
@@ -0,0 +1,246 @@
1
+ #import "CCPetsGlassView.h"
2
+ #import <QuartzCore/QuartzCore.h>
3
+
4
+ NSString *const CCPetsPanelThemeKey = @"CCPetsPanelTheme";
5
+
6
+ NSString *CCPetsPanelTheme(void) {
7
+ NSString *theme = [NSUserDefaults.standardUserDefaults stringForKey:CCPetsPanelThemeKey];
8
+ // 早期版本有过 "system" 选项,行为与 liquid 完全一致,读到时按 liquid 处理。
9
+ if ([theme isEqualToString:@"system"]) return @"liquid";
10
+ return [theme isEqualToString:@"liquid"] ? theme : @"classic";
11
+ }
12
+
13
+ NSString *const CCPetsGlassDimKey = @"CCPetsGlassDim";
14
+
15
+ NSArray<NSNumber *> *CCPetsGlassDimLevels(void) { return @[@0, @15, @25, @45]; }
16
+
17
+ // 档位来自对照实测:0 最通透但亮背景下小字看不清;25 在暗、亮壁纸上都基本可读;
18
+ // 45 最清楚但明显偏暗。没设置过或值不在档位里时用 25。
19
+ NSInteger CCPetsGlassDimLevel(void) {
20
+ id stored = [NSUserDefaults.standardUserDefaults objectForKey:CCPetsGlassDimKey];
21
+ if (![stored isKindOfClass:NSNumber.class]) return 25;
22
+ return [CCPetsGlassDimLevels() containsObject:stored] ? [stored integerValue] : 25;
23
+ }
24
+
25
+ CGFloat CCPetsGlassCardScrimAlpha(void) {
26
+ switch (CCPetsGlassDimLevel()) {
27
+ case 0: return 0.06;
28
+ case 15: return 0.10;
29
+ case 45: return 0.16;
30
+ default: return 0.12;
31
+ }
32
+ }
33
+
34
+ BOOL CCPetsLiquidGlassAvailable(void) {
35
+ #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000
36
+ if (@available(macOS 26.0, *)) return YES;
37
+ #endif
38
+ return NO;
39
+ }
40
+
41
+ // 上下沿各一条从边缘向内渐隐的暗带,压 variant 11 自带的上下高光线。
42
+ @interface CCPetsEdgeShadeView : NSView
43
+ @property(nonatomic) CGFloat bandHeight;
44
+ @property(nonatomic) CGFloat bandAlpha;
45
+ @end
46
+
47
+ @implementation CCPetsEdgeShadeView
48
+ - (instancetype)initWithFrame:(NSRect)frame {
49
+ if ((self = [super initWithFrame:frame])) {
50
+ self.wantsLayer = YES;
51
+ self.layer.masksToBounds = YES;
52
+ self.layer.cornerCurve = kCACornerCurveContinuous;
53
+ for (int index = 0; index < 2; index++) [self.layer addSublayer:[CAGradientLayer layer]];
54
+ }
55
+ return self;
56
+ }
57
+ - (NSView *)hitTest:(NSPoint)point { return nil; }
58
+ - (void)setFrameSize:(NSSize)size {
59
+ [super setFrameSize:size];
60
+ [self updateBands];
61
+ }
62
+ - (void)updateBands {
63
+ [CATransaction begin];
64
+ [CATransaction setDisableActions:YES];
65
+ id dark = (id)[NSColor colorWithWhite:0 alpha:self.bandAlpha].CGColor;
66
+ id clear = (id)[NSColor colorWithWhite:0 alpha:0].CGColor;
67
+ NSArray<CAGradientLayer *> *bands = (NSArray<CAGradientLayer *> *)self.layer.sublayers;
68
+ // 底带暗色贴下沿,顶带暗色贴上沿;CAGradientLayer 的颜色顺序沿 layer 坐标 y 递增。
69
+ bands[0].frame = CGRectMake(0, 0, NSWidth(self.bounds), self.bandHeight);
70
+ bands[0].colors = @[dark, clear];
71
+ bands[1].frame = CGRectMake(0, NSHeight(self.bounds) - self.bandHeight,
72
+ NSWidth(self.bounds), self.bandHeight);
73
+ bands[1].colors = @[clear, dark];
74
+ [CATransaction commit];
75
+ }
76
+ @end
77
+
78
+ @interface CCPetsGlassView ()
79
+ @property(nonatomic) NSView *contentView;
80
+ @property(nonatomic) NSView *effectView;
81
+ @property(nonatomic) NSView *backdropDimView;
82
+ @property(nonatomic) CCPetsEdgeShadeView *edgeShadeView;
83
+ @property(nonatomic) BOOL experimentalVariantApplied;
84
+ @property(nonatomic) BOOL usesLiquidGlass;
85
+ @property(nonatomic) NSVisualEffectMaterial fallbackMaterial;
86
+ @end
87
+
88
+ @implementation CCPetsGlassView
89
+ - (instancetype)initWithFrame:(NSRect)frame material:(NSVisualEffectMaterial)material
90
+ appearance:(NSAppearanceName)appearance cornerRadius:(CGFloat)cornerRadius {
91
+ self = [super initWithFrame:frame];
92
+ if (self) {
93
+ _fallbackMaterial = material;
94
+ _cornerRadius = cornerRadius;
95
+ _edgeShadeHeight = 12;
96
+ _edgeShadeAlpha = 0.6;
97
+ self.appearance = [NSAppearance appearanceNamed:appearance];
98
+ _contentView = [[NSView alloc] initWithFrame:self.bounds];
99
+ _contentView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
100
+ [self applyTheme];
101
+ }
102
+ return self;
103
+ }
104
+
105
+ - (void)applyTheme {
106
+ #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000
107
+ if (@available(macOS 26.0, *)) {
108
+ if ([self.effectView isKindOfClass:NSGlassEffectView.class]) {
109
+ ((NSGlassEffectView *)self.effectView).contentView = nil;
110
+ }
111
+ }
112
+ #endif
113
+ [self.contentView removeFromSuperview];
114
+ // NSGlassEffectView 接管 contentView 时会把它改成 Auto Layout(关掉自动转换约束)。
115
+ // 移到别的父视图后若不恢复,布局引擎会按固有尺寸把它压成 0 宽,里面的滚动视图随之
116
+ // 变成 0×0、内容全被裁掉(实测)。重建时统一恢复成按 autoresizingMask 布局。
117
+ self.contentView.translatesAutoresizingMaskIntoConstraints = YES;
118
+ [self.effectView removeFromSuperview];
119
+ [self.backdropDimView removeFromSuperview];
120
+ self.backdropDimView = nil;
121
+ [self.edgeShadeView removeFromSuperview];
122
+ self.edgeShadeView = nil;
123
+ self.experimentalVariantApplied = NO;
124
+ self.usesLiquidGlass = NO;
125
+ self.contentView.frame = self.bounds;
126
+ // 编译期和运行期双重保护,仍能用旧 SDK 构建并在 macOS 13 上运行。
127
+ #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000
128
+ if (@available(macOS 26.0, *)) {
129
+ if ([CCPetsPanelTheme() isEqualToString:@"liquid"]) {
130
+ NSGlassEffectView *glass = [[NSGlassEffectView alloc] initWithFrame:self.bounds];
131
+ glass.style = self.usesWidgetGlass
132
+ ? NSGlassEffectViewStyleClear : NSGlassEffectViewStyleRegular;
133
+ if (self.usesWidgetGlass) glass = [self applyWidgetGlass:glass];
134
+ glass.cornerRadius = self.cornerRadius;
135
+ // 暗带要盖在玻璃上、又不能盖住文字,所以私有 variant 生效时内容改放到玻璃
136
+ // 外面最上层;玻璃只拿一个空的 contentView。
137
+ glass.contentView = self.experimentalVariantApplied
138
+ ? [[NSView alloc] initWithFrame:self.bounds] : self.contentView;
139
+ self.effectView = glass;
140
+ self.usesLiquidGlass = YES;
141
+ }
142
+ }
143
+ #endif
144
+ if (!self.usesLiquidGlass) {
145
+ NSVisualEffectView *blur = [[NSVisualEffectView alloc] initWithFrame:self.bounds];
146
+ blur.material = self.fallbackMaterial;
147
+ blur.blendingMode = NSVisualEffectBlendingModeBehindWindow;
148
+ blur.state = NSVisualEffectStateActive;
149
+ blur.wantsLayer = YES;
150
+ blur.layer.cornerRadius = self.cornerRadius;
151
+ blur.layer.cornerCurve = kCACornerCurveContinuous;
152
+ blur.layer.masksToBounds = YES;
153
+ if (self.fallbackMaterial == NSVisualEffectMaterialPopover) {
154
+ blur.layer.borderWidth = 1;
155
+ blur.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
156
+ }
157
+ [blur addSubview:self.contentView];
158
+ self.effectView = blur;
159
+ }
160
+ self.effectView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
161
+ [self addSubview:self.effectView];
162
+ if (self.experimentalVariantApplied) {
163
+ CCPetsEdgeShadeView *shade = [[CCPetsEdgeShadeView alloc] initWithFrame:self.bounds];
164
+ shade.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
165
+ shade.layer.cornerRadius = self.cornerRadius;
166
+ // 默认 12pt / 0.6 是额度面板的对照实测值:再深会在亮背景上压出一条明显的黑带,
167
+ // 再浅压不住深色背景上的亮线。
168
+ shade.bandHeight = self.edgeShadeHeight;
169
+ shade.bandAlpha = self.edgeShadeAlpha;
170
+ [shade updateBands];
171
+ [self addSubview:shade];
172
+ self.edgeShadeView = shade;
173
+ [self addSubview:self.contentView];
174
+ self.contentView.frame = self.bounds;
175
+ }
176
+ }
177
+
178
+ #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000
179
+ // macOS 27 上实测:公开的 Clear/Regular 在 App 未激活、窗口不是 key 时会被换成磨砂的
180
+ // 非激活样式;桌宠永远是 nonactivating 面板,在这个系统上公开样式基本是一块奶白。未公开的
181
+ // _variant 不跟随 key 状态,能保持清透和折射。扫过 0–35:只有 11 有厚玻璃的边缘折射,
182
+ // 但它上下沿自带很亮的高光线,深色背景下扎眼,由 CCPetsEdgeShadeView 压下去;14 没有亮线,
183
+ // 但折射也几乎没了,看起来不像玻璃。它是实现细节而不是
184
+ // API:只在验证过的系统主版本上启用,并可用 defaults 关掉,其余情况一律用公开 Clear。
185
+ static BOOL CCPetsExperimentalGlassVariantEnabled(void) {
186
+ if ([NSUserDefaults.standardUserDefaults boolForKey:@"CCPetsDisableExperimentalGlass"]) return NO;
187
+ return NSProcessInfo.processInfo.operatingSystemVersion.majorVersion == 27;
188
+ }
189
+ //
190
+ // 可读性不能靠 tintColor 或 contentView 里的深色底:前者对这个 variant 无效,后者会被
191
+ // 玻璃的 vibrant 混合吃掉。有效的做法是把压暗层放在玻璃背后,让玻璃采样到的背景本身
192
+ // 变暗,折射和高光都还在。
193
+ //
194
+ // 压暗层在私有 variant 失败、被关闭或系统版本不符时同样保留:此时公开 Clear 在非 key
195
+ // 窗口里是磨砂,没有这层垫底白字会更难读。这是刻意的设计,不是遗留。
196
+ - (NSGlassEffectView *)applyWidgetGlass:(NSGlassEffectView *)glass API_AVAILABLE(macos(26.0)) {
197
+ if (CCPetsExperimentalGlassVariantEnabled() &&
198
+ [glass respondsToSelector:NSSelectorFromString(@"set_variant:")]) {
199
+ @try {
200
+ [glass setValue:@11 forKey:@"_variant"];
201
+ self.experimentalVariantApplied = YES;
202
+ } @catch (NSException *exception) {
203
+ // 赋值抛到一半时内部状态不可信,换一个全新的公开 Clear 实例。
204
+ glass = [[NSGlassEffectView alloc] initWithFrame:self.bounds];
205
+ glass.style = NSGlassEffectViewStyleClear;
206
+ }
207
+ }
208
+ NSView *dim = [[NSView alloc] initWithFrame:self.bounds];
209
+ dim.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
210
+ dim.wantsLayer = YES;
211
+ dim.layer.cornerRadius = self.cornerRadius;
212
+ dim.layer.cornerCurve = kCACornerCurveContinuous;
213
+ [self addSubview:dim];
214
+ self.backdropDimView = dim;
215
+ [self applyDimLevel];
216
+ return glass;
217
+ }
218
+ #endif
219
+
220
+ - (void)applyDimLevel {
221
+ CGFloat alpha = CCPetsGlassDimLevel() / 100.0;
222
+ self.backdropDimView.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:alpha].CGColor;
223
+ self.backdropDimView.hidden = alpha <= 0;
224
+ }
225
+
226
+ - (void)setUsesWidgetGlass:(BOOL)usesWidgetGlass {
227
+ if (_usesWidgetGlass == usesWidgetGlass) return;
228
+ _usesWidgetGlass = usesWidgetGlass;
229
+ [self applyTheme];
230
+ }
231
+
232
+ - (void)setCornerRadius:(CGFloat)cornerRadius {
233
+ _cornerRadius = cornerRadius;
234
+ self.backdropDimView.layer.cornerRadius = cornerRadius;
235
+ self.edgeShadeView.layer.cornerRadius = cornerRadius;
236
+ #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000
237
+ if (@available(macOS 26.0, *)) {
238
+ if (self.usesLiquidGlass) {
239
+ ((NSGlassEffectView *)self.effectView).cornerRadius = cornerRadius;
240
+ return;
241
+ }
242
+ }
243
+ #endif
244
+ self.effectView.layer.cornerRadius = cornerRadius;
245
+ }
246
+ @end
@@ -8,6 +8,13 @@ NSString *ClaudeUsagePath(void);
8
8
  // 额度文件的写锁。挂在单独的文件上:数据文件本身由 rename 整体替换,
9
9
  // 锁在它上面的话两个写者会锁到不同的 inode,等于没锁。
10
10
  NSString *ClaudeUsageLockPath(void);
11
+ // 最近一次 Codex App Server 实时额度。桌宠随最后一个客户端退出,重启后先用它,
12
+ // 不从会话日志里可能早已过时的快照起步。
13
+ NSString *CodexLiveUsagePath(void);
14
+ // codex-with-pet 每次启动登记的终端,以及 Codex 会话(thread)与它的配对。
15
+ // 读改写必须在锁里:多个 hook 可能同时第一次见到各自的新会话。
16
+ NSString *CodexLaunchRegistryPath(void);
17
+ NSString *CodexLaunchRegistryLockPath(void);
11
18
  // 桌宠端用:只看主账号,不受继承来的 CLAUDE_CONFIG_DIR 影响。
12
19
  NSString *DefaultClaudeConfigDirectory(void);
13
20
  NSString *CurrentClaudeConfigDirectory(void);
@@ -107,6 +107,20 @@ NSString *ClaudeUsageLockPath(void) {
107
107
  return [ClaudeUsagePath() stringByAppendingPathExtension:@"lock"];
108
108
  }
109
109
 
110
+ NSString *CodexLiveUsagePath(void) {
111
+ NSString *name = [NSString stringWithFormat:@"cc-pets-%u-codex-live-usage.json", getuid()];
112
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
113
+ }
114
+
115
+ NSString *CodexLaunchRegistryPath(void) {
116
+ NSString *name = [NSString stringWithFormat:@"cc-pets-%u-codex-launches.json", getuid()];
117
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
118
+ }
119
+
120
+ NSString *CodexLaunchRegistryLockPath(void) {
121
+ return [CodexLaunchRegistryPath() stringByAppendingPathExtension:@"lock"];
122
+ }
123
+
110
124
  NSString *ApplicationSupportDirectory(void) {
111
125
  NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_APPLICATION_SUPPORT_DIR"];
112
126
  if (override.length > 0) return override.stringByStandardizingPath;
@@ -2,10 +2,25 @@
2
2
 
3
3
  // 包装脚本在 Agent 启动时固定下来的终端身份。Hook 子进程继承这些环境变量,
4
4
  // 因此任务结束时即使用户已经切到别的应用,也不会把目标错记成当前前台窗口。
5
+ // 由 Codex 共享服务(app-server --managed-daemon)拉起的 hook 返回空目标,见实现处注释。
5
6
  NSDictionary *TerminalFocusTargetFromEnvironment(void);
7
+ BOOL TerminalFocusRunsUnderSharedAgentHost(void);
8
+
9
+ // hook 用:普通情况同 TerminalFocusTargetFromEnvironment;Codex 共享服务下按会话 ID 找
10
+ // codex-with-pet 登记的终端,找不到返回空目标。
11
+ NSDictionary *TerminalFocusTargetForHook(NSDictionary *payload, NSString *provider);
12
+ // cc-pets --codex-launch:codex-with-pet 在 exec 真正的 codex 之前登记自己的终端。
13
+ int RegisterCodexLaunch(void);
14
+ // 以下两个供测试直接驱动。
15
+ BOOL RegisterCodexLaunchForProcess(pid_t pid, NSString *cwd, NSDictionary *terminal,
16
+ NSTimeInterval launchedAt);
17
+ NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload);
6
18
 
7
19
  // Terminal / iTerm2 按 TTY 精确选中 tab/session;其他终端在无扩展模式下激活应用。
8
20
  BOOL ActivateTerminalFocusTarget(NSDictionary *target);
9
21
 
22
+ // 回跳目标的候选 bundle ID,按优先级排列,已去重去空。
23
+ NSArray<NSString *> *TerminalFocusBundleCandidates(NSDictionary *target);
24
+
10
25
  // 供包装脚本在 exec Agent 之前捕获承载终端的应用。
11
26
  NSString *FrontmostApplicationBundleIdentifier(void);
@@ -1,5 +1,8 @@
1
1
  #import "CCPetsTerminalFocus.h"
2
2
  #import "CCPetsEvents.h"
3
+ #import "CCPetsPaths.h"
4
+ #import <fcntl.h>
5
+ #import <sys/file.h>
3
6
  #import <sys/sysctl.h>
4
7
  #import <sys/stat.h>
5
8
  #import <stdlib.h>
@@ -40,12 +43,53 @@ static NSString *HostApplicationBundleIdentifier(void) {
40
43
  return @"";
41
44
  }
42
45
 
46
+ // KERN_PROCARGS2 的布局:argc(int),可执行文件路径,若干 \0 填充,然后是 argc 个参数。
47
+ static NSArray<NSString *> *ProcessArguments(pid_t pid) {
48
+ int name[3] = { CTL_KERN, KERN_PROCARGS2, pid };
49
+ size_t size = 0;
50
+ if (sysctl(name, 3, NULL, &size, NULL, 0) != 0 || size <= sizeof(int)) return @[];
51
+ NSMutableData *buffer = [NSMutableData dataWithLength:size];
52
+ if (sysctl(name, 3, buffer.mutableBytes, &size, NULL, 0) != 0 || size <= sizeof(int)) return @[];
53
+ const char *bytes = buffer.bytes;
54
+ int argc = 0;
55
+ memcpy(&argc, bytes, sizeof(argc));
56
+ size_t offset = sizeof(argc);
57
+ while (offset < size && bytes[offset] != '\0') offset++; // 可执行文件路径
58
+ while (offset < size && bytes[offset] == '\0') offset++;
59
+ NSMutableArray<NSString *> *arguments = [NSMutableArray array];
60
+ while (offset < size && (int)arguments.count < argc) {
61
+ size_t length = strnlen(bytes + offset, size - offset);
62
+ NSString *argument = [[NSString alloc] initWithBytes:bytes + offset length:length
63
+ encoding:NSUTF8StringEncoding];
64
+ [arguments addObject:argument ?: @""];
65
+ offset += length + 1;
66
+ }
67
+ return arguments;
68
+ }
69
+
70
+ // 新版 Codex 把各个终端里的会话都交给一个常驻的共享服务(codex app-server --managed-daemon)
71
+ // 执行,hook 是这个服务拉起的,继承的是它自己的环境。那份环境停在第一次拉起服务的终端上:
72
+ // 实测服务从 IntelliJ 启动后,VS Code 里的 Codex 会话事件全被记成 IntelliJ 的 ttys001,
73
+ // 点气泡跳到了别的终端。此时 CC_PETS_TERMINAL_*、控制终端、父进程链都说明不了会话在哪儿。
74
+ BOOL TerminalFocusRunsUnderSharedAgentHost(void) {
75
+ pid_t pid = getppid();
76
+ for (NSUInteger depth = 0; depth < 16 && pid > 1; depth++) {
77
+ if ([ProcessArguments(pid) containsObject:@"--managed-daemon"]) return YES;
78
+ struct kinfo_proc info;
79
+ if (!ProcessInfoForPID(pid, &info)) break;
80
+ pid = info.kp_eproc.e_ppid;
81
+ }
82
+ return NO;
83
+ }
84
+
43
85
  static NSString *TerminalTargetValue(NSDictionary<NSString *, NSString *> *environment,
44
86
  NSString *key, NSUInteger maximumLength) {
45
87
  return SanitizedShortString(environment[key], maximumLength);
46
88
  }
47
89
 
48
90
  NSDictionary *TerminalFocusTargetFromEnvironment(void) {
91
+ // 记不准就不记:没有目标时点气泡不跳,比跳到别人的终端好。
92
+ if (TerminalFocusRunsUnderSharedAgentHost()) return @{};
49
93
  NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
50
94
  NSString *tty = environment[@"CC_PETS_TERMINAL_TTY"];
51
95
  if ([tty isKindOfClass:NSString.class]) tty = tty.lastPathComponent;
@@ -127,24 +171,271 @@ static NSString *BundleIDForTerminalProgram(NSString *program) {
127
171
  return @"";
128
172
  }
129
173
 
130
- BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
131
- if (![target isKindOfClass:NSDictionary.class]) return NO;
132
- NSString *tty = SanitizedShortString(target[@"tty"], 64);
174
+ // TERM_PROGRAM=vscode 是整个 VS Code 家族共用的标记:官方 VS Code、Cursor、Windsurf、
175
+ // Antigravity 这些分支全都这么写。它认不出具体是哪一个应用,固定映射到 com.microsoft.
176
+ // VSCode 就会把所有分支编辑器的回跳打死——那个 bundle ID 在机器上根本没有进程,激活
177
+ // 直接失败,点状态卡片毫无反应。家族内部谁是谁只有捕获到的 bundleID 知道。
178
+ static BOOL TerminalProgramIsVSCodeFamily(NSString *program) {
179
+ return [program.lowercaseString isEqualToString:@"vscode"];
180
+ }
181
+
182
+ NSArray<NSString *> *TerminalFocusBundleCandidates(NSDictionary *target) {
183
+ if (![target isKindOfClass:NSDictionary.class]) return @[];
184
+ NSString *program = SanitizedShortString(target[@"program"], 64);
133
185
  // 已知 TERM_PROGRAM 比“启动瞬间的前台应用”更可靠:VS Code Task 可能在窗口不位于
134
186
  // 前台时启动 shell。JetBrains 等没有稳定统一 bundle ID 的宿主才使用捕获值兜底。
135
- NSString *bundleID = BundleIDForTerminalProgram(
136
- SanitizedShortString(target[@"program"], 64));
137
- if (bundleID.length == 0) bundleID = SanitizedShortString(target[@"bundleID"], 128);
138
- if (bundleID.length == 0) return NO;
139
- if (RunTerminalSelectionScript(bundleID, tty)) return YES;
140
-
141
- NSArray<NSRunningApplication *> *applications =
142
- [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
143
- NSRunningApplication *application = applications.firstObject;
144
- if (!application) return NO;
187
+ // vscode 家族是例外,那个值分不出分支,只能反过来让捕获值当第一候选。
188
+ NSString *mapped = BundleIDForTerminalProgram(program);
189
+ NSString *captured = SanitizedShortString(target[@"bundleID"], 128);
190
+ NSArray<NSString *> *ordered = TerminalProgramIsVSCodeFamily(program)
191
+ ? @[captured, mapped] : @[mapped, captured];
192
+ NSMutableArray<NSString *> *candidates = [NSMutableArray array];
193
+ for (NSString *candidate in ordered) {
194
+ if (candidate.length == 0 || [candidates containsObject:candidate]) continue;
195
+ [candidates addObject:candidate];
196
+ }
197
+ return candidates;
198
+ }
199
+
200
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
201
+ NSString *tty = SanitizedShortString(target[@"tty"], 64);
202
+ // 候选按优先级往下试,没在运行的直接跳过:映射值和捕获值总有一个指向真正承载
203
+ // 会话的那个应用,卡在第一个候选上就会白白丢掉一次可用的回跳。
204
+ for (NSString *bundleID in TerminalFocusBundleCandidates(target)) {
205
+ if (RunTerminalSelectionScript(bundleID, tty)) return YES;
206
+ NSRunningApplication *application =
207
+ [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID].firstObject;
208
+ if (!application) continue;
145
209
  #pragma clang diagnostic push
146
210
  #pragma clang diagnostic ignored "-Wdeprecated-declarations"
147
- return [application activateWithOptions:
148
- NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
211
+ return [application activateWithOptions:
212
+ NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
149
213
  #pragma clang diagnostic pop
214
+ }
215
+ return NO;
216
+ }
217
+
218
+ #pragma mark - Codex 共享服务下的会话 → 终端配对
219
+
220
+ // Codex 共享服务拉起的 hook 不知道会话在哪个终端(见 TerminalFocusRunsUnderSharedAgentHost)。
221
+ // 能确定的只有两头:codex-with-pet 启动时知道自己的终端、工作目录和时刻;hook 知道会话 ID,
222
+ // 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。新会话在 CLI 启动后一秒左右
223
+ // 就会创建,所以"同一目录里、紧挨在会话创建之前启动的那个 CLI"就是它的终端。配对结果记下来,
224
+ // 同一会话之后的事件直接查表。
225
+ static const NSUInteger CodexLaunchThreadLimit = 32;
226
+ static const NSTimeInterval CodexThreadCreationSlack = 5.0;
227
+
228
+ static NSTimeInterval ProcessStartTime(pid_t pid) {
229
+ struct kinfo_proc info;
230
+ if (!ProcessInfoForPID(pid, &info)) return 0;
231
+ struct timeval start = info.kp_proc.p_starttime;
232
+ return start.tv_sec + start.tv_usec / 1e6;
233
+ }
234
+
235
+ // pid 会被复用,只看 kill(pid, 0) 可能把登记套到一个毫不相干的新进程上。启动时刻对得上才算同一个。
236
+ static BOOL CodexLaunchIsAlive(NSDictionary *entry) {
237
+ pid_t pid = (pid_t)[entry[@"pid"] intValue];
238
+ if (pid <= 1) return NO;
239
+ NSTimeInterval started = ProcessStartTime(pid);
240
+ return started > 0 && fabs(started - [entry[@"processStartedAt"] doubleValue]) < 1.0;
241
+ }
242
+
243
+ static int LockCodexLaunchRegistry(void) {
244
+ NSString *path = CodexLaunchRegistryLockPath();
245
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
246
+ withIntermediateDirectories:YES attributes:nil error:nil];
247
+ int descriptor = open(path.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
248
+ if (descriptor < 0) return -1;
249
+ // 同 Claude 额度文件的写锁:拿不到就放弃这一次,hook 不能被一个卡住的写者挂住。
250
+ for (int attempt = 0; attempt < 50; attempt++) {
251
+ if (flock(descriptor, LOCK_EX | LOCK_NB) == 0) return descriptor;
252
+ if (errno != EWOULDBLOCK) break;
253
+ usleep(20 * 1000);
254
+ }
255
+ close(descriptor);
256
+ return -1;
257
+ }
258
+
259
+ static void UnlockCodexLaunchRegistry(int descriptor) {
260
+ flock(descriptor, LOCK_UN);
261
+ close(descriptor);
262
+ }
263
+
264
+ // 读出来时顺手丢掉已经退出的 CLI:它们不可能再是任何新会话的终端。
265
+ static NSMutableDictionary<NSString *, NSDictionary *> *LoadLiveCodexLaunches(void) {
266
+ NSData *data = [NSData dataWithContentsOfFile:CodexLaunchRegistryPath()];
267
+ id value = data.length > 0 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
268
+ NSMutableDictionary *launches = [NSMutableDictionary dictionary];
269
+ if (![value isKindOfClass:NSDictionary.class]) return launches;
270
+ [(NSDictionary *)value enumerateKeysAndObjectsUsingBlock:^(id key, id entry, BOOL *stop) {
271
+ if ([key isKindOfClass:NSString.class] && [entry isKindOfClass:NSDictionary.class] &&
272
+ CodexLaunchIsAlive(entry)) launches[key] = entry;
273
+ }];
274
+ return launches;
275
+ }
276
+
277
+ static void SaveCodexLaunches(NSDictionary *launches) {
278
+ NSData *json = [NSJSONSerialization dataWithJSONObject:launches options:0 error:nil];
279
+ NSString *path = CodexLaunchRegistryPath();
280
+ if (json && [json writeToFile:path options:NSDataWritingAtomic error:nil]) {
281
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
282
+ }
283
+ }
284
+
285
+ BOOL RegisterCodexLaunchForProcess(pid_t pid, NSString *cwd, NSDictionary *terminal,
286
+ NSTimeInterval launchedAt) {
287
+ NSTimeInterval processStartedAt = ProcessStartTime(pid);
288
+ if (processStartedAt <= 0 || cwd.length == 0 || terminal.count == 0) return NO;
289
+ int lock = LockCodexLaunchRegistry();
290
+ if (lock < 0) return NO;
291
+ NSMutableDictionary *launches = LoadLiveCodexLaunches();
292
+ launches[[NSString stringWithFormat:@"%d", pid]] = @{
293
+ @"pid": @(pid),
294
+ @"processStartedAt": @(processStartedAt),
295
+ @"launchedAt": @(launchedAt),
296
+ @"cwd": cwd.stringByStandardizingPath,
297
+ @"terminal": terminal,
298
+ @"threads": @[]
299
+ };
300
+ SaveCodexLaunches(launches);
301
+ UnlockCodexLaunchRegistry(lock);
302
+ return YES;
303
+ }
304
+
305
+ // codex-with-pet 在 exec 真正的 codex 之前调用;exec 不换 pid,所以父进程就是之后的 CLI。
306
+ int RegisterCodexLaunch(void) {
307
+ RegisterCodexLaunchForProcess(getppid(), NSFileManager.defaultManager.currentDirectoryPath,
308
+ TerminalFocusTargetFromEnvironment(), NSDate.date.timeIntervalSince1970);
309
+ return EXIT_SUCCESS;
310
+ }
311
+
312
+ // 会话记录按 sessions/YYYY/MM/DD/rollout-<时间>-<会话 ID>.jsonl 存放,目录名字典序即时间序。
313
+ // 刚开始收事件的会话一定在最近几天的目录里;resume 的旧会话找不到也没关系,按工作目录兜底。
314
+ static NSString *CodexRolloutPathForThread(NSString *thread) {
315
+ NSString *sessions = [DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"sessions"];
316
+ NSFileManager *files = NSFileManager.defaultManager;
317
+ NSString *suffix = [NSString stringWithFormat:@"-%@.jsonl", thread];
318
+ NSUInteger examinedDays = 0;
319
+ NSArray *(^descending)(NSString *) = ^NSArray *(NSString *directory) {
320
+ return [[files contentsOfDirectoryAtPath:directory error:nil]
321
+ sortedArrayUsingSelector:@selector(compare:)].reverseObjectEnumerator.allObjects ?: @[];
322
+ };
323
+ for (NSString *year in descending(sessions)) {
324
+ NSString *yearPath = [sessions stringByAppendingPathComponent:year];
325
+ for (NSString *month in descending(yearPath)) {
326
+ NSString *monthPath = [yearPath stringByAppendingPathComponent:month];
327
+ for (NSString *day in descending(monthPath)) {
328
+ if (++examinedDays > 7) return nil;
329
+ NSString *dayPath = [monthPath stringByAppendingPathComponent:day];
330
+ for (NSString *name in [files contentsOfDirectoryAtPath:dayPath error:nil]) {
331
+ if ([name hasSuffix:suffix]) return [dayPath stringByAppendingPathComponent:name];
332
+ }
333
+ }
334
+ }
335
+ }
336
+ return nil;
337
+ }
338
+
339
+ // 第一行是 session_meta,带 cwd 和创建时刻;它里面有完整的系统提示词,可能很长,读到换行为止。
340
+ static NSDictionary *CodexThreadMeta(NSString *thread, NSDictionary *payload) {
341
+ NSString *path = [payload[@"transcript_path"] isKindOfClass:NSString.class]
342
+ ? payload[@"transcript_path"] : nil;
343
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) path = CodexRolloutPathForThread(thread);
344
+ NSFileHandle *handle = path ? [NSFileHandle fileHandleForReadingAtPath:path] : nil;
345
+ NSMutableData *line = [NSMutableData data];
346
+ while (handle && line.length < 8 * 1024 * 1024) {
347
+ NSData *chunk = [handle readDataOfLength:64 * 1024];
348
+ if (chunk.length == 0) break;
349
+ NSRange newline = [chunk rangeOfData:[NSData dataWithBytes:"\n" length:1] options:0
350
+ range:NSMakeRange(0, chunk.length)];
351
+ if (newline.location != NSNotFound) {
352
+ [line appendData:[chunk subdataWithRange:NSMakeRange(0, newline.location)]];
353
+ break;
354
+ }
355
+ [line appendData:chunk];
356
+ }
357
+ [handle closeFile];
358
+ id root = line.length > 0 ? [NSJSONSerialization JSONObjectWithData:line options:0 error:nil] : nil;
359
+ NSDictionary *meta = [root isKindOfClass:NSDictionary.class] &&
360
+ [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : @{};
361
+ NSMutableDictionary *result = [NSMutableDictionary dictionary];
362
+ NSString *cwd = [meta[@"cwd"] isKindOfClass:NSString.class] ? meta[@"cwd"]
363
+ : ([payload[@"cwd"] isKindOfClass:NSString.class] ? payload[@"cwd"] : nil);
364
+ if (cwd.length > 0) result[@"cwd"] = cwd.stringByStandardizingPath;
365
+ if ([meta[@"timestamp"] isKindOfClass:NSString.class]) {
366
+ NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
367
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime |
368
+ NSISO8601DateFormatWithFractionalSeconds;
369
+ NSDate *created = [formatter dateFromString:meta[@"timestamp"]];
370
+ if (!created) {
371
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime;
372
+ created = [formatter dateFromString:meta[@"timestamp"]];
373
+ }
374
+ if (created) result[@"createdAt"] = @(created.timeIntervalSince1970);
375
+ }
376
+ return result;
377
+ }
378
+
379
+ // 在同一工作目录的候选里挑:优先还没配过会话的 CLI;会话创建时刻已知时,取创建前最后一个
380
+ // 启动的(resume 的旧会话创建得比所有 CLI 都早,退回"最近启动的")。一个 TUI 里 /new 出来
381
+ // 的新会话没有空闲候选可配,这时同目录只剩一个 CLI 才认它,多于一个宁可不配。
382
+ static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
383
+ NSString *cwd, NSNumber *createdAt) {
384
+ NSMutableArray<NSString *> *sameDirectory = [NSMutableArray array];
385
+ NSMutableArray<NSString *> *unbound = [NSMutableArray array];
386
+ for (NSString *key in launches) {
387
+ NSDictionary *entry = launches[key];
388
+ if (![entry[@"cwd"] isEqualToString:cwd]) continue;
389
+ [sameDirectory addObject:key];
390
+ if ([entry[@"threads"] count] == 0) [unbound addObject:key];
391
+ }
392
+ if (unbound.count == 0) return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
393
+ NSArray<NSString *> *byLaunch = [unbound sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
394
+ return [launches[a][@"launchedAt"] compare:launches[b][@"launchedAt"]];
395
+ }];
396
+ if (createdAt) {
397
+ NSString *preceding = nil;
398
+ for (NSString *key in byLaunch) {
399
+ if ([launches[key][@"launchedAt"] doubleValue] <=
400
+ createdAt.doubleValue + CodexThreadCreationSlack) preceding = key;
401
+ }
402
+ if (preceding) return preceding;
403
+ }
404
+ return byLaunch.lastObject;
405
+ }
406
+
407
+ NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload) {
408
+ if (thread.length == 0) return @{};
409
+ int lock = LockCodexLaunchRegistry();
410
+ if (lock < 0) return @{};
411
+ NSMutableDictionary<NSString *, NSDictionary *> *launches = LoadLiveCodexLaunches();
412
+ NSDictionary *terminal = nil;
413
+ for (NSDictionary *entry in launches.allValues) {
414
+ if ([entry[@"threads"] containsObject:thread]) {
415
+ terminal = entry[@"terminal"];
416
+ break;
417
+ }
418
+ }
419
+ if (!terminal) {
420
+ NSDictionary *meta = CodexThreadMeta(thread, payload);
421
+ NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"]) : nil;
422
+ if (key) {
423
+ NSMutableDictionary *entry = [launches[key] mutableCopy];
424
+ NSMutableArray *threads = [entry[@"threads"] mutableCopy] ?: [NSMutableArray array];
425
+ [threads addObject:thread];
426
+ while (threads.count > CodexLaunchThreadLimit) [threads removeObjectAtIndex:0];
427
+ entry[@"threads"] = threads;
428
+ launches[key] = entry;
429
+ terminal = entry[@"terminal"];
430
+ }
431
+ }
432
+ SaveCodexLaunches(launches);
433
+ UnlockCodexLaunchRegistry(lock);
434
+ return [terminal isKindOfClass:NSDictionary.class] ? terminal : @{};
435
+ }
436
+
437
+ NSDictionary *TerminalFocusTargetForHook(NSDictionary *payload, NSString *provider) {
438
+ if (!TerminalFocusRunsUnderSharedAgentHost()) return TerminalFocusTargetFromEnvironment();
439
+ if (![provider isEqualToString:@"Codex"]) return @{};
440
+ return CodexLaunchTerminalForThread(SanitizedShortString(payload[@"session_id"], 128), payload);
150
441
  }
@@ -5,6 +5,8 @@ int RecordClaudeUsage(void);
5
5
  NSDictionary *ClaudeRateLimits(void);
6
6
  NSDictionary *LatestClaudeUsage(void);
7
7
  NSDictionary *LatestUsage(void);
8
+ // 清掉 resets_at 已经翻篇(或不可能属于当前窗口)的额度窗口,缺 resets_at 的保留。
9
+ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage);
8
10
 
9
11
  // 增量跟读 ~/.claude/projects 下的会话转录,按官方 5 小时 / 7 天窗口聚合本地 Token。
10
12
  @interface ClaudeUsageReader : NSObject