cc-pets 2.3.0 → 2.4.0

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 (76) hide show
  1. package/CC_BRIDGE.md +19 -0
  2. package/CC_BRIDGE.zh-CN.md +15 -0
  3. package/CHANGELOG.md +51 -0
  4. package/CHANGELOG.zh-CN.md +51 -0
  5. package/CONTRIBUTING.md +22 -0
  6. package/CONTRIBUTING.zh-CN.md +17 -0
  7. package/README.md +117 -26
  8. package/README.zh-CN.md +92 -22
  9. package/Resources/AgentIcons/claude.png +0 -0
  10. package/Resources/AgentIcons/codex.icns +0 -0
  11. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  12. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +155 -27
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +12 -6
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +1 -1
  16. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +113 -47
  18. package/Sources/CCPets/App/CCPetsAppDelegate.h +2 -2
  19. package/Sources/CCPets/App/main.m +6 -0
  20. package/Sources/CCPets/Bridge/CCPetsBridge.m +11 -6
  21. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +78 -38
  22. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +2 -3
  23. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +50 -32
  24. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +46 -40
  25. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +9 -6
  26. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +171 -53
  27. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  28. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  29. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  30. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  31. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +2 -1
  32. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +107 -25
  33. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  34. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  35. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  36. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  37. package/Sources/CCPets/Pet/PetView+Menu.m +2 -2
  38. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  39. package/Sources/CCPets/Support/CCPetsPreferences.h +2 -0
  40. package/Sources/CCPets/Support/CCPetsPreferences.m +34 -2
  41. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  42. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  43. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  44. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  45. package/Sources/CCPets/UI/CCPetsSettingsPage.h +2 -0
  46. package/Sources/CCPets/UI/CCPetsSettingsPage.m +561 -66
  47. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  48. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  49. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  50. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  51. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  52. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  53. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  54. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  55. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  56. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  57. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  58. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  59. package/THIRD_PARTY_NOTICES.md +7 -3
  60. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  61. package/bin/claude-with-pet +2 -0
  62. package/bin/codex-with-pet +2 -0
  63. package/package.json +5 -1
  64. package/plugins/jetbrains/README.md +62 -0
  65. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  66. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  67. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  68. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  69. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  70. package/plugins/vscode/README.md +63 -0
  71. package/plugins/vscode/extension.js +210 -0
  72. package/plugins/vscode/package.json +18 -0
  73. package/scripts/build-idea-plugin.sh +101 -0
  74. package/scripts/build-vscode-extension.sh +112 -0
  75. package/scripts/build.sh +24 -2
  76. package/scripts/compile-cached.zsh +133 -0
@@ -135,10 +135,7 @@
135
135
  // 状态卡和说话气泡原来是浅色磨砂配深色字;换成原生清透玻璃后背景是任意壁纸加一层
136
136
  // 压暗,深色字会看不见,改成白字加贴字形的投影,和额度面板一致。
137
137
  - (void)applyBubbleTextStyle {
138
- NSShadow *shadow = [NSShadow new];
139
- shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.45];
140
- shadow.shadowBlurRadius = 2;
141
- shadow.shadowOffset = NSMakeSize(0, -0.5);
138
+ NSShadow *shadow = CCPetsGlassTextShadow();
142
139
  BOOL statusLiquid = self.statusGlass.usesLiquidGlass;
143
140
  self.statusTitleLabel.textColor = statusLiquid ? [NSColor colorWithWhite:1 alpha:0.78]
144
141
  : [NSColor colorWithWhite:0.42 alpha:0.90];
@@ -156,9 +153,9 @@
156
153
  [self updateGlassDimLevel:sender.representedObject];
157
154
  }
158
155
  - (void)updateGlassDimLevel:(NSNumber *)level {
159
- // 主窗口的滑块是连续值,菜单是四档;两边都走这里,统一取整并夹在 0–45。
156
+ // 主窗口的滑块是连续值,菜单是四档;两边都传 0–100 的展示强度,取整后换算成实际的 0–45 存下。
160
157
  if (![level isKindOfClass:NSNumber.class] || isnan(level.doubleValue)) return;
161
- NSInteger value = MAX((NSInteger)0, MIN(CCPetsGlassDimMaximum, (NSInteger)lround(level.doubleValue)));
158
+ double value = CCPetsGlassDimLevelForPercent(lround(level.doubleValue));
162
159
  if ([[NSUserDefaults.standardUserDefaults objectForKey:CCPetsGlassDimKey] isEqual:@(value)]) return;
163
160
  CCPetsPrefSetObject(CCPetsGlassDimKey, @(value));
164
161
  [self.quotaGlass applyDimLevel];
@@ -1,9 +1,34 @@
1
1
  // 说话气泡与碎碎念。
2
2
  #import "CCPetsAppDelegate+Private.h"
3
+ #import "CCPetsUsageMode.h"
3
4
 
4
5
  // 档位写进 defaults 的键;PetView 的右键菜单也要读它。
5
6
  NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
6
7
 
8
+ // 两个 Provider 的字段名不同;已过期的窗口不能触发提醒或填入台词。
9
+ static NSDictionary *SpeechFiveHourQuota(NSDictionary *usage) {
10
+ NSDictionary *quota = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class] ? usage[@"fiveHour"] : nil;
11
+ NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
12
+ if (reset && reset.doubleValue <= NSDate.date.timeIntervalSince1970) return nil;
13
+ return quota;
14
+ }
15
+
16
+ static NSInteger SpeechQuotaRemaining(NSDictionary *usage) {
17
+ NSDictionary *quota = SpeechFiveHourQuota(usage);
18
+ id used = quota[@"used_percentage"] ?: quota[@"used_percent"];
19
+ if (![used isKindOfClass:NSNumber.class]) return -1;
20
+ return MAX((NSInteger)0, MIN((NSInteger)100, 100 - [used integerValue]));
21
+ }
22
+
23
+ static NSString *SpeechQuotaResetTime(NSDictionary *usage) {
24
+ id reset = SpeechFiveHourQuota(usage)[@"resets_at"];
25
+ if (![reset isKindOfClass:NSNumber.class]) return nil;
26
+ NSDateFormatter *formatter = [NSDateFormatter new];
27
+ formatter.dateFormat = @"HH:mm";
28
+ formatter.timeZone = NSTimeZone.systemTimeZone;
29
+ return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[reset doubleValue]]];
30
+ }
31
+
7
32
  @implementation AppDelegate (Speech)
