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
@@ -1,12 +1,15 @@
1
1
  #import "CCPetsTerminalFocus.h"
2
2
  #import "CCPetsEvents.h"
3
3
  #import "CCPetsPaths.h"
4
+ #import "CCPetsIDEIntegration.h"
5
+ #import "CCPetsVSCodeIntegration.h"
4
6
  #import <fcntl.h>
5
7
  #import <sys/file.h>
6
8
  #import <sys/sysctl.h>
7
9
  #import <sys/stat.h>
8
10
  #import <stdlib.h>
9
11
  #import <unistd.h>
12
+ #import <sqlite3.h>
10
13
 
11
14
  static BOOL ProcessInfoForPID(pid_t pid, struct kinfo_proc *info) {
12
15
  if (pid <= 0) return NO;
@@ -15,6 +18,50 @@ static BOOL ProcessInfoForPID(pid_t pid, struct kinfo_proc *info) {
15
18
  return sysctl(name, 4, info, &length, NULL, 0) == 0 && length > 0;
16
19
  }
17
20
 
21
+ BOOL IsCodexDesktopFocusTarget(NSDictionary *target) {
22
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
23
+ return [target[@"bundleID"] isEqual:@"com.openai.codex"] &&
24
+ (![target[@"tty"] isKindOfClass:NSString.class] || [target[@"tty"] length] == 0);
25
+ }
26
+
27
+ BOOL CodexDesktopFocusTargetIsLive(NSDictionary *target, NSTimeInterval eventTime) {
28
+ if (!IsCodexDesktopFocusTarget(target) || !(eventTime > 0)) return NO;
29
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.openai.codex"]) {
30
+ if (!app.terminated && app.launchDate && app.launchDate.timeIntervalSince1970 <= eventTime) return YES;
31
+ }
32
+ return NO;
33
+ }
34
+
35
+ BOOL CodexDesktopApplicationIsRunning(void) {
36
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.openai.codex"]) {
37
+ if (!app.terminated) return YES;
38
+ }
39
+ return NO;
40
+ }
41
+
42
+ NSNumber *CodexPersistentThreadStatus(NSString *thread, NSString *codexHome) {
43
+ if (thread.length == 0 || !codexHome.isAbsolutePath) return nil;
44
+ sqlite3 *db = NULL;
45
+ NSString *path = [codexHome stringByAppendingPathComponent:@"state_5.sqlite"];
46
+ if (sqlite3_open_v2(path.fileSystemRepresentation, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
47
+ if (db) sqlite3_close(db);
48
+ return nil;
49
+ }
50
+ sqlite3_busy_timeout(db, 10);
51
+ sqlite3_stmt *statement = NULL;
52
+ NSNumber *result = nil;
53
+ // 索引不可读或版本改变时返回未知,不能把错误当作“会话已退出”。
54
+ if (sqlite3_prepare_v2(db, "SELECT archived FROM threads WHERE id = ? LIMIT 1", -1, &statement, NULL) == SQLITE_OK) {
55
+ sqlite3_bind_text(statement, 1, thread.UTF8String, -1, SQLITE_TRANSIENT);
56
+ int step = sqlite3_step(statement);
57
+ if (step == SQLITE_ROW) result = @(sqlite3_column_int(statement, 0) == 0);
58
+ else if (step == SQLITE_DONE) result = @NO;
59
+ }
60
+ sqlite3_finalize(statement);
61
+ sqlite3_close(db);
62
+ return result;
63
+ }
64
+
18
65
  // 包装脚本没被走到时(用户直接跑 codex / claude,或终端窗口早于 shim 安装就已打开)
19
66
  // 环境里没有 CC_PETS_TERMINAL_*。记录端自己是 Agent 的子进程,控制终端就是 Agent
20
67
  // 所在的那个 tty,直接问内核即可——stdin 是 JSON 管道,isatty 这类办法在这里没用。
@@ -97,11 +144,13 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
97
144
  NSString *program = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_PROGRAM", 64);
98
145
  NSString *session = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_SESSION", 128);
99
146
  NSString *bundleID = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_BUNDLE_ID", 128);
147
+ NSString *ideInstance = TerminalTargetValue(environment, @"CC_PETS_IDE_INSTANCE_ID", 64);
148
+ NSString *ideTerminal = TerminalTargetValue(environment, @"CC_PETS_IDE_TERMINAL_ID", 64);
100
149
  if (tty.length == 0) tty = SanitizedShortString(ControllingTerminalName(), 64);
101
150
  if (bundleID.length == 0) {
102
151
  bundleID = SanitizedShortString(HostApplicationBundleIdentifier(), 128);
103
152
  }
104
- if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0) {
153
+ if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0 && ideInstance.length == 0) {
105
154
  return @{};
106
155
  }
