cc-pets 2.4.0 → 2.5.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 (53) hide show
  1. package/CC_BRIDGE.md +46 -9
  2. package/CC_BRIDGE.zh-CN.md +29 -6
  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 +69 -16
  10. package/README.zh-CN.md +54 -19
  11. package/Resources/zh-Hans.lproj/Localizable.strings +35 -11
  12. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +47 -4
  13. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +109 -14
  14. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +8 -6
  15. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  16. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +13 -0
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +6 -1
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +5 -3
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +4 -1
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +4 -0
  21. package/Sources/CCPets/App/CCPetsAppDelegate.h +10 -0
  22. package/Sources/CCPets/App/CCPetsAppDelegate.m +4 -2
  23. package/Sources/CCPets/Bridge/CCPetsBridge.m +34 -12
  24. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +100 -33
  25. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +12 -3
  26. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +317 -89
  27. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  28. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +210 -95
  29. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +28 -3
  30. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +222 -35
  31. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  32. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  33. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +1 -1
  34. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +6 -0
  35. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +54 -5
  36. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  37. package/Sources/CCPets/Pet/PetView+Menu.m +9 -1
  38. package/Sources/CCPets/Pet/PetView.h +7 -0
  39. package/Sources/CCPets/Pet/PetView.m +12 -1
  40. package/Sources/CCPets/Support/CCPetsPreferences.h +10 -0
  41. package/Sources/CCPets/Support/CCPetsPreferences.m +18 -0
  42. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  43. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  44. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  45. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +528 -0
  46. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  47. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +95 -0
  48. package/Sources/CCPets/UI/CCPetsSettingsPage.h +4 -1
  49. package/Sources/CCPets/UI/CCPetsSettingsPage.m +16 -0
  50. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  51. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  52. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +5 -3
  53. package/package.json +1 -1
@@ -202,15 +202,73 @@ static NSString *CodexApprovalBlock(NSArray<NSString *> *tools) {
202
202
  return [lines componentsJoinedByString:@"\n"];
203
203
  }
204
204
 