8
33
  - (BOOL)speechEnabled {
9
34
  // 缺省开启;用户可在右键菜单里关掉。
@@ -60,6 +85,9 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
60
85
  return [self speechSlotsWithTool:self.lastSpeechTool];
61
86
  }
62
87
  - (NSDictionary<NSString *, NSString *> *)speechSlotsWithTool:(NSString *)tool {
88
+ return [self speechSlotsWithTool:tool usage:[self speechQuotaUsage]];
89
+ }
90
+ - (NSDictionary<NSString *, NSString *> *)speechSlotsWithTool:(NSString *)tool usage:(NSDictionary *)usage {
63
91
  NSMutableDictionary<NSString *, NSString *> *slots = [NSMutableDictionary dictionary];
64
92
  NSCalendar *calendar = NSCalendar.currentCalendar;
65
93
  slots[@"hour"] = [@([calendar component:NSCalendarUnitHour fromDate:NSDate.date]) stringValue];
@@ -71,11 +99,11 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
71
99
  self.sessionStartedAt) / 60.0);
72
100
  if (minutes > 0) slots[@"sessionMin"] = [@(minutes) stringValue];
73
101
  }
74
- NSInteger remaining = [self remainingFiveHourQuotaPercent];
102
+ NSInteger remaining = SpeechQuotaRemaining(usage);
75
103
  if (remaining >= 0) {
76
104
  slots[@"quota5h"] = [NSString stringWithFormat:@"%ld%%", (long)remaining];
77
105
  }
78
- NSString *reset = [self fiveHourResetTimeText];
106
+ NSString *reset = SpeechQuotaResetTime(usage);
79
107
  if (reset.length > 0) slots[@"resetTime"] = reset;
80
108
  // 工具名此前从来没被填过,导致 "{toolName} 这货不靠谱。" 这类台词永远被跳过。
81
109
  NSString *trimmed = [tool stringByTrimmingCharactersInSet:
@@ -83,54 +111,90 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
83
111
  if (trimmed.length > 0 && trimmed.length <= 24) slots[@"toolName"] = trimmed;
84
112
  return slots;
85
113
  }
86
- // 5 小时窗口的剩余百分比,取不到返回 -1。Claude 和 Codex 的字段名不一样,都认。
114
+ // 普通台词的额度槽位选剩余最少的订阅账号;低额度播报会显式传入触发账号。
115
+ - (NSDictionary *)speechQuotaUsage {
116
+ NSDictionary *selected = nil;
117
+ NSInteger lowest = 101;
118
+ NSDictionary *usages = self.quotaView.profileUsages;
119
+ for (NSDictionary *profile in self.quotaView.profiles) {
120
+ if (CCPetsProfileShowsAPIUsage(profile)) continue;
121
+ NSDictionary *usage = usages[profile[@"id"]];
122
+ NSInteger remaining = SpeechQuotaRemaining(usage);
123
+ if (remaining >= 0 && remaining < lowest) {
124
+ lowest = remaining;
125
+ selected = usage;
126
+ }
127
+ }
128
+ return selected;
129
+ }
87
130
  - (NSInteger)remainingFiveHourQuotaPercent {
88
- NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
89
- NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
90
- ? usage[@"fiveHour"] : nil;
91
- id used = fiveHour[@"used_percentage"] ?: fiveHour[@"used_percent"];
92
- if (![used isKindOfClass:NSNumber.class]) return -1;
93
- NSInteger remaining = 100 - [used integerValue];
94
- return MAX((NSInteger)0, MIN((NSInteger)100, remaining));
131
+ return SpeechQuotaRemaining([self speechQuotaUsage]);
95
132
  }
96
- // 回血时间,按本机时区格式化。没有这个槽位的话,带 {resetTime} 的词条会被整条跳过。
97
133
  - (NSString *)fiveHourResetTimeText {
98
- NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
99
- NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
100
- ? usage[@"fiveHour"] : nil;
101
- id resets = fiveHour[@"resets_at"];
102
- if (![resets isKindOfClass:NSNumber.class]) return nil;
103
- NSTimeInterval at = [resets doubleValue];
104
- if (at <= NSDate.date.timeIntervalSince1970) return nil;
105
- NSDateFormatter *formatter = [NSDateFormatter new];
106
- formatter.dateFormat = @"HH:mm";
107
- formatter.timeZone = NSTimeZone.systemTimeZone;
108
- return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:at]];
134
+ return SpeechQuotaResetTime([self speechQuotaUsage]);
109
135
  }