107
156
  NSMutableDictionary *target = [NSMutableDictionary dictionary];
@@ -109,6 +158,10 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
109
158
  if (program.length > 0) target[@"program"] = program;
110
159
  if (session.length > 0) target[@"session"] = session;
111
160
  if (bundleID.length > 0) target[@"bundleID"] = bundleID;
161
+ if (ideInstance.length > 0 && ideTerminal.length > 0) {
162
+ target[@"ideInstance"] = ideInstance;
163
+ target[@"ideTerminal"] = ideTerminal;
164
+ }
112
165
  return target;
113
166
  }
114
167
 
@@ -152,11 +205,37 @@ static BOOL RunTerminalSelectionScript(NSString *bundleID, NSString *ttyName) {
152
205
  "end repeat\n"
153
206
  "end tell\n"
154
207
  "return false", tty];
208
+ } else if ([bundleID isEqualToString:@"com.mitchellh.ghostty"]) {
209
+ // Ghostty 1.4 起暴露 tty。先选中所属标签页并激活应用,再聚焦分屏;
210
+ // 不只依赖 focus 内部异步的窗口前置,状态卡本身是 NonactivatingPanel。
211
+ source = [NSString stringWithFormat:
212
+ @"tell application \"Ghostty\"\n"
213
+ "repeat with terminalWindow in windows\n"
214
+ "repeat with terminalTab in tabs of terminalWindow\n"
215
+ "repeat with terminalSurface in terminals of terminalTab\n"
216
+ "if (tty of terminalSurface) is \"%@\" then\n"
217
+ "set targetID to id of terminalSurface\n"
218
+ "select tab terminalTab\n"
219
+ "activate\n"
220
+ "focus (terminal id targetID)\n"
221
+ "return true\n"
222
+ "end if\n"
223
+ "end repeat\n"
224
+ "end repeat\n"
225
+ "end repeat\n"
226
+ "end tell\n"
227
+ "return false", tty];
155
228
  }
156
229
  if (!source) return NO;
157
230
  NSDictionary *error = nil;
158
231
  NSAppleScript *script = [[NSAppleScript alloc] initWithSource:source];
159
232
  NSAppleEventDescriptor *result = [script executeAndReturnError:&error];
233
+ if (error) {
234
+ NSLog(@"Terminal focus failed: bundle=%@ tty=%@ error=%@", bundleID, tty, error);
235
+ } else {
236
+ NSLog(@"Terminal focus: bundle=%@ tty=%@ matched=%@", bundleID, tty,
237
+ result.booleanValue ? @"yes" : @"no");
238
+ }
160
239
  return result.booleanValue && error == nil;
161
240
  }
162
241
 
@@ -197,7 +276,7 @@ NSArray<NSString *> *TerminalFocusBundleCandidates(NSDictionary *target) {
197
276
  return candidates;
198
277
  }
199
278
 
200
- // 没有脚本接口的宿主(JetBrains、VS Code 等)只能激活到应用这一级。activateWithOptions:
279
+ // 没有脚本或插件接口的宿主(如 Warp、未装扩展的 VS Code)退回激活应用。activateWithOptions:
201
280
  // 在 macOS 14 起走协作式激活:状态卡是 NonactivatingPanel,桌宠自己不在前台,请求可能
