cc-pets 2.3.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 (101) hide show
  1. package/CC_BRIDGE.md +63 -7
  2. package/CC_BRIDGE.zh-CN.md +43 -5
  3. package/CHANGELOG.md +106 -0
  4. package/CHANGELOG.zh-CN.md +106 -0
  5. package/CONTRIBUTING.md +23 -1
  6. package/CONTRIBUTING.zh-CN.md +18 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +177 -33
  10. package/README.zh-CN.md +137 -32
  11. package/Resources/AgentIcons/claude.png +0 -0
  12. package/Resources/AgentIcons/codex.icns +0 -0
  13. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  14. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  15. package/Resources/zh-Hans.lproj/Localizable.strings +187 -35
  16. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +47 -4
  17. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +121 -20
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +8 -6
  19. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +14 -1
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +6 -1
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +118 -50
  24. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +4 -1
  25. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +4 -0
  26. package/Sources/CCPets/App/CCPetsAppDelegate.h +12 -2
  27. package/Sources/CCPets/App/CCPetsAppDelegate.m +4 -2
  28. package/Sources/CCPets/App/main.m +6 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +45 -18
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +175 -68
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +14 -6
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +356 -110
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  34. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +247 -126
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +37 -9
  36. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +385 -80
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  39. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  40. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +1 -1
  42. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  43. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  44. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +8 -1
  45. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +156 -25
  46. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  47. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  48. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  49. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  50. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  51. package/Sources/CCPets/Pet/PetView+Menu.m +11 -3
  52. package/Sources/CCPets/Pet/PetView.h +7 -0
  53. package/Sources/CCPets/Pet/PetView.m +12 -1
  54. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  55. package/Sources/CCPets/Support/CCPetsPreferences.h +12 -0
  56. package/Sources/CCPets/Support/CCPetsPreferences.m +52 -2
  57. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  58. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  59. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  60. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  61. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  62. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  63. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  64. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +528 -0
  65. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  66. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +95 -0
  67. package/Sources/CCPets/UI/CCPetsSettingsPage.h +6 -1
  68. package/Sources/CCPets/UI/CCPetsSettingsPage.m +577 -66
  69. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  70. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  71. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  72. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  73. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  74. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  75. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  76. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +5 -3
  77. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  78. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  79. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  80. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  81. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  82. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  83. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  84. package/THIRD_PARTY_NOTICES.md +7 -3
  85. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  86. package/bin/claude-with-pet +2 -0
  87. package/bin/codex-with-pet +2 -0
  88. package/package.json +5 -1
  89. package/plugins/jetbrains/README.md +62 -0
  90. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  91. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  92. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  93. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  94. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  95. package/plugins/vscode/README.md +63 -0
  96. package/plugins/vscode/extension.js +210 -0
  97. package/plugins/vscode/package.json +18 -0
  98. package/scripts/build-idea-plugin.sh +101 -0
  99. package/scripts/build-vscode-extension.sh +112 -0
  100. package/scripts/build.sh +24 -2
  101. package/scripts/compile-cached.zsh +133 -0
@@ -6,6 +6,7 @@
6
6
  #import <CommonCrypto/CommonDigest.h>
7
7
  #import <sys/sysctl.h>
8
8
  #import <sys/stat.h>
9
+ #import <sys/file.h>
9
10
  #import <fcntl.h>
10
11
  #import <signal.h>
11
12
  #import <unistd.h>
@@ -39,6 +40,10 @@ static NSString *RandomHex(NSUInteger bytes) {
39
40
  return hex;
40
41
  }
41
42
 
