cc-pets 2.3.0 → 2.4.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.
- package/CC_BRIDGE.md +19 -0
- package/CC_BRIDGE.zh-CN.md +15 -0
- package/CHANGELOG.md +51 -0
- package/CHANGELOG.zh-CN.md +51 -0
- package/CONTRIBUTING.md +22 -0
- package/CONTRIBUTING.zh-CN.md +17 -0
- package/README.md +117 -26
- package/README.zh-CN.md +92 -22
- package/Resources/AgentIcons/claude.png +0 -0
- package/Resources/AgentIcons/codex.icns +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
- package/Resources/zh-Hans.lproj/Localizable.strings +155 -27
- package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +12 -6
- package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +1 -1
- package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
- package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +113 -47
- package/Sources/CCPets/App/CCPetsAppDelegate.h +2 -2
- package/Sources/CCPets/App/main.m +6 -0
- package/Sources/CCPets/Bridge/CCPetsBridge.m +11 -6
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +78 -38
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +2 -3
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +50 -32
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +46 -40
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +9 -6
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +171 -53
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +2 -1
- package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +107 -25
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
- package/Sources/CCPets/Pet/PetView+Menu.m +2 -2
- package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
- package/Sources/CCPets/Support/CCPetsPreferences.h +2 -0
- package/Sources/CCPets/Support/CCPetsPreferences.m +34 -2
- package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
- package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
- package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
- package/Sources/CCPets/UI/CCPetsSettingsPage.h +2 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.m +561 -66
- package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
- package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
- package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
- package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
- package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
- package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
- package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
- package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
- package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
- package/THIRD_PARTY_NOTICES.md +7 -3
- package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
- package/bin/claude-with-pet +2 -0
- package/bin/codex-with-pet +2 -0
- package/package.json +5 -1
- package/plugins/jetbrains/README.md +62 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
- package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
- package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
- package/plugins/vscode/README.md +63 -0
- package/plugins/vscode/extension.js +210 -0
- package/plugins/vscode/package.json +18 -0
- package/scripts/build-idea-plugin.sh +101 -0
- package/scripts/build-vscode-extension.sh +112 -0
- package/scripts/build.sh +24 -2
- 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
|
+
}
|
|
@@ -16,7 +16,8 @@ BOOL RegisterCodexLaunchForProcess(pid_t pid, NSString *cwd, NSDictionary *termi
|
|
|
16
16
|
NSTimeInterval launchedAt);
|
|
17
17
|
NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload);
|
|
18
18
|
|
|
19
|
-
// Terminal / iTerm2 按 TTY
|
|
19
|
+
// Terminal / iTerm2 / Ghostty 按 TTY 精确选择;JetBrains IDE 和 VS Code 家族通过插件/扩展
|
|
20
|
+
// 异步聚焦。YES 表示已执行或已交给插件处理,其他终端在无扩展模式下激活应用。
|
|
20
21
|
BOOL ActivateTerminalFocusTarget(NSDictionary *target);
|
|
21
22
|
|
|
22
23
|
// 回跳目标的候选 bundle ID,按优先级排列,已去重去空。
|
|
@@ -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;
|
|
@@ -97,11 +100,13 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
|
|
|
97
100
|
NSString *program = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_PROGRAM", 64);
|
|
98
101
|
NSString *session = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_SESSION", 128);
|
|
99
102
|
NSString *bundleID = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_BUNDLE_ID", 128);
|
|
103
|
+
NSString *ideInstance = TerminalTargetValue(environment, @"CC_PETS_IDE_INSTANCE_ID", 64);
|
|
104
|
+
NSString *ideTerminal = TerminalTargetValue(environment, @"CC_PETS_IDE_TERMINAL_ID", 64);
|
|
100
105
|
if (tty.length == 0) tty = SanitizedShortString(ControllingTerminalName(), 64);
|
|
101
106
|
if (bundleID.length == 0) {
|
|
102
107
|
bundleID = SanitizedShortString(HostApplicationBundleIdentifier(), 128);
|
|
103
108
|
}
|
|
104
|
-
if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0) {
|
|
109
|
+
if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0 && ideInstance.length == 0) {
|
|
105
110
|
return @{};
|
|
106
111
|
}
|
|
107
112
|
NSMutableDictionary *target = [NSMutableDictionary dictionary];
|
|
@@ -109,6 +114,10 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
|
|
|
109
114
|
if (program.length > 0) target[@"program"] = program;
|
|
110
115
|
if (session.length > 0) target[@"session"] = session;
|
|
111
116
|
if (bundleID.length > 0) target[@"bundleID"] = bundleID;
|
|
117
|
+
if (ideInstance.length > 0 && ideTerminal.length > 0) {
|
|
118
|
+
target[@"ideInstance"] = ideInstance;
|
|
119
|
+
target[@"ideTerminal"] = ideTerminal;
|
|
120
|
+
}
|
|
112
121
|
return target;
|
|
113
122
|
}
|
|
114
123
|
|
|
@@ -152,11 +161,37 @@ static BOOL RunTerminalSelectionScript(NSString *bundleID, NSString *ttyName) {
|
|
|
152
161
|
"end repeat\n"
|
|
153
162
|
"end tell\n"
|
|
154
163
|
"return false", tty];
|
|
164
|
+
} else if ([bundleID isEqualToString:@"com.mitchellh.ghostty"]) {
|
|
165
|
+
// Ghostty 1.4 起暴露 tty。先选中所属标签页并激活应用,再聚焦分屏;
|
|
166
|
+
// 不只依赖 focus 内部异步的窗口前置,状态卡本身是 NonactivatingPanel。
|
|
167
|
+
source = [NSString stringWithFormat:
|
|
168
|
+
@"tell application \"Ghostty\"\n"
|
|
169
|
+
"repeat with terminalWindow in windows\n"
|
|
170
|
+
"repeat with terminalTab in tabs of terminalWindow\n"
|
|
171
|
+
"repeat with terminalSurface in terminals of terminalTab\n"
|
|
172
|
+
"if (tty of terminalSurface) is \"%@\" then\n"
|
|
173
|
+
"set targetID to id of terminalSurface\n"
|
|
174
|
+
"select tab terminalTab\n"
|
|
175
|
+
"activate\n"
|
|
176
|
+
"focus (terminal id targetID)\n"
|
|
177
|
+
"return true\n"
|
|
178
|
+
"end if\n"
|
|
179
|
+
"end repeat\n"
|
|
180
|
+
"end repeat\n"
|
|
181
|
+
"end repeat\n"
|
|
182
|
+
"end tell\n"
|
|
183
|
+
"return false", tty];
|
|
155
184
|
}
|
|
156
185
|
if (!source) return NO;
|
|
157
186
|
NSDictionary *error = nil;
|
|
158
187
|
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:source];
|
|
159
188
|
NSAppleEventDescriptor *result = [script executeAndReturnError:&error];
|
|
189
|
+
if (error) {
|
|
190
|
+
NSLog(@"Terminal focus failed: bundle=%@ tty=%@ error=%@", bundleID, tty, error);
|
|
191
|
+
} else {
|
|
192
|
+
NSLog(@"Terminal focus: bundle=%@ tty=%@ matched=%@", bundleID, tty,
|
|
193
|
+
result.booleanValue ? @"yes" : @"no");
|
|
194
|
+
}
|
|
160
195
|
return result.booleanValue && error == nil;
|
|
161
196
|
}
|
|
162
197
|
|
|
@@ -197,7 +232,7 @@ NSArray<NSString *> *TerminalFocusBundleCandidates(NSDictionary *target) {
|
|
|
197
232
|
return candidates;
|
|
198
233
|
}
|
|
199
234
|
|
|
200
|
-
//
|
|
235
|
+
// 没有脚本或插件接口的宿主(如 Warp、未装扩展的 VS Code)退回激活应用。activateWithOptions:
|
|
201
236
|
// 在 macOS 14 起走协作式激活:状态卡是 NonactivatingPanel,桌宠自己不在前台,请求可能
|
|
202
237
|
// 被系统拒绝,窗口在别的桌面时更是不会切过去。改走和点 Dock 图标同一条路,让系统负责
|
|
203
238
|
// 切到应用窗口所在的桌面;拿不到 bundleURL 时才退回旧接口。
|
|
@@ -219,6 +254,8 @@ static BOOL ActivateApplicationAcrossSpaces(NSRunningApplication *application) {
|
|
|
219
254
|
}
|
|
220
255
|
|
|
221
256
|
BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
|
|
257
|
+
if (CCPetsRequestIDETerminalFocus(target)) return YES;
|
|
258
|
+
if (CCPetsRequestVSCodeTerminalFocus(target)) return YES;
|
|
222
259
|
NSString *tty = SanitizedShortString(target[@"tty"], 64);
|
|
223
260
|
// 候选按优先级往下试,没在运行的直接跳过:映射值和捕获值总有一个指向真正承载
|
|
224
261
|
// 会话的那个应用,卡在第一个候选上就会白白丢掉一次可用的回跳。
|
|
@@ -236,11 +273,11 @@ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
|
|
|
236
273
|
|
|
237
274
|
// Codex 共享服务拉起的 hook 不知道会话在哪个终端(见 TerminalFocusRunsUnderSharedAgentHost)。
|
|
238
275
|
// 能确定的只有两头:codex-with-pet 启动时知道自己的终端、工作目录和时刻;hook 知道会话 ID,
|
|
239
|
-
// 会话记录(rollout
|
|
240
|
-
//
|
|
241
|
-
//
|
|
276
|
+
// 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。CLI 启动后可能还要等网络
|
|
277
|
+
// 初始化,不能按包装脚本的启动先后猜测归属。多个候选时读取本机 TUI 就绪日志的 PID,
|
|
278
|
+
// 仅在会话创建前的一秒内存在唯一就绪候选时配对;信息不足就留空,之后的 Hook 可再试。
|
|
242
279
|
static const NSUInteger CodexLaunchThreadLimit = 32;
|
|
243
|
-
static const NSTimeInterval
|
|
280
|
+
static const NSTimeInterval CodexClientReadyWindow = 1.0;
|
|
244
281
|
|
|
245
282
|
static NSTimeInterval ProcessStartTime(pid_t pid) {
|
|
246
283
|
struct kinfo_proc info;
|
|
@@ -396,32 +433,77 @@ static NSDictionary *CodexThreadMeta(NSString *thread, NSDictionary *payload, NS
|
|
|
396
433
|
return result;
|
|
397
434
|
}
|
|
398
435
|
|
|
399
|
-
//
|
|
400
|
-
//
|
|
401
|
-
//
|
|
436
|
+
// Codex 0.166 的本机日志记录每个 TUI 的就绪时刻和带 PID 的 process_uuid。
|
|
437
|
+
// 只读这一类元数据,不读取提示词、输出或 HTTP 日志。内部日志格式改变、日志尚未落盘、
|
|
438
|
+
// 多个客户端同时就绪时都不能猜测;sqlite 的读锁等待和返回条数也有上限。
|
|
439
|
+
static int CodexLogQueryExpired(void *context) {
|
|
440
|
+
return CFAbsoluteTimeGetCurrent() > *(CFAbsoluteTime *)context;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
|
|
444
|
+
NSArray<NSString *> *candidates, NSNumber *createdAt, NSString *codexHome) {
|
|
445
|
+
if (!createdAt || createdAt.doubleValue <= 0) return nil;
|
|
446
|
+
NSString *path = [(codexHome.length ? codexHome : DefaultCodexHomeDirectory())
|
|
447
|
+
stringByAppendingPathComponent:@"logs_2.sqlite"];
|
|
448
|
+
sqlite3 *database = NULL;
|
|
449
|
+
if (sqlite3_open_v2(path.fileSystemRepresentation, &database, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
|
|
450
|
+
if (database) sqlite3_close(database);
|
|
451
|
+
return nil;
|
|
452
|
+
}
|
|
453
|
+
sqlite3_busy_timeout(database, 50);
|
|
454
|
+
CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + 0.15;
|
|
455
|
+
sqlite3_progress_handler(database, 1000, CodexLogQueryExpired, &deadline);
|
|
456
|
+
sqlite3_stmt *statement = NULL;
|
|
457
|
+
const char *query = "SELECT ts, ts_nanos, process_uuid FROM logs "
|
|
458
|
+
"WHERE ts BETWEEN ? AND ? AND target = 'codex_tui::app::startup' "
|
|
459
|
+
"AND feedback_log_body LIKE 'tui startup initial frame scheduled%' LIMIT 128";
|
|
460
|
+
NSMutableSet<NSString *> *matches = [NSMutableSet set];
|
|
461
|
+
BOOL complete = NO;
|
|
462
|
+
if (sqlite3_prepare_v2(database, query, -1, &statement, NULL) == SQLITE_OK) {
|
|
463
|
+
sqlite3_bind_int64(statement, 1, (sqlite3_int64)floor(createdAt.doubleValue - CodexClientReadyWindow));
|
|
464
|
+
sqlite3_bind_int64(statement, 2, (sqlite3_int64)ceil(createdAt.doubleValue));
|
|
465
|
+
int result;
|
|
466
|
+
NSUInteger rows = 0;
|
|
467
|
+
while ((result = sqlite3_step(statement)) == SQLITE_ROW) {
|
|
468
|
+
rows++;
|
|
469
|
+
double readyAt = sqlite3_column_int64(statement, 0) + sqlite3_column_int64(statement, 1) / 1e9;
|
|
470
|
+
if (readyAt > createdAt.doubleValue || readyAt < createdAt.doubleValue - CodexClientReadyWindow) continue;
|
|
471
|
+
const unsigned char *value = sqlite3_column_text(statement, 2);
|
|
472
|
+
NSString *process = value ? @((const char *)value) : @"";
|
|
473
|
+
for (NSString *key in candidates) {
|
|
474
|
+
NSDictionary *entry = launches[key];
|
|
475
|
+
NSString *prefix = [NSString stringWithFormat:@"pid:%d:", [entry[@"pid"] intValue]];
|
|
476
|
+
if ([process hasPrefix:prefix] && readyAt >= [entry[@"processStartedAt"] doubleValue] &&
|
|
477
|
+
readyAt >= [entry[@"launchedAt"] doubleValue]) [matches addObject:key];
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
complete = result == SQLITE_DONE && rows < 128;
|
|
481
|
+
}
|
|
482
|
+
if (statement) sqlite3_finalize(statement);
|
|
483
|
+
sqlite3_close(database);
|
|
484
|
+
return complete && matches.count == 1 ? matches.anyObject : nil;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// 显式 resume 优先按会话 ID;新会话用客户端就绪证据。多个同目录客户端时不能用
|
|
488
|
+
// “最新未绑定的进程”兜底:网络启动延迟和首次发消息的顺序都可能与启动顺序不同。
|
|
402
489
|
static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
|
|
403
|
-
NSString *cwd, NSNumber *createdAt) {
|
|
490
|
+
NSString *cwd, NSNumber *createdAt, NSString *thread, NSString *codexHome) {
|
|
404
491
|
NSMutableArray<NSString *> *sameDirectory = [NSMutableArray array];
|
|
405
|
-
NSMutableArray<NSString *> *
|
|
492
|
+
NSMutableArray<NSString *> *resumed = [NSMutableArray array];
|
|
406
493
|
for (NSString *key in launches) {
|
|
407
494
|
NSDictionary *entry = launches[key];
|
|
408
495
|
if (![entry[@"cwd"] isEqualToString:cwd]) continue;
|
|
409
496
|
[sameDirectory addObject:key];
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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;
|
|
497
|
+
NSArray *arguments = ProcessArguments([entry[@"pid"] intValue]);
|
|
498
|
+
NSUInteger resume = [arguments indexOfObject:@"resume"];
|
|
499
|
+
if (resume != NSNotFound && resume + 1 < arguments.count && [arguments[resume + 1] isEqual:thread]) {
|
|
500
|
+
[resumed addObject:key];
|
|
421
501
|
}
|
|
422
|
-
if (preceding) return preceding;
|
|
423
502
|
}
|
|
424
|
-
return
|
|
503
|
+
if (resumed.count > 0) return resumed.count == 1 ? resumed.firstObject : nil;
|
|
504
|
+
NSString *ready = ReadyCodexLaunch(launches, sameDirectory, createdAt, codexHome);
|
|
505
|
+
if (ready) return ready;
|
|
506
|
+
return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
|
|
425
507
|
}
|
|
426
508
|
|
|
427
509
|
static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDictionary *payload,
|
|
@@ -439,7 +521,7 @@ static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDict
|
|
|
439
521
|
}
|
|
440
522
|
if (!terminal) {
|
|
441
523
|
NSDictionary *meta = CodexThreadMeta(thread, payload, codexHome);
|
|
442
|
-
NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"]) : nil;
|
|
524
|
+
NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"], thread, codexHome) : nil;
|
|
443
525
|
if (key) {
|
|
444
526
|
NSMutableDictionary *entry = [launches[key] mutableCopy];
|
|
445
527
|
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);
|