202
281
  // 被系统拒绝,窗口在别的桌面时更是不会切过去。改走和点 Dock 图标同一条路,让系统负责
203
282
  // 切到应用窗口所在的桌面;拿不到 bundleURL 时才退回旧接口。
@@ -219,6 +298,8 @@ static BOOL ActivateApplicationAcrossSpaces(NSRunningApplication *application) {
219
298
  }
220
299
 
221
300
  BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
301
+ if (CCPetsRequestIDETerminalFocus(target)) return YES;
302
+ if (CCPetsRequestVSCodeTerminalFocus(target)) return YES;
222
303
  NSString *tty = SanitizedShortString(target[@"tty"], 64);
223
304
  // 候选按优先级往下试,没在运行的直接跳过:映射值和捕获值总有一个指向真正承载
224
305
  // 会话的那个应用,卡在第一个候选上就会白白丢掉一次可用的回跳。
@@ -236,11 +317,11 @@ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
236
317
 
237
318
  // Codex 共享服务拉起的 hook 不知道会话在哪个终端(见 TerminalFocusRunsUnderSharedAgentHost)。
238
319
  // 能确定的只有两头:codex-with-pet 启动时知道自己的终端、工作目录和时刻;hook 知道会话 ID,
239
- // 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。新会话在 CLI 启动后一秒左右
240
- // 就会创建,所以"同一目录里、紧挨在会话创建之前启动的那个 CLI"就是它的终端。配对结果记下来,
241
- // 同一会话之后的事件直接查表。
320
+ // 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。CLI 启动后可能还要等网络
321
+ // 初始化,不能按包装脚本的启动先后猜测归属。多个候选时读取本机 TUI 就绪日志的 PID,
322
+ // 仅在会话创建前后一秒内存在唯一就绪候选时配对;信息不足就留空,之后的 Hook 可再试。
242
323
  static const NSUInteger CodexLaunchThreadLimit = 32;
243
- static const NSTimeInterval CodexThreadCreationSlack = 5.0;
324
+ static const NSTimeInterval CodexClientReadyWindow = 1.0;
244
325
 
