cc-pets 2.2.0 → 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 (173) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +85 -0
  4. package/CHANGELOG.zh-CN.md +85 -0
  5. package/CONTRIBUTING.md +28 -11
  6. package/CONTRIBUTING.zh-CN.md +23 -11
  7. package/README.md +127 -27
  8. package/README.zh-CN.md +104 -30
  9. package/Resources/zh-Hans.lproj/Localizable.strings +573 -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} +89 -31
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +18 -4
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +90 -21
  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/App/CCPetsAppDelegate+Settings.m +269 -0
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +13 -7
  19. package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +71 -47
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +16 -2
  22. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +110 -12
  23. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  24. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  25. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  26. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  27. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  37. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  39. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  43. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  44. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  45. package/Sources/CCPets/Pet/CCPetsImageLoader.h +5 -0
  46. package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +10 -2
  47. package/Sources/CCPets/Pet/CCPetsPetSize.h +10 -0
  48. package/Sources/CCPets/Pet/CCPetsPetSize.m +21 -0
  49. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  50. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  51. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +18 -2
  52. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +53 -22
  53. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +42 -2
  54. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  55. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  56. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  57. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  58. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  59. package/Sources/CCPets/Pet/PetView.m +635 -0
  60. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  61. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  62. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  63. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  64. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  65. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  67. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  68. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  69. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  70. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  71. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  72. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  73. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  74. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  75. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  76. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  77. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  78. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  79. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  80. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  81. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  82. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  83. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  84. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  85. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  86. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  87. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  88. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  89. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  90. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  91. package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +3 -0
  92. package/Sources/CCPets/UI/MenuPetSizeView.h +5 -0
  93. package/Sources/CCPets/UI/MenuPetSizeView.m +73 -0
  94. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  95. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  96. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  97. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  98. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  99. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  100. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  101. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  102. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  103. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  104. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  105. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  106. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  107. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  108. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  109. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  110. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  111. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  112. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  113. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  114. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  115. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  116. package/THIRD_PARTY_NOTICES.md +1 -1
  117. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  118. package/bin/cc-pets +8 -6
  119. package/bin/claude-with-pet +10 -2
  120. package/bin/codex-with-pet +13 -5
  121. package/package.json +1 -1
  122. package/scripts/build.sh +7 -3
  123. package/scripts/i18n.zsh +9 -52
  124. package/scripts/install-app.sh +4 -0
  125. package/scripts/install-shell-integration.sh +17 -10
  126. package/scripts/uninstall-shell-integration.sh +6 -1
  127. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +0 -226
  128. package/Sources/CCPets/CCPetsEvents.h +0 -10
  129. package/Sources/CCPets/CCPetsImageLoader.h +0 -4
  130. package/Sources/CCPets/CCPetsUsage.h +0 -36
  131. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  132. package/Sources/CCPets/PetView.m +0 -1806
  133. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  134. package/scripts/bridge/cli.mjs +0 -237
  135. package/scripts/bridge/core.mjs +0 -228
  136. package/scripts/bridge/hook.mjs +0 -150
  137. package/scripts/bridge/install.mjs +0 -311
  138. package/scripts/bridge/mcp-server.mjs +0 -308
  139. package/scripts/bridge/options.mjs +0 -87
  140. package/scripts/bridge/process.mjs +0 -151
  141. package/scripts/bridge/reservations.mjs +0 -248
  142. package/scripts/bridge/store.mjs +0 -433
  143. package/scripts/bridge/watch.mjs +0 -69
  144. package/scripts/check-l10n.mjs +0 -168
  145. package/scripts/configure-updater.mjs +0 -43
  146. package/scripts/detect-cli.mjs +0 -68
  147. package/scripts/doctor.mjs +0 -470
  148. package/scripts/i18n.mjs +0 -122
  149. package/scripts/install-claude-hooks.mjs +0 -253
  150. package/scripts/install-codex-hooks.mjs +0 -78
  151. package/scripts/integration-markers.mjs +0 -51
  152. package/scripts/locales/zh-Hans.json +0 -366
  153. package/scripts/pet-store.mjs +0 -415
  154. package/scripts/uninstall-integrations.mjs +0 -205
  155. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  156. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  157. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  159. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  161. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  162. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  163. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  164. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  165. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  166. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  167. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  168. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  169. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  170. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  171. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  172. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  173. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,779 @@
