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,367 @@
1
+ #import "CCPetsLaunchPreflight.h"
2
+ #import "CCPetsCLISupport.h"
3
+ #import "CCPetsL10n.h"
4
+ #import "CCPetsPreferences.h"
5
+ #import <arpa/inet.h>
6
+
7
+ static int BlockLaunch(NSString *provider, NSString *reason) {
8
+ CCPetsPrintLine(stderr, CCPetsInterpolate(
9
+ L(@"CC Pets blocked {provider}: {reason}"), @{@"provider": provider, @"reason": reason}));
10
+ CCPetsPrintLine(stderr, L(@"Connect Shadowrocket and select an exit outside mainland China / Hong Kong, then check routing and DNS settings. You can turn off this check in Main menu → Settings → Launch Protection."));
11
+ return 1;
12
+ }
13
+
14
+ static BOOL ShadowrocketConnected(NSString **reason) {
15
+ NSString *output = nil;
16
+ // 只匹配 VPN provider ID;用户改过服务名称仍能识别,其他 VPN 不会被误认。
17
+ int status = CCPetsRun(@"/usr/sbin/scutil", @[@"--nc", @"list"], nil, nil, 3, &output, NULL);
18
+ if (status != 0) {
19
+ *reason = L(@"Unable to read the system VPN status.");
20
+ return NO;
21
+ }
22
+ NSRegularExpression *providerPattern = [NSRegularExpression regularExpressionWithPattern:
23
+ @"\\[VPN:com\\.liguangming\\.Shadowrocket\\]\\s*$" options:0 error:nil];
24
+ NSRegularExpression *connectedPattern = [NSRegularExpression regularExpressionWithPattern:
25
+ @"^\\*\\s+\\(Connected\\)\\s+" options:0 error:nil];
26
+ BOOL found = NO;
27
+ for (NSString *line in [output componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
28
+ NSRange range = NSMakeRange(0, line.length);
29
+ if (![providerPattern firstMatchInString:line options:0 range:range]) continue;
30
+ found = YES;
31
+ if ([connectedPattern firstMatchInString:line options:0 range:range]) return YES;
32
+ }
33
+ *reason = found ? L(@"Shadowrocket is not connected. Opening the app alone is not enough.")
34
+ : L(@"No Shadowrocket VPN configuration was found.");
35
+ return NO;
36
+ }
37
+
38
+ static NSDictionary *ReadJSONObject(NSString *path) {
39
+ NSData *data = [NSData dataWithContentsOfFile:path];
40
+ id value = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
41
+ return [value isKindOfClass:NSDictionary.class] ? value : nil;
42
+ }
43
+
44
+ static NSString *NonemptyString(id value) {
45
+ return [value isKindOfClass:NSString.class] && [value length] > 0 ? value : nil;
46
+ }
47
+
48
+ // 仅支持明确的单行 TOML 字符串。未支持的路由写法必须报错,不能猜测官方出口。
49
+ static NSDictionary *CodexRouting(NSString *home, NSString **reason) {
50
+ NSString *path = [home stringByAppendingPathComponent:@"config.toml"];
51
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) return @{};
52
+ NSString *config = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
53
+ if (!config) { *reason = L(@"Unable to read the CLI network configuration."); return nil; }
54
+ NSMutableDictionary *routing = [NSMutableDictionary dictionary];
55
+ __block NSString *section = @"";
56
+ __block NSString *multilineDelimiter = nil;
57
+ __block BOOL valid = YES;
58
+ NSRegularExpression *table = [NSRegularExpression regularExpressionWithPattern:
59
+ @"^\\[([A-Za-z0-9_.-]+)\\]\\s*(?:#.*)?$" options:0 error:nil];
60
+ NSRegularExpression *assignment = [NSRegularExpression regularExpressionWithPattern:
61
+ @"^([A-Za-z0-9_.-]+)\\s*=\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|'[^']*')\\s*(?:#.*)?$" options:0 error:nil];
62
+ NSRegularExpression *routeKey = [NSRegularExpression regularExpressionWithPattern:
63
+ @"(?:^|[^A-Za-z0-9_])(model_provider|model_providers|profile|profiles|base_url|chatgpt_base_url)(?:[^A-Za-z0-9_]|$)"
64
+ options:0 error:nil];
65
+ [config enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
66
+ NSString *trimmed = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
67
+ if (multilineDelimiter) {
68
+ if ([trimmed containsString:multilineDelimiter]) multilineDelimiter = nil;
69
+ return;
70
+ }
71
+ if (trimmed.length == 0 || [trimmed hasPrefix:@"#"]) return;
72
+ for (NSString *delimiter in @[@"\"\"\"", @"'''"]) {
73
+ NSRange start = [trimmed rangeOfString:delimiter];
74
+ if (start.location == NSNotFound) continue;
75
+ NSString *key = [[trimmed componentsSeparatedByString:@"="] firstObject];
76
+ if ([routeKey firstMatchInString:key options:0 range:NSMakeRange(0, key.length)]) valid = NO;
77
+ if (![[trimmed substringFromIndex:NSMaxRange(start)] containsString:delimiter]) multilineDelimiter = delimiter;
78
+ return;
79
+ }
80
+ if ([trimmed hasPrefix:@"["]) {
81
+ NSTextCheckingResult *match = [table firstMatchInString:trimmed options:0 range:NSMakeRange(0, trimmed.length)];
82
+ // 引号表名、内联表和多行值不在本探测器的 TOML 子集内。
83
+ if (!match && [routeKey firstMatchInString:trimmed options:0 range:NSMakeRange(0, trimmed.length)]) valid = NO;
84
+ section = match ? [trimmed substringWithRange:[match rangeAtIndex:1]] : @"<other>";
85
+ return;
86
+ }
87
+ NSString *key = [[trimmed componentsSeparatedByString:@"="] firstObject];
88
+ if ([section isEqualToString:@"model_providers"] || [section isEqualToString:@"profiles"]) { valid = NO; return; }
89
+ if (![routeKey firstMatchInString:key options:0 range:NSMakeRange(0, key.length)]) return;
90
+ if (section.length > 0 && ![section hasPrefix:@"profiles."] && ![section hasPrefix:@"model_providers."]) return;
91
+ NSTextCheckingResult *match = [assignment firstMatchInString:trimmed options:0 range:NSMakeRange(0, trimmed.length)];
92
+ if (!match) { valid = NO; return; }
93
+ key = [trimmed substringWithRange:[match rangeAtIndex:1]];
94
+ NSString *literal = [trimmed substringWithRange:[match rangeAtIndex:2]];
95
+ NSString *value = [literal hasPrefix:@"'"] ? [literal substringWithRange:NSMakeRange(1, literal.length - 2)] :
96
+ [NSJSONSerialization JSONObjectWithData:[literal dataUsingEncoding:NSUTF8StringEncoding]
97
+ options:NSJSONReadingFragmentsAllowed error:nil];
98
+ NSString *fullKey = section.length > 0 ? [section stringByAppendingFormat:@".%@", key] : key;
99
+ if (!NonemptyString(value) || routing[fullKey]) { valid = NO; return; }
100
+ routing[fullKey] = value;
101
+ }];
102
+ if (!valid || multilineDelimiter) { *reason = L(@"Unable to determine the CLI endpoint from its network configuration."); return nil; }
103
+ return routing;
104
+ }
105
+
106
+ static NSString *TraceURL(NSString *baseURL, NSString **reason) {
107
+ NSURLComponents *url = [NSURLComponents componentsWithString:baseURL];
108
+ if (![url.scheme.lowercaseString isEqualToString:@"https"] || !url.host.length || url.user || url.password) {
109
+ *reason = L(@"The exit check requires an HTTPS endpoint without embedded credentials.");
110
+ return nil;
111
+ }
112
+ url.path = @"/cdn-cgi/trace";
113
+ url.query = nil;
114
+ url.fragment = nil;
115
+ return url.string;
116
+ }
117
+
118
+ static NSArray<NSString *> *ProbeURLs(NSString *provider, NSMutableDictionary *environment, NSString *selectedProfile, NSString **reason) {
119
+ if ([provider isEqualToString:@"claude"]) {
120
+ // 读取网络相关 env,不执行 apiKeyHelper,也不把账号凭据放进探测请求。
121
+ NSString *path = [CCPetsClaudeHome() stringByAppendingPathComponent:@"settings.json"];
122
+ NSDictionary *settings = ReadJSONObject(path);
123
+ if (!settings && [NSFileManager.defaultManager fileExistsAtPath:path]) {
124
+ *reason = L(@"Unable to read the CLI network configuration."); return nil;
125
+ }
126
+ NSDictionary *env = [settings[@"env"] isKindOfClass:NSDictionary.class] ? settings[@"env"] : @{};
127
+ for (NSString *key in @[@"ANTHROPIC_BASE_URL", @"HTTPS_PROXY", @"https_proxy", @"HTTP_PROXY", @"http_proxy",
128
+ @"NO_PROXY", @"no_proxy", @"CLAUDE_CODE_USE_BEDROCK", @"CLAUDE_CODE_USE_VERTEX", @"CLAUDE_CODE_USE_FOUNDRY"]) {
129
+ if ([env[key] isKindOfClass:NSString.class]) environment[key] = env[key];
130
+ }
131
+ for (NSString *key in @[@"CLAUDE_CODE_USE_BEDROCK", @"CLAUDE_CODE_USE_VERTEX", @"CLAUDE_CODE_USE_FOUNDRY"]) {
132
+ if ([environment[key] isEqualToString:@"1"]) {
133
+ *reason = L(@"Exit checks for this cloud provider are not supported. No official-domain fallback was used."); return nil;
134
+ }
135
+ }
136
+ // curl 与 Claude 对代理变量的优先级不同,明确指定 Claude 的 HTTPS 代理。
137
+ NSString *proxy = NonemptyString(environment[@"https_proxy"]) ?: NonemptyString(environment[@"HTTPS_PROXY"]) ?:
138
+ NonemptyString(environment[@"http_proxy"]) ?: NonemptyString(environment[@"HTTP_PROXY"]);
139
+ [environment removeObjectForKey:@"ALL_PROXY"];
140
+ [environment removeObjectForKey:@"all_proxy"];
141
+ if (proxy) { environment[@"https_proxy"] = proxy; environment[@"HTTPS_PROXY"] = proxy; }
142
+ NSString *url = TraceURL(NonemptyString(environment[@"ANTHROPIC_BASE_URL"]) ?: @"https://api.anthropic.com", reason);
143
+ return url ? @[url] : nil;
144
+ }
145
+
146
+ NSDictionary *routing = CodexRouting(CCPetsCodexHome(), reason);
147
+ if (!routing) return nil;
148
+ NSString *profile = selectedProfile ?: routing[@"profile"];
149
+ if (profile) {
150
+ NSString *prefix = [NSString stringWithFormat:@"profiles.%@.", profile];
151
+ NSMutableDictionary *effective = [routing mutableCopy];
152
+ for (NSString *key in routing) {
153
+ if ([key hasPrefix:prefix]) effective[[key substringFromIndex:prefix.length]] = routing[key];
154
+ }
155
+ routing = effective;
156
+ }
157
+ NSString *modelProvider = routing[@"model_provider"] ?: @"openai";
158
+ NSString *baseURL = routing[[NSString stringWithFormat:@"model_providers.%@.base_url", modelProvider]];
159
+ if (!baseURL && [modelProvider isEqualToString:@"openai"]) baseURL = NonemptyString(environment[@"OPENAI_BASE_URL"]);
160
+ if (baseURL) {
161
+ NSString *url = TraceURL(baseURL, reason);
162
+ return url ? @[url] : nil;
163
+ }
164
+ if (![modelProvider isEqualToString:@"openai"]) {
165
+ *reason = L(@"Unable to determine the CLI endpoint from its network configuration."); return nil;
166
+ }
167
+ NSString *chatGPTBase = routing[@"chatgpt_base_url"] ?: @"https://chatgpt.com";
168
+ NSDictionary *auth = ReadJSONObject([CCPetsCodexHome() stringByAppendingPathComponent:@"auth.json"]);
169
+ NSString *mode = NonemptyString(auth[@"auth_mode"]);
170
+ BOOL api = [mode isEqualToString:@"apikey"];
171
+ BOOL chatGPT = [@[@"chatgpt", @"chatgptAuthTokens"] containsObject:mode ?: @""];
172
+ if (!mode) {
173
+ BOOL key = NonemptyString(auth[@"OPENAI_API_KEY"]) != nil;
174
+ NSDictionary *tokens = [auth[@"tokens"] isKindOfClass:NSDictionary.class] ? auth[@"tokens"] : nil;
175
+ BOOL token = NonemptyString(tokens[@"access_token"]) != nil;
176
+ api = key && !token;
177
+ chatGPT = token && !key;
178
+ }
179
+ if (mode && !api && !chatGPT) {
180
+ *reason = L(@"Unable to determine the CLI endpoint from its network configuration."); return nil;
181
+ }
182
+ NSString *chatGPTURL = TraceURL(chatGPTBase, reason);
183
+ if (!chatGPTURL) return nil;
184
+ if (api) return @[@"https://api.openai.com/cdn-cgi/trace"];
185
+ if (chatGPT) return @[chatGPTURL];
186
+ // 未登录或凭据位于 Keychain 时不猜模式;两个候选出口都必须通过。
187
+ CCPetsPrintLine(stderr, L(@"Codex login mode is unknown; checking both ChatGPT and OpenAI API exits."));
188
+ return @[chatGPTURL, @"https://api.openai.com/cdn-cgi/trace"];
189
+ }
190
+
191
+ static NSDictionary *ParseTrace(NSString *body, NSString *host) {
192
+ NSMutableDictionary *fields = [NSMutableDictionary dictionary];
193
+ for (NSString *line in [body componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
194
+ NSRange equals = [line rangeOfString:@"="];
195
+ if (equals.location == NSNotFound) continue;
196
+ NSString *key = [line substringToIndex:equals.location];
197
+ if (![@[@"ip", @"loc", @"h"] containsObject:key]) continue;
198
+ if (fields[key]) return nil;
199
+ fields[key] = [line substringFromIndex:NSMaxRange(equals)];
200
+ }
201
+ NSString *ip = fields[@"ip"], *loc = fields[@"loc"];
202
+ struct in6_addr address;
203
+ if (!ip || (inet_pton(AF_INET, ip.UTF8String, &address) != 1 && inet_pton(AF_INET6, ip.UTF8String, &address) != 1)) return nil;
204
+ if (loc.length != 2 || ![NSLocale.ISOCountryCodes containsObject:loc]) return nil;
205
+ if (![fields[@"h"] isKindOfClass:NSString.class] || ![[fields[@"h"] lowercaseString] isEqualToString:host.lowercaseString]) return nil;
206
+ return fields;
207
+ }
208
+
209
+ static const NSTimeInterval ExitConnectTimeout = 8;
210
+ static const NSTimeInterval ExitRequestTimeout = 15;
211
+ static const NSTimeInterval ExitProcessTimeout = 16;
212
+ static const NSInteger ExitMaxAttempts = 2;
213
+
214
+ static BOOL RetryableExitFailure(int status, NSInteger httpStatus) {
215
+ // 仅重试临时传输故障和网关错误,不重试 TLS / 证书错误、拒绝访问或无效 trace。
216
+ if (status == 0) return httpStatus == 502 || httpStatus == 503 || httpStatus == 504;
217
+ return status == CCPetsRunTimedOut || [@[@5, @6, @7, @18, @28, @52, @55, @56, @92] containsObject:@(status)];
218
+ }
219
+
220
+ static NSDictionary *ProbeExit(NSString *url, NSString *host, NSDictionary *environment, NSString **reason) {
221
+ for (NSInteger attempt = 1; attempt <= ExitMaxAttempts; attempt++) {
222
+ NSString *output = nil;
223
+ NSTimeInterval started = NSProcessInfo.processInfo.systemUptime;
224
+ // -q 必须是首个参数;不携带 CLI token、不跟随重定向、正常校验证书。
225
+ // write-out 单独占最后一行,避免把 trace 正文或错误页当作诊断指标。
226
+ // 不使用 curl --retry,确保每次尝试独立解析,不能用旧的合法响应掩盖后续失败。
227
+ int status = CCPetsRun(@"/usr/bin/curl", @[@"-q", @"--silent", @"--globoff", @"--request", @"GET",
228
+ @"--write-out", @"\n%{http_code}\t%{time_namelookup}\t%{time_connect}\t%{time_appconnect}\t%{time_starttransfer}\t%{time_total}",
229
+ @"--max-filesize", @"16384",
230
+ @"--connect-timeout", [NSString stringWithFormat:@"%.0f", ExitConnectTimeout],
231
+ @"--max-time", [NSString stringWithFormat:@"%.0f", ExitRequestTimeout], @"--proto", @"=https", url],
232
+ nil, environment, ExitProcessTimeout, &output, NULL);
233
+ NSTimeInterval elapsed = NSProcessInfo.processInfo.systemUptime - started;
234
+ NSRange separator = output ? [output rangeOfString:@"\n" options:NSBackwardsSearch] : NSMakeRange(NSNotFound, 0);
235
+ NSArray<NSString *> *metrics = separator.location == NSNotFound ? @[] :
236
+ [[output substringFromIndex:NSMaxRange(separator)] componentsSeparatedByString:@"\t"];
237
+ BOOL hasMetrics = metrics.count == 6;
238
+ NSInteger httpStatus = hasMetrics ? metrics[0].integerValue : 0;
239
+ NSString *detail;
240
+ if (status == 0 && httpStatus == 200) {
241
+ NSDictionary *trace = ParseTrace([output substringToIndex:separator.location], host);
242
+ if (trace) return trace;
243
+ detail = L(@"No valid exit IP / region was returned.");
244
+ } else if (status == CCPetsRunTimedOut) {
245
+ detail = L(@"The exit-check process exceeded its 16s limit.");
246
+ } else if (status == 28) {
247
+ if (!hasMetrics) detail = L(@"The exit request timed out; connection timing is unavailable.");
248
+ else if (metrics[3].doubleValue <= 0) detail = L(@"Connection timed out before HTTPS was ready (DNS / TCP / TLS; 8s limit).");
249
+ else detail = L(@"HTTPS connected, but the response did not complete within the 15s request limit.");
250
+ } else if (status == 5 || status == 6) {
251
+ detail = L(@"The proxy or service hostname could not be resolved.");
252
+ } else if (status == 35 || status == 60) {
253
+ detail = L(@"TLS negotiation or certificate verification failed.");
254
+ } else if (status == 0) {
255
+ detail = CCPetsInterpolate(L(@"The exit-region endpoint returned HTTP {status}; the exit region could not be confirmed."),
256
+ @{@"status": @(httpStatus)});
257
+ } else {
258
+ detail = L(@"The exit-region request failed; the exit region could not be confirmed.");
259
+ }
260
+ // 只输出数值指标,不输出代理 URL、认证信息、curl 原始错误或服务响应正文。
261
+ NSString *diagnostics = CCPetsInterpolate(
262
+ L(@"Attempt {attempt}/{max}; elapsed {elapsed}s; curl={code}; HTTP={http}; DNS={dns}s, TCP={tcp}s, TLS={tls}s, first byte={first}s, request={total}s (cumulative timings)."),
263
+ @{@"attempt": @(attempt), @"max": @(ExitMaxAttempts), @"elapsed": [NSString stringWithFormat:@"%.2f", elapsed],
264
+ @"code": @(status), @"http": @(httpStatus),
265
+ @"dns": hasMetrics ? [NSString stringWithFormat:@"%.3f", metrics[1].doubleValue] : @"-",
266
+ @"tcp": hasMetrics ? [NSString stringWithFormat:@"%.3f", metrics[2].doubleValue] : @"-",
267
+ @"tls": hasMetrics ? [NSString stringWithFormat:@"%.3f", metrics[3].doubleValue] : @"-",
268
+ @"first": hasMetrics ? [NSString stringWithFormat:@"%.3f", metrics[4].doubleValue] : @"-",
269
+ @"total": hasMetrics ? [NSString stringWithFormat:@"%.3f", metrics[5].doubleValue] : @"-"});
270
+ *reason = [NSString stringWithFormat:@"%@ %@", detail, diagnostics];
271
+ if (attempt == ExitMaxAttempts || !RetryableExitFailure(status, httpStatus)) return nil;
272
+ CCPetsPrintLine(stderr, CCPetsInterpolate(
273
+ L(@"CC Pets: {host}: {detail} Retrying in 1s (attempt 2/2)."), @{@"host": host, @"detail": *reason}));
274
+ [NSThread sleepForTimeInterval:1];
275
+ if (!ShadowrocketConnected(reason)) return nil;
276
+ }
277
+ return nil;
278
+ }
279
+
280
+ // 不静默忽略会改变目标服务的命令行覆盖;配置 profile 可以直接参与解析。
281
+ static BOOL ResolveArguments(NSString *provider, NSArray<NSString *> *arguments, NSString **profile, NSString **directory) {
282
+ BOOL codex = [provider isEqualToString:@"codex"];
283
+ for (NSUInteger index = 0; index < arguments.count; index++) {
284
+ NSString *argument = arguments[index];
285
+ if ([argument isEqualToString:@"--"]) break;
286
+ if (codex && ([@[@"--profile", @"-p"] containsObject:argument] || [argument hasPrefix:@"--profile="])) {
287
+ NSString *value = [argument hasPrefix:@"--profile="] ? [argument substringFromIndex:10] :
288
+ (++index < arguments.count ? arguments[index] : nil);
289
+ if (!value.length) return NO;
290
+ *profile = value;
291
+ } else if (codex && ([@[@"--cd", @"-C"] containsObject:argument] || [argument hasPrefix:@"--cd="])) {
292
+ NSString *value = [argument hasPrefix:@"--cd="] ? [argument substringFromIndex:5] :
293
+ (++index < arguments.count ? arguments[index] : nil);
294
+ if (!value.length) return NO;
295
+ *directory = CCPetsResolvePath(value);
296
+ } else if (codex && ([@[@"-c", @"--config", @"--oss", @"--local-provider"] containsObject:argument] ||
297
+ [argument hasPrefix:@"--config="] || [argument hasPrefix:@"--local-provider="] ||
298
+ [argument hasPrefix:@"-c"] || [argument hasPrefix:@"-p"] || [argument hasPrefix:@"-C"])) {
299
+ // -c 可以覆盖任意嵌套项,不能当作默认配置放行。
300
+ return NO;
301
+ } else if (!codex && ([@[@"--settings", @"--setting-sources"] containsObject:argument] ||
302
+ [argument hasPrefix:@"--settings="] || [argument hasPrefix:@"--setting-sources="])) return NO;
303
+ }
304
+ return YES;
305
+ }
306
+
307
+ static BOOL HasLocalNetworkOverrides(NSString *provider, NSString *directory) {
308
+ BOOL claude = [provider isEqualToString:@"claude"];
309
+ NSArray *networkKeys = @[@"ANTHROPIC_BASE_URL", @"HTTPS_PROXY", @"https_proxy", @"HTTP_PROXY", @"http_proxy",
310
+ @"NO_PROXY", @"no_proxy", @"CLAUDE_CODE_USE_BEDROCK", @"CLAUDE_CODE_USE_VERTEX", @"CLAUDE_CODE_USE_FOUNDRY"];
311
+ // 项目配置是否受信任由 CLI 判断。包装器不替 CLI 信任项目中的代理地址。
312
+ for (NSString *parent = directory; parent.length > 0; parent = parent.stringByDeletingLastPathComponent) {
313
+ NSString *configHome = [parent stringByAppendingPathComponent:claude ? @".claude" : @".codex"];
314
+ NSString *userHome = claude ? CCPetsClaudeHome() : CCPetsCodexHome();
315
+ if (![configHome.stringByResolvingSymlinksInPath isEqualToString:userHome.stringByResolvingSymlinksInPath]) {
316
+ if (claude) {
317
+ for (NSString *file in @[@"settings.json", @"settings.local.json"]) {
318
+ NSString *path = [configHome stringByAppendingPathComponent:file];
319
+ NSDictionary *settings = ReadJSONObject(path);
320
+ if (!settings && [NSFileManager.defaultManager fileExistsAtPath:path]) return YES;
321
+ NSDictionary *env = [settings[@"env"] isKindOfClass:NSDictionary.class] ? settings[@"env"] : nil;
322
+ for (NSString *key in networkKeys) if (env[key]) return YES;
323
+ }
324
+ } else {
325
+ NSString *reason = nil;
326
+ NSDictionary *routing = CodexRouting(configHome, &reason);
327
+ if (!routing || routing.count > 0) return YES;
328
+ }
329
+ }
330
+ if ([parent isEqualToString:@"/"]) break;
331
+ }
332
+ return NO;
333
+ }
334
+
335
+ int CCPetsLaunchPreflight(NSString *provider, NSArray<NSString *> *arguments) {
336
+ if (![@[@"claude", @"codex"] containsObject:provider]) {
337
+ CCPetsPrintLine(stderr, L(@"Launch check expects claude or codex."));
338
+ return 2;
339
+ }
340
+ if (!CCPetsPrefBool(CCPetsShadowrocketLaunchCheckKey)) return 0;
341
+ NSString *name = [provider isEqualToString:@"claude"] ? @"Claude" : @"Codex";
342
+ CCPetsPrintLine(stderr, L(@"CC Pets: checking Shadowrocket and service exit regions ..."));
343
+ NSString *reason = nil;
344
+ if (!ShadowrocketConnected(&reason)) return BlockLaunch(name, reason);
345
+
346
+ NSString *profile = nil, *directory = NSFileManager.defaultManager.currentDirectoryPath;
347
+ if (!ResolveArguments(provider, arguments, &profile, &directory) || HasLocalNetworkOverrides(provider, directory)) {
348
+ return BlockLaunch(name, L(@"CLI arguments or project network overrides cannot be verified by this exit check."));
349
+ }
350
+ NSMutableDictionary *environment = [NSProcessInfo.processInfo.environment mutableCopy];
351
+ NSArray<NSString *> *urls = ProbeURLs(provider, environment, profile, &reason);
352
+ if (!urls) return BlockLaunch(name, reason);
353
+ for (NSString *url in urls) {
354
+ NSURLComponents *components = [NSURLComponents componentsWithString:url];
355
+ NSString *host = components.port ? [components.host stringByAppendingFormat:@":%@", components.port] : components.host;
356
+ NSDictionary *trace = ProbeExit(url, host, environment, &reason);
357
+ if (!trace) return BlockLaunch(name, CCPetsInterpolate(L(@"{host}: {detail}"), @{@"host": host, @"detail": reason}));
358
+ if ([@[@"CN", @"HK"] containsObject:trace[@"loc"]]) return BlockLaunch(name, CCPetsInterpolate(
359
+ L(@"{host}: exit {ip} ({region}) is in mainland China / Hong Kong."),
360
+ @{@"host": host, @"ip": trace[@"ip"], @"region": trace[@"loc"]}));
361
+ CCPetsPrintLine(stderr, CCPetsInterpolate(L(@"CC Pets: {host} exit {ip} ({region}) passed."),
362
+ @{@"host": host, @"ip": trace[@"ip"], @"region": trace[@"loc"]}));
363
+ }
364
+ // 探测期间用户可能断开 VPN,不沿用之前的状态。
365
+ if (!ShadowrocketConnected(&reason)) return BlockLaunch(name, reason);
366
+ return 0;
367
+ }
@@ -5,6 +5,12 @@
5
5
  // 由 Codex 共享服务(app-server --managed-daemon)拉起的 hook 返回空目标,见实现处注释。
6
6
  NSDictionary *TerminalFocusTargetFromEnvironment(void);
7
7
  BOOL TerminalFocusRunsUnderSharedAgentHost(void);
8
+ // 桌面宿主不使用终端 TTY;事件时间必须属于当前应用实例,避免重启后复活旧会话。
9
+ BOOL IsCodexDesktopFocusTarget(NSDictionary *target);
10
+ BOOL CodexDesktopFocusTargetIsLive(NSDictionary *target, NSTimeInterval eventTime);
11
+ BOOL CodexDesktopApplicationIsRunning(void);
12
+ // 只读本地聊天索引;YES 为已持久化聊天,NO 为未收录/已归档,nil 为无法确认。
13
+ NSNumber *CodexPersistentThreadStatus(NSString *thread, NSString *codexHome);
8
14
 
9
15
  // hook 用:普通情况同 TerminalFocusTargetFromEnvironment;Codex 共享服务下按会话 ID 找
10
16
  // codex-with-pet 登记的终端,找不到返回空目标。
@@ -16,7 +22,8 @@ BOOL RegisterCodexLaunchForProcess(pid_t pid, NSString *cwd, NSDictionary *termi
16
22
  NSTimeInterval launchedAt);
17
23
  NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload);
18
24
 
19
- // Terminal / iTerm2 按 TTY 精确选中 tab/session;其他终端在无扩展模式下激活应用。
25
+ // Terminal / iTerm2 / Ghostty 按 TTY 精确选择;JetBrains IDE 和 VS Code 家族通过插件/扩展
26
+ // 异步聚焦。YES 表示已执行或已交给插件处理,其他终端在无扩展模式下激活应用。
20
27
  BOOL ActivateTerminalFocusTarget(NSDictionary *target);
21
28
 
22
29
  // 回跳目标的候选 bundle ID,按优先级排列,已去重去空。