245
326
  static NSTimeInterval ProcessStartTime(pid_t pid) {
246
327
  struct kinfo_proc info;
@@ -396,32 +477,82 @@ static NSDictionary *CodexThreadMeta(NSString *thread, NSDictionary *payload, NS
396
477
  return result;
397
478
  }
398
479
 
399
- // 在同一工作目录的候选里挑:优先还没配过会话的 CLI;会话创建时刻已知时,取创建前最后一个
400
- // 启动的(resume 的旧会话创建得比所有 CLI 都早,退回"最近启动的")。一个 TUI 里 /new 出来
401
- // 的新会话没有空闲候选可配,这时同目录只剩一个 CLI 才认它,多于一个宁可不配。
480
+ // Codex 的本机日志记录每个 TUI 的就绪时刻和带 PID 的 process_uuid。
481
+ // 初始会话可能先于首帧就绪(0.167.1 实测晚约 1.56ms 才记录就绪),不能要求就绪
482
+ // 一定早于会话创建。前后使用同一窄窗口,并在整个窗口内检查唯一性,避免两侧各有
483
+ // 一个候选时误配;SQL 的秒级范围与下面的精确时间过滤必须使用相同的上下界。
484
+ // 只读这一类元数据,不读取提示词、输出或 HTTP 日志。内部日志格式改变、日志尚未落盘、
485
+ // 多个客户端同时就绪时都不能猜测;sqlite 的读锁等待和返回条数也有上限。
486
+ static int CodexLogQueryExpired(void *context) {
487
+ return CFAbsoluteTimeGetCurrent() > *(CFAbsoluteTime *)context;
488
+ }
489
+
490
+ static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
491
+ NSArray<NSString *> *candidates, NSNumber *createdAt, NSString *codexHome) {
492
+ if (!createdAt || createdAt.doubleValue <= 0) return nil;
493
+ NSString *path = [(codexHome.length ? codexHome : DefaultCodexHomeDirectory())
494
+ stringByAppendingPathComponent:@"logs_2.sqlite"];
495
+ sqlite3 *database = NULL;
496
+ if (sqlite3_open_v2(path.fileSystemRepresentation, &database, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
497
+ if (database) sqlite3_close(database);
498
+ return nil;
499
+ }
500
+ sqlite3_busy_timeout(database, 50);
501
+ CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + 0.15;
502
+ sqlite3_progress_handler(database, 1000, CodexLogQueryExpired, &deadline);
503
+ sqlite3_stmt *statement = NULL;
504
+ const char *query = "SELECT ts, ts_nanos, process_uuid FROM logs "
505
+ "WHERE ts BETWEEN ? AND ? AND target = 'codex_tui::app::startup' "
506
+ "AND feedback_log_body LIKE 'tui startup initial frame scheduled%' LIMIT 128";
507
+ NSMutableSet<NSString *> *matches = [NSMutableSet set];
508
+ BOOL complete = NO;
509
+ NSTimeInterval earliestReadyAt = createdAt.doubleValue - CodexClientReadyWindow;
510
+ NSTimeInterval latestReadyAt = createdAt.doubleValue + CodexClientReadyWindow;
511
+ if (sqlite3_prepare_v2(database, query, -1, &statement, NULL) == SQLITE_OK) {
512
+ sqlite3_bind_int64(statement, 1, (sqlite3_int64)floor(earliestReadyAt));
513
+ sqlite3_bind_int64(statement, 2, (sqlite3_int64)ceil(latestReadyAt));
514
+ int result;
515
+ NSUInteger rows = 0;
516
+ while ((result = sqlite3_step(statement)) == SQLITE_ROW) {
517
+ rows++;
518
+ double readyAt = sqlite3_column_int64(statement, 0) + sqlite3_column_int64(statement, 1) / 1e9;
519
+ if (readyAt < earliestReadyAt || readyAt > latestReadyAt) continue;
520
+ const unsigned char *value = sqlite3_column_text(statement, 2);
521
+ NSString *process = value ? @((const char *)value) : @"";
522
+ for (NSString *key in candidates) {
523
+ NSDictionary *entry = launches[key];
524
+ NSString *prefix = [NSString stringWithFormat:@"pid:%d:", [entry[@"pid"] intValue]];
525
+ if ([process hasPrefix:prefix] && readyAt >= [entry[@"processStartedAt"] doubleValue] &&
526
+ readyAt >= [entry[@"launchedAt"] doubleValue]) [matches addObject:key];
527
+ }
528
+ }
529
+ complete = result == SQLITE_DONE && rows < 128;
530
+ }
531
+ if (statement) sqlite3_finalize(statement);
532
+ sqlite3_close(database);
533
+ return complete && matches.count == 1 ? matches.anyObject : nil;
534
+ }
535
+
536
+ // 显式 resume 优先按会话 ID;新会话用客户端就绪证据。多个同目录客户端时不能用
537
+ // “最新未绑定的进程”兜底:网络启动延迟和首次发消息的顺序都可能与启动顺序不同。
402
538
  static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
403
- NSString *cwd, NSNumber *createdAt) {
539
+ NSString *cwd, NSNumber *createdAt, NSString *thread, NSString *codexHome) {
404
540
  NSMutableArray<NSString *> *sameDirectory = [NSMutableArray array];
405
- NSMutableArray<NSString *> *unbound = [NSMutableArray array];
541
+ NSMutableArray<NSString *> *resumed = [NSMutableArray array];
406
542
  for (NSString *key in launches) {
407
543
  NSDictionary *entry = launches[key];
408
544
  if (![entry[@"cwd"] isEqualToString:cwd]) continue;
409
545
  [sameDirectory addObject:key];
410
- if ([entry[@"threads"] count] == 0) [unbound addObject:key];
411
- }
412
- if (unbound.count == 0) return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
413
- NSArray<NSString *> *byLaunch = [unbound sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
414
- return [launches[a][@"launchedAt"] compare:launches[b][@"launchedAt"]];
415
- }];
416
- if (createdAt) {
417
- NSString *preceding = nil;
418
- for (NSString *key in byLaunch) {
419
- if ([launches[key][@"launchedAt"] doubleValue] <=
420
- createdAt.doubleValue + CodexThreadCreationSlack) preceding = key;
546
+ NSArray *arguments = ProcessArguments([entry[@"pid"] intValue]);
547
+ NSUInteger resume = [arguments indexOfObject:@"resume"];
548
+ if (resume != NSNotFound && resume + 1 < arguments.count && [arguments[resume + 1] isEqual:thread]) {
549
+ [resumed addObject:key];
421
550
  }
422
- if (preceding) return preceding;
423
551
  }
424
- return byLaunch.lastObject;
552
+ if (resumed.count > 0) return resumed.count == 1 ? resumed.firstObject : nil;
553
+ NSString *ready = ReadyCodexLaunch(launches, sameDirectory, createdAt, codexHome);
554
+ if (ready) return ready;
555
+ return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
425
556
  }
