cc-pets 2.4.0 → 2.6.0-beta.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 (111) hide show
  1. package/CC_BRIDGE.md +93 -14
  2. package/CC_BRIDGE.zh-CN.md +71 -11
  3. package/CHANGELOG.md +55 -0
  4. package/CHANGELOG.zh-CN.md +56 -1
  5. package/CONTRIBUTING.md +1 -1
  6. package/CONTRIBUTING.zh-CN.md +1 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +116 -34
  10. package/README.zh-CN.md +99 -35
  11. package/Resources/AgentIcons/antigravity.icns +0 -0
  12. package/Resources/zh-Hans.lproj/Localizable.strings +99 -26
  13. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +51 -4
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +120 -17
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +24 -11
  16. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +24 -1
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +21 -11
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +33 -17
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +43 -7
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +7 -4
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +7 -4
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +24 -22
  24. package/Sources/CCPets/App/CCPetsAppDelegate.h +10 -0
  25. package/Sources/CCPets/App/CCPetsAppDelegate.m +18 -8
  26. package/Sources/CCPets/App/CCPetsVersion.h +4 -0
  27. package/Sources/CCPets/App/CCPetsVersion.m +34 -0
  28. package/Sources/CCPets/App/main.m +11 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +41 -17
  30. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.h +4 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.m +119 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +3 -1
  33. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +272 -50
  34. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +12 -3
  35. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +341 -95
  36. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  37. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +227 -95
  38. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +35 -5
  39. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +310 -42
  40. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.h +12 -0
  41. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.m +105 -0
  42. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.h +17 -0
  43. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.m +462 -0
  44. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.h +5 -0
  45. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.m +180 -0
  46. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.h +3 -0
  47. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.m +463 -0
  48. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  49. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  50. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +1 -1
  51. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +38 -8
  52. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +15 -5
  53. package/Sources/CCPets/Integrations/CCPetsProfiles.h +2 -1
  54. package/Sources/CCPets/Integrations/CCPetsProfiles.m +112 -81
  55. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +11 -1
  56. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +217 -45
  57. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  58. package/Sources/CCPets/Pet/CCPetsPreviews.m +16 -8
  59. package/Sources/CCPets/Pet/PetView+Menu.m +64 -5
  60. package/Sources/CCPets/Pet/PetView.h +7 -0
  61. package/Sources/CCPets/Pet/PetView.m +12 -1
  62. package/Sources/CCPets/Support/CCPetsDoctor.m +126 -37
  63. package/Sources/CCPets/Support/CCPetsPaths.h +5 -0
  64. package/Sources/CCPets/Support/CCPetsPaths.m +15 -0
  65. package/Sources/CCPets/Support/CCPetsPreferences.h +14 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.m +36 -0
  67. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  68. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  69. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  70. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +533 -0
  71. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  72. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +98 -0
  73. package/Sources/CCPets/UI/CCPetsSettingsPage.h +7 -1
  74. package/Sources/CCPets/UI/CCPetsSettingsPage.m +205 -8
  75. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  76. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  77. package/Sources/CCPets/UI/CCPetsUIStyle.m +3 -1
  78. package/Sources/CCPets/UI/CCPetsUsagePage.h +4 -3
  79. package/Sources/CCPets/UI/CCPetsUsagePage.m +69 -43
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +11 -1
  81. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +6 -4
  82. package/Sources/CCPets/Usage/CCPetsAntigravityQuota.m +115 -0
  83. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.h +5 -0
  84. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.m +43 -0
  85. package/Sources/CCPets/Usage/CCPetsProviderRegistry+Testing.h +13 -0
  86. package/Sources/CCPets/Usage/CCPetsProviderRegistry.h +25 -0
  87. package/Sources/CCPets/Usage/CCPetsProviderRegistry.m +94 -0
  88. package/Sources/CCPets/Usage/CCPetsQuotaHistory.h +1 -1
  89. package/Sources/CCPets/Usage/CCPetsQuotaHistory.m +11 -8
  90. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +2 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +206 -14
  92. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +4 -4
  93. package/Sources/CCPets/Usage/CCPetsUsage.h +7 -2
  94. package/Sources/CCPets/Usage/CCPetsUsageMode.h +2 -0
  95. package/Sources/CCPets/Usage/CCPetsUsageMode.m +29 -4
  96. package/Sources/CCPets/Usage/CCPetsUsageMonitor.h +4 -4
  97. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +90 -7
  98. package/Sources/CCPets/Usage/QuotaDashboardView+CompactRow.m +81 -0
  99. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +5 -8
  100. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +26 -4
  101. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +99 -99
  102. package/Sources/CCPets/Usage/QuotaDashboardView.h +9 -10
  103. package/Sources/CCPets/Usage/QuotaDashboardView.m +232 -79
  104. package/THIRD_PARTY_NOTICES.md +5 -4
  105. package/THIRD_PARTY_NOTICES.zh-CN.md +6 -5
  106. package/bin/agy-with-pet +82 -0
  107. package/bin/cc-pets +1 -1
  108. package/bin/claude-with-pet +15 -0
  109. package/bin/codex-with-pet +17 -2
  110. package/package.json +5 -3
  111. package/scripts/install-shell-integration.sh +5 -0
@@ -1,11 +1,15 @@
1
1
  #import "CCPetsL10n.h"
2
2
  #import "CCPetsBridgeCLI.h"
3
+ #import "CCPetsBridgeAntigravityApp.h"
4
+ #import "CCPetsBridgeTerminalTitle.h"
5
+ #import "CCPetsBridgeTitleRelay.h"
3
6
  #import "CCPetsBridge.h"
4
7
  #import "CCPetsBridgeCore.h"
5
8
  #import "CCPetsBridgeSetup.h"
6
9
  #import "CCPetsBridgeStore.h"
7
10
  #import "CCPetsCLISupport.h"
8
11
  #import "CCPetsProfiles.h"
12
+ #import "CCPetsTerminalFocus.h"
9
13
  #import <unistd.h>
10
14
  #import <math.h>
11
15
 