43
+ static BOOL IsTerminalStatus(id status) {
44
+ return [@[@"delivered", @"expired", @"undeliverable"] containsObject:status ?: @""];
45
+ }
46
+
42
47
  NSString *CCBridgeSHA1Hex(NSString *text) {
43
48
  NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
44
49
  unsigned char digest[CC_SHA1_DIGEST_LENGTH];
@@ -75,7 +80,8 @@ BOOL CCBridgeMigrateLegacyFlag(void) {
75
80
 
76
81
  void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options) {
77
82
  if (!enabled) {
78
- unlink(EnabledFlagPath().fileSystemRepresentation);
83
+ if (unlink(EnabledFlagPath().fileSystemRepresentation) != 0 && errno != ENOENT)
84
+ [NSException raise:@"CCBridgeConfig" format:@"%@: %s", EnabledFlagPath(), strerror(errno)];
79
85
  return;
80
86
  }
81
87
  EnsureHomeDirectory();
@@ -85,7 +91,9 @@ void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options) {
85
91
  NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
86
92
  formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
87
93
  document[@"enabledAt"] = [formatter stringFromDate:NSDate.date];
88
- CCPetsWriteFileAtomically(EnabledFlagPath(), [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, NULL);
94
+ NSString *error = nil;
95
+ if (!CCPetsWriteFileAtomically(EnabledFlagPath(), [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, &error))
96
+ [NSException raise:@"CCBridgeConfig" format:@"%@", error ?: @"Could not save bridge settings"];
89
97
  }
90
98
 
91
99
  void CCBridgeWriteCLILocator(void) {
@@ -247,6 +255,23 @@ static NSArray<NSString *> *ListJSON(NSString *directory) {
247
255
  return [names sortedArrayUsingSelector:@selector(compare:)];
248
256
  }
249
257
 
258
+ static NSString *WaitForLock(NSString *name) {
259
+ // hook 有执行时限;锁繁忙时明确失败,不能无锁继续覆盖状态。
260
+ for (NSUInteger attempt = 0; attempt < 200; attempt++) {
261
+ NSString *lock = CCBridgeAcquireLock(name);
262
+ if (lock) return lock;
263
+ usleep(10000);
264
+ }
265
+ [NSException raise:@"CCBridgeLock" format:@"Timed out waiting for bridge lock: %@", name];
266
+ return nil;
267
+ }
268
+
269
+ id CCBridgeWithLock(NSString *name, id (^body)(void)) {
270
+ NSString *lock = WaitForLock(name);
271
+ @try { return body(); }
272
+ @finally { CCBridgeReleaseLock(lock); }
273
+ }
274
+
250
275
  #pragma mark - 会话注册表
251
276
 
252
277
  NSString *CCBridgeSessionRef(NSString *sessionId) {
@@ -276,7 +301,27 @@ NSArray<NSDictionary *> *CCBridgeListSessions(void) {
276
301
 
277
302
  void CCBridgeRemoveSession(id sessionId) {
278
303
  NSString *safe = CCBridgeSafeSessionId(sessionId);
279
- if (safe) unlink(SessionFile(safe).fileSystemRepresentation);
304
+ if (!safe) return;
305
+ NSString *lock = WaitForLock(@"sessions");
306
+ @try { unlink(SessionFile(safe).fileSystemRepresentation); }
307
+ @finally { CCBridgeReleaseLock(lock); }
308
+ }
309
+
310
+ void CCBridgeRemoveSessionIfOffline(id sessionId) {
311
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
312
+ if (!safe) return;
313
+ NSString *lock = WaitForLock(@"sessions");
314
+ @try {
315
+ if (!CCBridgeSessionLive(CCBridgeReadSession(safe))) unlink(SessionFile(safe).fileSystemRepresentation);
316
+ } @finally { CCBridgeReleaseLock(lock); }
317
+ }
318
+
319
+ static NSArray<NSDictionary *> *RegisteredLiveSessions(void) {
320
+ NSMutableArray *sessions = [NSMutableArray array];
321
+ for (NSDictionary *session in CCBridgeListSessions()) {
322
+ if (CCBridgeSessionLive(session)) [sessions addObject:session];
323
+ }
324
+ return sessions;
280
325
  }
281
326
 
282
327
  // 小写,连续的非 [a-z0-9] 合并成 -,截到 limit 后去掉首尾的 -;结果可能为空。
@@ -311,6 +356,51 @@ static NSArray<NSString *> *NameAnimals(void) {
311
356
  return animals;
312
357
  }
313
358
 
359
+ NSString *CCBridgeSessionAnimalAlias(NSDictionary *session) {
360
+ if (![CCPetsCurrentLanguage() hasPrefix:@"zh"] ||
361
+ ![StringValue(session[@"nameSource"]) isEqualToString:@"generated"]) return @"";
362
+ static NSDictionary<NSString *, NSString *> *aliases;
363
+ static dispatch_once_t once;
364
+ dispatch_once(&once, ^{
365
+ aliases = @{
366
+ @"otter": @"水獭", @"panda": @"熊猫", @"quokka": @"短尾矮袋鼠", @"corgi": @"柯基", @"koala": @"考拉",
367
+ @"capy": @"水豚", @"puffin": @"海鹦", @"lemur": @"狐猴", @"alpaca": @"羊驼", @"wombat": @"袋熊",
368
+ @"bunny": @"小兔", @"kitten": @"小猫", @"puppy": @"小狗", @"hamster": @"仓鼠", @"fox": @"狐狸",
369
+ @"owl": @"猫头鹰", @"seal": @"海豹", @"penguin": @"企鹅", @"duck": @"鸭子", @"llama": @"美洲驼",
370
+ @"sloth": @"树懒", @"fennec": @"耳廓狐", @"bear": @"熊", @"cub": @"幼崽", @"lamb": @"小羊",
371
+ @"fawn": @"小鹿", @"deer": @"鹿", @"dolphin": @"海豚", @"beluga": @"白鲸", @"orca": @"虎鲸",
372
+ @"narwhal": @"独角鲸", @"walrus": @"海象", @"manatee": @"海牛", @"turtle": @"乌龟", @"frog": @"青蛙",
373
+ @"gecko": @"壁虎", @"chick": @"小鸡", @"robin": @"知更鸟", @"finch": @"雀鸟", @"wren": @"鹪鹩",
374
+ @"sparrow": @"麻雀", @"toucan": @"巨嘴鸟", @"parrot": @"鹦鹉", @"macaw": @"金刚鹦鹉", @"dove": @"鸽子",
375
+ @"swan": @"天鹅", @"owlet": @"小猫头鹰", @"goose": @"鹅", @"koi": @"锦鲤", @"bee": @"蜜蜂",
376
+ @"ladybug": @"瓢虫", @"raccoon": @"浣熊", @"ferret": @"雪貂", @"badger": @"獾", @"beaver": @"河狸",
377
+ @"marmot": @"旱獭", @"meerkat": @"狐獴", @"mouse": @"小鼠", @"gerbil": @"沙鼠", @"pony": @"矮马",
378
+ @"foal": @"小马驹", @"piglet": @"小猪", @"calf": @"小牛", @"giraffe": @"长颈鹿", @"zebra": @"斑马",
379
+ @"hippo": @"河马", @"rhino": @"犀牛", @"tapir": @"貘", @"okapi": @"霍加狓", @"lynx": @"猞猁",
380
+ @"tiger": @"老虎", @"cheetah": @"猎豹", @"lion": @"狮子", @"husky": @"哈士奇", @"shiba": @"柴犬",
381
+ @"beagle": @"比格犬", @"pug": @"巴哥犬", @"poodle": @"贵宾犬", @"collie": @"柯利犬", @"dingo": @"澳洲野犬",
382
+ @"newt": @"蝾螈", @"tadpole": @"蝌蚪", @"octopus": @"章鱼", @"squid": @"鱿鱼", @"crab": @"螃蟹",
383
+ @"snail": @"蜗牛", @"peacock": @"孔雀", @"emu": @"鸸鹋", @"quail": @"鹌鹑", @"magpie": @"喜鹊",
384
+ @"kea": @"啄羊鹦鹉", @"heron": @"鹭鸟", @"stork": @"鹳", @"ibis": @"朱鹭", @"numbat": @"袋食蚁兽",
385
+ @"bilby": @"兔耳袋狸", @"possum": @"负鼠", @"dugong": @"儒艮", @"yak": @"牦牛", @"bison": @"野牛",
386
+ };
387
+ });
388
+ NSArray<NSString *> *parts = [StringValue(session[@"name"]) componentsSeparatedByString:@"."];
389
+ if (parts.count != 3) return @"";
390
+ NSString *animal = parts.lastObject;
391
+ NSCharacterSet *digits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
392
+ NSUInteger end = animal.length;
393
+ while (end > 0 && [digits characterIsMember:[animal characterAtIndex:end - 1]]) end--;
394
+ NSString *alias = aliases[[animal substringToIndex:end]];
395
+ return alias ? [alias stringByAppendingString:[animal substringFromIndex:end]] : @"";
396
+ }
397
+
398
+ NSString *CCBridgeSessionDisplayName(NSDictionary *session) {
399
+ NSString *name = StringValue(session[@"name"]) ?: @"";
400
+ NSString *alias = CCBridgeSessionAnimalAlias(session);
401
+ return alias.length > 0 ? [name stringByAppendingFormat:@" · %@", alias] : name;
402
+ }
403
+
314
404
  static NSDictionary *NameTakenBy(NSString *name, NSString *sessionId, NSArray<NSDictionary *> *liveSessions) {
315
405
  for (NSDictionary *entry in liveSessions) {
316
406
  if (![entry[@"session"] isEqual:sessionId] && [entry[@"name"] isEqual:name]) return entry;
@@ -346,12 +436,25 @@ static NSString *AllocateName(NSString *provider, NSString *profileName, NSStrin
346
436
  }
347
437
  }
348
438
 
439
+ // 状态卡这类窄地方用的短名:去掉默认名字开头的账号段(claude.my-app.otter → my-app.otter),
440
+ // 只处理明确标记为自动生成的名字;自定义名字和来源不明的旧记录原样返回。
441
+ NSString *CCBridgeSessionShortName(NSDictionary *session) {
442
+ NSString *name = StringValue(session[@"name"]);
443
+ if (name.length == 0) return @"";
444
+ if (![StringValue(session[@"nameSource"]) isEqualToString:@"generated"]) return name;
445
+ // 自动名字的首段就是分配时的账号名,不依赖之后可能变化的 profileName。
446
+ NSRange separator = [name rangeOfString:@"."];
447
+ return separator.location != NSNotFound && separator.location > 0 && NSMaxRange(separator) < name.length
448
+ ? [name substringFromIndex:NSMaxRange(separator)] : name;
449
+ }
450
+
349
451
  // 启动时指定的名字被占用就追加序号(frontend → frontend-2),不让会话因此注册失败。
350
452
  static NSString *AllocateCustomName(NSString *name, NSString *sessionId, NSArray<NSDictionary *> *liveSessions) {
351
453
  if (!NameTakenBy(name, sessionId, liveSessions)) return name;
352
454
  for (NSUInteger index = 2; ; index++) {
353
- NSString *candidate = [NSString stringWithFormat:@"%@-%lu", name, (unsigned long)index];
354
- if (candidate.length > 40) candidate = [candidate substringToIndex:40];
455
+ NSString *suffix = [NSString stringWithFormat:@"-%lu", (unsigned long)index];
456
+ NSString *base = [name substringToIndex:MIN(name.length, 40 - suffix.length)];
457
+ NSString *candidate = [base stringByAppendingString:suffix];
355
458
  if (!NameTakenBy(candidate, sessionId, liveSessions)) return candidate;
356
459
  }
357
460
  }
@@ -365,7 +468,7 @@ NSString *CCBridgeNormalizeSessionName(id value) {
365
468
  return [pattern firstMatchInString:name options:0 range:NSMakeRange(0, name.length)] ? name : nil;
366
469
  }
367
470
 
368
- NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
471
+ static NSDictionary *UpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
369
472
  NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
370
473
  NSString *profileName, NSArray<NSDictionary *> *liveSessions) {
371
474
  NSString *safe = CCBridgeSafeSessionId(sessionId);
@@ -381,12 +484,16 @@ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSN
381
484
  if (cwd.length > 0) record[@"cwd"] = cwd;
382
485
  if (tty.length > 0) record[@"tty"] = tty;
383
486
  if (profileID.length > 0) record[@"profileId"] = profileID;
487
+ NSString *home = CCPetsEnvironmentValue(@"CC_PETS_PROFILE_HOME");
488
+ if (home.length == 0 && [provider isEqual:@"Codex"]) home = CCPetsCodexHome();
489
+ if (home.length > 0) record[@"home"] = home;
384
490
  if (profileName.length > 0) record[@"profileName"] = profileName;
385
491
  if (!StringValue(record[@"name"])) {
386
492
  NSString *custom = CCBridgeNormalizeSessionName(preferredName);
387
493
  record[@"name"] = custom ? AllocateCustomName(custom, safe, liveSessions ?: @[])
388
494
  : AllocateName(StringValue(record[@"provider"]) ?: @"", StringValue(record[@"profileName"]),
389
495
  StringValue(record[@"cwd"]), safe, liveSessions ?: @[]);
496
+ record[@"nameSource"] = custom ? @"custom" : @"generated";
390
497
  }
391
498
  if (status) record[@"status"] = status;
392
499
  record[@"updatedAt"] = @(now);
@@ -394,7 +501,7 @@ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSN
394
501
  return record;
395
502
  }
396
503
 
397
- NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
504
+ static NSDictionary *RenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
398
505
  NSMutableDictionary *record = [CCBridgeReadSession(sessionId) mutableCopy];
399
506
  if (!record) return @{@"error": L(@"This session isn't registered yet.")};
400
507
  NSString *name = CCBridgeNormalizeSessionName(requestedName);
@@ -408,11 +515,28 @@ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName
408
515
  }
409
516
  NSString *previous = StringValue(record[@"name"]) ?: @"";
410
517
  record[@"name"] = name;
518
+ record[@"nameSource"] = @"custom";
411
519
  record[@"updatedAt"] = @(CCPetsMilliseconds());
412
520
  CCBridgeWriteJSON(SessionFile(record[@"session"]), record);
413
521
  return @{@"session": record, @"previous": previous};
414
522
  }
415
523
 
524
+ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
525
+ NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
526
+ NSString *profileName, NSArray<NSDictionary *> *liveSessions) {
527
+ NSString *lock = WaitForLock(@"sessions");
528
+ @try {
529
+ return UpsertSession(sessionId, provider, pid, cwd, tty, status, preferredName, profileID,
530
+ profileName, CCBridgeReadSession(sessionId) ? @[] : RegisteredLiveSessions());
531
+ } @finally { CCBridgeReleaseLock(lock); }
532
+ }
533
+
534
+ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
535
+ NSString *lock = WaitForLock(@"sessions");
536
+ @try { return RenameSession(sessionId, requestedName, RegisteredLiveSessions()); }
537
+ @finally { CCBridgeReleaseLock(lock); }
538
+ }
539
+
416
540
  #pragma mark - 消息
417
541
 
418
542
  NSString *CCBridgeNewMessageId(void) {
@@ -446,17 +570,26 @@ NSDictionary *CCBridgeReadReceipt(id messageId) {
446
570
  return [receipt isKindOfClass:NSDictionary.class] ? receipt : nil;
447
571
  }
448
572
 
573
+ // 回执只是元数据:正文只在信箱里,送达后随之删除,不跟着回执再留 48 小时。
449
574
  void CCBridgeWriteReceipt(NSDictionary *message) {
450
- CCBridgeWriteJSON(ReceiptFile(message[@"id"]), message);
575
+ NSMutableDictionary *receipt = [message mutableCopy];
576
+ [receipt removeObjectForKey:@"body"];
577
+ CCBridgeWriteJSON(ReceiptFile(message[@"id"]), receipt);
451
578
  }
452
579
 
453
580
  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;
581
+ if (!IsMessageId(messageId)) return nil;
582
+ NSString *lock = WaitForLock(@"receipts");
583
+ @try {
584
+ NSMutableDictionary *next = [CCBridgeReadReceipt(messageId) mutableCopy];
585
+ if (!next) return nil;
586
+ // 终态不能被迟到的 pending、失败回调等覆盖。
587
+ if (IsTerminalStatus(next[@"status"])) return next;
588
+ [next addEntriesFromDictionary:patch];
589
+ next[@"updatedAt"] = @(CCPetsMilliseconds());
590
+ CCBridgeWriteReceipt(next);
591
+ return next;
592
+ } @finally { CCBridgeReleaseLock(lock); }
460
593
  }
461
594
 
462
595
  NSArray<NSDictionary *> *CCBridgeListReceipts(void) {
@@ -494,56 +627,186 @@ NSString *CCBridgeCheckSendLimits(NSString *fromSession, NSString *toSession) {
494
627
  return nil;
495
628
  }
496
629
 
497
- void CCBridgeEnqueueInbox(NSDictionary *message) {
630
+ // 和清理共用信箱锁,并在锁内复查:发送可能卡在 codex queue 上几十秒,这期间 Bridge 可能已关闭、
631
+ // 目标可能已退出。锁外检查的话,清理做完之后这里才写入,正文就再也没人收拾了。
632
+ NSString *CCBridgeEnqueueInbox(NSDictionary *message) {
498
633
  NSString *target = CCBridgeSafeSessionId(PartySession(message, @"to"));
499
634
  if (!target) [NSException raise:@"CCBridgeInbox" format:@"%@", L(@"invalid target session id")];
500
- CCBridgeWriteJSON([CCBridgeSubdirectory(@[@"inbox", target]) stringByAppendingPathComponent:
501
- [message[@"id"] stringByAppendingString:@".json"]], message);
635
+ return CCBridgeWithLock([@"inbox-" stringByAppendingString:target], ^id {
636
+ if (!CCBridgeEnabled()) return L(@"CC Bridge is off.");
637
+ if (!CCBridgeSessionLive(CCBridgeReadSession(target))) return L(@"the target session is offline");
638
+ CCBridgeWriteJSON([CCBridgeSubdirectory(@[@"inbox", target]) stringByAppendingPathComponent:
639
+ [message[@"id"] stringByAppendingString:@".json"]], message);
640
+ return nil;
641
+ });
642
+ }
643
+
644
+ static NSString *InboxLockFile(NSString *sessionId) {
645
+ return [CCBridgeSubdirectory(@[@"locks"]) stringByAppendingPathComponent:
646
+ [NSString stringWithFormat:@"inbox-%@.pid", sessionId]];
502
647
  }
503
648
 
649
+ // 持有每个信箱的内核锁直到输出成功。崩溃后 claimed 保留,下次消费者会重新读取。
504
650
  NSArray<NSDictionary *> *CCBridgeClaimInbox(id sessionId) {
505
651
  NSString *safe = CCBridgeSafeSessionId(sessionId);
506
652
  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;
653
+ NSString *lock = CCBridgeAcquireLock([@"inbox-" stringByAppendingString:safe]);
654
+ if (!lock) return @[];
655
+ @try {
656
+ NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
657
+ NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
658
+ for (NSString *name in ListJSON(inbox)) {
659
+ NSString *source = [inbox stringByAppendingPathComponent:name];
660
+ NSString *destination = [claimed stringByAppendingPathComponent:name];
661
+ if ([NSFileManager.defaultManager fileExistsAtPath:destination]) continue;
662
+ if (rename(source.fileSystemRepresentation, destination.fileSystemRepresentation) != 0 && errno != ENOENT)
663
+ [NSException raise:@"CCBridgeInbox" format:@"%@: %s", source, strerror(errno)];
664
+ }
665
+ NSMutableArray *messages = [NSMutableArray array];
666
+ for (NSString *name in ListJSON(claimed)) {
667
+ NSString *file = [claimed stringByAppendingPathComponent:name];
668
+ id message = CCBridgeReadJSON(file);
669
+ if (![message isKindOfClass:NSDictionary.class] || !IsMessageId(message[@"id"])) continue;
670
+ if (IsTerminalStatus(CCBridgeReadReceipt(message[@"id"])[@"status"])) {
671
+ unlink(file.fileSystemRepresentation);
672
+ continue;
673
+ }
674
+ if (CCPetsMilliseconds() - NumberValue(message[@"createdAt"]) > CCBridgeMessageTTL) {
675
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"expired"});
676
+ unlink(file.fileSystemRepresentation);
677
+ continue;
678
+ }
679
+ [messages addObject:message];
521
680
  }
522
- [messages addObject:message];
681
+ if (messages.count == 0) CCBridgeReleaseLock(lock);
682
+ return messages;
683
+ } @catch (NSException *exception) {
684
+ CCBridgeReleaseLock(lock);
685
+ @throw;
523
686
  }
524
- return messages;
687
+ }
688
+
689
+ void CCBridgeFinishInbox(id sessionId, NSArray<NSDictionary *> *messages, NSString *transport) {
690
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
691
+ if (!safe) return;
692
+ @try {
693
+ if (!transport) return; // 输出失败:保留 claimed,供下次重新投递。
694
+ NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
695
+ for (NSDictionary *message in messages) {
696
+ NSDictionary *receipt = CCBridgeUpdateReceipt(message[@"id"],
697
+ @{@"status": @"delivered", @"transport": @{@"kind": transport}});
698
+ if (!receipt) continue;
699
+ unlink([claimed stringByAppendingPathComponent:[message[@"id"] stringByAppendingString:@".json"]].fileSystemRepresentation);
700
+ }
701
+ } @finally { CCBridgeReleaseLock(InboxLockFile(safe)); }
525
702
  }
526
703
 
527
704
  NSUInteger CCBridgePendingCount(id sessionId) {
528
705
  NSString *safe = CCBridgeSafeSessionId(sessionId);
529
- return safe ? ListJSON(CCBridgeSubdirectory(@[@"inbox", safe])).count : 0;
706
+ if (!safe) return 0;
707
+ return ListJSON(CCBridgeSubdirectory(@[@"inbox", safe])).count +
708
+ ListJSON(CCBridgeSubdirectory(@[@"claimed", safe])).count;
709
+ }
710
+
711
+ static NSString *SessionDirectory(NSString *kind, NSString *sessionId) {
712
+ return [[CCBridgeStateDirectory() stringByAppendingPathComponent:kind] stringByAppendingPathComponent:sessionId];
713
+ }
714
+
715
+ // 调用方持有该信箱的锁。空目录一并删掉,否则已退出的会话会在状态目录里留下痕迹。
716
+ static void AbandonInboxLocked(NSString *sessionId, NSString *reason) {
717
+ for (NSString *kind in @[@"inbox", @"claimed"]) {
718
+ NSString *directory = SessionDirectory(kind, sessionId);
719
+ for (NSString *name in ListJSON(directory)) {
720
+ NSString *file = [directory stringByAppendingPathComponent:name];
721
+ id message = CCBridgeReadJSON(file);
722
+ if ([message isKindOfClass:NSDictionary.class]) {
723
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"undeliverable", @"reason": reason});
724
+ }
725
+ unlink(file.fileSystemRepresentation);
726
+ }
727
+ rmdir(directory.fileSystemRepresentation);
728
+ }
530
729
  }