1
+ #import "CCPetsL10n.h"
2
+ #import "CCPetsBridgeStore.h"
3
+ #import "CCPetsBridge.h"
4
+ #import "CCPetsCLISupport.h"
5
+ #import "CCPetsJSON.h"
6
+ #import <CommonCrypto/CommonDigest.h>
7
+ #import <sys/sysctl.h>
8
+ #import <sys/stat.h>
9
+ #import <fcntl.h>
10
+ #import <signal.h>
11
+ #import <unistd.h>
12
+ #import <errno.h>
13
+
14
+ #define LF(localized, values) CCPetsInterpolate(localized, values)
15
+
16
+ const NSUInteger CCBridgeMessageBodyLimit = 16 * 1024;
17
+ const long long CCBridgeMessageTTL = 24LL * 60 * 60 * 1000;
18
+ // 同一对会话 10 分钟内来回超过这个数,基本可以断定是两个 Agent 在互相自动回复。
19
+ static const long long PairLimitWindow = 10LL * 60 * 1000;
20
+ const NSUInteger CCBridgePairLimitCount = 20;
21
+ static const NSUInteger SenderLimitCount = 40;
22
+ // 没有 pid 的会话记录退回到活动窗口判断在线,与桌宠"没有 pid 文件就看最近事件"的思路一致。
23
+ static const long long StaleWithoutPid = 6LL * 60 * 60 * 1000;
24
+
25
+ static long long NumberValue(id value) {
26
+ return [value isKindOfClass:NSNumber.class] ? [value longLongValue] : 0;
27
+ }
28
+
29
+ static NSString *StringValue(id value) {
30
+ return [value isKindOfClass:NSString.class] ? value : nil;
31
+ }
32
+
33
+ static NSString *RandomHex(NSUInteger bytes) {
34
+ uint8_t buffer[16];
35
+ bytes = MIN(bytes, sizeof buffer);
36
+ arc4random_buf(buffer, bytes);
37
+ NSMutableString *hex = [NSMutableString string];
38
+ for (NSUInteger index = 0; index < bytes; index++) [hex appendFormat:@"%02x", buffer[index]];
39
+ return hex;
40
+ }
41
+
42
+ NSString *CCBridgeSHA1Hex(NSString *text) {
43
+ NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
44
+ unsigned char digest[CC_SHA1_DIGEST_LENGTH];
45
+ #pragma clang diagnostic push
46
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
47
+ CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
48
+ #pragma clang diagnostic pop
49
+ NSMutableString *hex = [NSMutableString string];
50
+ for (int index = 0; index < CC_SHA1_DIGEST_LENGTH; index++) [hex appendFormat:@"%02x", digest[index]];
51
+ return hex;
52
+ }
53
+
54
+ #pragma mark - 开关与选项
55
+
56
+ static NSString *EnabledFlagPath(void) {
57
+ return [CCBridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-enabled"];
58
+ }
59
+
60
+ static void EnsureHomeDirectory(void) {
61
+ [NSFileManager.defaultManager createDirectoryAtPath:CCBridgeHomeDirectory() withIntermediateDirectories:YES
62
+ attributes:@{NSFilePosixPermissions: @0700} error:nil];
63
+ }
64
+
65
+ BOOL CCBridgeMigrateLegacyFlag(void) {
66
+ NSString *legacy = [CCBridgeHomeDirectory() stringByAppendingPathComponent:@"bus-enabled"];
67
+ if (![NSFileManager.defaultManager fileExistsAtPath:legacy]) return NO;
68
+ if ([NSFileManager.defaultManager fileExistsAtPath:EnabledFlagPath()]) {
69
+ unlink(legacy.fileSystemRepresentation);
70
+ } else {
71
+ rename(legacy.fileSystemRepresentation, EnabledFlagPath().fileSystemRepresentation);
72
+ }
73
+ return YES;
74
+ }
75
+
76
+ void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options) {
77
+ if (!enabled) {
78
+ unlink(EnabledFlagPath().fileSystemRepresentation);
79
+ return;
80
+ }
81
+ EnsureHomeDirectory();
82
+ NSDictionary *normalized = CCBridgeNormalizeOptions(options);
83
+ CCPetsJSONObject *document = [CCPetsJSONObject new];
84
+ for (NSString *key in @[@"codexApprove", @"claudeAllow", @"wake", @"editGuard"]) document[key] = normalized[key];
85
+ NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
86
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
87
+ document[@"enabledAt"] = [formatter stringFromDate:NSDate.date];
88
+ CCPetsWriteFileAtomically(EnabledFlagPath(), [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, NULL);
89
+ }
90
+
91
+ void CCBridgeWriteCLILocator(void) {
92
+ EnsureHomeDirectory();
93
+ CCPetsJSONObject *document = [CCPetsJSONObject new];
94
+ document[@"schemaVersion"] = @2;
95
+ document[@"binary"] = CCPetsExecutablePath();
96
+ document[@"path"] = CCPetsEnvironmentValue(@"PATH") ?: @"";
97
+ CCPetsWriteFileAtomically([CCBridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-cli.json"],
98
+ [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, NULL);
99
+ }
100
+
101
+ static NSArray<NSString *> *AllTools(void) {
102
+ NSMutableArray<NSString *> *tools = [NSMutableArray array];
103
+ for (NSString *group in CCBridgeToolGroupNames()) [tools addObjectsFromArray:CCBridgeToolGroup(group)];
104
+ return tools;
105
+ }
106
+
107
+ NSArray<NSString *> *CCBridgeParseToolList(NSString *text, NSString *flag, NSString **error) {
108
+ NSMutableOrderedSet<NSString *> *tools = [NSMutableOrderedSet orderedSet];
109
+ NSMutableArray<NSString *> *unknown = [NSMutableArray array];
110
+ NSArray<NSString *> *all = AllTools();
111
+ for (NSString *raw in [text ?: @"" componentsSeparatedByString:@","]) {
112
+ NSString *item = [raw stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
113
+ if (item.length == 0) continue;
114
+ if ([CCBridgeToolGroupNames() containsObject:item]) [tools addObjectsFromArray:CCBridgeToolGroup(item)];
115
+ else if ([all containsObject:item]) [tools addObject:item];
116
+ else [unknown addObject:item];
117
+ }
118
+ if (unknown.count > 0) {
119
+ if (error) {
120
+ *error = LF(L(@"{flag} only accepts groups {TOOL_GROUPS} or tools {ALL_TOOLS}, got: {unknown}"), (@{
121
+ @"flag": flag, @"TOOL_GROUPS": [CCBridgeToolGroupNames() componentsJoinedByString:@", "],
122
+ @"ALL_TOOLS": [all componentsJoinedByString:@", "], @"unknown": [unknown componentsJoinedByString:@", "]}));
123
+ }
124
+ return nil;
125
+ }
126
+ NSMutableArray<NSString *> *ordered = [NSMutableArray array];
127
+ for (NSString *tool in all) {
128
+ if ([tools containsObject:tool]) [ordered addObject:tool];
129
+ }
130
+ return ordered;
131
+ }
132
+
133
+ NSNumber *CCBridgeParseSwitch(NSString *text, NSString *flag, NSString **error) {
134
+ NSString *value = [text ?: @"" stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].lowercaseString;
135
+ if ([@[@"on", @"true", @"1", @"yes"] containsObject:value]) return @YES;
136
+ if ([@[@"off", @"false", @"0", @"no"] containsObject:value]) return @NO;
137
+ if (error) *error = LF(L(@"{flag} only accepts on / off, got: {text}"), (@{@"flag": flag, @"text": text ?: @""}));
138
+ return nil;
139
+ }
140
+
141
+ NSDictionary *CCBridgeMergeOptionFlags(NSDictionary *base, NSDictionary<NSString *, NSString *> *flags, NSString **error) {
142
+ NSMutableDictionary *next = [CCBridgeNormalizeOptions(base) mutableCopy];
143
+ if (flags[@"approve"]) {
144
+ NSArray *tools = CCBridgeParseToolList(flags[@"approve"], @"--approve", error);
145
+ if (!tools) return nil;
146
+ next[@"codexApprove"] = tools;
147
+ next[@"claudeAllow"] = tools;
148
+ }
149
+ if (flags[@"codexApprove"]) {
150
+ NSArray *tools = CCBridgeParseToolList(flags[@"codexApprove"], @"--codex-approve", error);
151
+ if (!tools) return nil;
152
+ next[@"codexApprove"] = tools;
153
+ }
154
+ if (flags[@"claudeAllow"]) {
155
+ NSArray *tools = CCBridgeParseToolList(flags[@"claudeAllow"], @"--claude-allow", error);
156
+ if (!tools) return nil;
157
+ next[@"claudeAllow"] = tools;
158
+ }
159
+ if (flags[@"wake"]) {
160
+ NSNumber *value = CCBridgeParseSwitch(flags[@"wake"], @"--wake", error);
161
+ if (!value) return nil;
162
+ next[@"wake"] = value;
163
+ }
164
+ if (flags[@"editGuard"]) {
165
+ NSNumber *value = CCBridgeParseSwitch(flags[@"editGuard"], @"--edit-guard", error);
166
+ if (!value) return nil;
167
+ next[@"editGuard"] = value;
168
+ }
169
+ return next;
170
+ }
171
+
172
+ NSArray<NSString *> *CCBridgeDescribeOptions(NSDictionary *options) {
173
+ NSArray *codex = options[@"codexApprove"];
174
+ NSArray *claude = options[@"claudeAllow"];
175
+ return @[
176
+ LF(L(@"Codex auto-approve: {codexApprove}"), (@{@"codexApprove": codex.count > 0 ? [codex componentsJoinedByString:@", "] : L(@"none")})),
177
+ LF(L(@"Claude allow without asking: {claudeAllow}"), (@{@"claudeAllow": claude.count > 0 ? [claude componentsJoinedByString:@", "] : L(@"none")})),
178
+ LF(L(@"Wake idle sessions: {wake}"), (@{@"wake": [options[@"wake"] boolValue] ? L(@"on") : L(@"off")})),
179
+ LF(L(@"Pause edits on reserved files: {editGuard}"), (@{@"editGuard": [options[@"editGuard"] boolValue] ? L(@"on") : L(@"off")}))
180
+ ];
181
+ }
182
+
183
+ #pragma mark - 目录与文件
184
+
185
+ // 目录一律 0700:信箱里是消息正文,同机其他用户不能读,也不能往里塞"任务"。
186
+ // 已存在的目录也要校正权限并确认归属,防止有人提前在共享 /tmp 里抢建同名目录。
187
+ static NSString *EnsureDirectory(NSString *directory) {
188
+ [NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES
189
+ attributes:@{NSFilePosixPermissions: @0700} error:nil];
190
+ struct stat info;
191
+ if (lstat(directory.fileSystemRepresentation, &info) != 0 || !S_ISDIR(info.st_mode)) {
192
+ [NSException raise:@"CCBridgeDirectory"
193
+ format:@"%@", LF(L(@"{directory} isn't a regular directory"), @{@"directory": directory})];
194
+ }
195
+ if (info.st_uid != getuid()) {
196
+ [NSException raise:@"CCBridgeDirectory"
197
+ format:@"%@", LF(L(@"{directory} isn't owned by the current user"), @{@"directory": directory})];
198
+ }
199
+ if ((info.st_mode & 077) != 0) chmod(directory.fileSystemRepresentation, 0700);
200
+ return directory;
201
+ }
202
+
203
+ NSString *CCBridgeSubdirectory(NSArray<NSString *> *parts) {
204
+ NSString *root = EnsureDirectory(CCBridgeStateDirectory());
205
+ if (parts.count == 0) return root;
206
+ return EnsureDirectory([root stringByAppendingPathComponent:[NSString pathWithComponents:parts]]);
207
+ }
208
+
209
+ NSString *CCBridgeSafeSessionId(id value) {
210
+ NSString *text = StringValue(value);
211
+ if (text.length == 0 || text.length > 128) return nil;
212
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
213
+ @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"];
214
+ if ([text rangeOfCharacterFromSet:allowed.invertedSet].location != NSNotFound) return nil;
215
+ if ([text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]].length == 0) return nil;
216
+ return text;
217
+ }
218
+
219
+ // 先写同目录临时文件再 rename:读取端永远看不到写了一半的 JSON。
220
+ void CCBridgeWriteJSON(NSString *file, id value) {
221
+ NSString *temporary = [NSString stringWithFormat:@"%@.%d.%@.tmp", file, getpid(), RandomHex(4)];
222
+ NSData *data = [[CCPetsJSONStringify(value) stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
223
+ int descriptor = open(temporary.fileSystemRepresentation, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
224
+ if (descriptor < 0) {
225
+ [NSException raise:@"CCBridgeWrite" format:@"%@: %s", file, strerror(errno)];
226
+ }
227
+ BOOL written = write(descriptor, data.bytes, data.length) == (ssize_t)data.length;
228
+ close(descriptor);
229
+ if (!written || rename(temporary.fileSystemRepresentation, file.fileSystemRepresentation) != 0) {
230
+ unlink(temporary.fileSystemRepresentation);
231
+ [NSException raise:@"CCBridgeWrite" format:@"%@: %s", file, strerror(errno)];
232
+ }
233
+ }
234
+
235
+ id CCBridgeReadJSON(NSString *file) {
236
+ NSData *data = [NSData dataWithContentsOfFile:file];
237
+ if (data.length == 0) return nil;
238
+ return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
239
+ }
240
+
241
+ static NSArray<NSString *> *ListJSON(NSString *directory) {
242
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil];
243
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
244
+ for (NSString *name in entries) {
245
+ if ([name hasSuffix:@".json"]) [names addObject:name];
246
+ }
247
+ return [names sortedArrayUsingSelector:@selector(compare:)];
248
+ }
249
+
250
+ #pragma mark - 会话注册表
251
+
252
+ NSString *CCBridgeSessionRef(NSString *sessionId) {
253
+ return [CCBridgeSHA1Hex(sessionId) substringToIndex:6];
254
+ }
255
+
256
+ static NSString *SessionFile(NSString *sessionId) {
257
+ return [CCBridgeSubdirectory(@[@"sessions"]) stringByAppendingPathComponent:[sessionId stringByAppendingString:@".json"]];
258
+ }
259
+
260
+ NSDictionary *CCBridgeReadSession(id sessionId) {
261
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
262
+ if (!safe) return nil;
263
+ id record = CCBridgeReadJSON(SessionFile(safe));
264
+ return [record isKindOfClass:NSDictionary.class] ? record : nil;
265
+ }
266
+
267
+ NSArray<NSDictionary *> *CCBridgeListSessions(void) {
268
+ NSString *directory = CCBridgeSubdirectory(@[@"sessions"]);
269
+ NSMutableArray<NSDictionary *> *sessions = [NSMutableArray array];
270
+ for (NSString *name in ListJSON(directory)) {
271
+ id record = CCBridgeReadJSON([directory stringByAppendingPathComponent:name]);
272
+ if ([record isKindOfClass:NSDictionary.class]) [sessions addObject:record];
273
+ }
274
+ return sessions;
275
+ }
276
+
277
+ void CCBridgeRemoveSession(id sessionId) {
278
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
279
+ if (safe) unlink(SessionFile(safe).fileSystemRepresentation);
280
+ }
281
+
282
+ // 小写,连续的非 [a-z0-9] 合并成 -,截到 limit 后去掉首尾的 -;结果可能为空。
283
+ static NSString *NameSlug(NSString *text, NSUInteger limit) {
284
+ NSString *base = text.lowercaseString ?: @"";
285
+ NSRegularExpression *separators = [NSRegularExpression regularExpressionWithPattern:@"[^a-z0-9]+" options:0 error:nil];
286
+ NSString *slug = [separators stringByReplacingMatchesInString:base options:0 range:NSMakeRange(0, base.length) withTemplate:@"-"];
287
+ NSCharacterSet *dash = [NSCharacterSet characterSetWithCharactersInString:@"-"];
288
+ slug = [slug stringByTrimmingCharactersInSet:dash];
289
+ if (slug.length > limit) slug = [[slug substringToIndex:limit] stringByTrimmingCharactersInSet:dash];
290
+ return slug;
291
+ }
292
+
293
+ // 默认名字末尾的动物词:都是 7 个字母以内、好认好打的萌系动物,避开贬义词和编程语言 / 工具名。
294
+ static NSArray<NSString *> *NameAnimals(void) {
295
+ static NSArray<NSString *> *animals;
296
+ static dispatch_once_t once;
297
+ dispatch_once(&once, ^{
298
+ animals = @[
299
+ @"otter", @"panda", @"quokka", @"corgi", @"koala", @"capy", @"puffin", @"lemur", @"alpaca", @"wombat",
300
+ @"bunny", @"kitten", @"puppy", @"hamster", @"fox", @"owl", @"seal", @"penguin", @"duck", @"llama",
301
+ @"sloth", @"fennec", @"bear", @"cub", @"lamb", @"fawn", @"deer", @"dolphin", @"beluga", @"orca",
302
+ @"narwhal", @"walrus", @"manatee", @"turtle", @"frog", @"gecko", @"chick", @"robin", @"finch", @"wren",
303
+ @"sparrow", @"toucan", @"parrot", @"macaw", @"dove", @"swan", @"owlet", @"goose", @"koi", @"bee",
304
+ @"ladybug", @"raccoon", @"ferret", @"badger", @"beaver", @"marmot", @"meerkat", @"mouse", @"gerbil", @"pony",
305
+ @"foal", @"piglet", @"calf", @"giraffe", @"zebra", @"hippo", @"rhino", @"tapir", @"okapi", @"lynx",
306
+ @"tiger", @"cheetah", @"lion", @"husky", @"shiba", @"beagle", @"pug", @"poodle", @"collie", @"dingo",
307
+ @"newt", @"tadpole", @"octopus", @"squid", @"crab", @"snail", @"peacock", @"emu", @"quail", @"magpie",
308
+ @"kea", @"heron", @"stork", @"ibis", @"numbat", @"bilby", @"possum", @"dugong", @"yak", @"bison",
309
+ ];
310
+ });
311
+ return animals;
312
+ }
313
+
314
+ static NSDictionary *NameTakenBy(NSString *name, NSString *sessionId, NSArray<NSDictionary *> *liveSessions) {
315
+ for (NSDictionary *entry in liveSessions) {
316
+ if (![entry[@"session"] isEqual:sessionId] && [entry[@"name"] isEqual:name]) return entry;
317
+ }
318
+ return nil;
319
+ }
320
+
321
+ // 名字是给 Agent 和人看的地址:<账号名>.<项目目录名>.<动物>,例如 claude-x.my-app.otter。段内用 -,段间用 .,
322
+ // 账号名和项目名本身带 - 时也分得清边界。
323
+ // 账号名取多账号里的显示名(默认账号就是 claude / codex),取不到时退回 provider,这样多个账号开在同一项目里
324
+ // 也一眼能分清。动物从 session id 的哈希位置开始找同前缀下第一个没被在线会话占用的,同一会话结果稳定;
325
+ // 词库全被占用才追加序号。总长度控制在 40 以内:账号名最多 12 个字符,项目名用剩下的。
326
+ // ref 由 session id 派生,永不变化,用于重名时消歧。
327
+ static NSString *AllocateName(NSString *provider, NSString *profileName, NSString *cwd, NSString *sessionId,
328
+ NSArray<NSDictionary *> *liveSessions) {
329
+ NSString *account = NameSlug(profileName, 12);
330
+ if (account.length == 0) account = NameSlug(provider, 12);
331
+ if (account.length == 0) account = @"agent";
332
+ NSArray<NSString *> *animals = NameAnimals();
333
+ // 动物词最多 7 个字母,再给兜底序号留 2 位。
334
+ NSString *project = NameSlug(cwd.lastPathComponent, 40 - account.length - 9 - 2);
335
+ if (project.length == 0) project = @"session";
336
+ NSString *prefix = [NSString stringWithFormat:@"%@.%@", account, project];
337
+ unsigned long long hash = strtoull([CCBridgeSHA1Hex(sessionId) substringToIndex:8].UTF8String, NULL, 16);
338
+ for (NSUInteger offset = 0; offset < animals.count; offset++) {
339
+ NSString *candidate = [NSString stringWithFormat:@"%@.%@", prefix, animals[(hash + offset) % animals.count]];
340
+ if (!NameTakenBy(candidate, sessionId, liveSessions)) return candidate;
341
+ }
342
+ NSString *animal = animals[hash % animals.count];
343
+ for (NSUInteger index = 2; ; index++) {
344
+ NSString *candidate = [NSString stringWithFormat:@"%@.%@%lu", prefix, animal, (unsigned long)index];
345
+ if (!NameTakenBy(candidate, sessionId, liveSessions)) return candidate;
346
+ }
347
+ }
348
+
349
+ // 启动时指定的名字被占用就追加序号(frontend → frontend-2),不让会话因此注册失败。
350
+ static NSString *AllocateCustomName(NSString *name, NSString *sessionId, NSArray<NSDictionary *> *liveSessions) {
351
+ if (!NameTakenBy(name, sessionId, liveSessions)) return name;
352
+ for (NSUInteger index = 2; ; index++) {
353
+ NSString *candidate = [NSString stringWithFormat:@"%@-%lu", name, (unsigned long)index];
354
+ if (candidate.length > 40) candidate = [candidate substringToIndex:40];
355
+ if (!NameTakenBy(candidate, sessionId, liveSessions)) return candidate;
356
+ }
357
+ }
358
+
359
+ // 自定义名字只允许小写字母、数字和 . _ -,首字符必须是字母或数字,最长 40 个字符——名字会出现在
360
+ // 消息头和 Agent 的工具参数里,不能带空格、方括号(与 "名字 [ref]" 语法冲突)或控制字符。
361
+ NSString *CCBridgeNormalizeSessionName(id value) {
362
+ NSString *text = [value isKindOfClass:NSString.class] ? value : ([value isKindOfClass:NSNumber.class] ? [value stringValue] : @"");
363
+ NSString *name = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].lowercaseString;
364
+ NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"\\A[a-z0-9][a-z0-9._-]{0,39}\\z" options:0 error:nil];
365
+ return [pattern firstMatchInString:name options:0 range:NSMakeRange(0, name.length)] ? name : nil;
366
+ }
367
+
368
+ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
369
+ NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
370
+ NSString *profileName, NSArray<NSDictionary *> *liveSessions) {
371
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
372
+ if (!safe) return nil;
373
+ long long now = CCPetsMilliseconds();
374
+ NSMutableDictionary *record = [CCBridgeReadSession(safe) mutableCopy];
375
+ if (!record) {
376
+ record = [@{@"session": safe, @"ref": CCBridgeSessionRef(safe), @"startedAt": @(now)} mutableCopy];
377
+ if (provider) record[@"provider"] = provider;
378
+ }
379
+ if (provider) record[@"provider"] = provider;
380
+ if (pid && pid.intValue > 1) record[@"pid"] = pid;
381
+ if (cwd.length > 0) record[@"cwd"] = cwd;
382
+ if (tty.length > 0) record[@"tty"] = tty;
383
+ if (profileID.length > 0) record[@"profileId"] = profileID;
384
+ if (profileName.length > 0) record[@"profileName"] = profileName;
385
+ if (!StringValue(record[@"name"])) {
386
+ NSString *custom = CCBridgeNormalizeSessionName(preferredName);
387
+ record[@"name"] = custom ? AllocateCustomName(custom, safe, liveSessions ?: @[])
388
+ : AllocateName(StringValue(record[@"provider"]) ?: @"", StringValue(record[@"profileName"]),
389
+ StringValue(record[@"cwd"]), safe, liveSessions ?: @[]);
390
+ }
391
+ if (status) record[@"status"] = status;
392
+ record[@"updatedAt"] = @(now);
393
+ CCBridgeWriteJSON(SessionFile(safe), record);
394
+ return record;
395
+ }
396
+
397
+ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
398
+ NSMutableDictionary *record = [CCBridgeReadSession(sessionId) mutableCopy];
399
+ if (!record) return @{@"error": L(@"This session isn't registered yet.")};
400
+ NSString *name = CCBridgeNormalizeSessionName(requestedName);
401
+ if (!name) {
402
+ return @{@"error": L(@"Names may only contain lowercase letters, digits and . _ -, must start with a letter or digit, and be at most 40 characters.")};
403
+ }
404
+ NSDictionary *holder = NameTakenBy(name, record[@"session"], liveSessions);
405
+ if (holder) {
406
+ return @{@"error": LF(L(@"The name {name} is taken by {holder} [{ref}]; pick another."),
407
+ (@{@"name": name, @"holder": holder[@"name"] ?: @"", @"ref": holder[@"ref"] ?: @""}))};
408
+ }
409
+ NSString *previous = StringValue(record[@"name"]) ?: @"";
410
+ record[@"name"] = name;
411
+ record[@"updatedAt"] = @(CCPetsMilliseconds());
412
+ CCBridgeWriteJSON(SessionFile(record[@"session"]), record);
413
+ return @{@"session": record, @"previous": previous};
414
+ }
415
+
416
+ #pragma mark - 消息
417
+
418
+ NSString *CCBridgeNewMessageId(void) {
419
+ unsigned long long now = (unsigned long long)CCPetsMilliseconds();
420
+ static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
421
+ char buffer[32];
422
+ int length = 0;
423
+ do {
424
+ buffer[length++] = digits[now % 36];
425
+ now /= 36;
426
+ } while (now > 0);
427
+ NSMutableString *base36 = [NSMutableString string];
428
+ while (length > 0) [base36 appendFormat:@"%c", buffer[--length]];
429
+ return [NSString stringWithFormat:@"m%@%@", base36, RandomHex(5)];
430
+ }
431
+
432
+ static NSString *ReceiptFile(NSString *messageId) {
433
+ return [CCBridgeSubdirectory(@[@"sent"]) stringByAppendingPathComponent:[messageId stringByAppendingString:@".json"]];
434
+ }
435
+
436
+ static BOOL IsMessageId(id value) {
437
+ NSString *text = StringValue(value);
438
+ if (text.length == 0) return NO;
439
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz0123456789"];
440
+ return [text rangeOfCharacterFromSet:allowed.invertedSet].location == NSNotFound;
441
+ }
442
+
443
+ NSDictionary *CCBridgeReadReceipt(id messageId) {
444
+ if (!IsMessageId(messageId)) return nil;
445
+ id receipt = CCBridgeReadJSON(ReceiptFile(messageId));
446
+ return [receipt isKindOfClass:NSDictionary.class] ? receipt : nil;
447
+ }
448
+
449
+ void CCBridgeWriteReceipt(NSDictionary *message) {
450
+ CCBridgeWriteJSON(ReceiptFile(message[@"id"]), message);
451
+ }
452
+
453
+ NSDictionary *CCBridgeUpdateReceipt(NSString *messageId, NSDictionary *patch) {
454
+ NSMutableDictionary *next = [CCBridgeReadReceipt(messageId) mutableCopy];
455
+ if (!next) return nil;
456
+ [next addEntriesFromDictionary:patch];
457
+ next[@"updatedAt"] = @(CCPetsMilliseconds());
458
+ CCBridgeWriteReceipt(next);
459
+ return next;
460
+ }
461
+
462
+ NSArray<NSDictionary *> *CCBridgeListReceipts(void) {
463
+ NSString *directory = CCBridgeSubdirectory(@[@"sent"]);
464
+ NSMutableArray<NSDictionary *> *receipts = [NSMutableArray array];
465
+ for (NSString *name in ListJSON(directory)) {
466
+ id receipt = CCBridgeReadJSON([directory stringByAppendingPathComponent:name]);
467
+ if ([receipt isKindOfClass:NSDictionary.class]) [receipts addObject:receipt];
468
+ }
469
+ return receipts;
470
+ }
471
+
472
+ static NSString *PartySession(NSDictionary *receipt, NSString *key) {
473
+ NSDictionary *party = [receipt[key] isKindOfClass:NSDictionary.class] ? receipt[key] : nil;
474
+ return StringValue(party[@"session"]);
475
+ }
476
+
477
+ NSString *CCBridgeCheckSendLimits(NSString *fromSession, NSString *toSession) {
478
+ long long now = CCPetsMilliseconds();
479
+ NSUInteger pair = 0, sent = 0;
480
+ for (NSDictionary *entry in CCBridgeListReceipts()) {
481
+ if (now - NumberValue(entry[@"createdAt"]) >= PairLimitWindow) continue;
482
+ NSString *from = PartySession(entry, @"from");
483
+ NSString *to = PartySession(entry, @"to");
484
+ if (([from isEqual:fromSession] && [to isEqual:toSession]) || ([from isEqual:toSession] && [to isEqual:fromSession])) pair++;
485
+ if ([from isEqual:fromSession]) sent++;
486
+ }
487
+ if (pair >= CCBridgePairLimitCount) {
488
+ return LF(L(@"These two sessions exchanged {length} messages in 10 minutes, which looks like an auto-reply loop, so sending is paused. Ask the user before continuing."),
489
+ @{@"length": @(pair)});
490
+ }
491
+ if (sent >= SenderLimitCount) {
492
+ return LF(L(@"This session sent {length} messages in 10 minutes, over the limit, so sending is paused."), @{@"length": @(sent)});
493
+ }
494
+ return nil;
495
+ }
496
+
497
+ void CCBridgeEnqueueInbox(NSDictionary *message) {
498
+ NSString *target = CCBridgeSafeSessionId(PartySession(message, @"to"));
499
+ if (!target) [NSException raise:@"CCBridgeInbox" format:@"%@", L(@"invalid target session id")];
500
+ CCBridgeWriteJSON([CCBridgeSubdirectory(@[@"inbox", target]) stringByAppendingPathComponent:
501
+ [message[@"id"] stringByAppendingString:@".json"]], message);
502
+ }
503
+
504
+ NSArray<NSDictionary *> *CCBridgeClaimInbox(id sessionId) {
505
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
506
+ if (!safe) return @[];
507
+ NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
508
+ NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
509
+ long long now = CCPetsMilliseconds();
510
+ NSMutableArray<NSDictionary *> *messages = [NSMutableArray array];
511
+ for (NSString *name in ListJSON(inbox)) {
512
+ NSString *source = [inbox stringByAppendingPathComponent:name];
513
+ NSString *destination = [claimed stringByAppendingPathComponent:name];
514
+ if (rename(source.fileSystemRepresentation, destination.fileSystemRepresentation) != 0) continue;
515
+ id message = CCBridgeReadJSON(destination);
516
+ unlink(destination.fileSystemRepresentation);
517
+ if (![message isKindOfClass:NSDictionary.class]) continue;
518
+ if (now - NumberValue(message[@"createdAt"]) > CCBridgeMessageTTL) {
519
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"expired"});
520
+ continue;
521
+ }
522
+ [messages addObject:message];
523
+ }
524
+ return messages;
525
+ }
526
+
527
+ NSUInteger CCBridgePendingCount(id sessionId) {
528
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
529
+ return safe ? ListJSON(CCBridgeSubdirectory(@[@"inbox", safe])).count : 0;
530
+ }
531
+
532
+ void CCBridgeAbandonInbox(id sessionId) {
533
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
534
+ if (!safe) return;
535
+ NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
536
+ for (NSString *name in ListJSON(inbox)) {
537
+ NSString *file = [inbox stringByAppendingPathComponent:name];
538
+ id message = CCBridgeReadJSON(file);
539
+ unlink(file.fileSystemRepresentation);
540
+ if ([message isKindOfClass:NSDictionary.class]) {
541
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"undeliverable", @"reason": L(@"the target session has ended")});
542
+ }
543
+ }
544
+ }
545
+
546
+ // 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。
547
+ void CCBridgePruneReceipts(void) {
548
+ NSString *directory = CCBridgeSubdirectory(@[@"sent"]);
549
+ long long now = CCPetsMilliseconds();
550
+ for (NSString *name in ListJSON(directory)) {
551
+ NSString *file = [directory stringByAppendingPathComponent:name];
552
+ id receipt = CCBridgeReadJSON(file);
553
+ if (![receipt isKindOfClass:NSDictionary.class] || now - NumberValue(receipt[@"createdAt"]) > CCBridgeMessageTTL * 2) {
554
+ unlink(file.fileSystemRepresentation);
555
+ }
556
+ }
557
+ }
558
+
559
+ #pragma mark - 空闲订阅
560
+
561
+ void CCBridgeAddIdleSubscription(NSString *targetSession, NSString *subscriberSession) {
562
+ NSString *target = CCBridgeSafeSessionId(targetSession);
563
+ NSString *subscriber = CCBridgeSafeSessionId(subscriberSession);
564
+ if (!target || !subscriber) return;
565
+ CCBridgeWriteJSON([CCBridgeSubdirectory(@[@"subscriptions", target]) stringByAppendingPathComponent:
566
+ [subscriber stringByAppendingString:@".json"]], @{@"subscriber": subscriber, @"createdAt": @(CCPetsMilliseconds())});
567
+ }
568
+
569
+ BOOL CCBridgeHasIdleSubscriptions(NSString *targetSession) {
570
+ NSString *target = CCBridgeSafeSessionId(targetSession);
571
+ if (!target) return NO;
572
+ return ListJSON([[CCBridgeStateDirectory() stringByAppendingPathComponent:@"subscriptions"]
573
+ stringByAppendingPathComponent:target]).count > 0;
574
+ }
575
+
576
+ NSArray<NSString *> *CCBridgeTakeIdleSubscriptions(NSString *targetSession) {
577
+ NSString *target = CCBridgeSafeSessionId(targetSession);
578
+ if (!target) return @[];
579
+ NSString *directory = CCBridgeSubdirectory(@[@"subscriptions", target]);
580
+ NSMutableArray<NSString *> *subscribers = [NSMutableArray array];
581
+ for (NSString *name in ListJSON(directory)) {
582
+ NSString *file = [directory stringByAppendingPathComponent:name];
583
+ NSString *claimed = [file stringByAppendingString:@".taken"];
584
+ if (rename(file.fileSystemRepresentation, claimed.fileSystemRepresentation) != 0) continue;
585
+ id entry = CCBridgeReadJSON(claimed);
586
+ unlink(claimed.fileSystemRepresentation);
587
+ NSString *subscriber = [entry isKindOfClass:NSDictionary.class] ? StringValue(entry[@"subscriber"]) : nil;
588
+ if (subscriber) [subscribers addObject:subscriber];
589
+ }
590
+ return subscribers;
591
+ }
592
+
593
+ #pragma mark - 锁
594
+
595
+ static pid_t LockHolder(NSString *file) {
596
+ NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
597
+ return (pid_t)text.intValue;
598
+ }
599
+
600
+ NSString *CCBridgeAcquireLock(NSString *name) {
601
+ NSString *file = [CCBridgeSubdirectory(@[@"locks"]) stringByAppendingPathComponent:[name stringByAppendingString:@".pid"]];
602
+ for (int attempt = 0; attempt < 2; attempt++) {
603
+ int descriptor = open(file.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
604
+ if (descriptor >= 0) {
605
+ NSData *pid = [[NSString stringWithFormat:@"%d", getpid()] dataUsingEncoding:NSUTF8StringEncoding];
606
+ write(descriptor, pid.bytes, pid.length);
607
+ close(descriptor);
608
+ return file;
609
+ }
610
+ if (errno != EEXIST) [NSException raise:@"CCBridgeLock" format:@"%@: %s", file, strerror(errno)];
611
+ pid_t holder = LockHolder(file);
612
+ if (holder > 0 && CCBridgeProcessAlive(holder)) return nil;
613
+ unlink(file.fileSystemRepresentation);
614
+ }
615
+ return nil;
616
+ }
617
+
618
+ void CCBridgeReleaseLock(NSString *lockFile) {
619
+ if (lockFile && LockHolder(lockFile) == getpid()) unlink(lockFile.fileSystemRepresentation);
620
+ }
621
+
622
+ #pragma mark - 进程探测
623
+
624
+ BOOL CCBridgeProcessAlive(pid_t pid) {
625
+ if (pid <= 1) return NO;
626
+ return kill(pid, 0) == 0 || errno == EPERM;
627
+ }
628
+
629
+ static BOOL ProcessParent(pid_t pid, pid_t *parent, dev_t *tty) {
630
+ struct kinfo_proc info;
631
+ size_t size = sizeof info;
632
+ int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
633
+ if (sysctl(name, 4, &info, &size, NULL, 0) != 0 || size == 0) return NO;
634
+ if (parent) *parent = info.kp_eproc.e_ppid;
635
+ if (tty) *tty = info.kp_eproc.e_tdev;
636
+ return YES;
637
+ }
638
+
639
+ // 与 `ps -o command=` 一致:argv 用空格连起来。读不到参数区(别的用户的进程、僵尸)时退回 ps。
640
+ NSString *CCBridgeProcessCommand(pid_t pid) {
641
+ if (pid <= 0) return nil;
642
+ int argumentMaximum = 0;
643
+ size_t size = sizeof argumentMaximum;
644
+ int maximumName[] = {CTL_KERN, KERN_ARGMAX};
645
+ if (sysctl(maximumName, 2, &argumentMaximum, &size, NULL, 0) == 0 && argumentMaximum > 0) {
646
+ char *buffer = malloc((size_t)argumentMaximum);
647
+ size = (size_t)argumentMaximum;
648
+ int name[] = {CTL_KERN, KERN_PROCARGS2, pid};
649
+ if (buffer && sysctl(name, 3, buffer, &size, NULL, 0) == 0 && size > sizeof(int)) {
650
+ int argc = 0;
651
+ memcpy(&argc, buffer, sizeof argc);
652
+ char *cursor = buffer + sizeof argc;
653
+ char *end = buffer + size;
654
+ while (cursor < end && *cursor) cursor++; // 可执行文件路径
655
+ while (cursor < end && !*cursor) cursor++; // 对齐用的 \0
656
+ NSMutableArray<NSString *> *arguments = [NSMutableArray array];
657
+ for (int index = 0; index < argc && cursor < end; index++) {
658
+ size_t length = strnlen(cursor, (size_t)(end - cursor));
659
+ NSString *argument = [[NSString alloc] initWithBytes:cursor length:length encoding:NSUTF8StringEncoding];
660
+ [arguments addObject:argument ?: @""];
661
+ cursor += length + 1;
662
+ }
663
+ free(buffer);
664
+ if (arguments.count > 0) return [arguments componentsJoinedByString:@" "];
665
+ } else {
666
+ free(buffer);
667
+ }
668
+ }
669
+ NSString *output = nil;
670
+ if (CCPetsRun(@"/bin/ps", @[@"-o", @"command=", @"-p", [NSString stringWithFormat:@"%d", pid]], nil, nil, 10, &output, NULL) != 0) {
671
+ return nil;
672
+ }
673
+ NSString *command = [output stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
674
+ return command.length > 0 ? command : nil;
675
+ }
676
+
677
+ NSString *CCBridgeProcessTty(pid_t pid) {
678
+ dev_t device = NODEV;
679
+ if (pid <= 1 || !ProcessParent(pid, NULL, &device) || device == NODEV) return nil;
680
+ char *name = devname(device, S_IFCHR);
681
+ if (!name || name[0] == '?') return nil;
682
+ NSString *tty = [NSString stringWithUTF8String:name];
683
+ return [tty hasPrefix:@"tty"] ? tty : [@"tty" stringByAppendingString:tty];
684
+ }
685
+
686
+ // 只看可执行文件本身,不看参数:参数里出现 "claude" / "codex" 的进程太多了
687
+ // (比如 tmux new-session "codex …"、编辑器打开的某个路径)。
688
+ static NSArray<NSString *> *CommandTokens(NSString *command) {
689
+ NSMutableArray<NSString *> *tokens = [NSMutableArray array];
690
+ for (NSString *token in [command ?: @"" componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]) {
691
+ if (token.length > 0) [tokens addObject:token];
692
+ }
693
+ return tokens;
694
+ }
695
+
696
+ static BOOL Matches(NSString *pattern, NSString *text) {
697
+ if (text.length == 0) return NO;
698
+ NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
699
+ return [expression firstMatchInString:text options:0 range:NSMakeRange(0, text.length)] != nil;
700
+ }
701
+
702
+ BOOL CCBridgeCommandMatchesProvider(NSString *provider, NSString *command) {
703
+ NSArray<NSString *> *tokens = CommandTokens(command);
704
+ NSString *executable = tokens.firstObject ?: @"";
705
+ NSString *second = tokens.count > 1 ? tokens[1] : @"";
706
+ // Codex 的 npm 包是 node 包装器 + 原生二进制;hook 和 MCP 进程的直接祖先都是原生二进制,
707
+ // 取离自己最近的那个,两边才能落到同一个 pid。
708
+ if ([provider isEqualToString:@"Codex"]) {
709
+ return [executable.lastPathComponent isEqualToString:@"codex"] || Matches(@"/codex-[a-z0-9-]+/vendor/", executable);
710
+ }
711
+ if ([provider isEqualToString:@"Claude"]) {
712
+ return [executable.lastPathComponent isEqualToString:@"claude"] ||
713
+ Matches(@"@anthropic-ai/claude-code/", executable) || Matches(@"@anthropic-ai/claude-code/", second);
714
+ }
715
+ return NO;
716
+ }
717
+
718
+ // 取"最近"而不是"某一种":在 Claude 的 Bash 里再起一个 codex,里面的 MCP 进程属于那个 codex。
719
+ NSDictionary *CCBridgeFindAgentAncestor(pid_t startPid) {
720
+ // 测试 / 诊断覆盖:"Codex:1234"。测试本身常跑在某个 Claude 会话的 Bash 里,
721
+ // 不覆盖的话会沿进程树认到那个真实会话头上。
722
+ NSString *forced = CCPetsEnvironmentValue(@"CC_BRIDGE_AGENT");
723
+ if (forced) {
724
+ NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"\\A(Claude|Codex):(\\d+)\\z" options:0 error:nil];
725
+ NSTextCheckingResult *match = [pattern firstMatchInString:forced options:0 range:NSMakeRange(0, forced.length)];
726
+ if (match) {
727
+ return @{@"provider": [forced substringWithRange:[match rangeAtIndex:1]],
728
+ @"pid": @([[forced substringWithRange:[match rangeAtIndex:2]] intValue])};
729
+ }
730
+ }
731
+ pid_t pid = startPid;
732
+ for (int depth = 0; depth < 12 && pid > 1; depth++) {
733
+ pid_t parent = 0;
734
+ if (!ProcessParent(pid, &parent, NULL)) return nil;
735
+ NSString *command = CCBridgeProcessCommand(pid);
736
+ for (NSString *provider in @[@"Claude", @"Codex"]) {
737
+ if (CCBridgeCommandMatchesProvider(provider, command)) return @{@"provider": provider, @"pid": @(pid)};
738
+ }
739
+ pid = parent;
740
+ }
741
+ return nil;
742
+ }
743
+
744
+ BOOL CCBridgeSessionLive(NSDictionary *session) {
745
+ if (![session isKindOfClass:NSDictionary.class] || [session[@"status"] isEqual:@"gone"]) return NO;
746
+ id pid = session[@"pid"];
747
+ if ([pid isKindOfClass:NSNumber.class]) {
748
+ if (!CCBridgeProcessAlive([pid intValue])) return NO;
749
+ NSString *command = CCBridgeProcessCommand([pid intValue]);
750
+ return command == nil || CCBridgeCommandMatchesProvider(session[@"provider"], command);
751
+ }
752
+ return CCPetsMilliseconds() - NumberValue(session[@"updatedAt"]) < StaleWithoutPid;
753
+ }
754
+
755
+ // `codex queue` 是较新的 Codex 才有的子命令。旧版本把不认识的子命令当成交互式启动参数,
756
+ // `--help` 打出的是总帮助而不是报错,所以按帮助里有没有 --thread / --message 判断。
757
+ // 结果只用于提前提示:投递时 queue 失败本来就会退回信箱,探测失败一律算 unknown。
758
+ NSDictionary *CCBridgeProbeCodexQueue(NSString *executable) {
759
+ return CCBridgeProbeCodexQueueWithEnvironment(executable, nil);
760
+ }
761
+
762
+ NSDictionary *CCBridgeProbeCodexQueueWithEnvironment(NSString *executable, NSDictionary<NSString *, NSString *> *environment) {
763
+ if (executable.length == 0 || ![NSFileManager.defaultManager fileExistsAtPath:executable]) {
764
+ return @{@"status": @"missing", @"executable": executable ?: NSNull.null, @"version": NSNull.null};
765
+ }
766
+ NSString *(^run)(NSArray<NSString *> *) = ^NSString *(NSArray<NSString *> *arguments) {
767
+ NSString *output = nil, *errorOutput = nil;
768
+ int status = CCPetsRun(executable, arguments, nil, environment, 10, &output, &errorOutput);
769
+ if (status == CCPetsRunLaunchFailed || status == CCPetsRunTimedOut) return nil;
770
+ return status == 0 ? output : [output stringByAppendingString:errorOutput];
771
+ };
772
+ NSString *versionOutput = [run(@[@"--version"]) ?: @"" stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
773
+ NSString *version = [versionOutput componentsSeparatedByString:@"\n"].firstObject;
774
+ id versionValue = version.length > 0 ? version : NSNull.null;
775
+ NSString *help = run(@[@"queue", @"--help"]);
776
+ if (!help) return @{@"status": @"unknown", @"executable": executable, @"version": versionValue};
777
+ BOOL supported = [help containsString:@"--thread"] && [help containsString:@"--message"];
778
+ return @{@"status": supported ? @"supported" : @"unsupported", @"executable": executable, @"version": versionValue};
779
+ }