1337 lines · 53.4 KB · Swift
RawDownload
import Foundation public struct RateWindow: Codable, Equatable, Sendable {    public let usedPercent: Double    public let windowMinutes: Int?    public let resetsAt: Date?    /// Optional textual reset description (used by Claude CLI UI scrape).    public let resetDescription: String?    /// Optional percent restored on the next regeneration tick for providers with rolling recovery.    public let nextRegenPercent: Double?     public init(        usedPercent: Double,        windowMinutes: Int?,        resetsAt: Date?,        resetDescription: String?,        nextRegenPercent: Double? = nil)    {        self.usedPercent = usedPercent        self.windowMinutes = windowMinutes        self.resetsAt = resetsAt        self.resetDescription = resetDescription        self.nextRegenPercent = nextRegenPercent    }     public var remainingPercent: Double {        max(0, 100 - self.usedPercent)    }     public func backfillingResetTime(from cached: RateWindow?, now: Date = .init()) -> RateWindow {        if self.resetsAt != nil { return self }        guard let cachedReset = cached?.resetsAt, cachedReset > now else { return self }        let windowMinutes = if let windowMinutes = self.windowMinutes, windowMinutes > 0 {            windowMinutes        } else {            cached?.windowMinutes        }        return RateWindow(            usedPercent: self.usedPercent,            windowMinutes: windowMinutes,            resetsAt: cachedReset,            resetDescription: self.resetDescription ?? cached?.resetDescription,            nextRegenPercent: self.nextRegenPercent)    }} public struct NamedRateWindow: Codable, Equatable, Sendable {    public let id: String    public let title: String    public let window: RateWindow    /// Whether `window.usedPercent` reflects known quota usage.    ///    /// Some providers expose reset metadata for a named quota window before    /// they expose remaining usage. Keep those windows visible for reset/debug    /// context, but mark them so clients do not render `usedPercent` as a real    /// exhausted quota. Missing values decode as `true` for older cached payloads.    public let usageKnown: Bool     public init(id: String, title: String, window: RateWindow, usageKnown: Bool = true) {        self.id = id        self.title = title        self.window = window        self.usageKnown = usageKnown    }     private enum CodingKeys: String, CodingKey {        case id        case title        case window        case usageKnown    }     public init(from decoder: Decoder) throws {        let container = try decoder.container(keyedBy: CodingKeys.self)        self.id = try container.decode(String.self, forKey: .id)        self.title = try container.decode(String.self, forKey: .title)        self.window = try container.decode(RateWindow.self, forKey: .window)        self.usageKnown = try container.decodeIfPresent(Bool.self, forKey: .usageKnown) ?? true    }     public func encode(to encoder: Encoder) throws {        var container = encoder.container(keyedBy: CodingKeys.self)        try container.encode(self.id, forKey: .id)        try container.encode(self.title, forKey: .title)        try container.encode(self.window, forKey: .window)        if !self.usageKnown {            try container.encode(false, forKey: .usageKnown)        }    }} public struct ProviderIdentitySnapshot: Codable, Sendable {    public let providerID: UsageProvider?    public let accountEmail: String?    public let accountOrganization: String?    public let loginMethod: String?     public init(        providerID: UsageProvider?,        accountEmail: String?,        accountOrganization: String?,        loginMethod: String?)    {        self.providerID = providerID        self.accountEmail = accountEmail        self.accountOrganization = accountOrganization        self.loginMethod = loginMethod    }     public func scoped(to provider: UsageProvider) -> ProviderIdentitySnapshot {        if self.providerID == provider { return self }        return ProviderIdentitySnapshot(            providerID: provider,            accountEmail: self.accountEmail,            accountOrganization: self.accountOrganization,            loginMethod: self.loginMethod)    }} public enum UsageDataConfidence: String, Codable, Equatable, Sendable {    case exact    case estimated    case percentOnly    case unknown} public struct UsageSnapshot: Codable, Sendable {    public let primary: RateWindow?    public let secondary: RateWindow?    public let tertiary: RateWindow?    public let extraRateWindows: [NamedRateWindow]?    public let providerCost: ProviderCostSnapshot?    public let kiroUsage: KiroUsageDetails?    public let ampUsage: AmpUsageDetails?    public let zaiUsage: ZaiUsageSnapshot?    public let minimaxUsage: MiniMaxUsageSnapshot?    public let deepseekUsage: DeepSeekUsageSummary?    public let mimoUsage: MiMoUsageSnapshot?    public let openRouterUsage: OpenRouterUsageSnapshot?    public let openAIAPIUsage: OpenAIAPIUsageSnapshot?    public let codexResetCredits: CodexRateLimitResetCreditsSnapshot?    public let claudeAdminAPIUsage: ClaudeAdminAPIUsageSnapshot?    public let mistralUsage: MistralUsageSnapshot?    public let deepgramUsage: DeepgramUsageSnapshot?    public let poeUsage: PoeUsageHistorySnapshot?    public let cursorRequests: CursorRequestUsage?    /// Live-only marker for optional Command Code subscription lookup failure.    public let commandCodeSubscriptionEnrichmentUnavailable: Bool    /// Live-only marker that Command Code returned a recognized subscription plan.    public let commandCodeHasSubscriptionPlan: Bool    /// Live-only marker that Command Code's monthly grant has no remaining credits.    public let commandCodeMonthlyGrantDepleted: Bool    public let subscriptionExpiresAt: Date?    public let subscriptionRenewsAt: Date?    public let updatedAt: Date    public let identity: ProviderIdentitySnapshot?    public let dataConfidence: UsageDataConfidence     private enum CodingKeys: String, CodingKey {        case primary        case secondary        case tertiary        case extraRateWindows        case providerCost        case kiroUsage        case ampUsage        case mimoUsage        case openRouterUsage        case openAIAPIUsage        case codexResetCredits        case claudeAdminAPIUsage        case mistralUsage        case deepgramUsage        case poeUsage        case subscriptionExpiresAt        case subscriptionRenewsAt        case updatedAt        case identity        case dataConfidence        case accountEmail        case accountOrganization        case loginMethod    }     public init(        primary: RateWindow?,        secondary: RateWindow?,        tertiary: RateWindow? = nil,        extraRateWindows: [NamedRateWindow]? = nil,        kiroUsage: KiroUsageDetails? = nil,        ampUsage: AmpUsageDetails? = nil,        providerCost: ProviderCostSnapshot? = nil,        zaiUsage: ZaiUsageSnapshot? = nil,        minimaxUsage: MiniMaxUsageSnapshot? = nil,        deepseekUsage: DeepSeekUsageSummary? = nil,        mimoUsage: MiMoUsageSnapshot? = nil,        openRouterUsage: OpenRouterUsageSnapshot? = nil,        openAIAPIUsage: OpenAIAPIUsageSnapshot? = nil,        codexResetCredits: CodexRateLimitResetCreditsSnapshot? = nil,        claudeAdminAPIUsage: ClaudeAdminAPIUsageSnapshot? = nil,        mistralUsage: MistralUsageSnapshot? = nil,        deepgramUsage: DeepgramUsageSnapshot? = nil,        poeUsage: PoeUsageHistorySnapshot? = nil,        cursorRequests: CursorRequestUsage? = nil,        commandCodeSubscriptionEnrichmentUnavailable: Bool = false,        commandCodeHasSubscriptionPlan: Bool = false,        commandCodeMonthlyGrantDepleted: Bool = false,        subscriptionExpiresAt: Date? = nil,        subscriptionRenewsAt: Date? = nil,        updatedAt: Date,        identity: ProviderIdentitySnapshot? = nil,        dataConfidence: UsageDataConfidence = .unknown)    {        self.primary = primary        self.secondary = secondary        self.tertiary = tertiary        self.extraRateWindows = extraRateWindows        self.kiroUsage = kiroUsage        self.ampUsage = ampUsage        self.providerCost = providerCost        self.zaiUsage = zaiUsage        self.minimaxUsage = minimaxUsage        self.deepseekUsage = deepseekUsage        self.mimoUsage = mimoUsage        self.openRouterUsage = openRouterUsage        self.openAIAPIUsage = openAIAPIUsage        self.codexResetCredits = codexResetCredits        self.claudeAdminAPIUsage = claudeAdminAPIUsage        self.mistralUsage = mistralUsage        self.deepgramUsage = deepgramUsage        self.poeUsage = poeUsage        self.cursorRequests = cursorRequests        self.commandCodeSubscriptionEnrichmentUnavailable = commandCodeSubscriptionEnrichmentUnavailable        self.commandCodeHasSubscriptionPlan = commandCodeHasSubscriptionPlan        self.commandCodeMonthlyGrantDepleted = commandCodeMonthlyGrantDepleted        self.subscriptionExpiresAt = subscriptionExpiresAt        self.subscriptionRenewsAt = subscriptionRenewsAt        self.updatedAt = updatedAt        self.identity = identity        self.dataConfidence = dataConfidence    }     public func with(extraRateWindows: [NamedRateWindow]?) -> UsageSnapshot {        self.replacing(extraRateWindows: .value(extraRateWindows))    }     public func withCodexResetCredits(_ resetCredits: CodexRateLimitResetCreditsSnapshot?) -> UsageSnapshot {        self.replacing(codexResetCredits: .value(resetCredits))    }     public func with(primary: RateWindow?, secondary: RateWindow?) -> UsageSnapshot {        self.replacing(            primary: .value(primary),            secondary: .value(secondary))    }     public init(from decoder: Decoder) throws {        let container = try decoder.container(keyedBy: CodingKeys.self)        self.primary = try container.decodeIfPresent(RateWindow.self, forKey: .primary)        self.secondary = try container.decodeIfPresent(RateWindow.self, forKey: .secondary)        self.tertiary = try container.decodeIfPresent(RateWindow.self, forKey: .tertiary)        self.extraRateWindows = try container.decodeIfPresent([NamedRateWindow].self, forKey: .extraRateWindows)        self.providerCost = try container.decodeIfPresent(ProviderCostSnapshot.self, forKey: .providerCost)        self.kiroUsage = try container.decodeIfPresent(KiroUsageDetails.self, forKey: .kiroUsage)        self.ampUsage = try container.decodeIfPresent(AmpUsageDetails.self, forKey: .ampUsage)        self.zaiUsage = nil // Not persisted, fetched fresh each time        self.minimaxUsage = nil // Not persisted, fetched fresh each time        self.deepseekUsage = nil // Not persisted, fetched fresh each time        self.mimoUsage = try container.decodeIfPresent(MiMoUsageSnapshot.self, forKey: .mimoUsage)        self.openRouterUsage = try container.decodeIfPresent(OpenRouterUsageSnapshot.self, forKey: .openRouterUsage)        self.openAIAPIUsage = try container.decodeIfPresent(OpenAIAPIUsageSnapshot.self, forKey: .openAIAPIUsage)        self.codexResetCredits = try container.decodeIfPresent(            CodexRateLimitResetCreditsSnapshot.self,            forKey: .codexResetCredits)        self.claudeAdminAPIUsage = try container.decodeIfPresent(            ClaudeAdminAPIUsageSnapshot.self,            forKey: .claudeAdminAPIUsage)        self.mistralUsage = try container.decodeIfPresent(MistralUsageSnapshot.self, forKey: .mistralUsage)        self.deepgramUsage = try container.decodeIfPresent(DeepgramUsageSnapshot.self, forKey: .deepgramUsage)        self.poeUsage = try container.decodeIfPresent(PoeUsageHistorySnapshot.self, forKey: .poeUsage)        self.cursorRequests = nil // Not persisted, fetched fresh each time        self.commandCodeSubscriptionEnrichmentUnavailable = false // Live-only fetch state        self.commandCodeHasSubscriptionPlan = false // Live-only fetch state        self.commandCodeMonthlyGrantDepleted = false // Live-only fetch state        self.subscriptionExpiresAt = try container.decodeIfPresent(Date.self, forKey: .subscriptionExpiresAt)        self.subscriptionRenewsAt = try container.decodeIfPresent(Date.self, forKey: .subscriptionRenewsAt)        self.updatedAt = try container.decode(Date.self, forKey: .updatedAt)        if let dataConfidence = try container.decodeIfPresent(String.self, forKey: .dataConfidence) {            self.dataConfidence = UsageDataConfidence(rawValue: dataConfidence) ?? .unknown        } else {            self.dataConfidence = .unknown        }        if let identity = try container.decodeIfPresent(ProviderIdentitySnapshot.self, forKey: .identity) {            self.identity = identity        } else {            let email = try container.decodeIfPresent(String.self, forKey: .accountEmail)            let organization = try container.decodeIfPresent(String.self, forKey: .accountOrganization)            let loginMethod = try container.decodeIfPresent(String.self, forKey: .loginMethod)            if email != nil || organization != nil || loginMethod != nil {                self.identity = ProviderIdentitySnapshot(                    providerID: nil,                    accountEmail: email,                    accountOrganization: organization,                    loginMethod: loginMethod)            } else {                self.identity = nil            }        }    }     public func encode(to encoder: Encoder) throws {        var container = encoder.container(keyedBy: CodingKeys.self)        // Stable JSON schema: keep window keys present (encode `nil` as `null`).        try container.encode(self.primary, forKey: .primary)        try container.encode(self.secondary, forKey: .secondary)        try container.encode(self.tertiary, forKey: .tertiary)        try container.encodeIfPresent(self.extraRateWindows, forKey: .extraRateWindows)        try container.encodeIfPresent(self.providerCost, forKey: .providerCost)        try container.encodeIfPresent(self.kiroUsage, forKey: .kiroUsage)        try container.encodeIfPresent(self.ampUsage, forKey: .ampUsage)        try container.encodeIfPresent(self.mimoUsage, forKey: .mimoUsage)        try container.encodeIfPresent(self.openRouterUsage, forKey: .openRouterUsage)        try container.encodeIfPresent(self.openAIAPIUsage, forKey: .openAIAPIUsage)        try container.encodeIfPresent(self.codexResetCredits, forKey: .codexResetCredits)        try container.encodeIfPresent(self.claudeAdminAPIUsage, forKey: .claudeAdminAPIUsage)        try container.encodeIfPresent(self.mistralUsage, forKey: .mistralUsage)        try container.encodeIfPresent(self.deepgramUsage, forKey: .deepgramUsage)        try container.encodeIfPresent(self.poeUsage, forKey: .poeUsage)        try container.encodeIfPresent(self.subscriptionExpiresAt, forKey: .subscriptionExpiresAt)        try container.encodeIfPresent(self.subscriptionRenewsAt, forKey: .subscriptionRenewsAt)        try container.encode(self.updatedAt, forKey: .updatedAt)        try container.encodeIfPresent(self.identity, forKey: .identity)        if self.dataConfidence != .unknown {            try container.encode(self.dataConfidence, forKey: .dataConfidence)        }        try container.encodeIfPresent(self.identity?.accountEmail, forKey: .accountEmail)        try container.encodeIfPresent(self.identity?.accountOrganization, forKey: .accountOrganization)        try container.encodeIfPresent(self.identity?.loginMethod, forKey: .loginMethod)    }     public func identity(for provider: UsageProvider) -> ProviderIdentitySnapshot? {        guard let identity, identity.providerID == provider else { return nil }        return identity    }     public func automaticPerplexityWindow() -> RateWindow? {        let fallbackWindows = self.orderedPerplexityFallbackWindows()        guard let primary = self.primary else {            return fallbackWindows.first        }        if primary.remainingPercent > 0 || fallbackWindows.isEmpty {            return primary        }        return fallbackWindows.first    }     public func orderedPerplexityDisplayWindows() -> [RateWindow] {        let fallbackWindows = self.orderedPerplexityFallbackWindows()        guard let primary = self.primary else {            return fallbackWindows        }        if primary.remainingPercent > 0 || fallbackWindows.isEmpty {            return [primary] + fallbackWindows        }        return fallbackWindows + [primary]    }     public func switcherWeeklyWindow(for provider: UsageProvider, showUsed: Bool) -> RateWindow? {        switch provider {        case .factory:            // Factory prefers secondary window            return self.secondary ?? self.primary        case .perplexity:            return self.automaticPerplexityWindow()        case .cursor:            // Cursor: fall back to on-demand budget when the included plan is exhausted (only in            // "show remaining" mode). The secondary/tertiary lanes are Total/Auto/API breakdowns,            // not extra capacity, so they should not replace the remaining paid quota indicator.            if !showUsed,               let primary = self.primary,               primary.remainingPercent <= 0,               let providerCost = self.providerCost,               providerCost.limit > 0            {                let usedPercent = max(0, min(100, (providerCost.used / providerCost.limit) * 100))                return RateWindow(                    usedPercent: usedPercent,                    windowMinutes: nil,                    resetsAt: providerCost.resetsAt,                    resetDescription: nil)            }            return self.primary ?? self.secondary        default:            return self.primary ?? self.secondary        }    }     public func accountEmail(for provider: UsageProvider) -> String? {        self.identity(for: provider)?.accountEmail    }     public func accountOrganization(for provider: UsageProvider) -> String? {        self.identity(for: provider)?.accountOrganization    }     public func loginMethod(for provider: UsageProvider) -> String? {        self.identity(for: provider)?.loginMethod    }     public var hasRateLimitWindows: Bool {        self.primary != nil || self.secondary != nil || self.tertiary != nil ||            !(self.extraRateWindows?.isEmpty ?? true)    }     public func rateLimitsUnavailable(for provider: UsageProvider) -> Bool {        UsageLimitsAvailability.resolve(provider: provider, snapshot: self).isUnavailable    }     public func withIdentity(_ identity: ProviderIdentitySnapshot?) -> UsageSnapshot {        self.replacing(identity: .value(identity))    }     public func withDataConfidence(_ dataConfidence: UsageDataConfidence) -> UsageSnapshot {        self.replacing(dataConfidence: .value(dataConfidence))    }     public func scoped(to provider: UsageProvider) -> UsageSnapshot {        guard let identity else { return self }        let scopedIdentity = identity.scoped(to: provider)        if scopedIdentity.providerID == identity.providerID { return self }        return self.withIdentity(scopedIdentity)    }     public func backfillingResetTimes(from cached: UsageSnapshot?, now: Date = .init()) -> UsageSnapshot {        guard let cached else { return self }        guard Self.identitiesMatch(self.identity, cached.identity) else { return self }        let primary = self.primary?.backfillingResetTime(from: cached.primary, now: now)        let secondary = self.secondary?.backfillingResetTime(from: cached.secondary, now: now)        let tertiary = self.tertiary?.backfillingResetTime(from: cached.tertiary, now: now)        if primary == self.primary, secondary == self.secondary, tertiary == self.tertiary {            return self        }        return self.replacing(            primary: .value(primary),            secondary: .value(secondary),            tertiary: .value(tertiary))    }     private func orderedPerplexityFallbackWindows() -> [RateWindow] {        let fallbackWindows = [self.tertiary, self.secondary].compactMap(\.self)        let usableFallback = fallbackWindows.filter { $0.remainingPercent > 0 }        let exhaustedFallback = fallbackWindows.filter { $0.remainingPercent <= 0 }        return usableFallback + exhaustedFallback    }     private static func identitiesMatch(_ lhs: ProviderIdentitySnapshot?, _ rhs: ProviderIdentitySnapshot?) -> Bool {        if lhs == nil, rhs == nil { return true }        guard let lhs, let rhs else { return false }        let lhsEmail = lhs.accountEmail?.trimmingCharacters(in: .whitespacesAndNewlines)        let rhsEmail = rhs.accountEmail?.trimmingCharacters(in: .whitespacesAndNewlines)        if let lhsEmail, let rhsEmail, !lhsEmail.isEmpty, !rhsEmail.isEmpty {            return lhsEmail == rhsEmail        }        return true    }     private enum Replacement<Value> {        case unchanged        case value(Value)         func resolving(_ current: Value) -> Value {            switch self {            case .unchanged: current            case let .value(value): value            }        }    }     private func replacing(        primary: Replacement<RateWindow?> = .unchanged,        secondary: Replacement<RateWindow?> = .unchanged,        tertiary: Replacement<RateWindow?> = .unchanged,        extraRateWindows: Replacement<[NamedRateWindow]?> = .unchanged,        codexResetCredits: Replacement<CodexRateLimitResetCreditsSnapshot?> = .unchanged,        identity: Replacement<ProviderIdentitySnapshot?> = .unchanged,        dataConfidence: Replacement<UsageDataConfidence> = .unchanged) -> UsageSnapshot    {        UsageSnapshot(            primary: primary.resolving(self.primary),            secondary: secondary.resolving(self.secondary),            tertiary: tertiary.resolving(self.tertiary),            extraRateWindows: extraRateWindows.resolving(self.extraRateWindows),            kiroUsage: self.kiroUsage,            ampUsage: self.ampUsage,            providerCost: self.providerCost,            zaiUsage: self.zaiUsage,            minimaxUsage: self.minimaxUsage,            deepseekUsage: self.deepseekUsage,            mimoUsage: self.mimoUsage,            openRouterUsage: self.openRouterUsage,

Lines 1–500 of 1337.