531
730
 
532
731
  void CCBridgeAbandonInbox(id sessionId) {
533
732
  NSString *safe = CCBridgeSafeSessionId(sessionId);
534
733
  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")});
734
+ NSString *lock = WaitForLock([@"inbox-" stringByAppendingString:safe]);
735
+ @try { AbandonInboxLocked(safe, L(@"the target session has ended")); }
736
+ @finally { CCBridgeReleaseLock(lock); }
737
+ }
738
+
739
+ void CCBridgeAbandonAllInboxes(NSString *reason) {
740
+ NSMutableSet<NSString *> *sessions = [NSMutableSet set];
741
+ for (NSString *kind in @[@"inbox", @"claimed"]) {
742
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:kind];
743
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
744
+ if (CCBridgeSafeSessionId(name)) [sessions addObject:name];
745
+ }
746
+ }
747
+ // 已注册的会话也要过一遍锁:信箱目录可能正在被创建,只看现有目录会漏掉锁内还没写完的发送。
748
+ for (NSDictionary *session in CCBridgeListSessions()) {
749
+ if (CCBridgeSafeSessionId(session[@"session"])) [sessions addObject:session[@"session"]];
750
+ }
751
+ for (NSString *session in sessions) {
752
+ NSString *lock = WaitForLock([@"inbox-" stringByAppendingString:session]);
753
+ @try { AbandonInboxLocked(session, reason); }
754
+ @finally { CCBridgeReleaseLock(lock); }
755
+ }
756
+ }
757
+
758
+ // 崩溃的会话不会触发 SessionEnd。这里只试一次锁:抢不到说明有人正在处理,留给下一次清理,
759
+ // 不能让查询在线列表的调用方等锁。锁内复查在线,防止同一 ID 刚被 resume。
760
+ void CCBridgeAbandonOfflineSession(id sessionId) {
761
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
762
+ if (!safe) return;
763
+ NSString *lock = CCBridgeAcquireLock([@"inbox-" stringByAppendingString:safe]);
764
+ if (!lock) return;
765
+ @try {
766
+ if (CCBridgeSessionLive(CCBridgeReadSession(safe))) return;
767
+ AbandonInboxLocked(safe, L(@"the target session has ended"));
768
+ CCBridgeClearIdleSubscriptions(safe);
769
+ CCBridgeDropWatcher(safe);
770
+ } @finally { CCBridgeReleaseLock(lock); }
771
+ }
772
+
773
+ static void ExpireInbox(NSString *sessionId) {
774
+ NSString *lock = CCBridgeAcquireLock([@"inbox-" stringByAppendingString:sessionId]);
775
+ if (!lock) return;
776
+ @try {
777
+ long long now = CCPetsMilliseconds();
778
+ for (NSString *kind in @[@"inbox", @"claimed"]) {
779
+ NSString *directory = SessionDirectory(kind, sessionId);
780
+ for (NSString *name in ListJSON(directory)) {
781
+ NSString *file = [directory stringByAppendingPathComponent:name];
782
+ id message = CCBridgeReadJSON(file);
783
+ if (![message isKindOfClass:NSDictionary.class]) {
784
+ unlink(file.fileSystemRepresentation);
785
+ } else if (now - NumberValue(message[@"createdAt"]) > CCBridgeMessageTTL) {
786
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"expired"});
787
+ unlink(file.fileSystemRepresentation);
788
+ }
789
+ }
542
790
  }
