using System.Text.Json; using System.Text.Json.Serialization; using FinalToken.Core; namespace FinalToken.Fleet; public sealed record AccountConfig(string Id, Provider Provider, string Label, string ExpectedEmail, string TimeZone = "UTC", string? LegacyMachine = null, string? LegacyProfile = null, DateTimeOffset? HistoryBefore = null); public sealed record ProfileBinding(string Id, string AccountId); public sealed record MachineConfig(string Id, string Label, string OsUser, IReadOnlyList Profiles); public sealed record ServerConfig(IReadOnlyList Accounts, IReadOnlyList Machines); public sealed record WorkerProfile(string Id, Provider Provider, string ExpectedEmail, string ConfigDirectory, string DataDirectory, string? CliPath = null, bool EnableLegacyClaudeProbe = false); public sealed record WorkerConfig(string MachineId, string ServerUrl, string StateDirectory, IReadOnlyList Profiles); public sealed record AuthHealth(string State, string? Email, DateTimeOffset CheckedAt, string Reason); // Claude: absolute response counts; Codex: cumulative session counts. Never send transcript content/project paths. public sealed record SourceUsage(string Key, string? Session, DateTimeOffset Time, string? Model, TokenCounts Counts); public sealed record ProfileReport(string Id, Provider Provider, AuthHealth Auth, Settings Settings, IReadOnlyList Usage, IReadOnlyList Samples, IReadOnlyList LegacyTokens, string? CollectionError = null, string? DataEmail = null, string? CollectionNote = null); public sealed record WorkerReport(string MachineId, string OsUser, string BootId, DateTimeOffset CollectedAt, IReadOnlyList Profiles, IReadOnlyList Logins); public sealed record MachineState(string MachineId, DateTimeOffset SeenAt, WorkerReport Report); public sealed record FleetState(IReadOnlyList Machines); public sealed record LoginUpdate(string Id, string ProfileId, string State, string? Url = null, string? DeviceCode = null, string? Email = null, bool InputAccepted = false); public sealed record LoginCommand(string Id, string ProfileId, DateTimeOffset ExpiresAt, bool Cancel = false, string? Response = null); public sealed record WorkerReply(IReadOnlyList Commands); public sealed record LoginView(string Id, string MachineId, string ProfileId, string State, DateTimeOffset ExpiresAt, string? Url, string? DeviceCode, string? Email); public sealed record StartLogin(string MachineId, string ProfileId); public sealed record LoginResponse(string Response); public sealed record SignIn(string Key); public sealed record BrowserSession(string Csrf); public sealed record WindowView(LimitWindow Window, bool Stale, PaceResult Pace, double? UseAtReset, double? RemainingAtReset, RateForecast? Recent, LimitEstimate? Analysis, ResetHistory? Resets); public sealed record AccountView(AccountConfig Account, IReadOnlyList Windows, IReadOnlyList Tokens, TokenCounts Total, decimal? ApiValue, long UnpricedTokens, IReadOnlyList Warnings, DateOnly PricesCheckedOn, IReadOnlyList Sessions, bool HasConsumptionData); public sealed record SessionConsumption(string Id, TokenCounts Tokens); public sealed record ProfileConsumption(string ProfileId, TokenCounts? Tokens, int Sessions); public sealed record MachineView(string Id, string Label, string OsUser, bool Online, DateTimeOffset? SeenAt, IReadOnlyList Profiles, IReadOnlyList Bindings, IReadOnlyList Consumption); public sealed record DashboardView(DateTimeOffset Now, IReadOnlyList Accounts, IReadOnlyList Machines); [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)] [JsonSerializable(typeof(ServerConfig))] [JsonSerializable(typeof(WorkerConfig))] [JsonSerializable(typeof(WorkerReport))] [JsonSerializable(typeof(FleetState))] [JsonSerializable(typeof(WorkerReply))] [JsonSerializable(typeof(DashboardView))] [JsonSerializable(typeof(LoginView))] [JsonSerializable(typeof(StartLogin))] [JsonSerializable(typeof(LoginResponse))] [JsonSerializable(typeof(SignIn))] [JsonSerializable(typeof(BrowserSession))] [JsonSerializable(typeof(List))] public partial class FleetJsonContext : JsonSerializerContext; public static class FleetValidation { public static bool Identifier(string? value) => value is { Length: > 0 and <= 64 } && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'); public static void Config(ServerConfig config) { if (config.Accounts is null || config.Machines is null || config.Accounts.Select(a => a.Id).Distinct().Count() != config.Accounts.Count || config.Machines.Select(m => m.Id).Distinct().Count() != config.Machines.Count) throw new InvalidDataException("Duplicate or missing configuration."); foreach (var account in config.Accounts) { if (!Identifier(account.Id) || !Enum.IsDefined(account.Provider) || string.IsNullOrWhiteSpace(account.ExpectedEmail)) throw new InvalidDataException("Invalid account configuration."); _ = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone); if (account.HistoryBefore is { } cutoff && (cutoff.UtcTicks % TimeSpan.TicksPerHour != 0 || !config.Machines.Any(m => m.Id == account.LegacyMachine && m.Profiles.Any(p => p.Id == account.LegacyProfile && p.AccountId == account.Id)))) throw new InvalidDataException("Legacy history requires one bound source and an exact UTC hour cutoff."); } foreach (var machine in config.Machines) if (!Identifier(machine.Id) || string.IsNullOrWhiteSpace(machine.OsUser) || machine.Profiles is null || machine.Profiles.Select(p => p.Id).Distinct().Count() != machine.Profiles.Count || machine.Profiles.Any(p => !Identifier(p.Id) || !config.Accounts.Any(a => a.Id == p.AccountId))) throw new InvalidDataException("Invalid machine/profile configuration."); } public static bool Counts(TokenCounts c) => c.Input is >= 0 and <= 1_000_000_000_000 && c.Output is >= 0 and <= 1_000_000_000_000 && c.CacheRead is >= 0 and <= 1_000_000_000_000 && c.CacheWrite is >= 0 and <= 1_000_000_000_000 && c.ReasoningOutput is >= 0 and <= 1_000_000_000_000 && c.Total is >= 0 and <= 4_000_000_000_000; }