| 1 | using System.Diagnostics; |
| 2 | using System.Text; |
| 3 | using System.Text.Json; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | internal static class Backend |
| 8 | { |
| 9 | public static bool ClientOnly => File.Exists(Path.Combine(AppContext.BaseDirectory, "resources", "client-only")); |
| 10 | private static string ConfigPath => Path.GetFullPath( |
| 11 | Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG") is { Length: > 0 } configured |
| 12 | ? configured : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude-cage", ClientOnly ? "client" : "", "config.json")); |
| 13 | public static string Root => Path.GetDirectoryName(ConfigPath)!; |
| 14 | public static string Executable => Path.Combine(AppContext.BaseDirectory, "resources", "cage.exe"); |
| 15 | |
| 16 | public static List<Process> CaptureSmokeControllers() |
| 17 | { |
| 18 | var processes = new List<Process>(); |
| 19 | try |
| 20 | { |
| 21 | foreach (var profile in new[] { Root, Path.Combine(Root, "desktop-entry") }) |
| 22 | { |
| 23 | var record = Path.Combine(profile, "control.json"); |
| 24 | if (!File.Exists(record)) continue; |
| 25 | using var data = JsonDocument.Parse(File.ReadAllText(record)); |
| 26 | Process process; |
| 27 | try { process = Process.GetProcessById(data.RootElement.GetProperty("pid").GetInt32()); } |
| 28 | catch (ArgumentException) { continue; } |
| 29 | try |
| 30 | { |
| 31 | |
| 32 | |
| 33 | _ = process.SafeHandle; |
| 34 | if (process.HasExited) { process.Dispose(); continue; } |
| 35 | if (!string.Equals(Path.GetFullPath(process.MainModule!.FileName), Path.GetFullPath(Executable), StringComparison.OrdinalIgnoreCase)) |
| 36 | throw new IOException("自检后台身份与当前应用不符,未等待其他程序"); |
| 37 | processes.Add(process); |
| 38 | } |
| 39 | catch { process.Dispose(); throw; } |
| 40 | } |
| 41 | return processes; |
| 42 | } |
| 43 | catch { foreach (var process in processes) process.Dispose(); throw; } |
| 44 | } |
| 45 | |
| 46 | public static ProcessStartInfo StartInfo(string executable, params string[] arguments) |
| 47 | { |
| 48 | var start = new ProcessStartInfo(executable) { |
| 49 | UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, |
| 50 | RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, |
| 51 | WorkingDirectory = AppContext.BaseDirectory, |
| 52 | }; |
| 53 | |
| 54 | |
| 55 | start.Environment["CLAUDE_CAGE_CONFIG"] = ConfigPath; |
| 56 | if (arguments.Length > 0 && arguments[0] == "desktop") start.Environment["CAGE_DESKTOP_OWNER_PID"] = Environment.ProcessId.ToString(); |
| 57 | foreach (var arg in arguments) start.ArgumentList.Add(arg); |
| 58 | return start; |
| 59 | } |
| 60 | |
| 61 | public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536) => |
| 62 | JsonAt(Executable, arguments, cancellation, deadline, outputLimit); |
| 63 | |
| 64 | public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536) |
| 65 | { |
| 66 | using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); |
| 67 | timeout.CancelAfter(deadline ?? TimeSpan.FromMinutes(3)); |
| 68 | using var process = new Process { StartInfo = StartInfo(executable, arguments) }; |
| 69 | if (!process.Start()) throw new IOException("无法启动 Cage 后台"); |
| 70 | using var abort = timeout.Token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } }); |
| 71 | try |
| 72 | { |
| 73 | var errors = Drain(process.StandardError, timeout.Token); |
| 74 | var text = await ReadLimited(process.StandardOutput, outputLimit, timeout.Token); |
| 75 | await process.WaitForExitAsync(timeout.Token); await errors; |
| 76 | try { return (process.ExitCode, JsonDocument.Parse(text).RootElement.Clone()); } |
| 77 | catch (JsonException) { throw new IOException("Cage 后台未返回有效状态,请查看工作台日志"); } |
| 78 | } |
| 79 | finally |
| 80 | { |
| 81 | if (!process.HasExited) { process.Kill(); await process.WaitForExitAsync(); } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | public static async Task<string> ReadLimited(StreamReader reader, int limit, CancellationToken token) |
| 86 | { |
| 87 | var text = new StringBuilder(); var buffer = new char[4096]; int count; |
| 88 | while ((count = await reader.ReadAsync(buffer.AsMemory(), token)) > 0) |
| 89 | { |
| 90 | text.Append(buffer, 0, count); |
| 91 | if (text.Length > limit) throw new IOException("后台响应超过允许大小"); |
| 92 | } |
| 93 | return text.ToString(); |
| 94 | } |
| 95 | |
| 96 | public static async Task Drain(StreamReader reader, CancellationToken token) |
| 97 | { |
| 98 | var buffer = new char[4096]; |
| 99 | while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { } |
| 100 | } |
| 101 | public static async Task Report(string message) |
| 102 | { |
| 103 | try |
| 104 | { |
| 105 | using var process = new Process { StartInfo = StartInfo(Executable, "diagnostic-event") }; |
| 106 | process.StartInfo.RedirectStandardInput = true; |
| 107 | if (!process.Start()) return; |
| 108 | await process.StandardInput.WriteAsync(JsonSerializer.Serialize(new { source = "native", message = message[..Math.Min(message.Length, 4096)] })); |
| 109 | process.StandardInput.Close(); |
| 110 | using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| 111 | await process.WaitForExitAsync(timeout.Token); |
| 112 | } |
| 113 | catch (Exception) { } |
| 114 | } |
| 115 | public static string Text(this JsonElement data, string name) => |
| 116 | data.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; |
| 117 | } |