110
- // 额度是"跨阈值"事件,不是状态事件,所以单独判档。
111
- //
112
- // 只在向下穿档时说一次:低于 20%% 就一直念叨会变成唠叨,而额度刷新是每分钟级别的,
113
- // 不设档位的话一小时预算瞬间就被烧光。回血(档位回升)时把标记还回去,
114
- // 下个周期才能再触发。
136
+ // 每个账号独立记档,首次采样只初始化。冷却期间排队,避免同时跨档时只播报第一个账号。
115
137
  - (void)considerQuotaSpeech {
116
- NSInteger remaining = [self remainingFiveHourQuotaPercent];
117
- if (remaining < 0) return;
118
- NSInteger tier;
119
- if (remaining <= 5) tier = 0;
120
- else if (remaining <= 10) tier = 1;
121
- else if (remaining <= 20) tier = 2;
122
- else tier = 3;
123
-
124
- NSInteger previous = self.lastQuotaTier;
125
- self.lastQuotaTier = tier;
126
- // 首次拿到数据只记档不出声,免得每次启动都通报一遍额度。
127
- // (lastQuotaTier 的初值 0 恰好是最低档,不加这道判断的话冷启动必然误判成"刚跌到 5%"。)
128
- if (!self.lastQuotaTierInitialized) {
129
- self.lastQuotaTierInitialized = YES;
138
+ if (!self.quotaSpeechStates) self.quotaSpeechStates = [NSMutableDictionary dictionary];
139
+ if (!self.pendingQuotaSpeechProfileIDs) self.pendingQuotaSpeechProfileIDs = [NSMutableOrderedSet orderedSet];
140
+ NSArray<NSDictionary *> *profiles = self.quotaView.profiles;
141
+ NSDictionary *usages = self.quotaView.profileUsages;
142
+ NSMutableSet<NSString *> *liveIDs = [NSMutableSet set];
143
+ for (NSDictionary *profile in profiles) {
144
+ NSString *profileID = profile[@"id"];
145
+ if (profileID.length == 0 || CCPetsProfileShowsAPIUsage(profile)) continue;
146
+ [liveIDs addObject:profileID];
147
+ NSString *home = profile[@"home"] ?: @"";
148
+ NSDictionary *previous = self.quotaSpeechStates[profileID];
149
+ if (previous && ![previous[@"home"] isEqualToString:home]) {
150
+ [self.quotaSpeechStates removeObjectForKey:profileID];
151
+ [self.pendingQuotaSpeechProfileIDs removeObject:profileID];
152
+ previous = nil;
153
+ }
154
+ NSInteger remaining = SpeechQuotaRemaining(usages[profileID]);
155
+ if (remaining < 0) {
156
+ [self.pendingQuotaSpeechProfileIDs removeObject:profileID];
157
+ continue;
158
+ }
159
+ NSInteger tier = remaining <= 5 ? 0 : remaining <= 10 ? 1 : remaining <= 20 ? 2 : 3;
160
+ self.quotaSpeechStates[profileID] = @{@"home": home, @"tier": @(tier)};
161
+ if (!previous || tier > [previous[@"tier"] integerValue]) {
162
+ [self.pendingQuotaSpeechProfileIDs removeObject:profileID];
163
+ } else if (tier < [previous[@"tier"] integerValue]) {
164
+ [self.pendingQuotaSpeechProfileIDs addObject:profileID];
165
+ }
166
+ }
167
+ for (NSString *profileID in self.quotaSpeechStates.allKeys) {
168
+ if (![liveIDs containsObject:profileID]) {
169
+ [self.quotaSpeechStates removeObjectForKey:profileID];
170
+ [self.pendingQuotaSpeechProfileIDs removeObject:profileID];
171
+ }
172
+ }
173
+ // 用户关闭说话时不积攒提醒;更新气泡、冷却和预算只延后播报。
174
+ if (![self speechEnabled]) {
175
+ [self.pendingQuotaSpeechProfileIDs removeAllObjects];
130
176
  return;
131
177
  }
132
- if (tier >= previous) return; // 回血或没跨档
133
- [self speakWithTag:PetPhraseTagQuotaLow];
178
+ if (self.updateBubbleVisible || ![self canSpeakNow]) return;
179
+ for (NSString *profileID in self.pendingQuotaSpeechProfileIDs.array) {
180
+ NSDictionary *profile = nil;
181
+ for (NSDictionary *candidate in profiles) {
182
+ if ([candidate[@"id"] isEqualToString:profileID]) { profile = candidate; break; }
183
+ }
184
+ [self.pendingQuotaSpeechProfileIDs removeObject:profileID];
185
+ if (!profile) continue;
186
+ NSDictionary *slots = [self speechSlotsWithTool:self.lastSpeechTool usage:usages[profileID]];
187
+ NSString *text = PetPhraseForTag(PetPhraseTagQuotaLow, slots);
188
+ if (text.length == 0) continue;
189
+ NSString *provider = [profile[@"provider"] isEqualToString:CCPetsProfileProviderCodex] ? @"Codex" : @"Claude";
190
+ NSString *name = profile[@"displayName"] ?: profile[@"slug"] ?: provider;
191
+ text = [NSString stringWithFormat:@"%@ · %@: %@", provider, name, text];
192
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
193
+ [self.speechTimestamps addObject:@(now)];
194
+ self.speechCooldownUntil = now + [self speechCooldownSeconds];
195
+ [self presentSpeechText:text];
196
+ break;
197
+ }
134
198
  }
135
199
  - (void)buildSpeechPanelIfNeeded {
136
200
  if (self.speechPanel) return;
@@ -155,14 +219,14 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
155
219
  initWithFrame:NSMakeRect(6, 6, glassSize.width, glassSize.height)
156
220
  material:NSVisualEffectMaterialPopover appearance:NSAppearanceNameAqua
157
221
  cornerRadius:glassSize.height / 2.0];
158
- self.speechGlass.edgeShadeHeight = 9;
159
- self.speechGlass.edgeShadeAlpha = 0.6;
222
+ self.speechGlass.edgeShadeHeight = CCPetsSpeechBubbleEdgeShadeHeight;
223
+ self.speechGlass.edgeShadeAlpha = CCPetsSpeechBubbleEdgeShadeAlpha;
160
224
  self.speechGlass.usesWidgetGlass = YES;
161
225
 
162
226
  self.speechLabel = [NSTextField labelWithString:@""];
163
227
  self.speechLabel.frame = NSMakeRect(14, 10, glassSize.width - 28, 18);
164
228
  // 独立气泡里这句话是唯一元素,不与标题争,比并入状态卡时大半档。
165
- self.speechLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];
229
+ self.speechLabel.font = [NSFont systemFontOfSize:CCPetsSpeechBubbleFontSize weight:NSFontWeightMedium];
166
230
  self.speechLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
