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
@@ -0,0 +1,503 @@
1
+ #import "CCPetsIDEIntegration.h"
2
+ #import "CCPetsEvents.h"
3
+ #import "CCPetsL10n.h"
4
+ #import "CCPetsVSCodeIntegration.h"
5
+ #import <sys/stat.h>
6
+ #import <sys/time.h>
7
+ #import <unistd.h>
8
+
9
+ static NSString *const IDEPluginID = @"com.ccpets.terminal";
10
+
11
+ // Any IntelliJ-platform IDE (IDEA, PyCharm, WebStorm, GoLand, Rider, Android Studio…)
12
+ // can host the plugin. The registration is still bound to the running PID and app path.
13
+ static BOOL IDEBundleIsJetBrains(NSString *bundleID) {
14
+ if (![bundleID isKindOfClass:NSString.class]) return NO;
15
+ return [bundleID hasPrefix:@"com.jetbrains."] || [bundleID isEqualToString:@"com.google.android.studio"];
16
+ }
17
+
18
+ static NSString *IDERegistryDirectory(void) {
19
+ return [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/CC Pets/ide-instances"];
20
+ }
21
+
22
+ // A registration never chooses an arbitrary URL. Only authenticated IPv4 loopback
23
+ // is used, with redirects and system proxies disabled.
24
+ @interface CCPetsIDELocalSession : NSObject <NSURLSessionTaskDelegate>
25
+ @end
26
+ @implementation CCPetsIDELocalSession
27
+ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
28
+ willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request
29
+ completionHandler:(void (^)(NSURLRequest *))completionHandler {
30
+ completionHandler(nil);
31
+ }
32
+ @end
33
+
34
+ NSDictionary *CCPetsIDEBridgeRequest(NSDictionary *instance, NSString *route, NSDictionary *body) {
35
+ NSInteger port = [instance[@"port"] integerValue];
36
+ NSString *token = instance[@"token"];
37
+ if (port < 1 || port > 65535 || ![token isKindOfClass:NSString.class] || token.length < 32) return nil;
38
+ NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://127.0.0.1:%ld/%@", (long)port, route]];
39
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
40
+ request.HTTPMethod = @"POST";
41
+ request.HTTPBody = [NSJSONSerialization dataWithJSONObject:body ?: @{} options:0 error:nil];
42
+ [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
43
+ [request setValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
44
+ NSTimeInterval timeout = [route isEqualToString:@"focus"] ? 4 : 1;
45
+ NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration;
46
+ configuration.timeoutIntervalForRequest = timeout;
47
+ configuration.timeoutIntervalForResource = timeout;
48
+ configuration.connectionProxyDictionary = @{};
49
+ configuration.URLCache = nil;
50
+ configuration.HTTPCookieStorage = nil;
51
+ NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
52
+ delegate:[CCPetsIDELocalSession new] delegateQueue:nil];
53
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
54
+ __block NSDictionary *result = nil;
55
+ NSURLSessionDataTask *task = [session dataTaskWithRequest:request
56
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
57
+ NSInteger status = [(NSHTTPURLResponse *)response statusCode];
58
+ if (!error && data.length < 65536 && status >= 200 && status < 500) {
59
+ id value = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
60
+ if ([value isKindOfClass:NSDictionary.class]) result = value;
61
+ }
62
+ dispatch_semaphore_signal(done);
63
+ }];
64
+ [task resume];
65
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, (int64_t)((timeout + 0.2) * NSEC_PER_SEC)))) {
66
+ [task cancel];
67
+ [session invalidateAndCancel];
68
+ return nil;
69
+ }
70
+ [session finishTasksAndInvalidate];
71
+ return result;
72
+ }
73
+
74
+ NSArray<NSDictionary *> *CCPetsIDEBridgeInstances(BOOL (^accept)(NSDictionary *record, NSRunningApplication *app)) {
75
+ NSMutableArray *instances = [NSMutableArray array];
76
+ NSString *directory = IDERegistryDirectory();
77
+ for (NSString *file in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
78
+ if (![file.pathExtension isEqualToString:@"json"]) continue;
79
+ NSString *path = [directory stringByAppendingPathComponent:file];
80
+ struct stat info;
81
+ if (lstat(path.fileSystemRepresentation, &info) || !S_ISREG(info.st_mode) ||
82
+ info.st_uid != getuid() || (info.st_mode & 0077) || info.st_size > 65536) continue;
83
+ NSData *data = [NSData dataWithContentsOfFile:path];
84
+ id record = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
85
+ if (![record isKindOfClass:NSDictionary.class] || [record[@"schemaVersion"] integerValue] != 1 ||
86
+ ![record[@"instanceID"] isKindOfClass:NSString.class] ||
87
+ ![[file stringByDeletingPathExtension] isEqualToString:record[@"instanceID"]]) continue;
88
+ NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:[record[@"pid"] intValue]];
89
+ if (!app || app.terminated || ![app.bundleURL.path isEqualToString:record[@"appPath"]] ||
90
+ !accept(record, app)) continue;
91
+ [instances addObject:record];
92
+ if (instances.count >= 16) break;
93
+ }
94
+ return instances;
95
+ }
96
+
97
+ // JetBrains registrations carry no "kind"; other bridges (VS Code) tag themselves.
98
+ static NSArray<NSDictionary *> *IDEInstances(void) {
99
+ return CCPetsIDEBridgeInstances(^BOOL(NSDictionary *record, NSRunningApplication *app) {
100
+ return record[@"kind"] == nil && IDEBundleIsJetBrains(app.bundleIdentifier);
101
+ });
102
+ }
103
+
104
+ static NSString *IDEPluginArchive(void) {
105
+ NSString *relative = @"IDEPlugins/cc-pets-terminal.zip";
106
+ NSString *bundled = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:relative];
107
+ if ([NSFileManager.defaultManager fileExistsAtPath:bundled]) return bundled;
108
+ NSString *besideBinary = [[NSProcessInfo.processInfo.arguments.firstObject stringByDeletingLastPathComponent]
109
+ stringByAppendingPathComponent:relative];
110
+ return [NSFileManager.defaultManager fileExistsAtPath:besideBinary] ? besideBinary : nil;
111
+ }
112
+
113
+ void CCPetsShowIDEPluginInstaller(void) {
114
+ NSString *archive = IDEPluginArchive();
115
+ NSAlert *alert = [NSAlert new];
116
+ alert.messageText = L(@"Install the JetBrains plugin");
117
+ if (!archive) {
118
+ alert.informativeText = L(@"The JetBrains plugin ZIP is missing from this CC Pets installation. Reinstall CC Pets to restore it.");
119
+ [alert addButtonWithTitle:L(@"OK")];
120
+ [alert runModal];
121
+ return;
122
+ }
123
+ [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:archive]]];
124
+ alert.informativeText = L(@"In your JetBrains IDE, open Settings → Plugins → ⚙ → Install Plugin from Disk, then choose cc-pets-terminal.zip. Restart the IDE if prompted. Open a project and use the Reworked terminal; CC Pets connects automatically.");
125
+ [alert addButtonWithTitle:L(@"Copy ZIP Path")];
126
+ [alert addButtonWithTitle:L(@"Done")];
127
+ if ([alert runModal] == NSAlertFirstButtonReturn) {
128
+ [NSPasteboard.generalPasteboard clearContents];
129
+ [NSPasteboard.generalPasteboard setString:archive forType:NSPasteboardTypeString];
130
+ }
131
+ }
132
+
133
+ #pragma mark - Plugin versions
134
+
135
+ static NSString *const IDEPluginFolder = @"cc-pets-terminal";
136
+ static NSString *const IDEPluginJar = @"cc-pets-terminal/lib/cc-pets-terminal.jar";
137
+
138
+ static NSData *IDEUnzipEntry(NSString *archive, NSString *entry) {
139
+ NSTask *task = [NSTask new];
140
+ task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/unzip"];
141
+ task.arguments = @[@"-p", archive, entry];
142
+ NSPipe *output = [NSPipe pipe];
143
+ task.standardOutput = output;
144
+ task.standardError = NSFileHandle.fileHandleWithNullDevice;
145
+ if (![task launchAndReturnError:nil]) return nil;
146
+ NSData *data = [output.fileHandleForReading readDataToEndOfFile];
147
+ [task waitUntilExit];
148
+ return task.terminationStatus == 0 && data.length < 4 * 1024 * 1024 ? data : nil;
149
+ }
150
+
151
+ static NSString *IDEVersionFromPluginXML(NSData *xml) {
152
+ NSString *text = xml ? [[NSString alloc] initWithData:xml encoding:NSUTF8StringEncoding] : nil;
153
+ if (!text) return nil;
154
+ NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:
155
+ @"<version>\\s*([0-9A-Za-z.\\-]{1,32})\\s*</version>" options:0 error:nil];
156
+ NSTextCheckingResult *match = [pattern firstMatchInString:text options:0 range:NSMakeRange(0, text.length)];
157
+ return match ? [text substringWithRange:[match rangeAtIndex:1]] : nil;
158
+ }
159
+
160
+ // Reading a version spawns unzip, so results are cached by path, size and mtime.
161
+ static NSString *IDECachedVersion(NSString *path, NSString *(^read)(void)) {
162
+ static NSMutableDictionary<NSString *, NSString *> *cache;
163
+ static dispatch_once_t once;
164
+ dispatch_once(&once, ^{ cache = [NSMutableDictionary dictionary]; });
165
+ struct stat info;
166
+ if (stat(path.fileSystemRepresentation, &info)) return nil;
167
+ NSString *key = [NSString stringWithFormat:@"%@|%lld|%ld.%09ld", path, (long long)info.st_size,
168
+ (long)info.st_mtimespec.tv_sec, info.st_mtimespec.tv_nsec];
169
+ @synchronized(cache) {
170
+ if (cache[key]) return cache[key].length ? cache[key] : nil;
171
+ }
172
+ NSString *version = read() ?: @"";
173
+ @synchronized(cache) { cache[key] = version; }
174
+ return version.length ? version : nil;
175
+ }
176
+
177
+ static NSString *IDEInstalledPluginVersion(NSString *jar) {
178
+ return IDECachedVersion(jar, ^NSString *{
179
+ return IDEVersionFromPluginXML(IDEUnzipEntry(jar, @"META-INF/plugin.xml"));
180
+ });
181
+ }
182
+
183
+ static NSString *IDEBundledPluginVersion(void) {
184
+ NSString *archive = IDEPluginArchive();
185
+ if (!archive) return nil;
186
+ return IDECachedVersion(archive, ^NSString *{
187
+ NSData *jar = IDEUnzipEntry(archive, IDEPluginJar);
188
+ if (!jar) return nil;
189
+ NSString *temporary = [NSTemporaryDirectory() stringByAppendingPathComponent:
190
+ [NSString stringWithFormat:@"cc-pets-plugin-%@.jar", NSUUID.UUID.UUIDString]];
191
+ if (![jar writeToFile:temporary options:NSDataWritingAtomic error:nil]) return nil;
192
+ NSString *version = IDEVersionFromPluginXML(IDEUnzipEntry(temporary, @"META-INF/plugin.xml"));
193
+ [NSFileManager.defaultManager removeItemAtPath:temporary error:nil];
194
+ return version;
195
+ });
196
+ }
197
+
198
+ #pragma mark - Paths
199
+
200
+ static BOOL IDEOwnedDirectory(NSString *path) {
201
+ struct stat info;
202
+ return path.length && !lstat(path.fileSystemRepresentation, &info) && S_ISDIR(info.st_mode) &&
203
+ info.st_uid == getuid();
204
+ }
205
+
206
+ // idea.config.path / idea.plugins.path overrides make the inferred folder unreliable.
207
+ static BOOL IDEPropertiesOverridePaths(NSString *file) {
208
+ NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
209
+ for (NSString *raw in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
210
+ NSString *line = [raw stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
211
+ if ([line hasPrefix:@"idea.config.path"] || [line hasPrefix:@"idea.plugins.path"]) return YES;
212
+ }
213
+ return NO;
214
+ }
215
+
216
+ #pragma mark - Snapshot
217
+
218
+ NSArray<NSDictionary *> *CCPetsIDEIntegrationSnapshot(void) {
219
+ NSMutableOrderedSet<NSString *> *paths = [NSMutableOrderedSet orderedSet];
220
+ NSMutableDictionary<NSString *, NSString *> *bundleIDs = [NSMutableDictionary dictionary];
221
+ for (NSString *directory in @[@"/Applications", [NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]]) {
222
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
223
+ if (![name.pathExtension isEqualToString:@"app"]) continue;
224
+ NSString *path = [directory stringByAppendingPathComponent:name];
225
+ NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:
226
+ [path stringByAppendingPathComponent:@"Contents/Info.plist"]];
227
+ if (!IDEBundleIsJetBrains(plist[@"CFBundleIdentifier"])) continue;
228
+ [paths addObject:path];
229
+ bundleIDs[path] = plist[@"CFBundleIdentifier"];
230
+ }
231
+ }
232
+ NSMutableDictionary<NSString *, NSDate *> *launched = [NSMutableDictionary dictionary];
233
+ for (NSRunningApplication *app in NSWorkspace.sharedWorkspace.runningApplications) {
234
+ NSString *path = app.bundleURL.path;
235
+ if (!IDEBundleIsJetBrains(app.bundleIdentifier) || !path) continue;
236
+ [paths addObject:path];
237
+ bundleIDs[path] = app.bundleIdentifier;
238
+ launched[path] = app.launchDate ?: NSDate.distantPast;
239
+ }
240
+ NSArray *instances = IDEInstances();
241
+ NSMutableDictionary *connected = [NSMutableDictionary dictionary];
242
+ for (NSDictionary *instance in instances) {
243
+ NSDictionary *status = CCPetsIDEBridgeRequest(instance, @"status", nil);
244
+ if ([status[@"instanceID"] isEqual:instance[@"instanceID"]] && [status[@"schemaVersion"] integerValue] == 1)
245
+ connected[instance[@"appPath"]] = status;
246
+ }
247
+ NSString *bundledVersion = IDEBundledPluginVersion();
248
+ NSMutableArray *rows = [NSMutableArray array];
249
+ for (NSString *path in paths) {
250
+ NSData *data = [NSData dataWithContentsOfFile:[path stringByAppendingPathComponent:@"Contents/Resources/product-info.json"]];
251
+ id info = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
252
+ if (![info isKindOfClass:NSDictionary.class]) continue;
253
+ NSString *version = [info[@"version"] isKindOfClass:NSString.class] ? info[@"version"] : @"";
254
+ NSString *build = [info[@"buildNumber"] isKindOfClass:NSString.class] ? info[@"buildNumber"] : @"";
255
+ // Some products prefix the build with their product code (e.g. "AI-251.…").
256
+ NSString *bareBuild = [build componentsSeparatedByString:@"-"].lastObject;
257
+ NSInteger baseline = [bareBuild componentsSeparatedByString:@"."].firstObject.integerValue;
258
+ BOOL compatible = baseline == 262 || baseline == 263;
259
+ // product-info.json names the per-product config folder (e.g. PyCharm2026.2,
260
+ // Google/AndroidStudio2025.1); fall back to the IDEA layout for older metadata.
261
+ NSString *dataDirectory = [info[@"dataDirectoryName"] isKindOfClass:NSString.class] ? info[@"dataDirectoryName"] : nil;
262
+ if (dataDirectory.length == 0) {
263
+ NSArray *parts = [version componentsSeparatedByString:@"."];
264
+ NSString *suffix = parts.count >= 2 ? [NSString stringWithFormat:@"%@.%@", parts[0], parts[1]] : version;
265
+ dataDirectory = [@"IntelliJIdea" stringByAppendingString:suffix];
266
+ }
267
+ BOOL google = [dataDirectory hasPrefix:@"AndroidStudio"];
268
+ NSString *config = [[NSHomeDirectory() stringByAppendingPathComponent:
269
+ google ? @"Library/Application Support/Google" : @"Library/Application Support/JetBrains"]
270
+ stringByAppendingPathComponent:dataDirectory];
271
+ NSString *plugins = [config stringByAppendingPathComponent:@"plugins"];
272
+ // A live registration supplies the IDE's real paths (Toolbox, idea.config.path, …).
273
+ BOOL registered = NO;
274
+ for (NSDictionary *instance in instances) {
275
+ if (![instance[@"appPath"] isEqual:path]) continue;
276
+ if ([instance[@"configPath"] isKindOfClass:NSString.class]) config = instance[@"configPath"];
277
+ if ([instance[@"pluginsPath"] isKindOfClass:NSString.class]) plugins = instance[@"pluginsPath"];
278
+ registered = YES;
279
+ }
280
+ BOOL customPaths = !registered &&
281
+ (IDEPropertiesOverridePaths([path stringByAppendingPathComponent:@"Contents/bin/idea.properties"]) ||
282
+ IDEPropertiesOverridePaths([config stringByAppendingPathComponent:@"idea.properties"]));
283
+ // The IDE must have run once so its config folder exists; never create it ourselves.
284
+ BOOL autoInstall = compatible && !customPaths && IDEOwnedDirectory(config);
285
+
286
+ NSString *pluginDirectory = [plugins stringByAppendingPathComponent:IDEPluginFolder];
287
+ NSString *jar = [plugins stringByAppendingPathComponent:IDEPluginJar];
288
+ BOOL installed = [NSFileManager.defaultManager fileExistsAtPath:jar];
289
+ NSString *installedVersion = installed ? IDEInstalledPluginVersion(jar) : nil;
290
+ NSDictionary *status = connected[path];
291
+ NSString *runningVersion = [status[@"pluginVersion"] isKindOfClass:NSString.class] ? status[@"pluginVersion"] : nil;
292
+ BOOL outdated = installed && bundledVersion.length && installedVersion.length &&
293
+ [installedVersion compare:bundledVersion options:NSNumericSearch] == NSOrderedAscending;
294
+ // Installed or updated after the IDE started: files are in place but not loaded yet.
295
+ struct stat folder;
296
+ BOOL changedSinceLaunch = launched[path] && installed &&
297
+ !stat(pluginDirectory.fileSystemRepresentation, &folder) &&
298
+ folder.st_mtimespec.tv_sec > (time_t)launched[path].timeIntervalSince1970;
299
+ BOOL pendingRestart = launched[path] && installed &&
300
+ (status ? (runningVersion.length && ![runningVersion isEqualToString:@"unknown"] && installedVersion.length &&
301
+ ![runningVersion isEqualToString:installedVersion])
302
+ : changedSinceLaunch);
303
+
304
+ NSString *disabled = [NSString stringWithContentsOfFile:[config stringByAppendingPathComponent:@"disabled_plugins.txt"]
305
+ encoding:NSUTF8StringEncoding error:nil];
306
+ BOOL isDisabled = [[disabled componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet] containsObject:IDEPluginID];
307
+ NSString *state;
308
+ if (!compatible && !status) state = @"unsupported";
309
+ else if (isDisabled && !status) state = @"disabled";
310
+ else if (!installed && !status) state = @"missing";
311
+ else if (outdated) state = @"outdated";
312
+ else if (pendingRestart) state = @"pendingRestart";
313
+ else if (status) state = @"connected";
314
+ else state = @"installed";
315
+ NSMutableDictionary *row = [@{@"name": [path.lastPathComponent stringByDeletingPathExtension],
316
+ @"version": version, @"state": state, @"path": path, @"compatible": @(compatible),
317
+ @"autoInstall": @(autoInstall), @"running": @(launched[path] != nil),
318
+ @"configPath": config, @"pluginsPath": plugins} mutableCopy];
319
+ if (bundleIDs[path]) row[@"bundleID"] = bundleIDs[path];
320
+ // 同一产品的多个版本(含 EAP)共用 product-info 里的 name,设置页据此合并成一行。
321
+ if ([info[@"name"] isKindOfClass:NSString.class]) row[@"productName"] = info[@"name"];
322
+ if (installedVersion) row[@"pluginVersion"] = installedVersion;
323
+ if (bundledVersion) row[@"bundledVersion"] = bundledVersion;
324
+ [rows addObject:row];
325
+ }
326
+ return rows;
327
+ }
328
+
329
+ #pragma mark - Install
330
+
331
+ static NSError *IDEInstallError(NSString *message) {
332
+ return [NSError errorWithDomain:@"CCPetsIDEPlugin" code:1 userInfo:@{NSLocalizedDescriptionKey: message}];
333
+ }
334
+
335
+ // Returns nil on success, otherwise a message for the user.
336
+ static NSString *IDESwapInPlugin(NSString *archive, NSString *staging, NSString *target) {
337
+ struct stat info;
338
+ NSTask *task = [NSTask new];
339
+ task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/ditto"];
340
+ task.arguments = @[@"-x", @"-k", archive, staging];
341
+ task.standardOutput = NSFileHandle.fileHandleWithNullDevice;
342
+ task.standardError = NSFileHandle.fileHandleWithNullDevice;
343
+ if (![task launchAndReturnError:nil]) return L(@"Installation failed.");
344
+ [task waitUntilExit];
345
+ NSString *fresh = [staging stringByAppendingPathComponent:IDEPluginFolder];
346
+ NSString *freshJar = [staging stringByAppendingPathComponent:IDEPluginJar];
347
+ if (task.terminationStatus != 0 || lstat(freshJar.fileSystemRepresentation, &info) || !S_ISREG(info.st_mode)) {
348
+ return L(@"The bundled plugin ZIP is damaged. Reinstall CC Pets to restore it.");
349
+ }
350
+ NSString *previous = [staging stringByAppendingPathComponent:@"previous"];
351
+ BOOL hadPrevious = lstat(target.fileSystemRepresentation, &info) == 0;
352
+ if (hadPrevious && rename(target.fileSystemRepresentation, previous.fileSystemRepresentation) != 0) {
353
+ return [NSString stringWithFormat:@"%@ (%s)", target, strerror(errno)];
354
+ }
355
+ if (rename(fresh.fileSystemRepresentation, target.fileSystemRepresentation) != 0) {
356
+ NSString *message = [NSString stringWithFormat:@"%@ (%s)", target, strerror(errno)];
357
+ if (hadPrevious) rename(previous.fileSystemRepresentation, target.fileSystemRepresentation);
358
+ return message;
359
+ }
360
+ // The ZIP carries fixed timestamps; mark the folder with the install time so a
361
+ // running IDE can be reported as needing a restart.
362
+ utimes(target.fileSystemRepresentation, NULL);
363
+ return nil;
364
+ }
365
+
366
+ // Extracts the bundled ZIP next to the target and swaps it in with renames, so a failed
367
+ // extraction never leaves a half-written plugin behind.
368
+ BOOL CCPetsInstallIDEPlugin(NSDictionary *ide, NSError **error) {
369
+ NSString *archive = IDEPluginArchive();
370
+ NSString *config = ide[@"configPath"];
371
+ NSString *plugins = ide[@"pluginsPath"];
372
+ NSFileManager *files = NSFileManager.defaultManager;
373
+ if (!archive) {
374
+ if (error) *error = IDEInstallError(L(@"The JetBrains plugin ZIP is missing from this CC Pets installation. Reinstall CC Pets to restore it."));
375
+ return NO;
376
+ }
377
+ if (![ide[@"autoInstall"] boolValue] || ![config isKindOfClass:NSString.class] ||
378
+ ![plugins isKindOfClass:NSString.class] || !IDEOwnedDirectory(config)) {
379
+ if (error) *error = IDEInstallError(L(@"This IDE's plugin folder could not be determined safely."));
380
+ return NO;
381
+ }
382
+ struct stat info;
383
+ if (lstat(plugins.fileSystemRepresentation, &info) == 0) {
384
+ if (!IDEOwnedDirectory(plugins)) {
385
+ if (error) *error = IDEInstallError(L(@"This IDE's plugin folder could not be determined safely."));
386
+ return NO;
387
+ }
388
+ } else if (mkdir(plugins.fileSystemRepresentation, 0755) != 0) {
389
+ if (error) *error = IDEInstallError([NSString stringWithFormat:@"%@ (%s)", plugins, strerror(errno)]);
390
+ return NO;
391
+ }
392
+ NSString *target = [plugins stringByAppendingPathComponent:IDEPluginFolder];
393
+ if (lstat(target.fileSystemRepresentation, &info) == 0 && (!S_ISDIR(info.st_mode) || info.st_uid != getuid())) {
394
+ if (error) *error = IDEInstallError(L(@"This IDE's plugin folder could not be determined safely."));
395
+ return NO;
396
+ }
397
+ char pattern[PATH_MAX];
398
+ snprintf(pattern, sizeof pattern, "%s/.cc-pets-terminal-install-XXXXXX", plugins.fileSystemRepresentation);
399
+ if (!mkdtemp(pattern)) {
400
+ if (error) *error = IDEInstallError([NSString stringWithFormat:@"%@ (%s)", plugins, strerror(errno)]);
401
+ return NO;
402
+ }
403
+ NSString *staging = [files stringWithFileSystemRepresentation:pattern length:strlen(pattern)];
404
+ NSString *failure = IDESwapInPlugin(archive, staging, target);
405
+ [files removeItemAtPath:staging error:nil];
406
+ if (failure && error) *error = IDEInstallError(failure);
407
+ return failure == nil;
408
+ }
409
+
410
+ void CCPetsPromptInstallIDEPlugin(NSDictionary *ide, void (^completion)(void)) {
411
+ if (![ide[@"autoInstall"] boolValue]) {
412
+ CCPetsShowIDEPluginInstaller();
413
+ if (completion) completion();
414
+ return;
415
+ }
416
+ BOOL update = [ide[@"state"] isEqualToString:@"outdated"];
417
+ NSString *name = ide[@"name"];
418
+ NSAlert *confirm = [NSAlert new];
419
+ confirm.messageText = [NSString stringWithFormat:
420
+ update ? L(@"Update CC Pets Terminal in %@?") : L(@"Install CC Pets Terminal in %@?"), name];
421
+ NSString *where = [NSString stringWithFormat:L(@"The plugin will be written to %@."),
422
+ [ide[@"pluginsPath"] stringByAbbreviatingWithTildeInPath]];
423
+ confirm.informativeText = [ide[@"running"] boolValue]
424
+ ? [NSString stringWithFormat:@"%@ %@", where, [NSString stringWithFormat:L(@"Restart %@ afterwards to load it."), name]]
425
+ : [NSString stringWithFormat:@"%@ %@", where, L(@"It loads the next time the IDE starts.")];
426
+ [confirm addButtonWithTitle:update ? L(@"Update") : L(@"Install")];
427
+ [confirm addButtonWithTitle:L(@"Cancel")];
428
+ if ([confirm runModal] != NSAlertFirstButtonReturn) {
429
+ if (completion) completion();
430
+ return;
431
+ }
432
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
433
+ NSError *error = nil;
434
+ BOOL ok = CCPetsInstallIDEPlugin(ide, &error);
435
+ dispatch_async(dispatch_get_main_queue(), ^{
436
+ if (!ok) {
437
+ NSAlert *alert = [NSAlert new];
438
+ alert.alertStyle = NSAlertStyleWarning;
439
+ alert.messageText = L(@"Could not install the plugin automatically");
440
+ alert.informativeText = error.localizedDescription ?: L(@"Installation failed.");
441
+ [alert addButtonWithTitle:L(@"Install Manually…")];
442
+ [alert addButtonWithTitle:L(@"OK")];
443
+ if ([alert runModal] == NSAlertFirstButtonReturn) CCPetsShowIDEPluginInstaller();
444
+ }
445
+ if (completion) completion();
446
+ });
447
+ });
448
+ }
449
+
450
+ static void IDEFocusNotice(BOOL pluginMissing, NSString *bundleID) {
451
+ NSAlert *alert = [NSAlert new];
452
+ alert.messageText = L(@"JetBrains terminal jump");
453
+ alert.informativeText = pluginMissing
454
+ ? L(@"Install and enable CC Pets Terminal in your JetBrains IDE, then open a project. The plugin connects automatically and selects the terminal for this card.")
455
+ : L(@"The matching JetBrains terminal is unavailable. Use a local Reworked terminal and trigger a new agent event. If the IDE is showing a dialog, close it and try again.");
456
+ if (pluginMissing) [alert addButtonWithTitle:L(@"Install Plugin…")];
457
+ [alert addButtonWithTitle:L(@"OK")];
458
+ if ([alert runModal] != NSAlertFirstButtonReturn || !pluginMissing) return;
459
+ // Install straight into the IDE that hosts this card when it is unambiguous.
460
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
461
+ NSMutableArray *matches = [NSMutableArray array];
462
+ for (NSDictionary *ide in CCPetsIDEIntegrationSnapshot()) {
463
+ if ([ide[@"bundleID"] isEqualToString:bundleID] && [ide[@"running"] boolValue]) [matches addObject:ide];
464
+ }
465
+ dispatch_async(dispatch_get_main_queue(), ^{
466
+ if (matches.count == 1) CCPetsPromptInstallIDEPlugin(matches.firstObject, nil);
467
+ else CCPetsShowIDEPluginInstaller();
468
+ });
469
+ });
470
+ }
471
+
472
+ BOOL CCPetsRequestIDETerminalFocus(NSDictionary *target) {
473
+ NSString *bundle = [target[@"bundleID"] isKindOfClass:NSString.class] ? target[@"bundleID"] : @"";
474
+ NSString *instanceID = SanitizedShortString(target[@"ideInstance"], 64);
475
+ NSString *terminalID = SanitizedShortString(target[@"ideTerminal"], 64);
476
+ NSString *tty = SanitizedShortString([target[@"tty"] isKindOfClass:NSString.class]
477
+ ? [target[@"tty"] lastPathComponent] : nil, 64);
478
+ // A VS Code window started from a JetBrains terminal inherits its CC_PETS_IDE_* values;
479
+ // those never name a VS Code terminal.
480
+ if (CCPetsBundleIsVSCodeFamily(bundle)) return NO;
481
+ if (!IDEBundleIsJetBrains(bundle) && instanceID.length == 0) return NO;
482
+ // AppKit stays responsive while the IDE selects its content on its own UI thread.
483
+ static BOOL focusing = NO;
484
+ if (focusing) return YES;
485
+ focusing = YES;
486
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
487
+ NSArray *instances = IDEInstances();
488
+ BOOL found = NO, focused = NO;
489
+ for (NSDictionary *instance in instances) {
490
+ if (instanceID.length && ![instance[@"instanceID"] isEqualToString:instanceID]) continue;
491
+ NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:[instance[@"pid"] intValue]];
492
+ if (!instanceID.length && ![app.bundleIdentifier isEqualToString:bundle]) continue;
493
+ found = YES;
494
+ NSDictionary *response = CCPetsIDEBridgeRequest(instance, @"focus", @{@"tty": tty ?: @"", @"terminalID": terminalID ?: @""});
495
+ if ([response[@"focused"] boolValue]) { focused = YES; break; }
496
+ }
497
+ dispatch_async(dispatch_get_main_queue(), ^{
498
+ focusing = NO;
499
+ if (!focused) IDEFocusNotice(!found, bundle);
500
+ });
501
+ });
502
+ return YES;
503
+ }
@@ -391,7 +391,7 @@ int InstallCodexHooksAtHome(NSString *binary, NSString *codexHome) {
391
391
  CCPetsShellQuote(codexHome), CCPetsShellQuote(binary)];
392
392
  ReplaceManagedHooks(config, @[@[CCPetsCodexHookMarker, @"cc-pets"], @[CCPetsLegacyCodexHookMarker, @"codex-pet"]], command, @[
393
393
  @"SessionStart", @"UserPromptSubmit", @"PreToolUse", @"PermissionRequest", @"PostToolUse",
394
- @"SubagentStart", @"SubagentStop", @"Stop"
394
+ @"SubagentStart", @"SubagentStop", @"Stop", @"SessionEnd"
395
395
  ]);
396
396
 
397
397
  NSString *text = [CCPetsJSONStringify(config) stringByAppendingString:@"\n"];
@@ -0,0 +1,5 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // 包装器在登记会话、发送 starting 和启动桌宠之前调用。
4
+ // 开关关闭时直接返回 0;检查失败时向 stderr 给出原因并返回非零。
5
+ int CCPetsLaunchPreflight(NSString *provider, NSArray<NSString *> *arguments);