using System.Runtime.InteropServices; using System.Text.Json; using System.Text.Json.Serialization; using FinalToken.Core; using FinalToken.Core.Collectors; using FinalToken.Core.Processes; namespace FinalToken.ProcessHost; public static class Program { public static async Task Main(string[] args) { if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server")) return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode); if (!OperatingSystem.IsWindows()) return 0; if (args is ["--handles"]) return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17; if (args is ["--utf8"]) { await Console.OpenStandardOutput().WriteAsync(System.Text.Encoding.UTF8.GetBytes("{\"marker\":\"· •\"}")); return 0; } if (args.Length < 2) return 2; Native.FreeConsole(); foreach (var id in new[] { -10, -11, -12 }) Native.SetStdHandle(id, 0); var report = new ProbeReport { HostHasConsole = Native.GetConsoleWindow() != 0, HostInputValid = Native.GetFileType(Native.GetStdHandle(-10)) != 0, OutputCodePage = Console.OutputEncoding.CodePage }; var live = args[0] == "--claude"; var utf8 = args[0] == "--utf8-probe"; var cli = live ? CliDiscovery.Find(Provider.Claude).Command : new CliCommand(Environment.ProcessPath!, []); if (cli is null) return 3; var result = await new ProcessRunner().RunAsync(new(cli, live ? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : utf8 ? ["--utf8"] : ["--handles"], Path.GetDirectoryName(Path.GetFullPath(args[1]))!, TimeSpan.FromSeconds(60)), CancellationToken.None); report = report with { ExitCode = result.ExitCode, TimedOut = result.TimedOut, Utf8Matched = utf8 && result.Output == "{\"marker\":\"· •\"}" }; if (live) { var diagnostics = new DiagnosticLog(); var windows = ClaudeUsageParser.ParseEnvelope(result.Output, DateTimeOffset.UtcNow, diagnostics); report = report with { WindowCount = windows.Count, DiagnosticCodes = diagnostics.Recent.Select(d => d.Code).ToArray() }; } await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport)); return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode; } private static async Task RpcAsync(string mode) { Console.InputEncoding = System.Text.Encoding.UTF8; Console.OutputEncoding = new System.Text.UTF8Encoding(false); if (mode == "--rpc-eof") return 0; var initialize = await Console.In.ReadLineAsync(); using var first = JsonDocument.Parse(initialize ?? "null"); if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20; if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; } await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}"); using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null"); using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null"); if (initialized.RootElement.GetProperty("method").GetString() != "initialized" || request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21; await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}"); var response = mode switch { "--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}", "--rpc-garbage" => "not JSON", "--rpc-shape" => "[]", "--rpc-bound" => new string('x', 1024 * 1024 + 1), _ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}" }; await Console.Out.WriteLineAsync(response); return 0; } } public sealed record ProbeReport { public bool HostHasConsole { get; init; } public bool HostInputValid { get; init; } public int ExitCode { get; init; } public bool TimedOut { get; init; } public int WindowCount { get; init; } public int OutputCodePage { get; init; } public bool Utf8Matched { get; init; } public string[] DiagnosticCodes { get; init; } = []; } [JsonSerializable(typeof(ProbeReport))] internal partial class ProbeJsonContext : JsonSerializerContext; internal static partial class Native { [LibraryImport("kernel32.dll")] internal static partial nint GetStdHandle(int id); [LibraryImport("kernel32.dll")] internal static partial uint GetFileType(nint handle); [LibraryImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SetStdHandle(int id, nint handle); [LibraryImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool FreeConsole(); [LibraryImport("kernel32.dll")] internal static partial nint GetConsoleWindow(); }