167
231
  self.speechLabel.alignment = NSTextAlignmentCenter;
168
232
  self.speechLabel.lineBreakMode = NSLineBreakByTruncatingTail;
@@ -307,6 +371,8 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
307
371
  // 挂在已有的客户端存活定时器上,不新起 timer——常驻唤醒一个都不该多。
308
372
  - (void)considerIdleSpeech {
309
373
  [self consumeSpeechDebugTrigger];
374
+ // 复用存活定时器消费待播报账号,不等待下一次额度刷新,也不额外唤醒。
375
+ if (self.pendingQuotaSpeechProfileIDs.count > 0) [self considerQuotaSpeech];
310
376
  if (self.updateBubbleDeferred && ![self agentBusyForSpeech]) [self showUpdateBubble];
311
377
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
312
378
  // 真正的判断最多 30 秒做一次,3 秒一跳的定时器上不必每次都算。
@@ -385,7 +451,7 @@ NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
385
451
  // 独立气泡:左右各 16 内边距,没有图标。
386
452
  - (void)resizeSpeechBubbleToFitText {
387
453
  if (!self.speechPanel) return;
388
- const CGFloat padding = 16;
454
+ const CGFloat padding = CCPetsSpeechBubblePadding;
389
455
  CGFloat width = padding * 2 + PetMeasuredLabelWidth(self.speechLabel);
390
456
  width = fmax(96.0, fmin(width, 300.0));
391
457
  NSSize panelSize = NSMakeSize(width + 12, PetSpeechBodyHeight + 12);
@@ -26,8 +26,8 @@
26
26
  // 最近一次 agent 事件的工具名,供 {toolName} 槽位使用。
27
27
  @property(copy) NSString *lastSpeechTool;
28
28
  // 上次播报额度时剩余百分比落在哪一档。只在向下穿档时说,不是"低于阈值就一直说"。
29
- @property NSInteger lastQuotaTier;
30
- @property BOOL lastQuotaTierInitialized;
29
+ @property NSMutableDictionary<NSString *, NSDictionary *> *quotaSpeechStates;
30
+ @property NSMutableOrderedSet<NSString *> *pendingQuotaSpeechProfileIDs;
31
31
  @property NSPanel *statusPanel;
32
32
  @property CCPetsGlassView *statusGlass;
33
33
  @property CCPetsGlassView *quotaGlass;
@@ -17,6 +17,7 @@
17
17
  #import "CCPetsCLISupport.h"
18
18
  #import "CCPetsTerminalFocus.h"
19
19
  #import "CCPetsProfiles.h"
20
+ #import "CCPetsLaunchPreflight.h"
20
21
  #import <sys/file.h>
21
22
  #import <sys/stat.h>
22
23
  #import <fcntl.h>
@@ -26,6 +27,11 @@ int main(int argc, const char *argv[]) {
26
27
  @autoreleasepool {
27
28
  // 下面这些都是命令行入口,输出语言跟终端走;真正启动桌宠前再切回 App 的语言规则。
28
29
  CCPetsUseCommandLineLanguage(YES);
30
+ if (argc > 1 && strcmp(argv[1], "--launch-preflight") == 0) {
31
+ NSMutableArray<NSString *> *arguments = [NSMutableArray array];
32
+ for (int index = 3; index < argc; index++) [arguments addObject:@(argv[index])];
33
+ return CCPetsLaunchPreflight(argc >= 3 ? @(argv[2]) : @"", arguments);
34
+ }
29
35
  if (argc > 1 && (strcmp(argv[1], "doctor") == 0 || strcmp(argv[1], "paths") == 0)) {
30
36
  NSMutableArray<NSString *> *arguments = [NSMutableArray array];
31
37
  for (int index = 1; index < argc; index++) [arguments addObject:@(argv[index])];
@@ -160,6 +160,8 @@ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
160
160
  @"ref": BridgeSafeString(record[@"ref"], 6),
161
161
  @"provider": BridgeSafeString(record[@"provider"], 16)
162
162
  } mutableCopy];
163
+ NSString *profileID = BridgeSafeString(record[@"profileId"], 128);
164
+ if (profileID.length > 0) entry[@"profileId"] = profileID;
163
165
  NSString *tty = BridgeSafeString(record[@"tty"], 32);
164
166
  if (tty.length > 0) entry[@"tty"] = tty;
165
167
  sessions[session] = entry;
@@ -190,6 +192,7 @@ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteg
190
192
  @"from": fromName,
191
193
  @"to": toName,
192
194
  @"toSession": toSession,
195
+ @"fromSession": BridgeSafeString(from[@"session"], 128),
193
196
  @"at": @(at)
194
197
  }];
195
198
  }
