using System.Text.Json; namespace FinalToken.Core.Collectors; public static class TranscriptParser { public static UsageEvent? Parse(string line, DiagnosticLog diagnostics) { try { using var document = JsonDocument.Parse(line); var root = document.RootElement; if (root.Text("type") != "assistant") return null; var message = root.Field("message"); if (message.Text("model") == "") return null; if (message.Field("usage").ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null; var counts = JsonFields.Counts(message.Field("usage"), true); if (root.Text("requestId") is not { Length: > 0 } && counts == new TokenCounts()) return null; if (message.Text("id") is not { Length: > 0 } id || root.Text("requestId") is not { Length: > 0 } request || root.Field("timestamp").Timestamp() is not { } time) throw new FormatException(); // Length prefixes avoid collisions between ids that contain separators (D3). return new(Provider.Claude, time, message.Text("model"), root.Text("cwd"), counts, $"claude:{id.Length}:{id}{request.Length}:{request}"); } catch (Exception e) when (e is JsonException or FormatException or OverflowException) { diagnostics.Add(Provider.Claude, "transcript-parse", "Malformed assistant usage entry skipped."); return null; } } }