@@ -68,7 +72,7 @@ static BOOL WriteOutput(FILE *stream, NSString *text) {
68
72
  static NSString *USAGE(void) {
69
73
  return L(@"Usage: cc-pets bridge <command>\n"
70
74
  "\n"
71
- " enable [options] Turn on CC Bridge: write Claude Code / Codex hooks and register MCP\n"
75
+ " enable [options] Turn on CC Bridge: install Agent hooks and register MCP\n"
72
76
  " configure [options] Change options while enabled (doesn't re-register MCP)\n"
73
77
  " disable Turn off and remove all CC Bridge integrations\n"
74
78
  " status Show whether it's on and which sessions are online\n"
@@ -81,22 +85,26 @@ static NSString *USAGE(void) {
81
85
  " --approve=<list> Auto-approve in both Codex and Claude\n"
82
86
  " --codex-approve=<list> Auto-approve in Codex only\n"
83
87
  " --claude-allow=<list> Allow without asking in Claude only\n"
88
+ " --agy-allow=<list> Allow without asking in Antigravity only\n"
84
89
  " Use groups view, send, reserve, name, or tool names; pass an empty value to clear\n"
85
- " --wake=on|off Wake idle sessions automatically (off saves tokens; messages arrive with the next user input)\n"
90
+ " --agy-app=on|off Enable or disable the Antigravity App Sidecar (off by default)\n"
91
+ " --tab-title=on|off Append Bridge nicknames to CLI terminal titles (off by default)\n"
92
+ " --wake=on|off Wake supported idle sessions automatically (off saves tokens; messages arrive with the next user input)\n"
86
93
  " --edit-guard=on|off Pause once when editing a file another session reserved\n"
87
94
  "\n"
88
- "Name a session at launch: CC_BRIDGE_NAME=frontend claude (or codex)\n"
95
+ "Name a session at launch: CC_BRIDGE_NAME=frontend claude (or codex, or agy)\n"
89
96
  "\n"
90
- "CC Bridge lets local Claude Code and Codex terminal sessions find, message and wake each other.\n"
97
+ "CC Bridge connects local Claude Code, Codex and Antigravity sessions.\n"
91
98
  "Message bodies are stored in a local temp directory readable only by you. Off by default.");
92
99
  }
93
100
 
94
101
  #pragma mark - 参数
95
102
 
96
- static NSString *ParseFlag(NSMutableArray<NSString *> *arguments, NSString *name) {
103
+ // 只在前 limit 个参数里找:send 的正文可以出现任意文字,包括 --from。
104
+ static NSString *ParseFlagWithin(NSMutableArray<NSString *> *arguments, NSString *name, NSUInteger limit) {
97
105
  NSString *exact = [@"--" stringByAppendingString:name];
98
106
  NSString *prefix = [exact stringByAppendingString:@"="];
99
- for (NSUInteger index = 0; index < arguments.count; index++) {
107
+ for (NSUInteger index = 0; index < MIN(limit, arguments.count); index++) {
100
108
  NSString *argument = arguments[index];
101
109
  if (![argument isEqualToString:exact] && ![argument hasPrefix:prefix]) continue;
102
110
  [arguments removeObjectAtIndex:index];
@@ -106,16 +114,21 @@ static NSString *ParseFlag(NSMutableArray<NSString *> *arguments, NSString *name
106
114
  [arguments removeObjectAtIndex:index];
107
115
  return value;
108
116
  }
109
- return nil;
117
+ Fail(LF(L(@"{flag} needs a value."), @{@"flag": exact}));
110
118
  }
111
119
  return nil;
112
120
  }
113
121
 
122
+ static NSString *ParseFlag(NSMutableArray<NSString *> *arguments, NSString *name) {
123
+ return ParseFlagWithin(arguments, name, NSUIntegerMax);
124
+ }
125
+
114
126
  static NSDictionary<NSString *, NSString *> *ReadOptionFlags(NSMutableArray<NSString *> *arguments) {
115
127
  NSMutableDictionary<NSString *, NSString *> *flags = [NSMutableDictionary dictionary];
116
128
  NSDictionary<NSString *, NSString *> *names = @{@"approve": @"approve", @"codex-approve": @"codexApprove",
117
- @"claude-allow": @"claudeAllow", @"wake": @"wake", @"edit-guard": @"editGuard"};
118
- for (NSString *flag in @[@"approve", @"codex-approve", @"claude-allow", @"wake", @"edit-guard"]) {
129
+ @"claude-allow": @"claudeAllow", @"agy-allow": @"antigravityAllow", @"agy-app": @"antigravityApp",
130
+ @"tab-title": @"tabTitle", @"wake": @"wake", @"edit-guard": @"editGuard"};
131
+ for (NSString *flag in @[@"approve", @"codex-approve", @"claude-allow", @"agy-allow", @"agy-app", @"tab-title", @"wake", @"edit-guard"]) {
119
132
  NSString *value = ParseFlag(arguments, flag);
120
133
  if (value) flags[names[flag]] = value;
121
134
  }
@@ -126,6 +139,8 @@ static NSDictionary *MergedOptions(NSDictionary *base, NSMutableArray<NSString *
126
139
  NSString *error = nil;
127
140
  NSDictionary *options = CCBridgeMergeOptionFlags(base, ReadOptionFlags(arguments), &error);
128
141
  if (!options) Fail(error);
142
+ // 拼错的选项不能当成"没给":用户以为改了,其实什么都没变。
143
+ if (arguments.count > 0) Fail(LF(L(@"Unknown option: {option}"), @{@"option": arguments.firstObject}));
129
144
  return options;
130
145
  }
131
146
 
@@ -136,15 +151,15 @@ static void PrintSessions(void) {
136
151
  return;
137
152
  }
138
153
  for (NSDictionary *session in sessions) {
139
- Print([NSString stringWithFormat:@"%@ %@ %@ pid=%@ %@ %@ %@=%lu", CCBridgeDescribeSession(session), session[@"provider"],
140
- StringValue(session[@"status"]) ?: @"-", session[@"pid"] ?: @"-", StringValue(session[@"tty"]) ?: @"-",
154
+ Print([NSString stringWithFormat:@"%@ %@ %@ pid=%@ %@ %@ %@=%lu", CCBridgeDescribeSessionForDisplay(session), session[@"provider"],
155
+ StringValue(session[@"status"]) ?: @"-", CCBridgeSessionHostPID(session) ?: @"-", StringValue(session[@"tty"]) ?: @"-",
141
156
  StringValue(session[@"cwd"]) ?: @"-", L(@"pending"), (unsigned long)CCBridgePendingCount(session[@"session"])]);
142
157
  }
143
158
  }
144
159
 
145
- static NSDictionary *SelfOrFrom(NSMutableArray<NSString *> *arguments) {
160
+ static NSDictionary *SelfOrFrom(NSMutableArray<NSString *> *arguments, NSUInteger flagLimit) {
146
161
  if (!CCBridgeEnabled()) Fail(L(@"CC Bridge is off. Run cc-pets bridge enable first."));
147
- NSString *from = ParseFlag(arguments, @"from");
162
+ NSString *from = ParseFlagWithin(arguments, @"from", flagLimit);
148
163
  if (from.length > 0) {
149
164
  NSDictionary *resolved = CCBridgeResolveTarget(from, CCBridgeLiveSessions());
150
165
  if (resolved[@"error"]) Fail(resolved[@"error"]);
@@ -157,23 +172,30 @@ static NSDictionary *SelfOrFrom(NSMutableArray<NSString *> *arguments) {
157
172
 
158
173
  #pragma mark - hook
159
174
 
175
+ static NSString *SessionIdentityContext(NSString *sessionId) {
176
+ return LF(L(@"[cc-bridge identity] Your current session_id is {session_id}. Pass this exact value as session_id on every CC Bridge tool call. Do not use a recipient's ID or an ID from a cross-session message."),
177
+ @{@"session_id": sessionId});
178
+ }
179
+
180
+ static NSDictionary *HookContext(NSString *eventName, NSString *context) {
181
+ return @{@"hookSpecificOutput": @{@"hookEventName": eventName, @"additionalContext": context}};
182
+ }
183
+
160
184
  static NSDictionary *InjectPending(NSString *sessionId, NSString *eventName) {
161
185
  NSArray<NSDictionary *> *messages = ClaimForOutput(sessionId, @"prompt-inject");
162
- if (messages.count == 0) return nil;
163
- NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
186
+ // 每次用户输入都重新提供身份,覆盖 resume、上下文压缩和 MCP 重新连接。
187
+ NSMutableArray<NSString *> *envelopes = [NSMutableArray arrayWithObject:SessionIdentityContext(sessionId)];
164
188
  for (NSDictionary *message in messages) {
165
189
  [envelopes addObject:CCBridgeFormatEnvelope(message)];
166
190
  }
167
- return @{@"hookSpecificOutput": @{@"hookEventName": eventName, @"additionalContext": [envelopes componentsJoinedByString:@"\n\n"]}};
191
+ return HookContext(eventName, [envelopes componentsJoinedByString:@"\n\n"]);
168
192
  }
169
193
 
170
194
  // 首次拦截、重试放行:本会话第一次编辑某处他人预留的文件时返回 deny 并说明原因,同时记下"已提醒";
171
195
  // 重试同一操作时这处预留已确认,直接放行。用 deny 而不是只注入 additionalContext:实测 Codex 的
172
196
  // additionalContext 在工具调用发出之后才到达,拦不住这次编辑。不用 "ask":Codex 的 PreToolUse
173
197
  // 只支持 allow / deny,两边行为要一致。
174
- static NSDictionary *CheckReservations(NSDictionary *payload, NSString *sessionId) {
175
- NSArray<NSString *> *files = CCBridgeEditedFiles(payload[@"tool_input"]);
176
- NSString *cwd = StringValue(payload[@"cwd"]) ?: StringValue(CCBridgeReadSession(sessionId)[@"cwd"]);
198
+ static NSString *ReservationReason(NSArray<NSString *> *files, NSString *cwd, NSString *sessionId) {
177
199
  if (files.count == 0 || cwd.length == 0) return nil;
178
200
  NSMutableArray<NSDictionary *> *pending = [NSMutableArray array];
179
201
  for (NSDictionary *hit in CCBridgeFindForeignReservations(sessionId, cwd, files)) {
@@ -191,8 +213,69 @@ static NSDictionary *CheckReservations(NSDictionary *payload, NSString *sessionI
191
213
  // 实测 Codex 重试放行后只回复"已创建",用户不知道自己改的是别人正在改的区域。
192
214
  [lines addObject:[L(@"If you retry, tell the user in your reply that these files are reserved by the session above (include its name and reason), ")
193
215
  stringByAppendingString:L(@"so they can decide whether to coordinate.")]];
194
- return @{@"hookSpecificOutput": @{@"hookEventName": @"PreToolUse", @"permissionDecision": @"deny",
195
- @"permissionDecisionReason": [lines componentsJoinedByString:@"\n"]}};
216
+ return [lines componentsJoinedByString:@"\n"];
217
+ }
218
+
219
+ static NSDictionary *CheckReservations(NSDictionary *payload, NSString *sessionId) {
220
+ NSString *cwd = StringValue(payload[@"cwd"]) ?: StringValue(CCBridgeReadSession(sessionId)[@"cwd"]);
221
+ NSString *reason = ReservationReason(CCBridgeEditedFiles(payload[@"tool_input"]), cwd, sessionId);
222
+ return reason ? @{@"hookSpecificOutput": @{@"hookEventName": @"PreToolUse", @"permissionDecision": @"deny",
223
+ @"permissionDecisionReason": reason}} : nil;
224
+ }
225
+
226
+ NSDictionary *CCBridgeHandleAntigravityHook(NSString *event, NSDictionary *payload) {
227
+ if (!CCBridgeEnabled()) return nil;
228
+ NSString *sessionId = CCBridgeSafeSessionId(payload[@"conversationId"]);
229
+ NSDictionary *ancestor = CCBridgeFindAgentAncestor(getppid());
230
+ NSString *provider = ancestor[@"provider"];
231
+ BOOL app = [provider isEqual:CCBridgeAntigravityAppProvider];
232
+ if (!sessionId || (!app && ![provider isEqual:CCBridgeAntigravityProvider])) return nil;
233
+ NSDictionary *options = CCBridgeOptions();
234
+ if (app && ![options[@"antigravityApp"] boolValue]) return nil;
235
+
236
+ NSDictionary *known = CCBridgeReadSession(sessionId);
237
+ if (known && ![known[@"provider"] isEqual:provider] && CCBridgeSessionLive(known)) return nil;
238
+ NSArray *workspaces = [payload[@"workspacePaths"] isKindOfClass:NSArray.class] ? payload[@"workspacePaths"] : nil;
239
+ NSString *cwd = StringValue(workspaces.firstObject) ?: StringValue(payload[@"cwd"]);
240
+ if (!cwd.isAbsolutePath) cwd = StringValue(known[@"cwd"]) ?: NSFileManager.defaultManager.currentDirectoryPath;
241
+ if ([event isEqual:@"PreToolUse"]) {
242
+ if (![options[@"editGuard"] boolValue]) return nil;
243
+ NSDictionary *tool = [payload[@"toolCall"] isKindOfClass:NSDictionary.class] ? payload[@"toolCall"] : nil;
244
+ if (![@[@"write_to_file", @"replace_file_content", @"multi_replace_file_content", @"sed_file"] containsObject:tool[@"name"] ?: @""]) return nil;
245
+ NSDictionary *args = [tool[@"args"] isKindOfClass:NSDictionary.class] ? tool[@"args"] : nil;
246
+ NSString *file = StringValue(args[@"TargetFile"]) ?: StringValue(args[@"FilePath"]);
247
+ NSString *reason = file.length > 0 ? ReservationReason(@[file], cwd, sessionId) : nil;
248
+ return reason ? @{@"decision": @"deny", @"reason": reason} : nil;
249
+ }
250
+
251
+ NSString *status = @{@"SessionStart": @"idle", @"PreInvocation": @"busy", @"Stop": @"idle"}[event];
252
+ if (!status || ([event isEqual:@"Stop"] && [payload[@"fullyIdle"] isEqual:@NO])) return nil;
253
+ NSNumber *pid = ancestor[@"pid"];
254
+ CCBridgeUpsertSession(sessionId, provider, pid, cwd, app ? nil : CCBridgeProcessTty(pid.intValue),
255
+ status, CCPetsEnvironmentValue(@"CC_BRIDGE_NAME"), CCPetsEnvironmentValue(@"CC_PETS_PROFILE_ID"),
256
+ CCPetsEnvironmentValue(@"CC_PETS_PROFILE_NAME"), @[]);
257
+ if ([event isEqual:@"Stop"]) {
258
+ if (CCBridgeHasIdleSubscriptions(sessionId)) CCPetsSpawnDetached(CCPetsExecutablePath(), @[@"bridge", @"notify-idle", sessionId]);
259
+ return nil;
260
+ }
261
+ NSMutableArray<NSDictionary *> *steps = [NSMutableArray array];
262
+ if ([event isEqual:@"SessionStart"] || !known) {
263
+ [steps addObject:@{@"systemMessage": @{@"systemMessage": SessionIdentityContext(sessionId)}}];
264
+ }
265
+ BOOL wake = [options[@"wake"] boolValue];
266
+ BOOL previousWakePrompt = app && [payload[@"lastUserInput"] isEqual:CCBridgeAntigravityAppWakePrompt];
267
+ if ([event isEqual:@"PreInvocation"] && (wake || (!previousWakePrompt && ![known[@"status"] isEqual:@"busy"]))) {
268
+ NSMutableArray<NSString *> *messages = [NSMutableArray array];
269
+ for (NSDictionary *message in ClaimForOutput(sessionId, app ? @"agy-app-hook" : @"agy-hook")) {
270
+ [messages addObject:CCBridgeFormatEnvelope(message)];
271
+ }
272
+ if (messages.count > 0) [steps addObject:@{@"userMessage": [messages componentsJoinedByString:@"\n\n"]}];
273
+ }
274
+ return steps.count > 0 ? @{@"injectSteps": steps} : nil;
275
+ }
276
+
277
+ void CCBridgeFinishAntigravityHook(BOOL written) {
278
+ FinishInboxOutput(written);
196
279
  }
197
280
 
198
281
  static NSDictionary *RunHook(NSString *input) {
@@ -206,32 +289,68 @@ static NSDictionary *RunHook(NSString *input) {
206
289
  if (event.length == 0 || !sessionId) return nil;
207
290
 
208
291
  if ([event isEqualToString:@"SessionEnd"]) {
209
- CCBridgeRemoveSession(sessionId);
210
- CCBridgeAbandonInbox(sessionId);
211
- CCBridgeReleaseSessionReservations(sessionId);
292
+ // 各步互不依赖:一步等锁超时,其余的清理也要做完。
293
+ for (void (^step)(void) in @[
294
+ ^{ CCBridgeRemoveSession(sessionId); },
295
+ ^{ CCBridgeAbandonInbox(sessionId); },
296
+ ^{ CCBridgeReleaseSessionReservations(sessionId); },
297
+ ^{ CCBridgeClearIdleSubscriptions(sessionId); },
298
+ ^{ CCBridgeDropWatcher(sessionId); }
299
+ ]) {
300
+ @try { step(); } @catch (NSException *exception) {}
301
+ }
212
302
  return nil;
213
303
  }
214
304
  // 编辑前检查文件预留。不更新注册表——这个 hook 每次编辑都会跑,保持最轻。
215
305
  if ([event isEqualToString:@"PreToolUse"]) {
216
306
  return [CCBridgeOptions()[@"editGuard"] boolValue] ? CheckReservations(payload, sessionId) : nil;
217
307
  }
308
+ // 没有持久化转录的 Codex 临时任务不能作为 queue 的收件会话,但仍需检查文件预留。
309
+ // 缺字段的旧版 hook 保持兼容;SessionEnd 仍先走上面的清理。
310
+ if ([provider isEqualToString:@"Codex"] && payload[@"transcript_path"] == NSNull.null) return nil;
218
311
 
219
312
  NSString *status = @{@"SessionStart": @"idle", @"UserPromptSubmit": @"busy", @"Stop": @"idle"}[event];
220
313
  NSDictionary *known = CCBridgeReadSession(sessionId);
221
314
  // 每次都重新探测:`claude --resume` 会在新进程里沿用同一个 session id。
222
315
  NSDictionary *ancestor = CCBridgeFindAgentAncestor(getppid());
223
316
  NSNumber *pid = [ancestor[@"provider"] isEqual:provider] ? ancestor[@"pid"] : known[@"pid"];
317
+ BOOL titleEnabled = CCBridgeTerminalTitleEnabled();
318
+ BOOL interactiveEvent = [event isEqual:@"SessionStart"] || [event isEqual:@"UserPromptSubmit"];
319
+ NSDictionary *terminal = nil;
320
+ if (interactiveEvent && (titleEnabled || CCPetsEnvironmentValue(@"CC_PETS_BRIDGE_TITLE_TOKEN").length > 0)) {
321
+ @try { terminal = TerminalFocusTargetForHook(payload, provider); } @catch (NSException *exception) {}
322
+ }
323
+ NSString *titleToken = StringValue(terminal[@"bridgeTitleToken"]);
324
+ NSString *tty = titleToken ? StringValue(terminal[@"tty"]) : nil;
325
+ if (!tty) tty = [event isEqual:@"Stop"] ? StringValue(known[@"tty"]) : nil;
326
+ if (!tty && pid) tty = CCBridgeProcessTty(pid.intValue);
224
327
  // 账号名写进 profileName 字段,也作为默认会话名的前缀:<账号名>.<项目名>.<动物>。
225
328
  NSString *preferredName = CCPetsEnvironmentValue(@"CC_BRIDGE_NAME");
226
329
  CCBridgeUpsertSession(sessionId, provider, pid, StringValue(payload[@"cwd"]),
227
- pid ? CCBridgeProcessTty(pid.intValue) : nil, status,
330
+ tty, status,
228
331
  // hook 继承宿主 CLI 的环境:`CC_BRIDGE_NAME=frontend claude` 即以 frontend 注册。只在首次注册时生效。
229
332
  preferredName, CCPetsEnvironmentValue(@"CC_PETS_PROFILE_ID"),
230
333
  CCPetsEnvironmentValue(@"CC_PETS_PROFILE_NAME"), @[]);
334
+ if (titleEnabled && interactiveEvent) {
335
+ @try {
336
+ if (titleToken.length > 0) {
337
+ CCBridgeBindTerminalTitle(titleToken, provider, sessionId);
338
+ } else if ([provider isEqual:@"Codex"] && CodexHasTerminalTitleLaunch(StringValue(payload[@"cwd"])) &&
339
+ TerminalFocusRunsUnderSharedAgentHost()) {
340
+ CCPetsSpawnDetached(CCPetsExecutablePath(), @[@"bridge", @"retry-codex-title", sessionId,
341
+ StringValue(payload[@"cwd"]), StringValue(payload[@"transcript_path"]) ?: @""]);
342
+ }
343
+ } @catch (NSException *exception) {}
344
+ }
231
345
 
232
346
  if ([event isEqualToString:@"SessionStart"]) {
233
- CCBridgePruneReceipts();
234
- return nil;
347
+ // 清理失败不能影响身份注入。
348
+ @try {
349
+ CCBridgeSweepMessages();
350
+ CCBridgePruneReceipts();
351
+ } @catch (NSException *exception) {
352
+ }
353
+ return HookContext(event, SessionIdentityContext(sessionId));
235
354
  }
236
355
  if ([event isEqualToString:@"UserPromptSubmit"]) return InjectPending(sessionId, event);
237
356
  // 空闲通知可能要调 codex queue(秒级),放到脱离的子进程里做,不让 Stop hook 拖慢对方回合的收尾。
@@ -256,10 +375,44 @@ static int HookCommand(void) {
256
375
  return 0;
257
376
  }
258
377
 
378
+ static int RetryCodexTerminalTitleCommand(NSArray<NSString *> *arguments) {
379
+ if (arguments.count != 3 || !CCBridgeTerminalTitleEnabled()) return 0;
380
+ NSString *session = CCBridgeSafeSessionId(arguments[0]);
381
+ NSString *cwd = arguments[1];
382
+ if (!session || !cwd.isAbsolutePath) return 0;
383
+
384
+ NSString *lock = nil;
385
+ @try {
386
+ lock = CCBridgeAcquireLock([@"codex-title-retry-" stringByAppendingString:session]);
387
+ if (!lock) return 0;
388
+ // Codex can buffer TUI startup logs for 10 seconds. Wait outside the hook.
389
+ NSDictionary *payload = @{@"cwd": cwd, @"transcript_path": arguments[2]};
390
+ NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 16;
391
+ while (NSProcessInfo.processInfo.systemUptime < deadline) {
392
+ @autoreleasepool {
393
+ if (!CCBridgeTerminalTitleEnabled() || !CodexHasTerminalTitleLaunch(cwd)) break;
394
+ NSDictionary *record = CCBridgeReadSession(session);
395
+ if (![record[@"provider"] isEqual:@"Codex"] || !CCBridgeSessionLive(record)) break;
396
+ NSString *token = StringValue(CodexLaunchTerminalForThread(session, payload)[@"bridgeTitleToken"]);
397
+ if (token.length > 0) {
398
+ CCBridgeBindTerminalTitleIfUnbound(token, @"Codex", session);
399
+ break;
400
+ }
401
+ }
402
+ sleep(2);
403
+ }
404
+ } @catch (NSException *exception) {
405
+ } @finally {
406
+ CCBridgeReleaseLock(lock);
407
+ }
408
+ return 0;
409
+ }
410
+
259
411
  #pragma mark - watch
260
412
  // Claude 端的投递者:以 asyncRewake hook 运行,等信箱来消息后 exit 2 唤醒会话。实测:exit 2 时 stderr
261
413
  // 作为系统提醒进入会话,空闲会被唤醒、忙碌则注入当前回合;hook 的 timeout 会被强制执行,所以 watcher
262
- // 在超时前主动退出,下一次事件再重新挂上。每个会话只保留一个 watcher(锁文件)。
414
+ // 在超时前主动退出,下一次事件再重新挂上。每个会话只保留一个 watcher(锁文件):新挂上的取代旧的,
415
+ // 并从自己启动时重新计时,否则活跃的会话也会在第一个 watcher 到期后断掉唤醒,直到下一轮结束。
263
416
 
264
417
  static int WatchCommand(void) {
265
418
  NSString *lock = nil;
@@ -270,8 +423,7 @@ static int WatchCommand(void) {
270
423
  NSDictionary *payload = ParseJSON(ReadStandardInput());
271
424
  NSString *sessionId = [payload isKindOfClass:NSDictionary.class] ? CCBridgeSafeSessionId(payload[@"session_id"]) : nil;
272
425
  if (!sessionId) return 0;
273
- lock = CCBridgeAcquireLock([@"watch-" stringByAppendingString:sessionId]);
274
- if (!lock) return 0;
426
+ NSString *token = CCBridgeClaimWatcher(sessionId);
275
427
  // 安装时 hook 的 timeout 是 3600 秒,这里留 5 分钟余量主动退出,保证锁由自己释放。
276
428
  double seconds = CCPetsEnvironmentValue(@"CC_BRIDGE_WATCH_SECONDS").doubleValue;
277
429
  if (!(seconds > 0)) seconds = 3300;
@@ -283,7 +435,16 @@ static int WatchCommand(void) {
283
435
  if (!CCBridgeEnabled() || ![CCBridgeOptions()[@"wake"] boolValue]) return 0;
284
436
  // 宿主会话已经没了(被 kill -9 等,没来得及清理子进程)就别再占着锁。
285
437
  if (!CCBridgeProcessAlive(parent)) return 0;
286
- NSArray<NSDictionary *> *messages = ClaimForOutput(sessionId, @"claude-rewake");
438
+ if (!CCBridgeWatcherOwned(sessionId, token)) return 0;
439
+ // 旧 watcher 下一次轮询就会退出。升级时跑的旧版本不认登记,那就一直等到它到期。
440
+ if (!lock) lock = CCBridgeAcquireLock([@"watch-" stringByAppendingString:sessionId]);
441
+ if (!lock) {
442
+ usleep((useconds_t)(poll * 1000));
443
+ continue;
444
+ }
445
+ // 这里每秒走一次:信箱空着时只列目录,不去写删锁文件。
446
+ NSArray<NSDictionary *> *messages = CCBridgePendingCount(sessionId) > 0
447
+ ? ClaimForOutput(sessionId, @"claude-rewake") : @[];
287
448
  if (messages.count > 0) {
288
449
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
289
450
  for (NSDictionary *message in messages) {
@@ -326,7 +487,10 @@ static NSString *AliasNote(void) {
326
487
  }
327
488
 
328
489
  static NSDictionary *Schema(NSDictionary *properties, NSArray<NSString *> *required) {
329
- NSMutableDictionary *schema = [@{@"type": @"object", @"properties": properties, @"additionalProperties": @NO} mutableCopy];
490
+ NSMutableDictionary *withIdentity = [properties mutableCopy];
491
+ withIdentity[@"session_id"] = @{@"type": @"string", @"minLength": @1, @"maxLength": @128,
492
+ @"description": L(@"Your current session ID from the cc-bridge hook context or your own shell's CODEX_THREAD_ID / CLAUDE_CODE_SESSION_ID. Pass it on every call when available; required to identify one of several sessions sharing a host. Never use the recipient's ID or guess from the session list.")};
493
+ NSMutableDictionary *schema = [@{@"type": @"object", @"properties": withIdentity, @"additionalProperties": @NO} mutableCopy];
330
494
  if (required) schema[@"required"] = required;
331
495
  return schema;
332
496
  }
@@ -335,7 +499,7 @@ static NSArray<NSDictionary *> *Tools(void) {
335
499
  return @[
336
500
  @{@"name": @"list_agents",
337
501
  @"description": [@[
338
- L(@"List the other Claude Code / Codex terminal sessions running on this machine that can exchange messages (cc-pets CC Bridge; "),
502
+ L(@"List other local sessions that can receive CC Bridge messages, including Claude Code, Codex, and Antigravity CLI sessions ("),
339
503
  L(@"this is what the user means by “bridge”, “cc-bridge”, “other sessions” or “another terminal”). "), AliasNote(),
340
504
  L(@"Each line shows: name [ref], CLI, busy/idle, terminal (tty), start time, working directory. "),
341
505
  L(@"The name is the send_message address; append ` [ref]` only when names collide. "),
@@ -345,7 +509,7 @@ static NSArray<NSDictionary *> *Tools(void) {
345
509
  @"annotations": @{@"readOnlyHint": @YES, @"title": L(@"List Agent sessions")}},
346
510
  @{@"name": @"send_message",
347
511
  @"description": [@[
348
- L(@"Send a message to another Claude Code / Codex session on this machine (what the user means by “message it via bridge” or “send to another session / terminal”). "),
512
+ L(@"Send a message to another CC Bridge session on this machine (what the user means by “message it via bridge” or “send to another session / terminal”). "),
349
513
  L(@"An idle recipient is woken; a busy one gets it after its current turn. "), AliasNote(),
350
514
  L(@"Delivery doesn't mean it was read or agreed to; replies arrive as new messages in this session. "),
351
515
  L(@"When replying, put the from name from the message header into to."), SafetyNote()
@@ -355,7 +519,7 @@ static NSArray<NSDictionary *> *Tools(void) {
355
519
  @"message": @{@"type": @"string",
356
520
  @"description": L(@"Message body. Say what it's about in the first sentence; don't rely on @file references, since attachments aren't delivered.")},
357
521
  @"notify_when_idle": @{@"type": @"boolean",
358
- @"description": L(@"When true, this session gets a one-time notice when the recipient next finishes a turn and goes idle.")}
522
+ @"description": L(@"When true, this session gets a one-time notice when the recipient next finishes a turn and goes idle. That turn may be one already in progress, so the notice doesn't mean this message was handled.")}
359
523
  }, @[@"to", @"message"]),
360
524
  @"annotations": @{@"readOnlyHint": @NO, @"destructiveHint": @NO, @"title": L(@"Send cross-session message")}},
361
525
  @{@"name": @"set_name",
@@ -415,8 +579,12 @@ static NSString *AgeText(id since) {
415
579
  return LF(L(@"started {minutes} h ago"), @{@"minutes": @((long long)floor(minutes / 60 + 0.5))});
416
580
  }
417
581
 
582
+ static NSString *IdentityNote(void) {
583
+ return L(@" Pass your current session_id on every CC Bridge tool call, using the ID from the cc-bridge hook context. If it is missing, read CODEX_THREAD_ID (Codex) or CLAUDE_CODE_SESSION_ID (Claude) in your own session's shell; if neither is available, refresh this session's bridge hooks. Never guess an ID from names, directories, activity or received messages, and never save one session's ID in shared MCP configuration.");
584
+ }
585
+
418
586
  static NSString *UnknownSelf(void) {
419
- return L(@"Current session identity is unavailable or ambiguous. Register this session through the bridge hooks and provide a valid session ID. A shared host PID cannot identify one of several sessions; no action was taken.");
587
+ return [L(@"Current session identity is unavailable or ambiguous. Register this session through the bridge hooks and provide a valid session ID. A shared host PID cannot identify one of several sessions; no action was taken.") stringByAppendingString:IdentityNote()];
420
588
  }
421
589
 
422
590
  static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
@@ -424,7 +592,14 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
424
592
  return TextResult(L(@"cc-pets CC Bridge isn't enabled. The user can turn it on by running `cc-pets bridge enable` in a terminal."), YES);
425
593
  }
426
594
  if (![arguments isKindOfClass:NSDictionary.class]) arguments = @{};
427
- NSDictionary *self = CCBridgeIdentifySelf();
595
+ NSString *identityFailure = nil;
596
+ NSDictionary *self = CCBridgeIdentifySelfForSession(arguments[@"session_id"], &identityFailure);
597
+ // 即使是列表工具,显式传错身份也要报错,不能伪装成一次成功的匿名查询。
598
+ if (arguments[@"session_id"] != nil && !self) {
599
+ NSString *invalid = L(@"Invalid session_id: it must identify a live registered session belonging to this MCP host. No action was taken.");
600
+ return TextResult([[invalid stringByAppendingFormat:@" %@", identityFailure ?: @""]
601
+ stringByAppendingString:IdentityNote()], YES);
602
+ }
428
603
 
429
604
  if ([name isEqualToString:@"list_agents"]) {
430
605
  NSArray<NSDictionary *> *live = CCBridgeLiveSessions();
@@ -433,8 +608,8 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
433
608
  if (![session[@"session"] isEqual:self[@"session"]]) [sessions addObject:session];
434
609
  }
435
610
  NSString *header = self
436
- ? LF(L(@"This session is {self}; other sessions use this name to message you (it isn't in the list below)."), @{@"self": CCBridgeDescribeSession(self)})
437
- : L(@"Current session identity is unavailable or ambiguous (you can view sessions, but cannot act as one).");
611
+ ? LF(L(@"This session is {self}; other sessions use this name to message you (it isn't in the list below)."), @{@"self": CCBridgeDescribeSessionForDisplay(self)})
612
+ : [L(@"Current session identity is unavailable or ambiguous (you can view sessions, but cannot act as one).") stringByAppendingString:IdentityNote()];
438
613
  if (sessions.count == 0) {
439
614
  return TextResult(LF(L(@"{header}\n\nNo other sessions online. New sessions will show up here once they start."), @{@"header": header}), NO);
440
615
  }
@@ -444,7 +619,7 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
444
619
  NSMutableArray<NSString *> *lines = [NSMutableArray array];
445
620
  for (NSDictionary *session in sessions) {
446
621
  NSUInteger count = [counts countForObject:session[@"session"]];
447
- NSString *line = [NSString stringWithFormat:@" %@ · %@ · %@ · %@ · %@ · %@", CCBridgeDescribeSession(session),
622
+ NSString *line = [NSString stringWithFormat:@" %@ · %@ · %@ · %@ · %@ · %@", CCBridgeDescribeSessionForDisplay(session),
448
623
  session[@"provider"], [session[@"status"] isEqual:@"busy"] ? @"busy" : @"idle", StringValue(session[@"tty"]) ?: @"-",
449
624
  AgeText(session[@"startedAt"]), StringValue(session[@"cwd"]) ?: @"-"];
450
625
  if (count > 0) line = [line stringByAppendingString:LF(L(@" · {count} reserved"), @{@"count": @(count)})];
@@ -501,7 +676,9 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
501
676
 
502
677
  if ([name isEqualToString:@"release_files"]) {
503
678
  if (!self) return TextResult(UnknownSelf(), YES);
504
- NSArray<NSString *> *released = CCBridgeReleaseFiles(self, arguments[@"paths"])[@"released"];
679
+ NSDictionary *result = CCBridgeReleaseFiles(self, arguments[@"paths"]);
680
+ if (result[@"error"]) return TextResult(result[@"error"], YES);
681
+ NSArray<NSString *> *released = result[@"released"];
505
682
  if (released.count == 0) return TextResult(L(@"Nothing to release."), NO);
506
683
  NSDictionary *values = @{@"length": @(released.count), @"released": [released componentsJoinedByString:L(@", ")]};
507
684
  return TextResult(released.count != 1 ? LF(L(@"Released {length} reservations: {released}"), values)
@@ -509,6 +686,8 @@ static NSDictionary *CallTool(NSString *name, NSDictionary *arguments) {
509
686
  }
510
687
 
511
688
  if ([name isEqualToString:@"list_reservations"]) {
689
+ // 共享宿主上 MCP 进程的目录不是调用者的仓库,退回它只会查错地方。
690
+ if (!self) return TextResult(UnknownSelf(), YES);
512
691
  NSString *cwd = StringValue(self[@"cwd"]) ?: NSFileManager.defaultManager.currentDirectoryPath;
513
692
  NSString *root = CCBridgeRepoRoot(cwd);
514
693
  NSArray<NSDictionary *> *reservations = CCBridgeActiveReservations(root, nil);
@@ -548,20 +727,40 @@ static NSDictionary *HandleRequest(NSDictionary *request, NSDictionary **error)
548
727
  @"capabilities": @{@"tools": @{}},
549
728
  @"serverInfo": @{@"name": @"cc-bridge", @"version": @"1.0.0"},
550
729
  @"instructions": [@[
551
- L(@"cc-pets CC Bridge: exchange messages with other Claude Code / Codex terminal sessions on this machine. "),
730
+ L(@"cc-pets CC Bridge: exchange messages with local Claude Code, Codex, and Antigravity CLI sessions. "),
552
731
  L(@"When the user mentions cc-bridge, bridge, pet, desktop pet, 桌宠, cc-pets, cross-session / cross-terminal messages, "),
553
732
  L(@"“message another session / terminal / Claude / Codex”, or names a session or tty (e.g. ttys003), "),
554
733
  L(@"use this server's tools directly; there's no need to look up bridge usage in project files. "), AliasNote(),
555
734
  L(@"Find the recipient's name with list_agents, then send with send_message. "),
556
735
  L(@"When a cross-session request needs clarification or is complete, reply to the originating session using send_message. "),
557
736
  L(@"When several sessions work in the same repository, reserve files with reserve_files before a larger change and release them with release_files afterwards. "),
558
- SafetyNote()
737
+ SafetyNote(), IdentityNote()
559
738
  ] componentsJoinedByString:@""]
560
739
  };
561
740
  }
562
741
  if ([method isEqualToString:@"ping"]) return @{};
563
742
  if ([method isEqualToString:@"tools/list"]) return @{@"tools": Tools()};
564
- if ([method isEqualToString:@"tools/call"]) return CallTool(StringValue(params[@"name"]), params[@"arguments"]);
743
+ if ([method isEqualToString:@"tools/call"]) {
744
+ NSDictionary *meta = [params[@"_meta"] isKindOfClass:NSDictionary.class] ? params[@"_meta"] : nil;
745
+ BOOL agyMCP = [CCPetsEnvironmentValue(@"CC_PETS_AGY_MCP") isEqual:@"1"];
746
+ NSString *rootConversation = CCBridgeSafeSessionId(meta[@"antigravity.google/root_conversation_id"]);
747
+ id arguments = params[@"arguments"];
748
+ if (agyMCP || rootConversation) {
749
+ NSString *provider = CCBridgeFindAgentAncestor(getppid())[@"provider"];
750
+ BOOL antigravity = [provider isEqual:CCBridgeAntigravityProvider] ||
751
+ ([provider isEqual:CCBridgeAntigravityAppProvider] && [CCBridgeOptions()[@"antigravityApp"] boolValue]);
752
+ if (agyMCP && !antigravity) return TextResult(L(@"CC Bridge is unavailable for this Antigravity host."), YES);
753
+ if (rootConversation && antigravity) {
754
+ NSMutableDictionary *withIdentity = [arguments isKindOfClass:NSDictionary.class] ? [arguments mutableCopy] : [NSMutableDictionary dictionary];
755
+ if (withIdentity[@"session_id"] && ![withIdentity[@"session_id"] isEqual:rootConversation]) {
756
+ return TextResult(L(@"The supplied session_id differs from the current Antigravity conversation."), YES);
757
+ }
758
+ withIdentity[@"session_id"] = rootConversation;
759
+ arguments = withIdentity;
760
+ }
761
+ }
762
+ return CallTool(StringValue(params[@"name"]), arguments);
763
+ }
565
764
  *error = @{@"code": @(-32601), @"message": [NSString stringWithFormat:@"Method not found: %@", method ?: @"undefined"]};
566
765
  return nil;
567
766
  }
@@ -577,7 +776,8 @@ static int MCPCommand(void) {
577
776
  while ((length = getline(&line, &capacity, stdin)) >= 0) {
578
777
  @autoreleasepool {
579
778
  NSString *text = [[NSString alloc] initWithBytes:line length:(NSUInteger)length encoding:NSUTF8StringEncoding];
580
- if ([text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length == 0) continue;
779
+ // 非法 UTF-8 时 text 为 nil,要走下面的解析错误:不回复的话客户端会一直等。
780
+ if (text && [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length == 0) continue;
581
781
  NSDictionary *request = ParseJSON(text);
582
782
  if (![request isKindOfClass:NSDictionary.class]) {
583
783
  WriteMessage(@{@"jsonrpc": @"2.0", @"id": NSNull.null, @"error": @{@"code": @(-32700), @"message": @"Parse error"}});
@@ -617,6 +817,16 @@ static NSArray<NSDictionary *> *RegisteredProfiles(void) {
617
817
 
618
818
  static BOOL InstallBridgeForRegisteredProfiles(NSDictionary *options, BOOL registerMcp) {
619
819
  __block BOOL succeeded = YES;
820
+ if ([options[@"antigravityApp"] boolValue]) {
821
+ NSString *home = [CCPetsHomeDirectory() stringByAppendingPathComponent:@".gemini"];
822
+ NSString *error = nil;
823
+ if (!CCPetsProfileForHome(CCPetsProfileProviderAntigravity, home) &&
824
+ (!CCPetsProfileHomeMatchesProvider(CCPetsProfileProviderAntigravity, home) ||
825
+ !CCPetsRegisterProfile(CCPetsProfileProviderAntigravity, home, nil, nil, &error))) {
826
+ CCPetsPrintLine(stderr, error ?: L(@"Open Antigravity App once before enabling its CC Bridge integration."));
827
+ return NO;
828
+ }
829
+ }
620
830
  NSArray<NSDictionary *> *profiles = RegisteredProfiles();
621
831
  if (profiles.count == 0) {
622
832
  Print(L(@"No Agent Homes are registered; CC Bridge will be applied when you add one from Multi-Account in the Main menu."));
@@ -703,6 +913,13 @@ static int DisableCommand(void) {
703
913
  // 先关闭运行时入口,卸载耗时或失败也不能继续发送/唤醒。
704
914
  CCBridgeSetEnabled(NO, nil);
705
915
  BOOL succeeded = UninstallBridgeForRegisteredProfiles(CCBridgeShouldTouchMCP());
916
+ // 关闭后 hook 不再运行,没人会来收尾。已送达的回执留作记录,它们不含正文。
917
+ @try {
918
+ CCBridgeAbandonAllInboxes(L(@"CC Bridge is off."));
919
+ } @catch (NSException *exception) {
920
+ succeeded = NO;
921
+ Print(exception.reason ?: exception.name);
922
+ }
706
923
  Print(succeeded ? L(@"CC Bridge is off.") : L(@"CC Bridge is off, but some integrations could not be removed. Retry disable after resolving the errors above."));
707
924
  return succeeded ? 0 : 1;
708
925
  }
@@ -738,9 +955,9 @@ static int StatusCommand(void) {
738
955
  if (receipts.count > 0) {
739
956
  Print(L(@"\nRecent messages:"));
740
957
  for (NSDictionary *receipt in receipts) {
741
- NSString *from = [receipt[@"from"][@"system"] boolValue] ? @"cc-pets" : receipt[@"from"][@"name"];
958
+ NSString *from = [receipt[@"from"][@"system"] boolValue] ? @"cc-pets" : CCBridgeSessionDisplayName(receipt[@"from"]);
742
959
  NSString *reason = StringValue(receipt[@"reason"]);
743
- Print([NSString stringWithFormat:@" %@ %@ → %@ %@%@", receipt[@"id"], from, receipt[@"to"][@"name"], receipt[@"status"],
960
+ Print([NSString stringWithFormat:@" %@ %@ → %@ %@%@", receipt[@"id"], from, CCBridgeSessionDisplayName(receipt[@"to"]), receipt[@"status"],
744
961
  reason ? LF(L(@" ({reason})"), @{@"reason": reason}) : @""]);
745
962
  }
746
963
  }
@@ -748,7 +965,8 @@ static int StatusCommand(void) {
748
965
  }
749
966
 
750
967
  static int SendCommand(NSMutableArray<NSString *> *arguments) {
751
- NSDictionary *from = SelfOrFrom(arguments);
968
+ // --from 只能写在收件人前后,再往后就是正文。
969
+ NSDictionary *from = SelfOrFrom(arguments, 2);
752
970
  if (arguments.count < 2) Fail(L(@"Usage: cc-pets bridge send <to> <message…>"));
753
971
  NSDictionary *target = CCBridgeResolveTarget(arguments[0], CCBridgeLiveSessions());
754
972
  if (target[@"error"]) Fail(target[@"error"]);
@@ -760,7 +978,7 @@ static int SendCommand(NSMutableArray<NSString *> *arguments) {
760
978
  }
761
979
 
762
980
  static int NameCommand(NSMutableArray<NSString *> *arguments) {
763
- NSDictionary *session = SelfOrFrom(arguments);
981
+ NSDictionary *session = SelfOrFrom(arguments, NSUIntegerMax);
764
982
  if (arguments.count == 0) Fail(L(@"Usage: cc-pets bridge name <new-name>"));
765
983
  NSDictionary *result = CCBridgeRenameSession(session[@"session"], arguments[0], @[]);
766
984
  if (result[@"error"]) Fail(result[@"error"]);
@@ -769,7 +987,7 @@ static int NameCommand(NSMutableArray<NSString *> *arguments) {
769
987
  }
770
988
 
771
989
  static int InboxCommand(NSMutableArray<NSString *> *arguments) {
772
- NSDictionary *session = SelfOrFrom(arguments);
990
+ NSDictionary *session = SelfOrFrom(arguments, NSUIntegerMax);
773
991
  NSArray<NSDictionary *> *messages = ClaimForOutput(session[@"session"], @"check-inbox");
774
992
  NSMutableArray<NSString *> *envelopes = [NSMutableArray array];
775
993
  for (NSDictionary *message in messages) {
@@ -802,6 +1020,10 @@ int CCBridgeCommandMain(NSArray<NSString *> *argv) {
802
1020
  if ([command isEqualToString:@"hook"]) return HookCommand();
803
1021
  if ([command isEqualToString:@"watch"]) return WatchCommand();
804
1022
  if ([command isEqualToString:@"mcp"]) return MCPCommand();
1023
+ if ([command isEqualToString:@"agy-app-sidecar"]) return arguments.count == 0 ? CCBridgeRunAntigravityAppSidecar() : 2;
1024
+ if ([command isEqualToString:@"terminal-title-enabled"]) return CCBridgeTerminalTitleEnabled() ? 0 : 1;
1025
+ if ([command isEqualToString:@"terminal-title-run"]) return CCPetsRunBridgeTitleRelay(arguments);
1026
+ if ([command isEqualToString:@"retry-codex-title"]) return RetryCodexTerminalTitleCommand(arguments);
805
1027
  @try {
806
1028
  if ([command isEqualToString:@"notify-idle"]) return NotifyIdleCommand(arguments);
807
1029
  NSDictionary<NSString *, int (^)(void)> *commands = @{