@@ -201,13 +204,15 @@ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteg
201
204
  }
202
205
 
203
206
  NSDictionary<NSString *, NSNumber *> *CCBridgePendingCounts(void) {
204
- NSString *inbox = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"inbox"];
205
207
  NSMutableDictionary<NSString *, NSNumber *> *counts = [NSMutableDictionary dictionary];
206
- for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:inbox error:nil]) {
207
- NSString *session = BridgeSafeString(name, 128);
208
- if (session.length == 0 || ![session isEqualToString:name]) continue;
209
- NSUInteger count = JSONFilesInDirectory([inbox stringByAppendingPathComponent:name]).count;
210
- if (count > 0) counts[session] = @(count);
208
+ for (NSString *kind in @[@"inbox", @"claimed"]) {
209
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:kind];
210
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
211
+ NSString *session = BridgeSafeString(name, 128);
212
+ if (session.length == 0 || ![session isEqualToString:name]) continue;
213
+ NSUInteger count = JSONFilesInDirectory([directory stringByAppendingPathComponent:name]).count;
214
+ if (count > 0) counts[session] = @([counts[session] unsignedIntegerValue] + count);
215
+ }
211
216
  }
212
217
  return counts;
213
218
  }
@@ -39,6 +39,32 @@ static void Print(NSString *text) {
39
39
  CCPetsPrintLine(stdout, text);
40
40
  }
41
41
 
