1270 lines · 50.0 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 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 openRouterUsage: OpenRouterUsageSnapshot?    public let openAIAPIUsage: OpenAIAPIUsageSnapshot?    public let claudeAdminAPIUsage: ClaudeAdminAPIUsageSnapshot?    public let mistralUsage: MistralUsageSnapshot?    public let deepgramUsage: DeepgramUsageSnapshot?    public let cursorRequests: CursorRequestUsage?    public let subscriptionExpiresAt: Date?    public let subscriptionRenewsAt: Date?    public let updatedAt: Date    public let identity: ProviderIdentitySnapshot?     private enum CodingKeys: String, CodingKey {        case primary        case secondary        case tertiary        case extraRateWindows        case providerCost        case kiroUsage        case ampUsage        case openRouterUsage        case openAIAPIUsage        case claudeAdminAPIUsage        case mistralUsage        case deepgramUsage        case subscriptionExpiresAt        case subscriptionRenewsAt        case updatedAt        case identity        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,        openRouterUsage: OpenRouterUsageSnapshot? = nil,        openAIAPIUsage: OpenAIAPIUsageSnapshot? = nil,        claudeAdminAPIUsage: ClaudeAdminAPIUsageSnapshot? = nil,        mistralUsage: MistralUsageSnapshot? = nil,        deepgramUsage: DeepgramUsageSnapshot? = nil,        cursorRequests: CursorRequestUsage? = nil,        subscriptionExpiresAt: Date? = nil,        subscriptionRenewsAt: Date? = nil,        updatedAt: Date,        identity: ProviderIdentitySnapshot? = nil)    {        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.openRouterUsage = openRouterUsage        self.openAIAPIUsage = openAIAPIUsage        self.claudeAdminAPIUsage = claudeAdminAPIUsage        self.mistralUsage = mistralUsage        self.deepgramUsage = deepgramUsage        self.cursorRequests = cursorRequests        self.subscriptionExpiresAt = subscriptionExpiresAt        self.subscriptionRenewsAt = subscriptionRenewsAt        self.updatedAt = updatedAt        self.identity = identity    }     public func with(extraRateWindows: [NamedRateWindow]?) -> UsageSnapshot {        UsageSnapshot(            primary: self.primary,            secondary: self.secondary,            tertiary: self.tertiary,            extraRateWindows: extraRateWindows,            kiroUsage: self.kiroUsage,            ampUsage: self.ampUsage,            providerCost: self.providerCost,            zaiUsage: self.zaiUsage,            minimaxUsage: self.minimaxUsage,            deepseekUsage: self.deepseekUsage,            openRouterUsage: self.openRouterUsage,            openAIAPIUsage: self.openAIAPIUsage,            claudeAdminAPIUsage: self.claudeAdminAPIUsage,            mistralUsage: self.mistralUsage,            deepgramUsage: self.deepgramUsage,            cursorRequests: self.cursorRequests,            subscriptionExpiresAt: self.subscriptionExpiresAt,            subscriptionRenewsAt: self.subscriptionRenewsAt,            updatedAt: self.updatedAt,            identity: self.identity)    }     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.openRouterUsage = try container.decodeIfPresent(OpenRouterUsageSnapshot.self, forKey: .openRouterUsage)        self.openAIAPIUsage = try container.decodeIfPresent(OpenAIAPIUsageSnapshot.self, forKey: .openAIAPIUsage)        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.cursorRequests = nil // Not persisted, fetched fresh each time        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 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.openRouterUsage, forKey: .openRouterUsage)        try container.encodeIfPresent(self.openAIAPIUsage, forKey: .openAIAPIUsage)        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.subscriptionExpiresAt, forKey: .subscriptionExpiresAt)        try container.encodeIfPresent(self.subscriptionRenewsAt, forKey: .subscriptionRenewsAt)        try container.encode(self.updatedAt, forKey: .updatedAt)        try container.encodeIfPresent(self.identity, forKey: .identity)        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    }     /// Keep this initializer-style copy in sync with UsageSnapshot fields so relabeling/scoping never drops data.    public func withIdentity(_ identity: ProviderIdentitySnapshot?) -> UsageSnapshot {        UsageSnapshot(            primary: self.primary,            secondary: self.secondary,            tertiary: self.tertiary,            extraRateWindows: self.extraRateWindows,            kiroUsage: self.kiroUsage,            ampUsage: self.ampUsage,            providerCost: self.providerCost,            zaiUsage: self.zaiUsage,            minimaxUsage: self.minimaxUsage,            deepseekUsage: self.deepseekUsage,            openRouterUsage: self.openRouterUsage,            openAIAPIUsage: self.openAIAPIUsage,            claudeAdminAPIUsage: self.claudeAdminAPIUsage,            mistralUsage: self.mistralUsage,            deepgramUsage: self.deepgramUsage,            cursorRequests: self.cursorRequests,            subscriptionExpiresAt: self.subscriptionExpiresAt,            subscriptionRenewsAt: self.subscriptionRenewsAt,            updatedAt: self.updatedAt,            identity: identity)    }     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 UsageSnapshot(            primary: primary,            secondary: secondary,            tertiary: tertiary,            extraRateWindows: self.extraRateWindows,            kiroUsage: self.kiroUsage,            ampUsage: self.ampUsage,            providerCost: self.providerCost,            zaiUsage: self.zaiUsage,            minimaxUsage: self.minimaxUsage,            deepseekUsage: self.deepseekUsage,            openRouterUsage: self.openRouterUsage,            openAIAPIUsage: self.openAIAPIUsage,            claudeAdminAPIUsage: self.claudeAdminAPIUsage,            mistralUsage: self.mistralUsage,            deepgramUsage: self.deepgramUsage,            cursorRequests: self.cursorRequests,            subscriptionExpiresAt: self.subscriptionExpiresAt,            subscriptionRenewsAt: self.subscriptionRenewsAt,            updatedAt: self.updatedAt,            identity: self.identity)    }     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    }} public struct AccountInfo: Equatable, Sendable {    public let email: String?    public let plan: String?     public var hasIdentity: Bool {        self.email?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false ||            self.plan?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false    }     public init(email: String?, plan: String?) {        self.email = email        self.plan = plan    }} public struct CodexCLIAccountSnapshot: Sendable {    public let usage: UsageSnapshot?    public let credits: CreditsSnapshot?     public init(usage: UsageSnapshot?, credits: CreditsSnapshot?) {        self.usage = usage        self.credits = credits    }} public enum UsageError: LocalizedError, Sendable {    case noSessions    case noRateLimitsFound    case decodeFailed     public var errorDescription: String? {        switch self {        case .noSessions:            "No Codex sessions found yet. Run at least one Codex prompt first."        case .noRateLimitsFound:            "Found sessions, but no rate limit events yet."        case .decodeFailed:            "Could not parse Codex session log."        }    }     public static func isNoRateLimitsFoundDescription(_ text: String?) -> Bool {        text?.trimmingCharacters(in: .whitespacesAndNewlines) == UsageError.noRateLimitsFound.errorDescription

Lines 1–500 of 1270.