791
+ } @finally { CCBridgeReleaseLock(lock); }
792
+ }
793
+
794
+ void CCBridgeSweepMessages(void) {
795
+ NSMutableSet<NSString *> *sessions = [NSMutableSet set];
796
+ for (NSString *kind in @[@"inbox", @"claimed", @"subscriptions"]) {
797
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:kind];
798
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
799
+ if (CCBridgeSafeSessionId(name)) [sessions addObject:name];
800
+ }
801
+ }
802
+ for (NSString *session in sessions) {
803
+ if (CCBridgeSessionLive(CCBridgeReadSession(session))) ExpireInbox(session);
804
+ else CCBridgeAbandonOfflineSession(session);
543
805
  }
544
806
  }
545
807
 
546
- // 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。
808
+ // 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。超过 TTL 仍未到终态的(目标崩溃、投递中途退出)
809
+ // 不会再有人更新,在这里收尾,发送方才能看到结果。
547
810
  void CCBridgePruneReceipts(void) {
548
811
  NSString *directory = CCBridgeSubdirectory(@[@"sent"]);
549
812
  long long now = CCPetsMilliseconds();
@@ -552,6 +815,8 @@ void CCBridgePruneReceipts(void) {
552
815
  id receipt = CCBridgeReadJSON(file);
553
816
  if (![receipt isKindOfClass:NSDictionary.class] || now - NumberValue(receipt[@"createdAt"]) > CCBridgeMessageTTL * 2) {
554
817
  unlink(file.fileSystemRepresentation);
818
+ } else if (now - NumberValue(receipt[@"createdAt"]) > CCBridgeMessageTTL && !IsTerminalStatus(receipt[@"status"])) {
819
+ CCBridgeUpdateReceipt(receipt[@"id"], @{@"status": @"expired"});
555
820
  }
556
821
  }
557
822
  }
