cc-pets 2.2.1 → 2.3.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 (171) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +60 -0
  4. package/CHANGELOG.zh-CN.md +60 -0
  5. package/CONTRIBUTING.md +13 -10
  6. package/CONTRIBUTING.zh-CN.md +11 -10
  7. package/README.md +113 -24
  8. package/README.zh-CN.md +89 -28
  9. package/Resources/zh-Hans.lproj/Localizable.strings +568 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +82 -23
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  22. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  23. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  24. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  25. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  26. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  27. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  35. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  38. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  39. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  41. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  43. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  44. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  45. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  46. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  47. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  48. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  49. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  50. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  51. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  52. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  53. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  54. package/Sources/CCPets/Pet/PetView.m +635 -0
  55. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  56. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  57. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  58. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  59. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  60. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  61. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  62. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  63. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  64. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  65. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  66. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  67. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  68. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  69. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  70. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  71. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  72. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  73. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  74. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  75. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  76. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  77. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  78. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  79. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  81. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  82. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  83. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  84. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  85. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  86. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  87. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  88. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  89. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  90. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  92. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  93. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  94. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  95. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  96. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  97. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  98. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  99. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  100. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  101. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  102. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  103. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  104. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  105. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  106. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  107. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  108. package/THIRD_PARTY_NOTICES.md +1 -1
  109. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  110. package/bin/cc-pets +8 -6
  111. package/bin/claude-with-pet +10 -2
  112. package/bin/codex-with-pet +13 -5
  113. package/package.json +1 -1
  114. package/scripts/build.sh +7 -3
  115. package/scripts/i18n.zsh +9 -52
  116. package/scripts/install-app.sh +4 -0
  117. package/scripts/install-shell-integration.sh +17 -10
  118. package/scripts/uninstall-shell-integration.sh +6 -1
  119. package/Sources/CCPets/CCPetsEvents.h +0 -10
  120. package/Sources/CCPets/CCPetsUsage.h +0 -36
  121. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  122. package/Sources/CCPets/PetView.m +0 -1839
  123. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  124. package/scripts/bridge/cli.mjs +0 -237
  125. package/scripts/bridge/core.mjs +0 -228
  126. package/scripts/bridge/hook.mjs +0 -150
  127. package/scripts/bridge/install.mjs +0 -311
  128. package/scripts/bridge/mcp-server.mjs +0 -308
  129. package/scripts/bridge/options.mjs +0 -87
  130. package/scripts/bridge/process.mjs +0 -151
  131. package/scripts/bridge/reservations.mjs +0 -248
  132. package/scripts/bridge/store.mjs +0 -433
  133. package/scripts/bridge/watch.mjs +0 -69
  134. package/scripts/check-l10n.mjs +0 -168
  135. package/scripts/configure-updater.mjs +0 -43
  136. package/scripts/detect-cli.mjs +0 -68
  137. package/scripts/doctor.mjs +0 -470
  138. package/scripts/i18n.mjs +0 -122
  139. package/scripts/install-claude-hooks.mjs +0 -253
  140. package/scripts/install-codex-hooks.mjs +0 -78
  141. package/scripts/integration-markers.mjs +0 -51
  142. package/scripts/locales/zh-Hans.json +0 -366
  143. package/scripts/pet-store.mjs +0 -415
  144. package/scripts/uninstall-integrations.mjs +0 -205
  145. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  146. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  147. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  148. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  149. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  150. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  151. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  152. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  153. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  154. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  155. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  156. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  157. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  159. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  161. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  162. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  163. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  164. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  165. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  166. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  167. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  168. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  169. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  170. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  171. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,501 @@