426
557
 
427
558
  static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDictionary *payload,
@@ -439,7 +570,7 @@ static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDict
439
570
  }
440
571
  if (!terminal) {
441
572
  NSDictionary *meta = CodexThreadMeta(thread, payload, codexHome);
442
- NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"]) : nil;
573
+ NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"], thread, codexHome) : nil;
443
574
  if (key) {
444
575
  NSMutableDictionary *entry = [launches[key] mutableCopy];
445
576
  NSMutableArray *threads = [entry[@"threads"] mutableCopy] ?: [NSMutableArray array];
@@ -0,0 +1,17 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // AppleScript 精确跳转的终端(终端 / iTerm2 / Ghostty)在设置页的检测结果。
4
+ // 每行:name、bundleID、version、group(@"apple" 或 @"ghostty")、state:
5
+ // granted 已允许 CC Pets 自动化控制
6
+ // notDetermined 尚未询问;首次跳转时系统会弹窗
7
+ // denied 已拒绝;跳转只能激活应用
8
+ // notRunning 应用未运行,无法查询授权
9
+ // unsupported 版本过低,不支持按 TTY 定位(Ghostty < 1.4)
10
+ // 未安装的终端不出现;系统自带的终端始终在。查询不会弹授权窗口,但可能短暂阻塞,在后台线程调用。
11
+ NSArray<NSDictionary *> *CCPetsTerminalIntegrationSnapshot(void);
12
+
13
+ // 主动请求自动化授权(应用需在运行,会弹系统窗口)。在后台执行,完成后在主线程回调。
14
+ void CCPetsRequestTerminalAutomation(NSString *bundleID, void (^completion)(void));
15
+
16
+ // 打开 系统设置 → 隐私与安全性 → 自动化。
17
+ void CCPetsOpenAutomationSettings(void);
@@ -0,0 +1,64 @@
1
+ #import "CCPetsTerminalIntegration.h"
2
+ #import <CoreServices/CoreServices.h>
3
+
4
+ static NSString *const GhosttyBundleID = @"com.mitchellh.ghostty";
5
+ // Ghostty 1.4 起在 AppleScript 字典里暴露 terminal 的 tty。
6
+ static NSString *const GhosttyMinimumVersion = @"1.4";
7
+
8
+ static NSString *AutomationState(NSString *bundleID, BOOL askUserIfNeeded) {
9
+ NSAppleEventDescriptor *target = [NSAppleEventDescriptor descriptorWithBundleIdentifier:bundleID];
10
+ OSStatus status = AEDeterminePermissionToAutomateTarget(target.aeDesc, typeWildCard, typeWildCard, askUserIfNeeded);
11
+ switch (status) {
12
+ case noErr: return @"granted";
13
+ case errAEEventNotPermitted: return @"denied";
14
+ case errAEEventWouldRequireUserConsent: return @"notDetermined";
15
+ case procNotFound: return @"notRunning";
16
+ default: return @"notDetermined";
17
+ }
18
+ }
19
+
20
+ static BOOL ApplicationIsRunning(NSString *bundleID) {
21
+ return [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID].count > 0;
22
+ }
23
+
24
+ NSArray<NSDictionary *> *CCPetsTerminalIntegrationSnapshot(void) {
25
+ NSArray<NSArray<NSString *> *> *terminals = @[
26
+ @[@"com.apple.Terminal", @"apple"],
27
+ @[@"com.googlecode.iterm2", @"apple"],
28
+ @[GhosttyBundleID, @"ghostty"],
29
+ ];
30
+ NSMutableArray *rows = [NSMutableArray array];
31
+ for (NSArray<NSString *> *terminal in terminals) {
32
+ NSString *bundleID = terminal[0];
33
+ NSURL *url = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleID];
34
+ if (!url) continue;
35
+ NSBundle *bundle = [NSBundle bundleWithURL:url];
36
+ NSString *name = [NSFileManager.defaultManager displayNameAtPath:url.path].stringByDeletingPathExtension;
37
+ NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
38
+ if (![version isKindOfClass:NSString.class]) version = @"";
39
+ NSString *state;
40
+ if ([bundleID isEqualToString:GhosttyBundleID] && version.length &&
41
+ [version compare:GhosttyMinimumVersion options:NSNumericSearch] == NSOrderedAscending) {
42
+ state = @"unsupported";
43
+ } else if (!ApplicationIsRunning(bundleID)) {
44
+ state = @"notRunning";
45
+ } else {
46
+ state = AutomationState(bundleID, NO);
47
+ }
48
+ [rows addObject:@{@"name": name ?: bundleID, @"bundleID": bundleID, @"version": version,
49
+ @"group": terminal[1], @"state": state}];
50
+ }
51
+ return rows;
52
+ }
53
+
54
+ void CCPetsRequestTerminalAutomation(NSString *bundleID, void (^completion)(void)) {
55
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
56
+ if (ApplicationIsRunning(bundleID)) AutomationState(bundleID, YES);
57
+ if (completion) dispatch_async(dispatch_get_main_queue(), completion);
58
+ });
59
+ }
60
+
61
+ void CCPetsOpenAutomationSettings(void) {
62
+ NSURL *url = [NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.security?Privacy_Automation"];
63
+ [NSWorkspace.sharedWorkspace openURL:url];
64
+ }
@@ -0,0 +1,23 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // VS Code and its forks (Cursor, Windsurf, VSCodium, …) via the bundled CC Pets Terminal
4
+ // extension. A fork is recognised by Contents/Resources/app/product.json, not by bundle ID.
5
+
6
+ // YES for an installed app of the VS Code family. Cheap enough for the main thread.
7
+ BOOL CCPetsBundleIsVSCodeFamily(NSString *bundleID);
8
+
9
+ // Snapshot (disk + authenticated loopback queries): call off the main thread.
10
+ // state: connected / installed / pendingRestart / outdated / missing / disabled / unsupported.
11
+ // autoInstall is YES when the app ships its command line tool, which does the install.
12
+ NSArray<NSDictionary *> *CCPetsVSCodeIntegrationSnapshot(void);
13
+ // Installs or updates the bundled VSIX through the app's own CLI. Blocking.
14
+ BOOL CCPetsInstallVSCodeExtension(NSDictionary *app, NSError **error);
15
+ // Confirms, installs in the background and reports failures; falls back to the manual
16
+ // installer when autoInstall is NO. completion runs on the main thread.
17
+ void CCPetsPromptInstallVSCodeExtension(NSDictionary *app, void (^completion)(void));
18
+ // Reveals the bundled VSIX and explains "Install from VSIX…".
19
+ void CCPetsShowVSCodeExtensionInstaller(NSString *appName);
20
+
21
+ // Exact focus for a VS Code family target. NO when no connected window of that app could
22
+ // own the terminal, so the caller falls back to bringing the app forward.
23
+ BOOL CCPetsRequestVSCodeTerminalFocus(NSDictionary *target);