205
- static NSString *StripTomlBlocks(NSString *text) {
205
+ typedef NS_ENUM(NSInteger, TomlLexState) {
206
+ TomlLexNormal,
207
+ TomlLexMultilineBasic,
208
+ TomlLexMultilineLiteral
209
+ };
210
+
211
+ // 扫过一行,返回行尾的词法状态。只关心多行字符串:字符串里的内容长得再像管理块也是用户的数据。
212
+ static TomlLexState AdvanceTomlState(NSString *line, TomlLexState state) {
213
+ NSUInteger length = line.length;
214
+ BOOL (^startsWith)(NSUInteger, NSString *) = ^BOOL(NSUInteger index, NSString *text) {
215
+ return index + text.length <= length &&
216
+ [[line substringWithRange:NSMakeRange(index, text.length)] isEqualToString:text];
217
+ };
218
+ for (NSUInteger index = 0; index < length; index++) {
219
+ unichar character = [line characterAtIndex:index];
220
+ if (state == TomlLexMultilineBasic) {
221
+ if (character == '\\') index++;
222
+ else if (startsWith(index, @"\"\"\"")) { state = TomlLexNormal; index += 2; }
223
+ } else if (state == TomlLexMultilineLiteral) {
224
+ if (startsWith(index, @"'''")) { state = TomlLexNormal; index += 2; }
225
+ } else if (character == '#') {
226
+ return state;
227
+ } else if (startsWith(index, @"\"\"\"")) {
228
+ state = TomlLexMultilineBasic;
229
+ index += 2;
230
+ } else if (startsWith(index, @"'''")) {
231
+ state = TomlLexMultilineLiteral;
232
+ index += 2;
233
+ } else if (character == '"' || character == '\'') {
234
+ for (index++; index < length && [line characterAtIndex:index] != character; index++) {
235
+ if (character == '"' && [line characterAtIndex:index] == '\\') index++;
236
+ }
237
+ }
238
+ }
239
+ return state;
240
+ }
241
+
242
+ // lines[start] 是管理块的起始标记时返回结束标记所在行,否则 NSNotFound。没有结束标记的不算管理块。
243
+ static NSUInteger TomlBlockEnd(NSArray<NSString *> *lines, NSUInteger start) {
244
+ NSCharacterSet *whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet;
245
+ NSString *first = [lines[start] stringByTrimmingCharactersInSet:whitespace];
206
246
  for (NSArray<NSString *> *block in TomlBlocks()) {
207
- NSString *pattern = [NSString stringWithFormat:@"\\n?%@[\\s\\S]*?%@\\n?",
208
- [NSRegularExpression escapedPatternForString:block[0]], [NSRegularExpression escapedPatternForString:block[1]]];
209
- NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
210
- text = [expression stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@"\n"];
247
+ if (![first isEqualToString:block[0]]) continue;
248
+ for (NSUInteger index = start + 1; index < lines.count; index++) {
249
+ if ([[lines[index] stringByTrimmingCharactersInSet:whitespace] isEqualToString:block[1]]) return index;
250
+ }
251
+ }
252
+ return NSNotFound;
253
+ }
254
+
255
+ // 只移除自己的管理块和安装时加在它前面的那一个空行,其余内容逐字保留:
256
+ // config.toml 是用户的文件,多行字符串里的空行也是值的一部分。
257
+ static NSString *StripTomlBlocks(NSString *text) {
258
+ NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
259
+ NSMutableArray<NSString *> *kept = [NSMutableArray array];
260
+ TomlLexState state = TomlLexNormal;
261
+ for (NSUInteger index = 0; index < lines.count; index++) {
262
+ NSUInteger end = state == TomlLexNormal ? TomlBlockEnd(lines, index) : NSNotFound;
263
+ if (end != NSNotFound) {
264
+ if ([kept.lastObject isEqualToString:@""]) [kept removeLastObject];
265
+ index = end;
266
+ continue;
267
+ }
268
+ [kept addObject:lines[index]];
269
+ state = AdvanceTomlState(lines[index], state);
211
270
  }
212
- NSRegularExpression *blank = [NSRegularExpression regularExpressionWithPattern:@"\\n{3,}" options:0 error:nil];
213
- return [blank stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@"\n\n"];
271
+ return [kept componentsJoinedByString:@"\n"];
214
272
  }
215
273
 
216
274
  static void SetCodexApprovalAtHome(NSArray<NSString *> *tools, NSString *codexHome) {
@@ -219,13 +277,11 @@ static void SetCodexApprovalAtHome(NSArray<NSString *> *tools, NSString *codexHo
219
277
  BOOL exists = stat(file.fileSystemRepresentation, &info) == 0;
220
278
  NSString *original = exists ? [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] : @"";
221
279
  if (!original) [NSException raise:@"CCBridgeConfig" format:@"Cannot read %@", file];
222
- // 只把末尾的空白收成一个换行:开头的空白属于用户的文件,原样保留。
223
- NSString *stripped = StripTomlBlocks(original);
224
- NSUInteger end = stripped.length;
225
- NSCharacterSet *whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet;
226
- while (end > 0 && [whitespace characterIsMember:[stripped characterAtIndex:end - 1]]) end--;
227
- NSString *updated = [[stripped substringToIndex:end] stringByAppendingString:@"\n"];
228
- if (tools.count > 0) updated = [updated stringByAppendingFormat:@"\n%@\n", CodexApprovalBlock(tools)];
280
+ NSString *updated = StripTomlBlocks(original);
281
+ if (tools.count > 0) {
282
+ if (updated.length > 0 && ![updated hasSuffix:@"\n"]) updated = [updated stringByAppendingString:@"\n"];
283
+ updated = [updated stringByAppendingFormat:updated.length > 0 ? @"\n%@\n" : @"%@\n", CodexApprovalBlock(tools)];
284
+ }
229
285
  if ([updated isEqualToString:original]) return;
230
286
  NSString *error = nil;
231
287
  if (!CCPetsWriteFileAtomically(file, updated, exists ? (info.st_mode & 0777) : 0600, &error)) {
@@ -233,16 +289,8 @@ static void SetCodexApprovalAtHome(NSArray<NSString *> *tools, NSString *codexHo
233
289
  }
234
290
  }
235
291
 
236
- static void SetCodexApproval(NSArray<NSString *> *tools) {
237
- SetCodexApprovalAtHome(tools, CCPetsCodexHome());
238
- }
239
-
240
292
  #pragma mark - MCP
241
293
 
242
- static BOOL RunQuietly(NSString *executable, NSArray<NSString *> *arguments) {
243
- return CCPetsRun(executable, arguments, nil, nil, 60, NULL, NULL) == 0;
244
- }
245
-
246
294
  static BOOL RunQuietlyForHome(NSString *executable, NSArray<NSString *> *arguments,
247
295
  NSString *provider, NSString *home) {
248
296
  NSMutableDictionary<NSString *, NSString *> *environment =
@@ -365,6 +413,145 @@ NSArray<NSString *> *CCBridgeInstallForProfile(NSDictionary *profile, NSDictiona
365
413
  return report;
366
414
  }
367
415
 
416
+ static NSUInteger TomlSkipSpaces(NSString *text, NSUInteger index) {
417
+ while (index < text.length && ([text characterAtIndex:index] == ' ' || [text characterAtIndex:index] == '\t')) index++;
418
+ return index;
419
+ }
420
+
421
+ // index 指向开引号,返回闭引号的位置;没有闭引号时返回 text.length。
422
+ static NSUInteger TomlStringEnd(NSString *text, NSUInteger index) {
423
+ unichar quote = [text characterAtIndex:index];
424
+ for (index++; index < text.length && [text characterAtIndex:index] != quote; index++) {
425
+ if (quote == '"' && [text characterAtIndex:index] == '\\') index++;
426
+ }
427
+ return MIN(index, text.length);
428
+ }
429
+
430
+ // 双引号键的转义要先解码才能比较:`"cc-bridge"` 就是 cc-bridge。不合法的转义按原样保留。
431
+ static NSString *TomlDecodeBasicString(NSString *text) {
432
+ if (![text containsString:@"\\"]) return text;
433
+ NSDictionary<NSString *, NSString *> *simple = @{@"b": @"\b", @"t": @"\t", @"n": @"\n", @"f": @"\f", @"r": @"\r",
434
+ @"e": @"\033", @"\"": @"\"", @"\\": @"\\"};
435
+ NSDictionary<NSString *, NSNumber *> *numeric = @{@"x": @2, @"u": @4, @"U": @8};
436
+ NSCharacterSet *notHex = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"].invertedSet;
437
+ NSMutableString *decoded = [NSMutableString string];
438
+ for (NSUInteger index = 0; index < text.length; index++) {
439
+ unichar character = [text characterAtIndex:index];
440
+ if (character != '\\' || index + 1 >= text.length) {
441
+ [decoded appendFormat:@"%C", character];
442
+ continue;
443
+ }
444
+ NSString *escape = [text substringWithRange:NSMakeRange(++index, 1)];
445
+ if (simple[escape]) {
446
+ [decoded appendString:simple[escape]];
447
+ continue;
448
+ }
449
+ NSUInteger digits = numeric[escape].unsignedIntegerValue;
450
+ NSString *hex = digits > 0 && index + digits < text.length
451
+ ? [text substringWithRange:NSMakeRange(index + 1, digits)] : nil;
452
+ uint32_t scalar = hex ? (uint32_t)strtoul(hex.UTF8String, NULL, 16) : 0;
453
+ BOOL valid = hex && [hex rangeOfCharacterFromSet:notHex].location == NSNotFound &&
454
+ scalar <= 0x10FFFF && (scalar < 0xD800 || scalar > 0xDFFF);
455
+ if (!valid) {
456
+ [decoded appendFormat:@"\\%@", escape];
457
+ continue;
458
+ }
459
+ [decoded appendString:[[NSString alloc] initWithBytes:&scalar length:sizeof scalar encoding:NSUTF32LittleEndianStringEncoding]];
460
+ index += digits;
461
+ }
462
+ return decoded;
463
+ }
464
+
465
+ // 从 cursor 读一个键路径(每一级可以是裸键或带引号),停在路径后第一个非空白字符上。不是键时返回 nil。
466
+ static NSArray<NSString *> *TomlParseKey(NSString *text, NSUInteger *cursor) {
467
+ NSMutableCharacterSet *bare = [NSMutableCharacterSet alphanumericCharacterSet];
468
+ [bare addCharactersInString:@"_-"];
469
+ NSMutableArray<NSString *> *path = [NSMutableArray array];
470
+ NSUInteger index = *cursor;
471
+ while (YES) {
472
+ index = TomlSkipSpaces(text, index);
473
+ if (index >= text.length) return nil;
474
+ unichar character = [text characterAtIndex:index];
475
+ if (character == '"' || character == '\'') {
476
+ NSUInteger end = TomlStringEnd(text, index);
477
+ if (end >= text.length) return nil;
478
+ NSString *key = [text substringWithRange:NSMakeRange(index + 1, end - index - 1)];
479
+ [path addObject:character == '"' ? TomlDecodeBasicString(key) : key];
480
+ index = end + 1;
481
+ } else {
482
+ NSUInteger start = index;
483
+ while (index < text.length && [bare characterIsMember:[text characterAtIndex:index]]) index++;
484
+ if (index == start) return nil;
485
+ [path addObject:[text substringWithRange:NSMakeRange(start, index - start)]];
486
+ }
487
+ index = TomlSkipSpaces(text, index);
488
+ if (index >= text.length || [text characterAtIndex:index] != '.') break;
489
+ index++;
490
+ }
491
+ *cursor = index;
492
+ return path;
493
+ }
494
+
495
+ // index 指向 { 之后:这张 inline table 的第一层是否有名为 name 的键。
496
+ static BOOL TomlInlineTableHasKey(NSString *text, NSUInteger index, NSString *name) {
497
+ while (YES) {
498
+ NSArray<NSString *> *key = TomlParseKey(text, &index);
499
+ if (!key || index >= text.length || [text characterAtIndex:index] != '=') return NO;
500
+ if ([key.firstObject isEqualToString:name]) return YES;
501
+ NSInteger depth = 0;
502
+ for (index++; index < text.length; index++) {
503
+ unichar character = [text characterAtIndex:index];
504
+ if (character == '"' || character == '\'') {
505
+ index = TomlStringEnd(text, index);
506
+ } else if (character == '{' || character == '[') {
507
+ depth++;
508
+ } else if (character == '}' || character == ']') {
509
+ if (depth == 0) return NO;
510
+ depth--;
511
+ } else if (character == ',' && depth == 0) {
512
+ break;
513
+ }
514
+ }
515
+ if (index >= text.length) return NO;
516
+ index++;
517
+ }
518
+ }
519
+
520
+ // 只认 mcp_servers 下这个服务器的声明:表头、点号键、[mcp_servers] 表里的键,以及 inline table,
521
+ // 每一级都可以带引号。项目路径、其他服务器的参数里出现同样的文字都不算,否则卸载会误报"移除失败";
522
+ // 真正的声明也不能漏,否则会跳过 mcp remove,注册还在却报告成功。
523
+ static BOOL TomlDeclaresMCPServer(NSString *text, NSString *name) {
524
+ BOOL (^isServer)(NSArray<NSString *> *) = ^BOOL(NSArray<NSString *> *path) {
525
+ return path.count >= 2 && [path[0] isEqualToString:@"mcp_servers"] && [path[1] isEqualToString:name];
526
+ };
527
+ TomlLexState state = TomlLexNormal;
528
+ NSArray<NSString *> *table = @[];
529
+ for (NSString *line in [text componentsSeparatedByString:@"\n"]) {
530
+ if (state == TomlLexNormal) {
531
+ NSUInteger index = TomlSkipSpaces(line, 0);
532
+ if (index < line.length && [line characterAtIndex:index] == '[') {
533
+ index += index + 1 < line.length && [line characterAtIndex:index + 1] == '[' ? 2 : 1;
534
+ NSArray<NSString *> *header = TomlParseKey(line, &index);
535
+ if (header && index < line.length && [line characterAtIndex:index] == ']') {
536
+ if (isServer(header)) return YES;
537
+ table = header;
538
+ }
539
+ } else {
540
+ NSArray<NSString *> *key = TomlParseKey(line, &index);
541
+ if (key && index < line.length && [line characterAtIndex:index] == '=') {
542
+ NSArray<NSString *> *path = [table arrayByAddingObjectsFromArray:key];
543
+ if (isServer(path)) return YES;
544
+ NSUInteger value = TomlSkipSpaces(line, index + 1);
545
+ if ([path isEqualToArray:@[@"mcp_servers"]] && value < line.length && [line characterAtIndex:value] == '{' &&
546
+ TomlInlineTableHasKey(line, value + 1, name)) return YES;
547
+ }
548
+ }
549
+ }
550
+ state = AdvanceTomlState(line, state);
551
+ }
552
+ return NO;
553
+ }
554
+
368
555
  // remove 对“本来就不存在”的注册也可能返回非零;只有确认不存在才按成功处理。
369
556
  static BOOL HasMCPRegistration(NSString *provider, NSString *home, NSString *name) {
370
557
  if ([provider isEqualToString:@"claude"]) {
@@ -380,12 +567,7 @@ static BOOL HasMCPRegistration(NSString *provider, NSString *home, NSString *nam
380
567
  if (![NSFileManager.defaultManager fileExistsAtPath:file]) return NO;
381
568
  NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
382
569
  if (!text) [NSException raise:@"CCBridgeConfig" format:@"Cannot read %@", file];
383
- // 常规表、带引号的键和 inline table 均保守识别;不能把读取失败当成已卸载。
384
- for (NSString *line in [text componentsSeparatedByString:@"\n"]) {
385
- NSString *trimmed = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
386
- if (![trimmed hasPrefix:@"#"] && [trimmed containsString:name]) return YES;
387
- }
388
- return NO;
570
+ return TomlDeclaresMCPServer(text, name);
389
571
  }
390
572
 
391
573
  static void RemoveMCPRegistration(NSString *executable, NSString *provider, NSString *home,
@@ -428,66 +610,6 @@ NSArray<NSString *> *CCBridgeUninstallForProfile(NSDictionary *profile, BOOL unr
428
610
  return report;
429
611
  }
430
612
 
431
- NSArray<NSString *> *CCBridgeInstall(NSDictionary *rawOptions, BOOL registerMcp) {
432
- NSDictionary *options = CCBridgeNormalizeOptions(rawOptions);
433
- NSArray<NSString *> *claudeAllow = options[@"claudeAllow"];
434
- NSArray<NSString *> *codexApprove = options[@"codexApprove"];
435
- NSMutableArray<NSString *> *report = [NSMutableArray array];
436
- if (CCPetsClaudeCLIInstalled()) {
437
- [NSFileManager.defaultManager createDirectoryAtPath:CCPetsClaudeHome() withIntermediateDirectories:YES attributes:nil error:nil];
438
- NSString *settingsPath = [CCPetsClaudeHome() stringByAppendingPathComponent:@"settings.json"];
439
- CCPetsJSONObject *config = ReadJSONConfig(settingsPath);
440
- StripBridgeHooks(config);
441
- AddClaudeHooks(config, options, nil);
442
- ApplyClaudeAllow(config, claudeAllow);
443
- WriteJSONConfig(settingsPath, config);
444
- [report addObject:LF(L(@"Claude Code hooks written to {path}"), @{@"path": settingsPath})];
445
- [report addObject:claudeAllow.count > 0
446
- ? LF(L(@"Claude Code allows these tools without asking: {claudeAllow}"), @{@"claudeAllow": [claudeAllow componentsJoinedByString:@", "]})
447
- : L(@"In Claude Code, cc-bridge tools follow your permission settings.")];
448
- if (registerMcp) {
449
- NSString *claude = CCPetsFindRealExecutable(@"claude", @"CLAUDE_REAL_BIN");
450
- for (NSString *name in MCPNames()) RunQuietly(claude ?: @"claude", @[@"mcp", @"remove", @"--scope", @"user", name]);
451
- BOOL ok = claude && RunQuietly(claude, ClaudeMCPAddArguments());
452
- [report addObject:ok
453
- ? LF(L(@"Claude Code MCP registered: {MCP_NAME} (on first use, Claude asks according to your permission settings)"), @{@"MCP_NAME": CCBridgeMCPName})
454
- : LF(L(@"Claude Code MCP registration failed. Run manually: claude {shellQuote}"), @{@"shellQuote": QuotedArguments(ClaudeMCPAddArguments())})];
455
- }
456
- } else {
457
- [report addObject:L(@"Claude Code CLI not detected, skipped.")];
458
- }
459
-
460
- if (CCPetsCodexCLIInstalled()) {
461
- [NSFileManager.defaultManager createDirectoryAtPath:CCPetsCodexHome() withIntermediateDirectories:YES attributes:nil error:nil];
462
- NSString *hooksPath = [CCPetsCodexHome() stringByAppendingPathComponent:@"hooks.json"];
463
- CCPetsJSONObject *config = ReadJSONConfig(hooksPath);
464
- StripBridgeHooks(config);
465
- AddCodexHooks(config, options, nil);
466
- WriteJSONConfig(hooksPath, config);
467
- [report addObject:LF(L(@"Codex hooks written to {path}. Next time you start Codex, run /hooks and trust the cc-pets bridge hooks."), @{@"path": hooksPath})];
468
- if (registerMcp) {
469
- NSString *codex = CCPetsFindRealExecutable(@"codex", @"CODEX_REAL_BIN");
470
- for (NSString *name in MCPNames()) RunQuietly(codex ?: @"codex", @[@"mcp", @"remove", name]);
471
- BOOL ok = codex && RunQuietly(codex, CodexMCPAddArguments());
472
- [report addObject:ok
473
- ? LF(L(@"Codex MCP registered: {MCP_NAME}"), @{@"MCP_NAME": CCBridgeMCPName})
474
- : LF(L(@"Codex MCP registration failed. Run manually: codex {shellQuote}"), @{@"shellQuote": QuotedArguments(CodexMCPAddArguments())})];
475
- // 只在 enable / refresh 时探测:configure 由桌宠菜单开关触发,不值得每次多拉起两次 codex。
476
- if ([options[@"wake"] boolValue]) {
477
- NSString *notice = CCBridgeDescribeCodexQueue(CCBridgeProbeCodexQueue(codex));
478
- if (notice) [report addObject:notice];
479
- }
480
- }
481
- SetCodexApproval(codexApprove);
482
- [report addObject:codexApprove.count > 0
483
- ? LF(L(@"Codex auto-approves these tools: {codexApprove} (restart Codex sessions to apply)"), @{@"codexApprove": [codexApprove componentsJoinedByString:@", "]})
484
- : L(@"cc-bridge tools keep Codex's default approvals (calls fail under approval_policy=never; allow them with --codex-approve).")];
485
- } else {
486
- [report addObject:L(@"Codex CLI not detected, skipped.")];
487
- }
488
- return report;
489
- }
490
-
491
613
  // 文件不存在、或里面本来就没有我们的东西时不改写——用户的文件不该因为一次卸载被重排格式。
492
614
  static BOOL RemoveJSONHooks(NSString *file, BOOL claudeAllow) {
493
615
  if (![NSFileManager.defaultManager fileExistsAtPath:file]) return NO;
@@ -498,10 +620,3 @@ static BOOL RemoveJSONHooks(NSString *file, BOOL claudeAllow) {
498
620
  WriteJSONConfig(file, config);
499
621
  return YES;
500
622
  }
501
-
502
- NSArray<NSString *> *CCBridgeUninstall(BOOL unregisterMcp) {
503
- NSMutableArray *report = [NSMutableArray array];
504
- [report addObjectsFromArray:CCBridgeUninstallForProfile(@{@"provider": @"claude", @"home": CCPetsClaudeHome()}, unregisterMcp)];
505
- [report addObjectsFromArray:CCBridgeUninstallForProfile(@{@"provider": @"codex", @"home": CCPetsCodexHome()}, unregisterMcp)];
506
- return report;
507
- }
@@ -51,6 +51,12 @@ NSArray<NSDictionary *> *CCBridgeListSessions(void);
51
51
  void CCBridgeRemoveSession(id sessionId);
52
52
  void CCBridgeRemoveSessionIfOffline(id sessionId);
53
53
  NSString *CCBridgeNormalizeSessionName(id value);
54
+ // 仅对标记为自动生成的名字去掉账号段;自定义名字及旧记录保持原名。
55
+ NSString *CCBridgeSessionShortName(NSDictionary *session);
56
+ // 中文界面下自动名称的动物别名;其他语言、自定义名称和旧记录返回空串。
57
+ NSString *CCBridgeSessionAnimalAlias(NSDictionary *session);
58
+ // 仅供展示,不可作为消息地址;原 name / ref 始终保持不变。
59
+ NSString *CCBridgeSessionDisplayName(NSDictionary *session);
54
60
  // liveSessions 参数保留兼容;名字分配/改名在注册表锁内重新读取在线会话,避免使用过期快照。
55
61
  NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
56
62
  NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
@@ -67,7 +73,8 @@ NSDictionary *CCBridgeUpdateReceipt(NSString *messageId, NSDictionary *patch);
67
73
  NSArray<NSDictionary *> *CCBridgeListReceipts(void);
68
74
  // 发送前的配额检查。nil 表示放行,否则返回拒绝原因。
69
75
  NSString *CCBridgeCheckSendLimits(NSString *fromSession, NSString *toSession);
70
- void CCBridgeEnqueueInbox(NSDictionary *message);
76
+ // 写入目标信箱。返回 nil 表示成功;Bridge 已关闭或目标已离线时不写入,返回拒绝原因。
77
+ NSString *CCBridgeEnqueueInbox(NSDictionary *message);
71
78
  // 认领并持有信箱锁:恢复上次未确认的 claimed;调用方必须在输出后 FinishInbox。
72
79
  NSArray<NSDictionary *> *CCBridgeClaimInbox(id sessionId);
73
80
  // transport 非 nil 表示输出成功;nil 保留消息供重试。两种情况都会释放锁。
@@ -75,6 +82,12 @@ void CCBridgeFinishInbox(id sessionId, NSArray<NSDictionary *> *messages, NSStri
75
82
  NSUInteger CCBridgePendingCount(id sessionId);
76
83
  // 会话结束:信箱里还没投出去的消息标记为 undeliverable。
77
84
  void CCBridgeAbandonInbox(id sessionId);
85
+ // 同上,但用于没有 SessionEnd 的离线会话(崩溃、被杀):连同它的空闲订阅一起清掉;锁繁忙或会话又上线时不动。
86
+ void CCBridgeAbandonOfflineSession(id sessionId);
87
+ // 关闭 Bridge:之后不会再有 hook 来清理,所有未投递的消息现在就标记 undeliverable 并删除。
88
+ void CCBridgeAbandonAllInboxes(NSString *reason);
89
+ // 扫描状态目录:离线会话按上面处理,在线会话里超过 TTL 的消息标记为 expired。锁繁忙的留给下一次。
90
+ void CCBridgeSweepMessages(void);
78
91
  void CCBridgePruneReceipts(void);
79
92
 
80
93
  #pragma mark - 空闲订阅(一次性)
@@ -82,20 +95,32 @@ void CCBridgePruneReceipts(void);
82
95
  void CCBridgeAddIdleSubscription(NSString *targetSession, NSString *subscriberSession);
83
96
  BOOL CCBridgeHasIdleSubscriptions(NSString *targetSession);
84
97
  NSArray<NSString *> *CCBridgeTakeIdleSubscriptions(NSString *targetSession);
98
+ void CCBridgeClearIdleSubscriptions(id targetSession);
99
+
100
+ #pragma mark - watcher 接替
101
+
102
+ // 新 watcher 登记后,旧的在下次轮询时退出,新的拿到锁并重新计时:每轮结束都能续满等待时间。
103
+ NSString *CCBridgeClaimWatcher(NSString *sessionId);
104
+ BOOL CCBridgeWatcherOwned(NSString *sessionId, NSString *token);
105
+ // 会话结束:清掉登记,还在等待的 watcher 随之退出。
106
+ void CCBridgeDropWatcher(id sessionId);
85
107
 
86
108
  #pragma mark - 锁
87
109
 
88
110
  // 稳定 inode 上的 flock;PID 文件只作诊断。进程退出自动释放,成功返回诊断文件路径。
89
111
  NSString *CCBridgeAcquireLock(NSString *name);
90
112
  void CCBridgeReleaseLock(NSString *lockFile);
113
+ // 等锁(有上限,超时抛异常)后执行 body。锁不可重入,body 里不能再取同名锁。
114
+ id CCBridgeWithLock(NSString *name, id (^body)(void));
91
115
 
92
116
  #pragma mark - 进程探测
93
117
 
94
118
  BOOL CCBridgeProcessAlive(pid_t pid);
95
- NSString *CCBridgeProcessCommand(pid_t pid);
119
+ // 进程的 argv,元素边界与启动时一致;读不到时返回 nil。
120
+ NSArray<NSString *> *CCBridgeProcessArguments(pid_t pid);
96
121
  // CLI 进程的控制终端,如 "ttys003";没有时返回 nil。
97
122
  NSString *CCBridgeProcessTty(pid_t pid);
98
- BOOL CCBridgeCommandMatchesProvider(NSString *provider, NSString *command);
123
+ BOOL CCBridgeArgumentsMatchProvider(NSString *provider, NSArray<NSString *> *arguments);
99
124
  // 离 startPid 最近的 Claude / Codex 祖先进程:@{provider, pid}。CC_BRIDGE_AGENT=Codex:1234 可强制指定。
100
125
  NSDictionary *CCBridgeFindAgentAncestor(pid_t startPid);
101
126
  // 有 pid 时以"进程还在且仍是同一种 CLI"为准(防 pid 复用);没有 pid 的记录退回 6 小时活动窗口。