@@ -590,33 +855,78 @@ NSArray<NSString *> *CCBridgeTakeIdleSubscriptions(NSString *targetSession) {
590
855
  return subscribers;
591
856
  }
592
857
 
858
+ void CCBridgeClearIdleSubscriptions(id targetSession) {
859
+ NSString *target = CCBridgeSafeSessionId(targetSession);
860
+ if (!target) return;
861
+ NSString *directory = SessionDirectory(@"subscriptions", target);
862
+ for (NSString *name in ListJSON(directory)) {
863
+ unlink([directory stringByAppendingPathComponent:name].fileSystemRepresentation);
864
+ }
865
+ rmdir(directory.fileSystemRepresentation);
866
+ }
867
+
593
868
  #pragma mark - 锁
594
869
 
595
- static pid_t LockHolder(NSString *file) {
596
- NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
597
- return (pid_t)text.intValue;
870
+ // 内核锁文件保持稳定 inode,PID 文件仅用于诊断;不能通过删除“陈旧锁”抢占。
871
+ static NSMutableDictionary<NSString *, NSNumber *> *HeldLocks(void) {
872
+ static NSMutableDictionary *locks;
873
+ static dispatch_once_t once;
874
+ dispatch_once(&once, ^{ locks = [NSMutableDictionary dictionary]; });
875
+ return locks;
598
876
  }
599
877
 
600
878
  NSString *CCBridgeAcquireLock(NSString *name) {
601
879
  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);
880
+ @synchronized (HeldLocks()) {
881
+ if (HeldLocks()[file]) return nil;
882
+ NSString *guard = [file stringByAppendingString:@".lock"];
883
+ int descriptor = open(guard.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
884
+ if (descriptor < 0) [NSException raise:@"CCBridgeLock" format:@"%@: %s", guard, strerror(errno)];
885
+ if (flock(descriptor, LOCK_EX | LOCK_NB) != 0) {
886
+ int failure = errno;
607
887
  close(descriptor);
608
- return file;
888
+ if (failure == EWOULDBLOCK || failure == EAGAIN) return nil;
889
+ [NSException raise:@"CCBridgeLock" format:@"%@: %s", guard, strerror(failure)];
609
890
  }
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);
891
+ HeldLocks()[file] = @(descriptor);
892
+ [[NSString stringWithFormat:@"%d", getpid()] writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
893
+ chmod(file.fileSystemRepresentation, 0600);
894
+ return file;
614
895
  }
615
- return nil;
616
896
  }
617
897
 
618
898
  void CCBridgeReleaseLock(NSString *lockFile) {
619
- if (lockFile && LockHolder(lockFile) == getpid()) unlink(lockFile.fileSystemRepresentation);
899
+ if (!lockFile) return;
900
+ @synchronized (HeldLocks()) {
901
+ NSNumber *descriptor = HeldLocks()[lockFile];
902
+ if (!descriptor) return;
903
+ unlink(lockFile.fileSystemRepresentation);
904
+ [HeldLocks() removeObjectForKey:lockFile];
905
+ close(descriptor.intValue); // 包括进程异常退出,内核都会释放 flock。
906
+ }
907
+ }
908
+
909
+ #pragma mark - watcher 接替
910
+
911
+ static NSString *WatcherOwnerFile(NSString *sessionId) {
912
+ return [CCBridgeSubdirectory(@[@"locks"]) stringByAppendingPathComponent:
913
+ [NSString stringWithFormat:@"watch-%@.owner", sessionId]];
914
+ }
915
+
916
+ NSString *CCBridgeClaimWatcher(NSString *sessionId) {
917
+ NSString *token = RandomHex(8);
918
+ CCBridgeWriteJSON(WatcherOwnerFile(sessionId), @{@"token": token});
919
+ return token;
920
+ }
921
+
922
+ BOOL CCBridgeWatcherOwned(NSString *sessionId, NSString *token) {
923
+ id owner = CCBridgeReadJSON(WatcherOwnerFile(sessionId));
924
+ return [owner isKindOfClass:NSDictionary.class] && [owner[@"token"] isEqual:token];
925
+ }
926
+
927
+ void CCBridgeDropWatcher(id sessionId) {
928
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
929
+ if (safe) unlink(WatcherOwnerFile(safe).fileSystemRepresentation);
620
930
  }
621
931
 
622
932
  #pragma mark - 进程探测
@@ -636,8 +946,9 @@ static BOOL ProcessParent(pid_t pid, pid_t *parent, dev_t *tty) {
636
946
  return YES;
637
947
  }
638
948
 
639
- // 与 `ps -o command=` 一致:argv 用空格连起来。读不到参数区(别的用户的进程、僵尸)时退回 ps。
640
- NSString *CCBridgeProcessCommand(pid_t pid) {
949
+ // 保留 argv 的边界:路径可以含空格(如 Application Support),拼成字符串再切分就认不出可执行文件了。
950
+ // 读不到参数区(别的用户的进程、僵尸)时退回 ps,那里没有边界,只能按空白切分。
951
+ NSArray<NSString *> *CCBridgeProcessArguments(pid_t pid) {
641
952
  if (pid <= 0) return nil;
642
953
  int argumentMaximum = 0;
643
954
  size_t size = sizeof argumentMaximum;
@@ -661,7 +972,7 @@ NSString *CCBridgeProcessCommand(pid_t pid) {
661
972
  cursor += length + 1;
662
973
  }
663
974
  free(buffer);
664
- if (arguments.count > 0) return [arguments componentsJoinedByString:@" "];
975
+ if (arguments.count > 0) return arguments;
665
976
  } else {
666
977
  free(buffer);
667
978
  }
@@ -670,8 +981,11 @@ NSString *CCBridgeProcessCommand(pid_t pid) {
670
981
  if (CCPetsRun(@"/bin/ps", @[@"-o", @"command=", @"-p", [NSString stringWithFormat:@"%d", pid]], nil, nil, 10, &output, NULL) != 0) {
671
982
  return nil;
672
983
  }
673
- NSString *command = [output stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
674
- return command.length > 0 ? command : nil;
984
+ NSMutableArray<NSString *> *tokens = [NSMutableArray array];
985
+ for (NSString *token in [output ?: @"" componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]) {
986
+ if (token.length > 0) [tokens addObject:token];
987
+ }
988
+ return tokens.count > 0 ? tokens : nil;
675
989
  }
676
990
 
677
991
  NSString *CCBridgeProcessTty(pid_t pid) {
@@ -683,26 +997,17 @@ NSString *CCBridgeProcessTty(pid_t pid) {
683
997
  return [tty hasPrefix:@"tty"] ? tty : [@"tty" stringByAppendingString:tty];
684
998
  }
685
999
 
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
1000
  static BOOL Matches(NSString *pattern, NSString *text) {
697
1001
  if (text.length == 0) return NO;
698
1002
  NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
699
1003
  return [expression firstMatchInString:text options:0 range:NSMakeRange(0, text.length)] != nil;
700
1004
  }
701
1005
 
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] : @"";
1006
+ // 只看可执行文件本身和脚本路径,不看其余参数:参数里出现 "claude" / "codex" 的进程太多了
1007
+ // (比如 tmux new-session "codex …"、编辑器打开的某个路径)。
1008
+ BOOL CCBridgeArgumentsMatchProvider(NSString *provider, NSArray<NSString *> *arguments) {
1009
+ NSString *executable = arguments.firstObject ?: @"";
1010
+ NSString *second = arguments.count > 1 ? arguments[1] : @"";
706
1011
  // Codex 的 npm 包是 node 包装器 + 原生二进制;hook 和 MCP 进程的直接祖先都是原生二进制,
707
1012
  // 取离自己最近的那个,两边才能落到同一个 pid。
708
1013
  if ([provider isEqualToString:@"Codex"]) {
@@ -732,9 +1037,9 @@ NSDictionary *CCBridgeFindAgentAncestor(pid_t startPid) {
732
1037
  for (int depth = 0; depth < 12 && pid > 1; depth++) {
733
1038
  pid_t parent = 0;
734
1039
  if (!ProcessParent(pid, &parent, NULL)) return nil;
735
- NSString *command = CCBridgeProcessCommand(pid);
1040
+ NSArray<NSString *> *arguments = CCBridgeProcessArguments(pid);
736
1041
  for (NSString *provider in @[@"Claude", @"Codex"]) {
737
- if (CCBridgeCommandMatchesProvider(provider, command)) return @{@"provider": provider, @"pid": @(pid)};
1042
+ if (CCBridgeArgumentsMatchProvider(provider, arguments)) return @{@"provider": provider, @"pid": @(pid)};
738
1043
  }
739
1044
  pid = parent;
740
1045
  }
@@ -746,8 +1051,8 @@ BOOL CCBridgeSessionLive(NSDictionary *session) {
746
1051
  id pid = session[@"pid"];
747
1052
  if ([pid isKindOfClass:NSNumber.class]) {
748
1053
  if (!CCBridgeProcessAlive([pid intValue])) return NO;
749
- NSString *command = CCBridgeProcessCommand([pid intValue]);
750
- return command == nil || CCBridgeCommandMatchesProvider(session[@"provider"], command);
1054
+ NSArray<NSString *> *arguments = CCBridgeProcessArguments([pid intValue]);
1055
+ return arguments == nil || CCBridgeArgumentsMatchProvider(session[@"provider"], arguments);
751
1056
  }
752
1057
  return CCPetsMilliseconds() - NumberValue(session[@"updatedAt"]) < StaleWithoutPid;
753
1058
  }