42
+ // stdio MCP 顺序处理请求;认领的消息在完整输出并 flush 成功后才确认。
43
+ static NSDictionary *PendingInboxOutput;
44
+
45
+ static NSArray<NSDictionary *> *ClaimForOutput(NSString *session, NSString *transport) {
46
+ NSArray *messages = CCBridgeClaimInbox(session);
47
+ if (messages.count > 0) PendingInboxOutput = @{@"session": session, @"messages": messages, @"transport": transport};
48
+ return messages;
49
+ }
50
+
51
+ static void FinishInboxOutput(BOOL written) {
52
+ NSDictionary *pending = PendingInboxOutput;
53
+ PendingInboxOutput = nil;
54
+ if (!pending) return;
55
+ @try {
56
+ CCBridgeFinishInbox(pending[@"session"], pending[@"messages"], written ? pending[@"transport"] : nil);
57
+ } @catch (NSException *exception) {
58
+ // 输出已经完成,不能再输出第二条协议响应;未确认文件留给下次恢复。
59
+ }
60
+ }
61
+
62
+ static BOOL WriteOutput(FILE *stream, NSString *text) {
63
+ NSData *data = [[text stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
64
+ BOOL written = data && fwrite(data.bytes, 1, data.length, stream) == data.length;
65
+ return fflush(stream) == 0 && written && !ferror(stream);
66
+ }
67
+
42
68
  static NSString *USAGE(void) {
43
69
  return L(@"Usage: cc-pets bridge <command>\n"
44
70
  "\n"
@@ -117,6 +143,7 @@ static void PrintSessions(void) {
117
143
  }
118
144
 
119
145
  static NSDictionary *SelfOrFrom(NSMutableArray<NSString *> *arguments) {
146
+ if (!CCBridgeEnabled()) Fail(L(@"CC Bridge is off. Run cc-pets bridge enable first."));
120
147
  NSString *from = ParseFlag(arguments, @"from");
121
148
  if (from.length > 0) {
122
149
  NSDictionary *resolved = CCBridgeResolveTarget(from, CCBridgeLiveSessions());
@@ -124,18 +151,17 @@ static NSDictionary *SelfOrFrom(NSMutableArray<NSString *> *arguments) {
124
151
  return resolved[@"session"];
125
152
  }
126
153
  NSDictionary *session = CCBridgeIdentifySelf();
127
- if (!session) Fail(L(@"Can't identify the current session; when debugging in a plain terminal, use --from <session-name>."));
154
+ if (!session) Fail(L(@"Current session identity is unavailable or ambiguous; use a valid session ID, or --from <session-name> for an explicit CLI selection."));
128
155
  return session;
129
156
  }
130
157
 
131
158
  #pragma mark - hook
132
159
 
133
160
  static NSDictionary *InjectPending(NSString *sessionId, NSString *eventName) {
134
- NSArray<NSDictionary *> *messages = CCBridgeClaimInbox(sessionId);
161
+ NSArray<NSDictionary *> *messages = ClaimForOutput(sessionId, @"prompt-inject");
135
162
  if (messages.count == 0) return nil;
136
163
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
137
164
  for (NSDictionary *message in messages) {
138
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"delivered", @"transport": @{@"kind": @"prompt-inject"}});
139
165
  [envelopes addObject:CCBridgeFormatEnvelope(message)];
140
166
  }
141
167
  return @{@"hookSpecificOutput": @{@"hookEventName": eventName, @"additionalContext": [envelopes componentsJoinedByString:@"\n\n"]}};
@@ -201,7 +227,7 @@ static NSDictionary *RunHook(NSString *input) {
201
227
  pid ? CCBridgeProcessTty(pid.intValue) : nil, status,
202
228
  // hook 继承宿主 CLI 的环境:`CC_BRIDGE_NAME=frontend claude` 即以 frontend 注册。只在首次注册时生效。
203
229
  preferredName, CCPetsEnvironmentValue(@"CC_PETS_PROFILE_ID"),
204
- CCPetsEnvironmentValue(@"CC_PETS_PROFILE_NAME"), known ? @[] : CCBridgeLiveSessions());
230
+ CCPetsEnvironmentValue(@"CC_PETS_PROFILE_NAME"), @[]);
205
231
 
206
232
  if ([event isEqualToString:@"SessionStart"]) {
207
233
  CCBridgePruneReceipts();
@@ -217,13 +243,15 @@ static NSDictionary *RunHook(NSString *input) {
217
243
 
218
244
  // 这是别人 CLI 的关键路径:任何异常都吞掉并 exit 0,CC Bridge 出错不能拖垮对方的一轮对话。
219
245
  static int HookCommand(void) {
246
+ BOOL written = NO;
220
247
  @try {
221
248
  NSDictionary *output = RunHook(ReadStandardInput());
222
249
  if (output) {
223
- fputs(CompactJSON(output).UTF8String, stdout);
224
- fflush(stdout);
250
+ written = WriteOutput(stdout, CompactJSON(output));
225
251
  }
226
252
  } @catch (NSException *exception) {
253
+ } @finally {
254
+ FinishInboxOutput(written);
227
255
  }
228
256
  return 0;
229
257
  }
@@ -235,6 +263,7 @@ static int HookCommand(void) {
235
263
 
236
264
  static int WatchCommand(void) {
237
265
  NSString *lock = nil;
266
+ BOOL written = NO;
238
267
  @try {
239
268
  // 关闭"自动唤醒"后 watcher 本不会被安装;配置还没刷新到对方 CLI 时在这里兜底。
240
269
  if (!CCBridgeEnabled() || ![CCBridgeOptions()[@"wake"] boolValue]) return 0;
@@ -251,17 +280,18 @@ static int WatchCommand(void) {
251
280
  NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:seconds];
252
281
  pid_t parent = getppid();
253
282
  while (deadline.timeIntervalSinceNow > 0) {
283
+ if (!CCBridgeEnabled() || ![CCBridgeOptions()[@"wake"] boolValue]) return 0;
254
284
  // 宿主会话已经没了(被 kill -9 等,没来得及清理子进程)就别再占着锁。
255
285
  if (!CCBridgeProcessAlive(parent)) return 0;
256
- NSArray<NSDictionary *> *messages = CCBridgeClaimInbox(sessionId);
286
+ NSArray<NSDictionary *> *messages = ClaimForOutput(sessionId, @"claude-rewake");
257
287
  if (messages.count > 0) {
258
288
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
259
289
  for (NSDictionary *message in messages) {
260
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"delivered", @"transport": @{@"kind": @"claude-rewake"}});
261
290
  [envelopes addObject:CCBridgeFormatEnvelope(message)];
262
291
  }
263
- CCPetsPrintLine(stderr, [envelopes componentsJoinedByString:@"\n\n"]);
264
- return 2;
292
+ if (!CCBridgeEnabled() || ![CCBridgeOptions()[@"wake"] boolValue]) return 0;
293
+ written = WriteOutput(stderr, [envelopes componentsJoinedByString:@"\n\n"]);
294
+ return written ? 2 : 0;
265
295
  }
266
296
  usleep((useconds_t)(poll * 1000));
267
297
  }
@@ -269,6 +299,7 @@ static int WatchCommand(void) {
269
299
  } @catch (NSException *exception) {
270
300
  return 0;
271
301
  } @finally {
302
+ FinishInboxOutput(written);
272
303
  CCBridgeReleaseLock(lock);
273
304
  }
274
305
  }
@@ -385,8 +416,7 @@ static NSString *AgeText(id since) {
385
416
  }
386
417
 
387
418
  static NSString *UnknownSelf(void) {
388
- return [L(@"Can't identify the current session: it isn't in the registry yet. Make sure `cc-pets bridge enable` was run; ")
389
- stringByAppendingString:L(@"Codex users also need to trust the cc-pets hooks in /hooks and send at least one message in this session.")];
419
+ return L(@"Current session identity is unavailable or ambiguous. Register this session through the bridge hooks and provide a valid session ID. A shared host PID cannot identify one of several sessions; no action was taken.");
390
420
  }
391
421
 
392
422
  static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
@@ -404,7 +434,7 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
404
434
  }
405
435
  NSString *header = self
406
436
  ? LF(L(@"This session is {self}; other sessions use this name to message you (it isn't in the list below)."), @{@"self": CCBridgeDescribeSession(self)})
407
- : L(@"This session isn't registered yet (you can see the list but can't send messages for now).");
437
+ : L(@"Current session identity is unavailable or ambiguous (you can view sessions, but cannot act as one).");
408
438
  if (sessions.count == 0) {
409
439
  return TextResult(LF(L(@"{header}\n\nNo other sessions online. New sessions will show up here once they start."), @{@"header": header}), NO);
410
440
  }
@@ -440,7 +470,7 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
440
470
 
441
471
  if ([name isEqualToString:@"set_name"]) {
442
472
  if (!self) return TextResult(UnknownSelf(), YES);
443
- NSDictionary *result = CCBridgeRenameSession(self[@"session"], arguments[@"name"], CCBridgeLiveSessions());
473
+ NSDictionary *result = CCBridgeRenameSession(self[@"session"], arguments[@"name"], @[]);
444
474
  if (result[@"error"]) return TextResult(result[@"error"], YES);
445
475
  return TextResult([LF(L(@"This session was renamed from {previous} to {session}. "),
446
476
  (@{@"previous": result[@"previous"], @"session": CCBridgeDescribeSession(result[@"session"])}))
@@ -497,11 +527,10 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
497
527
 
498
528
  if ([name isEqualToString:@"check_inbox"]) {
499
529
  if (!self) return TextResult(UnknownSelf(), YES);
500
- NSArray<NSDictionary *> *messages = CCBridgeClaimInbox(self[@"session"]);
530
+ NSArray<NSDictionary *> *messages = ClaimForOutput(self[@"session"], @"check-inbox");
501
531
  if (messages.count == 0) return TextResult(L(@"No new messages in the inbox."), NO);
502
532
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
503
533
  for (NSDictionary *message in messages) {
504
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"delivered", @"transport": @{@"kind": @"check-inbox"}});
505
534
  [envelopes addObject:CCBridgeFormatEnvelope(message)];
506
535
  }
507
536
  return TextResult([envelopes componentsJoinedByString:@"\n\n"], NO);
@@ -524,6 +553,7 @@ static NSDictionary *HandleRequest(NSDictionary *request, NSDictionary **error)
524
553
  L(@"“message another session / terminal / Claude / Codex”, or names a session or tty (e.g. ttys003), "),
525
554
  L(@"use this server's tools directly; there's no need to look up bridge usage in project files. "), AliasNote(),
526
555
  L(@"Find the recipient's name with list_agents, then send with send_message. "),
556
+ L(@"When a cross-session request needs clarification or is complete, reply to the originating session using send_message. "),
527
557
  L(@"When several sessions work in the same repository, reserve files with reserve_files before a larger change and release them with release_files afterwards. "),
528
558
  SafetyNote()
529
559
  ] componentsJoinedByString:@""]
@@ -536,9 +566,8 @@ static NSDictionary *HandleRequest(NSDictionary *request, NSDictionary **error)
536
566
  return nil;
537
567
  }
538
568
 
539
- static void WriteMessage(NSDictionary *message) {
540
- fputs([CompactJSON(message) stringByAppendingString:@"\n"].UTF8String, stdout);
541
- fflush(stdout);
569
+ static BOOL WriteMessage(NSDictionary *message) {
570
+ return WriteOutput(stdout, CompactJSON(message));
542
571
  }
543
572
 
544
573
  static int MCPCommand(void) {
@@ -564,8 +593,14 @@ static int MCPCommand(void) {
564
593
  } @catch (NSException *exception) {
565
594
  error = @{@"code": @(-32603), @"message": exception.reason ?: exception.name};
566
595
  }
567
- WriteMessage(error ? @{@"jsonrpc": @"2.0", @"id": identifier, @"error": error}
568
- : @{@"jsonrpc": @"2.0", @"id": identifier, @"result": result ?: @{}});
596
+ BOOL written = NO;
597
+ @try {
598
+ written = WriteMessage(error ? @{@"jsonrpc": @"2.0", @"id": identifier, @"error": error}
599
+ : @{@"jsonrpc": @"2.0", @"id": identifier, @"result": result ?: @{}});
600
+ } @finally {
601
+ FinishInboxOutput(written && !error);
602
+ }
603
+ if (!written) { free(line); return 1; }
569
604
  }
570
605
  }
571
606
  free(line);
@@ -610,19 +645,25 @@ static BOOL InstallBridgeForRegisteredProfiles(NSDictionary *options, BOOL regis
610
645
  return succeeded;
611
646
  }
612
647
 
613
- static void UninstallBridgeForRegisteredProfiles(BOOL unregisterMcp) {
648
+ static BOOL UninstallBridgeForRegisteredProfiles(BOOL unregisterMcp) {
649
+ BOOL succeeded = YES;
614
650
  NSArray<NSDictionary *> *profiles = RegisteredProfiles();
615
651
  if (profiles.count == 0) {
616
- return;
652
+ return YES;
617
653
  }
618
654
  for (NSDictionary *profile in profiles) {
619
655
  @try {
620
- for (NSString *line in CCBridgeUninstallForProfile(profile, unregisterMcp)) Print(line);
656
+ for (NSString *line in CCBridgeUninstallForProfile(profile, unregisterMcp)) {
657
+ Print(line);
658
+ if ([line hasPrefix:@"ERROR: "]) succeeded = NO;
659
+ }
621
660
  } @catch (NSException *exception) {
661
+ succeeded = NO;
622
662
  Print(LF(L(@"{name}: {error}"), (@{@"name": profile[@"displayName"] ?: profile[@"home"],
623
663
  @"error": exception.reason ?: exception.name})));
624
664
  }
625
665
  }
666
+ return succeeded;
626
667
  }
627
668
 
628
669
  static int EnableCommand(NSMutableArray<NSString *> *arguments) {
@@ -659,19 +700,16 @@ static int RefreshCommand(void) {
659
700
  }
660
701
 
661
702
  static int DisableCommand(void) {
662
- UninstallBridgeForRegisteredProfiles(CCBridgeShouldTouchMCP());
703
+ // 先关闭运行时入口,卸载耗时或失败也不能继续发送/唤醒。
663
704
  CCBridgeSetEnabled(NO, nil);
664
- Print(L(@"CC Bridge is off."));
665
- return 0;
705
+ BOOL succeeded = UninstallBridgeForRegisteredProfiles(CCBridgeShouldTouchMCP());
706
+ Print(succeeded ? L(@"CC Bridge is off.") : L(@"CC Bridge is off, but some integrations could not be removed. Retry disable after resolving the errors above."));
707
+ return succeeded ? 0 : 1;
666
708
  }
667
709
 
668
- // cc-pets uninstall 调用:移除全部 CC Bridge 集成并关掉开关。MCP 注册只在确实开启过时才去注销,
669
- // 避免卸载时无谓地拉起 claude / codex。
710
+ // 即使之前卸载失败已关掉开关,再次 teardown 也必须重试清理 MCP。
670
711
  static int TeardownCommand(void) {
671
- BOOL wasEnabled = CCBridgeEnabled();
672
- UninstallBridgeForRegisteredProfiles(wasEnabled && CCBridgeShouldTouchMCP());
673
- CCBridgeSetEnabled(NO, nil);
674
- return 0;
712
+ return DisableCommand();
675
713
  }
676
714
 
677
715
  static int StatusCommand(void) {
@@ -724,7 +762,7 @@ static int SendCommand(NSMutableArray<NSString *> *arguments) {
724
762
  static int NameCommand(NSMutableArray<NSString *> *arguments) {
725
763
  NSDictionary *session = SelfOrFrom(arguments);
726
764
  if (arguments.count == 0) Fail(L(@"Usage: cc-pets bridge name <new-name>"));
727
- NSDictionary *result = CCBridgeRenameSession(session[@"session"], arguments[0], CCBridgeLiveSessions());
765
+ NSDictionary *result = CCBridgeRenameSession(session[@"session"], arguments[0], @[]);
728
766
  if (result[@"error"]) Fail(result[@"error"]);
729
767
  Print(LF(L(@"Renamed {previous} to {session}."), (@{@"previous": result[@"previous"], @"session": CCBridgeDescribeSession(result[@"session"])})));
730
768
  return 0;
@@ -732,14 +770,14 @@ static int NameCommand(NSMutableArray<NSString *> *arguments) {
732
770
 
733
771
  static int InboxCommand(NSMutableArray<NSString *> *arguments) {
734
772
  NSDictionary *session = SelfOrFrom(arguments);
735
- NSArray<NSDictionary *> *messages = CCBridgeClaimInbox(session[@"session"]);
773
+ NSArray<NSDictionary *> *messages = ClaimForOutput(session[@"session"], @"check-inbox");
736
774
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
737
775
  for (NSDictionary *message in messages) {
738
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"delivered", @"transport": @{@"kind": @"check-inbox"}});
739
776
  [envelopes addObject:CCBridgeFormatEnvelope(message)];
740
777
  }
741
- Print(envelopes.count > 0 ? [envelopes componentsJoinedByString:@"\n\n"] : L(@"No new messages in the inbox."));
742
- return 0;
778
+ BOOL written = WriteOutput(stdout, envelopes.count > 0 ? [envelopes componentsJoinedByString:@"\n\n"] : L(@"No new messages in the inbox."));
779
+ FinishInboxOutput(written);
780
+ return written ? 0 : 1;
743
781
  }
744
782
 
745
783
  // Stop hook 脱离出来的子进程:给订阅了该会话空闲的会话发通知。
@@ -788,5 +826,7 @@ int CCBridgeCommandMain(NSArray<NSString *> *argv) {
788
826
  } @catch (NSException *exception) {
789
827
  CCPetsPrintLine(stderr, exception.reason ?: exception.name);
790
828
  return 1;
829
+ } @finally {
830
+ FinishInboxOutput(NO);
791
831
  }
792
832
  }
@@ -12,9 +12,8 @@
12
12
  NSArray<NSDictionary *> *CCBridgeLiveSessions(void);
13
13
  NSString *CCBridgeDescribeSession(NSDictionary *session);
14
14
 
15
- // 当前进程属于哪个会话。主判据是"离我最近的 CLI 祖先进程 pid → 注册表里该 pid 最近活跃的会话":
16
- // Codex 的 MCP 进程拿不到 thread id,只能这样反查;Claude 的 CLAUDE_CODE_SESSION_ID 是启动时的快照,
17
- // /clear、/resume 之后会过期。反查不到时才退回环境变量。
15
+ // 优先验证显式会话 ID;缺失时仅允许 provider + PID 唯一匹配。
16
+ // 显式 ID 失效、与宿主不符或 PID 匹配多个会话时返回 nil,禁止按活动时间猜测。
18
17
  NSDictionary *CCBridgeIdentifySelf(void);
19
18
 
20
19
  // 名字即地址;重名时追加 " [ref]"。也接受裸 ref 和完整 session id。返回 @{session} 或 @{error}。