1
+ #import "CCPetsL10n.h"
2
+ #import "CCPetsBridgeSetup.h"
3
+ #import "CCPetsBridge.h"
4
+ #import "CCPetsBridgeStore.h"
5
+ #import "CCPetsCLISupport.h"
6
+ #import "CCPetsJSON.h"
7
+ #import <sys/stat.h>
8
+
9
+ #define LF(localized, values) CCPetsInterpolate(localized, values)
10
+
11
+ NSString *const CCBridgeHookMarker = @"CC_BRIDGE_HOOK=";
12
+ NSString *const CCBridgeMCPName = @"cc-bridge";
13
+ static NSString *const TomlStart = @"# >>> cc-bridge >>>";
14
+ static NSString *const TomlEnd = @"# <<< cc-bridge <<<";
15
+
16
+ // 正式发布前这个功能叫过 "Agent Bus"(cc-pets bus)。启用过旧版的机器上还留着旧标记的 hooks、
17
+ // 旧名字的 MCP 注册和旧审批块,安装 / 卸载时一并识别清理,不留两套。
18
+ static NSArray<NSString *> *HookMarkers(void) {
19
+ return @[CCBridgeHookMarker, @"CC_PETS_BUS_HOOK="];
20
+ }
21
+
22
+ static NSArray<NSString *> *MCPNames(void) {
23
+ return @[CCBridgeMCPName, @"cc-pets-bus"];
24
+ }
25
+
26
+ static NSArray<NSArray<NSString *> *> *TomlBlocks(void) {
27
+ return @[@[TomlStart, TomlEnd], @[@"# >>> cc-pets-bus >>>", @"# <<< cc-pets-bus <<<"]];
28
+ }
29
+
30
+ // 文件预留提醒只挂在编辑类工具上,避免每次 shell / 读文件都多跑一次 hook。
31
+ static NSString *const ClaudeEditMatcher = @"Edit|Write|MultiEdit|NotebookEdit";
32
+ static NSString *const CodexEditMatcher = @"apply_patch|Edit|Write";
33
+
34
+ BOOL CCBridgeShouldTouchMCP(void) {
35
+ return ![CCPetsEnvironmentValue(@"CC_BRIDGE_SKIP_MCP") isEqualToString:@"1"];
36
+ }
37
+
38
+ // 写进 hooks 的命令直接调原生二进制,不经过 bin/cc-pets:hook 在对方 CLI 的关键路径上,越轻越好。
39
+ static NSString *BridgeCommand(NSString *provider, NSString *subcommand, NSDictionary *profile) {
40
+ NSString *identity = @"";
41
+ if ([profile[@"id"] isKindOfClass:NSString.class]) {
42
+ identity = [NSString stringWithFormat:@" CC_PETS_PROFILE_ID=%@ CC_PETS_PROFILE_NAME=%@ CC_PETS_PROFILE_HOME=%@",
43
+ CCPetsShellQuote(profile[@"id"]), CCPetsShellQuote(profile[@"displayName"] ?: profile[@"slug"] ?: provider),
44
+ CCPetsShellQuote(profile[@"home"] ?: @"")];
45
+ }
46
+ return [NSString stringWithFormat:@"%@%@%@ %@ bridge %@", CCBridgeHookMarker, provider, identity,
47
+ CCPetsShellQuote(CCPetsExecutablePath()), subcommand];
48
+ }
49
+
50
+ static BOOL IsBridgeHook(id handler) {
51
+ id command = [handler isKindOfClass:CCPetsJSONObject.class] ? ((CCPetsJSONObject *)handler)[@"command"] : nil;
52
+ if (![command isKindOfClass:NSString.class]) return NO;
53
+ for (NSString *marker in HookMarkers()) {
54
+ if ([command hasPrefix:marker]) return YES;
55
+ }
56
+ return NO;
57
+ }
58
+
59
+ #pragma mark - JSON 配置
60
+
61
+ static CCPetsJSONObject *ReadJSONConfig(NSString *file) {
62
+ NSString *error = nil;
63
+ id config = CCPetsReadConfig(file, &error);
64
+ if (!config && error) [NSException raise:@"CCBridgeConfig" format:@"%@: %@", file, error];
65
+ if (!config) return [CCPetsJSONObject new];
66
+ if (![config isKindOfClass:CCPetsJSONObject.class]) {
67
+ [NSException raise:@"CCBridgeConfig" format:@"%@", LF(L(@"{file} isn't a JSON object"), @{@"file": file})];
68
+ }
69
+ return config;
70
+ }
71
+
72
+ static void WriteJSONConfig(NSString *file, CCPetsJSONObject *config) {
73
+ struct stat info;
74
+ mode_t mode = stat(file.fileSystemRepresentation, &info) == 0 ? (info.st_mode & 0777) : 0600;
75
+ NSString *error = nil;
76
+ if (!CCPetsWriteFileAtomically(file, [CCPetsJSONStringify(config) stringByAppendingString:@"\n"], mode, &error)) {
77
+ [NSException raise:@"CCBridgeConfig" format:@"%@", error];
78
+ }
79
+ }
80
+
81
+ // 返回是否摘掉了东西。事件下一个 group 都不剩就删掉事件,hooks 空了也删掉。
82
+ static BOOL StripBridgeHooks(CCPetsJSONObject *config) {
83
+ CCPetsJSONObject *hooks = config[@"hooks"];
84
+ if (![hooks isKindOfClass:CCPetsJSONObject.class]) return NO;
85
+ BOOL changed = NO;
86
+ for (NSString *event in hooks.keys) {
87
+ NSArray *groups = hooks[event];
88
+ if (![groups isKindOfClass:NSArray.class]) continue;
89
+ NSMutableArray *kept = [NSMutableArray array];
90
+ for (id group in groups) {
91
+ NSArray *handlers = [group isKindOfClass:CCPetsJSONObject.class] ? ((CCPetsJSONObject *)group)[@"hooks"] : nil;
92
+ if (![handlers isKindOfClass:NSArray.class]) {
93
+ [kept addObject:group];
94
+ continue;
95
+ }
96
+ NSMutableArray *remaining = [NSMutableArray array];
97
+ for (id handler in handlers) {
98
+ if (!IsBridgeHook(handler)) [remaining addObject:handler];
99
+ }
100
+ if (remaining.count != handlers.count) changed = YES;
101
+ if (remaining.count == 0) continue;
102
+ CCPetsJSONObject *updated = [group copy];
103
+ updated[@"hooks"] = remaining;
104
+ [kept addObject:updated];
105
+ }
106
+ if (kept.count > 0) hooks[event] = kept;
107
+ else [hooks removeObjectForKey:event];
108
+ }
109
+ if (hooks.keys.count == 0) [config removeObjectForKey:@"hooks"];
110
+ return changed;
111
+ }
112
+
113
+ static CCPetsJSONObject *Handler(NSString *command, BOOL asyncRewake, NSInteger timeout) {
114
+ CCPetsJSONObject *handler = [CCPetsJSONObject new];
115
+ handler[@"type"] = @"command";
116
+ handler[@"command"] = command;
117
+ if (asyncRewake) handler[@"asyncRewake"] = @YES;
118
+ handler[@"timeout"] = @(timeout);
119
+ return handler;
120
+ }
121
+
122
+ static void AddHook(CCPetsJSONObject *config, NSString *event, CCPetsJSONObject *handler, NSString *matcher) {
123
+ if (![config[@"hooks"] isKindOfClass:CCPetsJSONObject.class]) config[@"hooks"] = [CCPetsJSONObject new];
124
+ CCPetsJSONObject *hooks = config[@"hooks"];
125
+ NSMutableArray *groups = [hooks[event] isKindOfClass:NSArray.class] ? [hooks[event] mutableCopy] : [NSMutableArray array];
126
+ CCPetsJSONObject *group = [CCPetsJSONObject new];
127
+ if (matcher) group[@"matcher"] = matcher;
128
+ group[@"hooks"] = @[handler];
129
+ [groups addObject:group];
130
+ hooks[event] = groups;
131
+ }
132
+
133
+ // Claude:同步 hook 维护注册表;asyncRewake watcher 负责投递(单例锁保证同时只有一个)。
134
+ // watcher 只挂 SessionStart / Stop,不挂 UserPromptSubmit:由 UserPromptSubmit 拉起的 watcher 在回合中途
135
+ // exit 2 时,Claude Code 会显示成 "Stop hook blocking error from command UserPromptSubmit",像报错。
136
+ // Stop 拉起的 watcher 会一直活过下一个忙碌回合,中途投递照常;watcher 超时退出后,用户开口时信箱里
137
+ // 已有的消息由同步 hook 注入。
138
+ //
139
+ // 选项决定装哪些:关闭"自动唤醒"时不装 watcher;关闭"编辑前预留拦截"时不装 PreToolUse。
140
+ // hook / watcher 自己也会再读一次选项兜底。
141
+ static void AddClaudeHooks(CCPetsJSONObject *config, NSDictionary *options, NSDictionary *profile) {
142
+ for (NSString *event in @[@"SessionStart", @"UserPromptSubmit", @"Stop", @"SessionEnd"]) {
143
+ AddHook(config, event, Handler(BridgeCommand(@"Claude", @"hook", profile), NO, 10), nil);
144
+ }
145
+ if ([options[@"editGuard"] boolValue]) {
146
+ AddHook(config, @"PreToolUse", Handler(BridgeCommand(@"Claude", @"hook", profile), NO, 10), ClaudeEditMatcher);
147
+ }
148
+ if ([options[@"wake"] boolValue]) {
149
+ for (NSString *event in @[@"SessionStart", @"Stop"]) {
150
+ AddHook(config, event, Handler(BridgeCommand(@"Claude", @"watch", profile), YES, 3600), nil);
151
+ }
152
+ }
153
+ }
154
+
155
+ static void AddCodexHooks(CCPetsJSONObject *config, NSDictionary *options, NSDictionary *profile) {
156
+ for (NSString *event in @[@"SessionStart", @"UserPromptSubmit", @"Stop", @"SessionEnd"]) {
157
+ AddHook(config, event, Handler(BridgeCommand(@"Codex", @"hook", profile), NO, 10), nil);
158
+ }
159
+ if ([options[@"editGuard"] boolValue]) {
160
+ AddHook(config, @"PreToolUse", Handler(BridgeCommand(@"Codex", @"hook", profile), NO, 10), CodexEditMatcher);
161
+ }
162
+ }
163
+
164
+ // Claude 的工具放行写在 settings.json 的 permissions.allow 里,条目形如 mcp__cc-bridge__send_message。
165
+ // 只增删这个前缀下的条目(含旧名 cc-pets-bus),不碰用户其他的放行规则。返回是否有变化。
166
+ static BOOL ApplyClaudeAllow(CCPetsJSONObject *config, NSArray<NSString *> *tools) {
167
+ CCPetsJSONObject *permissions = [config[@"permissions"] isKindOfClass:CCPetsJSONObject.class] ? config[@"permissions"] : nil;
168
+ NSArray *current = [permissions[@"allow"] isKindOfClass:NSArray.class] ? permissions[@"allow"] : @[];
169
+ NSRegularExpression *managed = [NSRegularExpression regularExpressionWithPattern:@"\\Amcp__(?:cc-bridge|cc-pets-bus)__[a-z_]+\\z" options:0 error:nil];
170
+ NSMutableArray *next = [NSMutableArray array];
171
+ for (id entry in current) {
172
+ BOOL ours = [entry isKindOfClass:NSString.class] &&
173
+ [managed firstMatchInString:entry options:0 range:NSMakeRange(0, [entry length])];
174
+ if (!ours) [next addObject:entry];
175
+ }
176
+ for (NSString *tool in tools) [next addObject:[NSString stringWithFormat:@"mcp__%@__%@", CCBridgeMCPName, tool]];
177
+ if ([next isEqualToArray:current] && (next.count > 0 || !permissions[@"allow"])) return NO;
178
+ if (next.count > 0) {
179
+ CCPetsJSONObject *updated = permissions ? [permissions copy] : [CCPetsJSONObject new];
180
+ updated[@"allow"] = next;
181
+ config[@"permissions"] = updated;
182
+ } else if (permissions) {
183
+ [permissions removeObjectForKey:@"allow"];
184
+ if (permissions.keys.count == 0) [config removeObjectForKey:@"permissions"];
185
+ }
186
+ return YES;
187
+ }
188
+
189
+ #pragma mark - Codex 工具审批
190
+ // Codex 默认每次 MCP 调用都要审批,approval_policy=never 时直接报错(实测)。用户选择放开时,
191
+ // 只在 config.toml 末尾追加一段带标记的块,移除时整段删掉。
192
+
193
+ static NSString *CodexApprovalBlock(NSArray<NSString *> *tools) {
194
+ NSMutableArray<NSString *> *lines = [NSMutableArray arrayWithObjects:TomlStart,
195
+ L(@"# Written by cc-pets bridge enable / configure; cc-pets bridge disable removes it."), nil];
196
+ for (NSString *tool in tools) {
197
+ [lines addObject:[NSString stringWithFormat:@"[mcp_servers.%@.tools.%@]", CCBridgeMCPName, tool]];
198
+ [lines addObject:@"approval_mode = \"approve\""];
199
+ [lines addObject:@""];
200
+ }
201
+ [lines addObject:TomlEnd];
202
+ return [lines componentsJoinedByString:@"\n"];
203
+ }
204
+
205
+ static NSString *StripTomlBlocks(NSString *text) {
206
+ for (NSArray<NSString *> *block in TomlBlocks()) {
207
+ NSString *pattern = [NSString stringWithFormat:@"\\n?%@[\\s\\S]*?%@\\n?",
208
+ [NSRegularExpression escapedPatternForString:block[0]], [NSRegularExpression escapedPatternForString:block[1]]];
209
+ NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
210
+ text = [expression stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@"\n"];
211
+ }
212
+ NSRegularExpression *blank = [NSRegularExpression regularExpressionWithPattern:@"\\n{3,}" options:0 error:nil];
213
+ return [blank stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@"\n\n"];
214
+ }
215
+
216
+ static void SetCodexApprovalAtHome(NSArray<NSString *> *tools, NSString *codexHome) {
217
+ NSString *file = [codexHome stringByAppendingPathComponent:@"config.toml"];
218
+ struct stat info;
219
+ BOOL exists = stat(file.fileSystemRepresentation, &info) == 0;
220
+ NSString *original = exists ? ([NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] ?: @"") : @"";
221
+ // 只把末尾的空白收成一个换行:开头的空白属于用户的文件,原样保留。
222
+ NSString *stripped = StripTomlBlocks(original);
223
+ NSUInteger end = stripped.length;
224
+ NSCharacterSet *whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet;
225
+ while (end > 0 && [whitespace characterIsMember:[stripped characterAtIndex:end - 1]]) end--;
226
+ NSString *updated = [[stripped substringToIndex:end] stringByAppendingString:@"\n"];
227
+ if (tools.count > 0) updated = [updated stringByAppendingFormat:@"\n%@\n", CodexApprovalBlock(tools)];
228
+ if ([updated isEqualToString:original]) return;
229
+ NSString *error = nil;
230
+ if (!CCPetsWriteFileAtomically(file, updated, exists ? (info.st_mode & 0777) : 0600, &error)) {
231
+ [NSException raise:@"CCBridgeConfig" format:@"%@", error];
232
+ }
233
+ }
234
+
235
+ static void SetCodexApproval(NSArray<NSString *> *tools) {
236
+ SetCodexApprovalAtHome(tools, CCPetsCodexHome());
237
+ }
238
+
239
+ #pragma mark - MCP
240
+
241
+ static BOOL RunQuietly(NSString *executable, NSArray<NSString *> *arguments) {
242
+ return CCPetsRun(executable, arguments, nil, nil, 60, NULL, NULL) == 0;
243
+ }
244
+
245
+ static BOOL RunQuietlyForHome(NSString *executable, NSArray<NSString *> *arguments,
246
+ NSString *provider, NSString *home) {
247
+ NSMutableDictionary<NSString *, NSString *> *environment =
248
+ [NSProcessInfo.processInfo.environment mutableCopy];
249
+ BOOL claude = [provider isEqualToString:@"claude"];
250
+ // 官方 ~/.claude 不能显式设 CLAUDE_CONFIG_DIR:一旦设了,user 级 MCP 会写进
251
+ // ~/.claude/.claude.json,而正常启动的 claude 读的是 ~/.claude.json。
252
+ NSString *officialClaude = CCPetsRealPath([CCPetsHomeDirectory() stringByAppendingPathComponent:@".claude"]);
253
+ if (claude && officialClaude.length > 0 && [CCPetsRealPath(home) isEqualToString:officialClaude]) {
254
+ [environment removeObjectForKey:@"CLAUDE_CONFIG_DIR"];
255
+ } else {
256
+ environment[claude ? @"CLAUDE_CONFIG_DIR" : @"CODEX_HOME"] = home;
257
+ }
258
+ return CCPetsRun(executable, arguments, nil, environment, 60, NULL, NULL) == 0;
259
+ }
260
+
261
+ // MCP 进程的环境会被 CLI 裁剪,PATH 里不一定找得到 codex;投递到 Codex 需要它,
262
+ // 注册时把安装时解析到的绝对路径固定下来。
263
+ static NSArray<NSString *> *MCPEnvironment(void) {
264
+ NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
265
+ return codex ? @[[@"CODEX_REAL_BIN=" stringByAppendingString:codex]] : @[];
266
+ }
267
+
268
+ static NSArray<NSString *> *MCPCommand(void) {
269
+ return @[@"--", CCPetsExecutablePath(), @"bridge", @"mcp"];
270
+ }
271
+
272
+ static NSArray<NSString *> *ClaudeMCPAddArguments(void) {
273
+ NSMutableArray<NSString *> *arguments = [@[@"mcp", @"add", @"--scope", @"user", CCBridgeMCPName] mutableCopy];
274
+ for (NSString *pair in MCPEnvironment()) [arguments addObjectsFromArray:@[@"-e", pair]];
275
+ [arguments addObjectsFromArray:MCPCommand()];
276
+ return arguments;
277
+ }
278
+
279
+ static NSArray<NSString *> *CodexMCPAddArguments(void) {
280
+ NSMutableArray<NSString *> *arguments = [@[@"mcp", @"add", CCBridgeMCPName] mutableCopy];
281
+ for (NSString *pair in MCPEnvironment()) [arguments addObjectsFromArray:@[@"--env", pair]];
282
+ [arguments addObjectsFromArray:MCPCommand()];
283
+ return arguments;
284
+ }
285
+
286
+ static NSString *QuotedArguments(NSArray<NSString *> *arguments) {
287
+ NSMutableArray<NSString *> *quoted = [NSMutableArray array];
288
+ for (NSString *argument in arguments) [quoted addObject:CCPetsShellQuote(argument)];
289
+ return [quoted componentsJoinedByString:@" "];
290
+ }
291
+
292
+ NSString *CCBridgeDescribeCodexQueue(NSDictionary *probe) {
293
+ NSString *version = [probe[@"version"] isKindOfClass:NSString.class]
294
+ ? LF(L(@" ({version})"), @{@"version": probe[@"version"]}) : @"";
295
+ NSString *status = probe[@"status"];
296
+ if ([status isEqualToString:@"supported"]) return nil;
297
+ if ([status isEqualToString:@"unsupported"]) {
298
+ return [LF(L(@"This Codex{version} doesn't support codex queue, so messages to Codex can't wake it; they go to its inbox "),
299
+ @{@"version": version}) stringByAppendingString:
300
+ L(@"and are picked up via check_inbox or with the next input. Upgrading Codex enables wake-up without re-enabling CC Bridge.")];
301
+ }
302
+ if ([status isEqualToString:@"missing"]) {
303
+ return L(@"codex executable not found, so messages to Codex can only go to its inbox; set CODEX_REAL_BIN and run cc-pets bridge enable.");
304
+ }
305
+ return L(@"Couldn't tell whether Codex supports codex queue; failed deliveries fall back to the inbox.");
306
+ }
307
+
308
+ #pragma mark - 安装 / 卸载
309
+
310
+ static BOOL RemoveJSONHooks(NSString *file, BOOL claudeAllow);
311
+
312
+ NSArray<NSString *> *CCBridgeInstallForProfile(NSDictionary *profile, NSDictionary *rawOptions, BOOL registerMcp) {
313
+ NSString *provider = [profile[@"provider"] isKindOfClass:NSString.class] ? profile[@"provider"] : @"";
314
+ NSString *home = [profile[@"home"] isKindOfClass:NSString.class] ? profile[@"home"] : @"";
315
+ if (home.length == 0 || (![provider isEqualToString:@"claude"] && ![provider isEqualToString:@"codex"])) {
316
+ [NSException raise:@"CCBridgeConfig" format:@"Invalid Agent profile."];
317
+ }
318
+ NSDictionary *options = CCBridgeNormalizeOptions(rawOptions);
319
+ NSMutableArray<NSString *> *report = [NSMutableArray array];
320
+ [NSFileManager.defaultManager createDirectoryAtPath:home withIntermediateDirectories:YES attributes:nil error:nil];
321
+ if ([provider isEqualToString:@"claude"]) {
322
+ NSString *settingsPath = [home stringByAppendingPathComponent:@"settings.json"];
323
+ CCPetsJSONObject *config = ReadJSONConfig(settingsPath);
324
+ StripBridgeHooks(config);
325
+ AddClaudeHooks(config, options, profile);
326
+ ApplyClaudeAllow(config, options[@"claudeAllow"]);
327
+ WriteJSONConfig(settingsPath, config);
328
+ [report addObject:LF(L(@"Claude Code hooks written to {path}"), @{@"path": settingsPath})];
329
+ if (registerMcp) {
330
+ NSString *claude = CCPetsFindRealExecutable(@"claude", @"CLAUDE_REAL_BIN");
331
+ for (NSString *name in MCPNames()) {
332
+ if (claude) RunQuietlyForHome(claude, @[@"mcp", @"remove", @"--scope", @"user", name], provider, home);
333
+ }
334
+ BOOL ok = claude && RunQuietlyForHome(claude, ClaudeMCPAddArguments(), provider, home);
335
+ [report addObject:ok
336
+ ? LF(L(@"Claude Code MCP registered: {MCP_NAME} (on first use, Claude asks according to your permission settings)"), @{@"MCP_NAME": CCBridgeMCPName})
337
+ : [@"ERROR: " stringByAppendingString:LF(L(@"Claude Code MCP registration failed. Run manually: claude {shellQuote}"), @{@"shellQuote": QuotedArguments(ClaudeMCPAddArguments())})]];
338
+ }
339
+ return report;
340
+ }
341
+
342
+ NSString *hooksPath = [home stringByAppendingPathComponent:@"hooks.json"];
343
+ CCPetsJSONObject *config = ReadJSONConfig(hooksPath);
344
+ StripBridgeHooks(config);
345
+ AddCodexHooks(config, options, profile);
346
+ WriteJSONConfig(hooksPath, config);
347
+ [report addObject:LF(L(@"Codex hooks written to {path}. Next time you start Codex, run /hooks and trust the cc-pets bridge hooks."), @{@"path": hooksPath})];
348
+ if (registerMcp) {
349
+ NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
350
+ for (NSString *name in MCPNames()) {
351
+ if (codex) RunQuietlyForHome(codex, @[@"mcp", @"remove", name], provider, home);
352
+ }
353
+ BOOL ok = codex && RunQuietlyForHome(codex, CodexMCPAddArguments(), provider, home);
354
+ [report addObject:ok
355
+ ? LF(L(@"Codex MCP registered: {MCP_NAME}"), @{@"MCP_NAME": CCBridgeMCPName})
356
+ : [@"ERROR: " stringByAppendingString:LF(L(@"Codex MCP registration failed. Run manually: codex {shellQuote}"), @{@"shellQuote": QuotedArguments(CodexMCPAddArguments())})]];
357
+ // 只在 enable / refresh 时探测:configure 由桌宠菜单开关触发,不值得每次多拉起两次 codex。
358
+ if ([options[@"wake"] boolValue]) {
359
+ NSString *notice = CCBridgeDescribeCodexQueue(CCBridgeProbeCodexQueue(codex));
360
+ if (notice) [report addObject:notice];
361
+ }
362
+ }
363
+ SetCodexApprovalAtHome(options[@"codexApprove"], home);
364
+ return report;
365
+ }
366
+
367
+ NSArray<NSString *> *CCBridgeUninstallForProfile(NSDictionary *profile, BOOL unregisterMcp) {
368
+ NSString *provider = [profile[@"provider"] isKindOfClass:NSString.class] ? profile[@"provider"] : @"";
369
+ NSString *home = [profile[@"home"] isKindOfClass:NSString.class] ? profile[@"home"] : @"";
370
+ NSMutableArray<NSString *> *report = [NSMutableArray array];
371
+ if ([provider isEqualToString:@"claude"]) {
372
+ if (RemoveJSONHooks([home stringByAppendingPathComponent:@"settings.json"], YES)) {
373
+ [report addObject:L(@"Removed the cc-bridge hooks and tool permissions from Claude Code.")];
374
+ }
375
+ if (unregisterMcp) {
376
+ NSString *claude = CCPetsFindRealExecutable(@"claude", @"CLAUDE_REAL_BIN");
377
+ if (!claude) [report addObject:[@"ERROR: " stringByAppendingString:
378
+ L(@"Claude Code executable not found; MCP registration was not removed.")]];
379
+ for (NSString *name in MCPNames()) {
380
+ if (claude && RunQuietlyForHome(claude, @[@"mcp", @"remove", @"--scope", @"user", name], provider, home)) {
381
+ [report addObject:LF(L(@"Removed Claude Code MCP: {name}."), @{@"name": name})];
382
+ }
383
+ }
384
+ }
385
+ } else if ([provider isEqualToString:@"codex"]) {
386
+ if (RemoveJSONHooks([home stringByAppendingPathComponent:@"hooks.json"], NO)) {
387
+ [report addObject:L(@"Removed the cc-bridge hooks from Codex.")];
388
+ }
389
+ SetCodexApprovalAtHome(@[], home);
390
+ if (unregisterMcp) {
391
+ NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
392
+ if (!codex) [report addObject:[@"ERROR: " stringByAppendingString:
393
+ L(@"Codex executable not found; MCP registration was not removed.")]];
394
+ for (NSString *name in MCPNames()) {
395
+ if (codex && RunQuietlyForHome(codex, @[@"mcp", @"remove", name], provider, home)) {
396
+ [report addObject:LF(L(@"Removed Codex MCP: {name}."), @{@"name": name})];
397
+ }
398
+ }
399
+ }
400
+ }
401
+ return report;
402
+ }
403
+
404
+ NSArray<NSString *> *CCBridgeInstall(NSDictionary *rawOptions, BOOL registerMcp) {
405
+ NSDictionary *options = CCBridgeNormalizeOptions(rawOptions);
406
+ NSArray<NSString *> *claudeAllow = options[@"claudeAllow"];
407
+ NSArray<NSString *> *codexApprove = options[@"codexApprove"];
408
+ NSMutableArray<NSString *> *report = [NSMutableArray array];
409
+ if (CCPetsClaudeCLIInstalled()) {
410
+ [NSFileManager.defaultManager createDirectoryAtPath:CCPetsClaudeHome() withIntermediateDirectories:YES attributes:nil error:nil];
411
+ NSString *settingsPath = [CCPetsClaudeHome() stringByAppendingPathComponent:@"settings.json"];
412
+ CCPetsJSONObject *config = ReadJSONConfig(settingsPath);
413
+ StripBridgeHooks(config);
414
+ AddClaudeHooks(config, options, nil);
415
+ ApplyClaudeAllow(config, claudeAllow);
416
+ WriteJSONConfig(settingsPath, config);
417
+ [report addObject:LF(L(@"Claude Code hooks written to {path}"), @{@"path": settingsPath})];
418
+ [report addObject:claudeAllow.count > 0
419
+ ? LF(L(@"Claude Code allows these tools without asking: {claudeAllow}"), @{@"claudeAllow": [claudeAllow componentsJoinedByString:@", "]})
420
+ : L(@"In Claude Code, cc-bridge tools follow your permission settings.")];
421
+ if (registerMcp) {
422
+ NSString *claude = CCPetsFindRealExecutable(@"claude", @"CLAUDE_REAL_BIN");
423
+ for (NSString *name in MCPNames()) RunQuietly(claude ?: @"claude", @[@"mcp", @"remove", @"--scope", @"user", name]);
424
+ BOOL ok = claude && RunQuietly(claude, ClaudeMCPAddArguments());
425
+ [report addObject:ok
426
+ ? LF(L(@"Claude Code MCP registered: {MCP_NAME} (on first use, Claude asks according to your permission settings)"), @{@"MCP_NAME": CCBridgeMCPName})
427
+ : LF(L(@"Claude Code MCP registration failed. Run manually: claude {shellQuote}"), @{@"shellQuote": QuotedArguments(ClaudeMCPAddArguments())})];
428
+ }
429
+ } else {
430
+ [report addObject:L(@"Claude Code CLI not detected, skipped.")];
431
+ }
432
+
433
+ if (CCPetsCodexCLIInstalled()) {
434
+ [NSFileManager.defaultManager createDirectoryAtPath:CCPetsCodexHome() withIntermediateDirectories:YES attributes:nil error:nil];
435
+ NSString *hooksPath = [CCPetsCodexHome() stringByAppendingPathComponent:@"hooks.json"];
436
+ CCPetsJSONObject *config = ReadJSONConfig(hooksPath);
437
+ StripBridgeHooks(config);
438
+ AddCodexHooks(config, options, nil);
439
+ WriteJSONConfig(hooksPath, config);
440
+ [report addObject:LF(L(@"Codex hooks written to {path}. Next time you start Codex, run /hooks and trust the cc-pets bridge hooks."), @{@"path": hooksPath})];
441
+ if (registerMcp) {
442
+ NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
443
+ for (NSString *name in MCPNames()) RunQuietly(codex ?: @"codex", @[@"mcp", @"remove", name]);
444
+ BOOL ok = codex && RunQuietly(codex, CodexMCPAddArguments());
445
+ [report addObject:ok
446
+ ? LF(L(@"Codex MCP registered: {MCP_NAME}"), @{@"MCP_NAME": CCBridgeMCPName})
447
+ : LF(L(@"Codex MCP registration failed. Run manually: codex {shellQuote}"), @{@"shellQuote": QuotedArguments(CodexMCPAddArguments())})];
448
+ // 只在 enable / refresh 时探测:configure 由桌宠菜单开关触发,不值得每次多拉起两次 codex。
449
+ if ([options[@"wake"] boolValue]) {
450
+ NSString *notice = CCBridgeDescribeCodexQueue(CCBridgeProbeCodexQueue(codex));
451
+ if (notice) [report addObject:notice];
452
+ }
453
+ }
454
+ SetCodexApproval(codexApprove);
455
+ [report addObject:codexApprove.count > 0
456
+ ? LF(L(@"Codex auto-approves these tools: {codexApprove} (restart Codex sessions to apply)"), @{@"codexApprove": [codexApprove componentsJoinedByString:@", "]})
457
+ : L(@"cc-bridge tools keep Codex's default approvals (calls fail under approval_policy=never; allow them with --codex-approve).")];
458
+ } else {
459
+ [report addObject:L(@"Codex CLI not detected, skipped.")];
460
+ }
461
+ return report;
462
+ }
463
+
464
+ // 文件不存在、或里面本来就没有我们的东西时不改写——用户的文件不该因为一次卸载被重排格式。
465
+ static BOOL RemoveJSONHooks(NSString *file, BOOL claudeAllow) {
466
+ if (![NSFileManager.defaultManager fileExistsAtPath:file]) return NO;
467
+ CCPetsJSONObject *config = ReadJSONConfig(file);
468
+ BOOL changed = StripBridgeHooks(config);
469
+ if (claudeAllow && ApplyClaudeAllow(config, @[])) changed = YES;
470
+ if (!changed) return NO;
471
+ WriteJSONConfig(file, config);
472
+ return YES;
473
+ }
474
+
475
+ NSArray<NSString *> *CCBridgeUninstall(BOOL unregisterMcp) {
476
+ NSMutableArray<NSString *> *report = [NSMutableArray array];
477
+ if (RemoveJSONHooks([CCPetsClaudeHome() stringByAppendingPathComponent:@"settings.json"], YES)) {
478
+ [report addObject:L(@"Removed the cc-bridge hooks and tool permissions from Claude Code.")];
479
+ }
480
+ if (RemoveJSONHooks([CCPetsCodexHome() stringByAppendingPathComponent:@"hooks.json"], NO)) {
481
+ [report addObject:L(@"Removed the cc-bridge hooks from Codex.")];
482
+ }
483
+ if ([NSFileManager.defaultManager fileExistsAtPath:[CCPetsCodexHome() stringByAppendingPathComponent:@"config.toml"]]) {
484
+ SetCodexApproval(@[]);
485
+ }
486
+ if (unregisterMcp) {
487
+ NSString *claude = CCPetsFindRealExecutable(@"claude", @"CLAUDE_REAL_BIN");
488
+ for (NSString *name in MCPNames()) {
489
+ if (claude && RunQuietly(claude, @[@"mcp", @"remove", @"--scope", @"user", name])) {
490
+ [report addObject:LF(L(@"Removed Claude Code MCP: {name}."), @{@"name": name})];
491
+ }
492
+ }
493
+ NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
494
+ for (NSString *name in MCPNames()) {
495
+ if (codex && RunQuietly(codex, @[@"mcp", @"remove", name])) {
496
+ [report addObject:LF(L(@"Removed Codex MCP: {name}."), @{@"name": name})];
497
+ }
498
+ }
499
+ }
500
+ return report;
501
+ }
@@ -0,0 +1,103 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // CC Bridge 的存储层:会话注册表、信箱、回执、订阅、锁,以及选项解析与进程探测。
4
+ //
5
+ // 全部是"一条记录一个文件",状态流转靠同一文件系统内的 rename 完成——rename 是原子的,
6
+ // 多个终端的 hook / watcher / MCP 进程同时抢同一条消息时,只有一个能 rename 成功,
7
+ // 其余拿到 ENOENT 直接跳过,不需要任何守护进程或数据库锁。
8
+ //
9
+ // 目录在 CCBridgeStateDirectory()(默认 $TMPDIR 下),与桌宠事件流同级:会话本身活不过重启,
10
+ // 注册表和未投递的消息也没有跨重启保留的意义。启用开关则放在 ~/.cc-pets 里持久保存。
11
+ //
12
+ // 目录准备失败(不是普通目录、不属于当前用户)时抛 NSException,由命令入口统一捕获。
13
+
14
+ extern const NSUInteger CCBridgeMessageBodyLimit;
15
+ extern const long long CCBridgeMessageTTL;
16
+ extern const NSUInteger CCBridgePairLimitCount;
17
+
18
+ #pragma mark - 开关与选项
19
+
20
+ // 正式发布前叫过 "Agent Bus",开关文件是 bus-enabled。迁移成新名字并保留当时的选项。
21
+ BOOL CCBridgeMigrateLegacyFlag(void);
22
+ void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options);
23
+ // 桌宠菜单靠这个文件找到 cc-pets 与终端里的 PATH,每次 refresh / enable / configure 都重写。
24
+ void CCBridgeWriteCLILocator(void);
25
+
26
+ // "view,send_message" → 展开分组、校验工具名。空字符串表示清空。失败返回 nil 并给出原因。
27
+ NSArray<NSString *> *CCBridgeParseToolList(NSString *text, NSString *flag, NSString **error);
28
+ // on / off(也认 true / false / 1 / 0 / yes / no)。失败返回 nil。
29
+ NSNumber *CCBridgeParseSwitch(NSString *text, NSString *flag, NSString **error);
30
+ // 在 base 之上叠加命令行里给出的选项(approve / codexApprove / claudeAllow / wake / editGuard),
31
+ // 没给的保持原值。失败返回 nil。
32
+ NSDictionary *CCBridgeMergeOptionFlags(NSDictionary *base, NSDictionary<NSString *, NSString *> *flags, NSString **error);
33
+ NSArray<NSString *> *CCBridgeDescribeOptions(NSDictionary *options);
34
+
35
+ #pragma mark - 目录与文件
36
+
37
+ NSString *CCBridgeSubdirectory(NSArray<NSString *> *parts);
38
+ // session id 会拼进文件路径,只放行 UUID 一类的安全字符,杜绝 ../ 之类的路径穿越。
39
+ NSString *CCBridgeSafeSessionId(id value);
40
+ void CCBridgeWriteJSON(NSString *file, id value);
41
+ id CCBridgeReadJSON(NSString *file);
42
+
43
+ // 只用来派生短标识(ref、预留 id),不涉及安全。
44
+ NSString *CCBridgeSHA1Hex(NSString *text);
45
+
46
+ #pragma mark - 会话注册表
47
+
48
+ NSString *CCBridgeSessionRef(NSString *sessionId);
49
+ NSDictionary *CCBridgeReadSession(id sessionId);
50
+ NSArray<NSDictionary *> *CCBridgeListSessions(void);
51
+ void CCBridgeRemoveSession(id sessionId);
52
+ NSString *CCBridgeNormalizeSessionName(id value);
53
+ // liveSessions 用于给新会话分配不冲突的名字(已注册的会话不重新命名)。
54
+ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
55
+ NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
56
+ NSString *profileName, NSArray<NSDictionary *> *liveSessions);
57
+ // 会话内改名:被其他在线会话占用时报错。返回 @{error} 或 @{session, previous}。
58
+ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions);
59
+
60
+ #pragma mark - 消息
61
+
62
+ NSString *CCBridgeNewMessageId(void);
63
+ NSDictionary *CCBridgeReadReceipt(id messageId);
64
+ void CCBridgeWriteReceipt(NSDictionary *message);
65
+ NSDictionary *CCBridgeUpdateReceipt(NSString *messageId, NSDictionary *patch);
66
+ NSArray<NSDictionary *> *CCBridgeListReceipts(void);
67
+ // 发送前的配额检查。nil 表示放行,否则返回拒绝原因。
68
+ NSString *CCBridgeCheckSendLimits(NSString *fromSession, NSString *toSession);
69
+ void CCBridgeEnqueueInbox(NSDictionary *message);
70
+ // 认领:inbox → claimed,rename 失败(被别的进程抢先)就跳过;过期的标记 expired 后丢弃。
71
+ NSArray<NSDictionary *> *CCBridgeClaimInbox(id sessionId);
72
+ NSUInteger CCBridgePendingCount(id sessionId);
73
+ // 会话结束:信箱里还没投出去的消息标记为 undeliverable。
74
+ void CCBridgeAbandonInbox(id sessionId);
75
+ void CCBridgePruneReceipts(void);
76
+
77
+ #pragma mark - 空闲订阅(一次性)
78
+
79
+ void CCBridgeAddIdleSubscription(NSString *targetSession, NSString *subscriberSession);
80
+ BOOL CCBridgeHasIdleSubscriptions(NSString *targetSession);
81
+ NSArray<NSString *> *CCBridgeTakeIdleSubscriptions(NSString *targetSession);
82
+
83
+ #pragma mark - 锁
84
+
85
+ // O_EXCL 创建,内容是持有者 pid;持有者已死的锁视为陈旧,可以抢占。成功返回锁文件路径。
86
+ NSString *CCBridgeAcquireLock(NSString *name);
87
+ void CCBridgeReleaseLock(NSString *lockFile);
88
+
89
+ #pragma mark - 进程探测
90
+
91
+ BOOL CCBridgeProcessAlive(pid_t pid);
92
+ NSString *CCBridgeProcessCommand(pid_t pid);
93
+ // CLI 进程的控制终端,如 "ttys003";没有时返回 nil。
94
+ NSString *CCBridgeProcessTty(pid_t pid);
95
+ BOOL CCBridgeCommandMatchesProvider(NSString *provider, NSString *command);
96
+ // 离 startPid 最近的 Claude / Codex 祖先进程:@{provider, pid}。CC_BRIDGE_AGENT=Codex:1234 可强制指定。
97
+ NSDictionary *CCBridgeFindAgentAncestor(pid_t startPid);
98
+ // 有 pid 时以"进程还在且仍是同一种 CLI"为准(防 pid 复用);没有 pid 的记录退回 6 小时活动窗口。
99
+ BOOL CCBridgeSessionLive(NSDictionary *session);
100
+ // `codex queue` 能力探测:@{status: supported|unsupported|missing|unknown, executable, version}。
101
+ NSDictionary *CCBridgeProbeCodexQueue(NSString *executable);
102
+ // environment 为 nil 时继承当前环境。npm 装的 codex 是 `env node` 脚本,主窗口得带上能找到 node 的 PATH。
103
+ NSDictionary *CCBridgeProbeCodexQueueWithEnvironment(NSString *executable, NSDictionary<NSString *, NSString *> *environment);