import Foundation#if canImport(FoundationNetworking)import FoundationNetworking#endif#if os(macOS)import SweetCookieKit private let factoryCookieImportOrder: BrowserCookieImportOrder = ProviderDefaults.metadata[.factory]?.browserCookieOrder ?? Browser.defaultImportOrder // MARK: - Factory Cookie Importer /// Imports Factory session cookies from browser cookies.public enum FactoryCookieImporter { private static let cookieClient = BrowserCookieClient() private static let sessionCookieNames: Set<String> = [ "wos-session", "__Secure-next-auth.session-token", "next-auth.session-token", "__Secure-authjs.session-token", "__Host-authjs.csrf-token", "authjs.session-token", "session", "access-token", ] private static let authSessionCookieNames: Set<String> = [ "__Secure-next-auth.session-token", "next-auth.session-token", "__Secure-authjs.session-token", "authjs.session-token", ] private static let appBaseURL = URL(string: "https://app.factory.ai")! private static let authBaseURL = URL(string: "https://auth.factory.ai")! private static let apiBaseURL = URL(string: "https://api.factory.ai")! public struct SessionInfo: Sendable { public let cookies: [HTTPCookie] public let sourceLabel: String public init(cookies: [HTTPCookie], sourceLabel: String) { self.cookies = cookies self.sourceLabel = sourceLabel } public var cookieHeader: String { self.cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; ") } } /// Returns all Factory sessions across supported browsers. public static func importSessions( browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) throws -> [SessionInfo] { let log: (String) -> Void = { msg in logger?("[factory-cookie] \(msg)") } var sessions: [SessionInfo] = [] // Filter to cookie-eligible browsers to avoid unnecessary keychain prompts let installedBrowsers = factoryCookieImportOrder.cookieImportCandidates(using: browserDetection) for browserSource in installedBrowsers { do { let perSource = try self.importSessions(from: browserSource, logger: logger) sessions.append(contentsOf: perSource) } catch { BrowserCookieAccessGate.recordIfNeeded(error) log("\(browserSource.displayName) cookie import failed: \(error.localizedDescription)") } } guard !sessions.isEmpty else { throw FactoryStatusProbeError.noSessionCookie } return sessions } public static func importSessions( from browserSource: Browser, logger: ((String) -> Void)? = nil) throws -> [SessionInfo] { let log: (String) -> Void = { msg in logger?("[factory-cookie] \(msg)") } let cookieDomains = ["factory.ai", "app.factory.ai", "auth.factory.ai"] let query = BrowserCookieQuery(domains: cookieDomains) let sources = try Self.cookieClient.codexBarRecords( matching: query, in: browserSource, logger: log) var sessions: [SessionInfo] = [] for source in sources where !source.records.isEmpty { let httpCookies = BrowserCookieClient.makeHTTPCookies(source.records, origin: query.origin) if httpCookies.contains(where: { Self.sessionCookieNames.contains($0.name) }) { log("Found \(httpCookies.count) Factory cookies in \(source.label)") log("\(source.label) cookie names: \(self.cookieNames(from: httpCookies))") if let token = httpCookies.first(where: { $0.name == "access-token" })?.value { let hint = token.contains(".") ? "jwt" : "opaque" log("\(source.label) access-token cookie: \(token.count) chars (\(hint))") } if let token = httpCookies.first(where: { self.authSessionCookieNames.contains($0.name) })?.value { let hint = token.contains(".") ? "jwt" : "opaque" log("\(source.label) session cookie: \(token.count) chars (\(hint))") } sessions.append(SessionInfo(cookies: httpCookies, sourceLabel: source.label)) } else { log("\(source.label) cookies found, but no Factory session cookie present") } } return sessions } /// Attempts to import Factory cookies using the standard browser import order. public static func importSession( browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) throws -> SessionInfo { let sessions = try self.importSessions(browserDetection: browserDetection, logger: logger) guard let first = sessions.first else { throw FactoryStatusProbeError.noSessionCookie } return first } /// Check if Factory session cookies are available public static func hasSession(browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) -> Bool { do { return try !(self.importSessions(browserDetection: browserDetection, logger: logger)).isEmpty } catch { return false } } private static func cookieNames(from cookies: [HTTPCookie]) -> String { let names = Set(cookies.map { "\($0.name)@\($0.domain)" }).sorted() return names.joined(separator: ", ") }} #endif // MARK: - Factory API Models public struct FactoryAuthResponse: Codable, Sendable { public let featureFlags: FactoryFeatureFlags? public let organization: FactoryOrganization? public let userProfile: FactoryUserProfile?} public struct FactoryUserProfile: Codable, Sendable { public let id: String? public let email: String?} public struct FactoryFeatureFlags: Codable, Sendable { public let flags: [String: Bool]? public let configs: [String: AnyCodable]?} public struct FactoryOrganization: Codable, Sendable { public let id: String? public let name: String? public let subscription: FactorySubscription? enum CodingKeys: String, CodingKey { case id case name case subscription }} public struct FactorySubscription: Codable, Sendable { public let factoryTier: String? public let orbSubscription: FactoryOrbSubscription?} public struct FactoryOrbSubscription: Codable, Sendable { public let plan: FactoryPlan? public let status: String?} public struct FactoryPlan: Codable, Sendable { public let name: String? public let id: String?} public struct FactoryUsageResponse: Codable, Sendable { public let usage: FactoryUsageData? public let source: String? public let userId: String?} public struct FactoryUsageData: Codable, Sendable { public let startDate: Int64? public let endDate: Int64? public let standard: FactoryTokenUsage? public let premium: FactoryTokenUsage?} public struct FactoryTokenUsage: Codable, Sendable { public let userTokens: Int64? public let orgTotalTokensUsed: Int64? public let totalAllowance: Int64? public let usedRatio: Double? public let orgOverageUsed: Int64? public let basicAllowance: Int64? public let orgOverageLimit: Int64?} public struct FactoryBillingLimitsResponse: Codable, Sendable { public let usesTokenRateLimitsBilling: Bool public let limits: FactoryTokenRateLimits? public let extraUsageBalanceCents: Int public let overagePreference: String? public let extraUsageAllowed: Bool public let tokenRateLimitsRolloutEligible: Bool enum CodingKeys: String, CodingKey { case usesTokenRateLimitsBilling case limits case extraUsageBalanceCents case overagePreference case extraUsageAllowed case tokenRateLimitsRolloutEligible } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.usesTokenRateLimitsBilling = try container .decodeIfPresent(Bool.self, forKey: .usesTokenRateLimitsBilling) ?? false self.limits = try container.decodeIfPresent(FactoryTokenRateLimits.self, forKey: .limits) self.extraUsageBalanceCents = try container.decodeIfPresent(Int.self, forKey: .extraUsageBalanceCents) ?? 0 self.overagePreference = try container.decodeIfPresent(String.self, forKey: .overagePreference) self.extraUsageAllowed = try container.decodeIfPresent(Bool.self, forKey: .extraUsageAllowed) ?? false self.tokenRateLimitsRolloutEligible = try container .decodeIfPresent(Bool.self, forKey: .tokenRateLimitsRolloutEligible) ?? false }} public struct FactoryTokenRateLimits: Codable, Sendable { public let standard: FactoryLimitPool public let core: FactoryLimitPool?} public struct FactoryLimitPool: Codable, Sendable { public let fiveHour: FactoryBillingWindow public let weekly: FactoryBillingWindow public let monthly: FactoryBillingWindow public var hasUsageData: Bool { [self.fiveHour, self.weekly, self.monthly].contains { $0.usedPercent > 0 || $0.windowEnd != nil || $0.secondsRemaining != nil } }} public struct FactoryBillingWindow: Codable, Sendable { public let usedPercent: Double public let windowEnd: FlexibleFactoryDate? public let secondsRemaining: Double? public func resetAt(now: Date) -> Date? { if let secondsRemaining, secondsRemaining > 0 { return now.addingTimeInterval(secondsRemaining) } guard let windowEnd = self.windowEnd?.date, windowEnd > now else { return nil } return windowEnd } public func effectiveUsedPercent(now: Date) -> Double { // Factory can leave stale values after short rolling windows expire. The web UI treats // that state as reset, so mirror it here instead of showing expired usage. if self.resetAt(now: now) == nil, self.windowEnd != nil, self.secondsRemaining == nil { return 0 } return min(100, max(0, self.usedPercent)) } public func rateWindow(windowMinutes: Int?, title: String, now: Date) -> RateWindow { let reset = self.resetAt(now: now) return RateWindow( usedPercent: self.effectiveUsedPercent(now: now), windowMinutes: windowMinutes, resetsAt: reset, resetDescription: reset.map { FactoryStatusSnapshot.formatResetDate($0) }) }} public struct FlexibleFactoryDate: Codable, Sendable { public let date: Date public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let seconds = try? container.decode(Double.self) { self.date = Date(timeIntervalSince1970: seconds > 1e12 ? seconds / 1000.0 : seconds) return } let string = try container.decode(String.self) if let numeric = Double(string) { self.date = Date(timeIntervalSince1970: numeric > 1e12 ? numeric / 1000.0 : numeric) return } let fractional = ISO8601DateFormatter() fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] if let parsed = fractional.date(from: string) ?? ISO8601DateFormatter().date(from: string) { self.date = parsed return } throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid Factory date") } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.date) }} /// Helper for encoding arbitrary JSONpublic struct AnyCodable: Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { return } _ = try? container.decode([String: AnyCodable].self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encodeNil() }} // MARK: - Factory Status Snapshot public struct FactoryStatusSnapshot: Sendable { /// Standard token usage (user) public let standardUserTokens: Int64 /// Standard token usage (org total) public let standardOrgTokens: Int64 /// Standard token allowance public let standardAllowance: Int64 /// Standard usage ratio from API (0.0-1.0), preferred over manual calculation /// Falls back to percent-scale (0.0-100.0) when allowance is unavailable. public let standardUsedRatio: Double? /// Premium token usage (user) public let premiumUserTokens: Int64 /// Premium token usage (org total) public let premiumOrgTokens: Int64 /// Premium token allowance public let premiumAllowance: Int64 /// Premium usage ratio from API (0.0-1.0), preferred over manual calculation /// Falls back to percent-scale (0.0-100.0) when allowance is unavailable. public let premiumUsedRatio: Double? /// Billing period start public let periodStart: Date? /// Billing period end public let periodEnd: Date? /// Plan name public let planName: String? /// Factory tier (enterprise, team, etc.) public let tier: String? /// Organization name public let organizationName: String? /// User email public let accountEmail: String? /// User ID public let userId: String? /// Raw JSON for debugging public let rawJSON: String? /// New Factory token-rate-limits billing payload, when enabled for the account. public let tokenRateLimits: FactoryTokenRateLimits? public let extraUsageBalanceCents: Int? public let overagePreference: String? public init( standardUserTokens: Int64, standardOrgTokens: Int64, standardAllowance: Int64, standardUsedRatio: Double? = nil, premiumUserTokens: Int64, premiumOrgTokens: Int64, premiumAllowance: Int64, premiumUsedRatio: Double? = nil, periodStart: Date?, periodEnd: Date?, planName: String?, tier: String?, organizationName: String?, accountEmail: String?, userId: String?, rawJSON: String?, tokenRateLimits: FactoryTokenRateLimits? = nil, extraUsageBalanceCents: Int? = nil, overagePreference: String? = nil) { self.standardUserTokens = standardUserTokens self.standardOrgTokens = standardOrgTokens self.standardAllowance = standardAllowance self.standardUsedRatio = standardUsedRatio self.premiumUserTokens = premiumUserTokens self.premiumOrgTokens = premiumOrgTokens self.premiumAllowance = premiumAllowance self.premiumUsedRatio = premiumUsedRatio self.periodStart = periodStart self.periodEnd = periodEnd self.planName = planName self.tier = tier self.organizationName = organizationName self.accountEmail = accountEmail self.userId = userId self.rawJSON = rawJSON self.tokenRateLimits = tokenRateLimits self.extraUsageBalanceCents = extraUsageBalanceCents self.overagePreference = overagePreference } /// Convert to UsageSnapshot for the common provider interface public func toUsageSnapshot() -> UsageSnapshot { if let tokenRateLimits { return self.tokenRateLimitsUsageSnapshot(from: tokenRateLimits) } // Primary: Standard tokens used (as percentage of allowance, capped reasonably) let standardPercent = self.calculateUsagePercent( used: self.standardUserTokens, allowance: self.standardAllowance, apiRatio: self.standardUsedRatio) let primary = RateWindow( usedPercent: standardPercent, windowMinutes: nil, resetsAt: self.periodEnd, resetDescription: self.periodEnd.map { Self.formatResetDate($0) }) // Secondary: Premium tokens used let premiumPercent = self.calculateUsagePercent( used: self.premiumUserTokens, allowance: self.premiumAllowance, apiRatio: self.premiumUsedRatio) let secondary = RateWindow( usedPercent: premiumPercent, windowMinutes: nil, resetsAt: self.periodEnd, resetDescription: self.periodEnd.map { Self.formatResetDate($0) }) // Format login method as tier + plan let loginMethod: String? = { var parts: [String] = [] if let tier = self.tier, !tier.isEmpty { parts.append("Factory \(tier.capitalized)") } if let plan = self.planName, !plan.isEmpty, !plan.lowercased().contains("factory") { parts.append(plan) } return parts.isEmpty ? nil : parts.joined(separator: " - ") }() let identity = ProviderIdentitySnapshot( providerID: .factory, accountEmail: self.accountEmail, accountOrganization: self.organizationName, loginMethod: loginMethod) return UsageSnapshot( primary: primary, secondary: secondary, tertiary: nil, providerCost: nil, updatedAt: Date(), identity: identity) } private func tokenRateLimitsUsageSnapshot(from limits: FactoryTokenRateLimits) -> UsageSnapshot { let now = Date() let primary = limits.standard.fiveHour.rateWindow(windowMinutes: 5 * 60, title: "5h", now: now) let secondary = limits.standard.weekly.rateWindow(windowMinutes: 7 * 24 * 60, title: "7-day", now: now) let tertiary = limits.standard.monthly.rateWindow(windowMinutes: nil, title: "Monthly", now: now) let coreWindows: [NamedRateWindow]? = if let core = limits.core, core.hasUsageData { [ NamedRateWindow( id: "factory-core-5h", title: "Core 5h", window: core.fiveHour.rateWindow(windowMinutes: 5 * 60, title: "Core 5h", now: now)), NamedRateWindow( id: "factory-core-7d", title: "Core 7-day", window: core.weekly.rateWindow(windowMinutes: 7 * 24 * 60, title: "Core 7-day", now: now)), NamedRateWindow( id: "factory-core-monthly", title: "Core Monthly", window: core.monthly.rateWindow(windowMinutes: nil, title: "Core Monthly", now: now)), ] } else { nil } let loginMethod: String? = {Lines 1–500 of 1485. Load more
import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif #if os(macOS) import SweetCookieKit private let factoryCookieImportOrder: BrowserCookieImportOrder = ProviderDefaults.metadata[.factory]?.browserCookieOrder ?? Browser.defaultImportOrder // MARK: - Factory Cookie Importer /// Imports Factory session cookies from browser cookies. public enum FactoryCookieImporter { private static let cookieClient = BrowserCookieClient() private static let sessionCookieNames: Set<String> = [ "wos-session", "__Secure-next-auth.session-token", "next-auth.session-token", "__Secure-authjs.session-token", "__Host-authjs.csrf-token", "authjs.session-token", "session", "access-token", ] private static let authSessionCookieNames: Set<String> = [ "__Secure-next-auth.session-token", "next-auth.session-token", "__Secure-authjs.session-token", "authjs.session-token", ] private static let appBaseURL = URL(string: "https://app.factory.ai")! private static let authBaseURL = URL(string: "https://auth.factory.ai")! private static let apiBaseURL = URL(string: "https://api.factory.ai")! public struct SessionInfo: Sendable { public let cookies: [HTTPCookie] public let sourceLabel: String public init(cookies: [HTTPCookie], sourceLabel: String) { self.cookies = cookies self.sourceLabel = sourceLabel } public var cookieHeader: String { self.cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; ") } } /// Returns all Factory sessions across supported browsers. public static func importSessions( browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) throws -> [SessionInfo] { let log: (String) -> Void = { msg in logger?("[factory-cookie] \(msg)") } var sessions: [SessionInfo] = [] // Filter to cookie-eligible browsers to avoid unnecessary keychain prompts let installedBrowsers = factoryCookieImportOrder.cookieImportCandidates(using: browserDetection) for browserSource in installedBrowsers { do { let perSource = try self.importSessions(from: browserSource, logger: logger) sessions.append(contentsOf: perSource) } catch { BrowserCookieAccessGate.recordIfNeeded(error) log("\(browserSource.displayName) cookie import failed: \(error.localizedDescription)") } } guard !sessions.isEmpty else { throw FactoryStatusProbeError.noSessionCookie } return sessions } public static func importSessions( from browserSource: Browser, logger: ((String) -> Void)? = nil) throws -> [SessionInfo] { let log: (String) -> Void = { msg in logger?("[factory-cookie] \(msg)") } let cookieDomains = ["factory.ai", "app.factory.ai", "auth.factory.ai"] let query = BrowserCookieQuery(domains: cookieDomains) let sources = try Self.cookieClient.codexBarRecords( matching: query, in: browserSource, logger: log) var sessions: [SessionInfo] = [] for source in sources where !source.records.isEmpty { let httpCookies = BrowserCookieClient.makeHTTPCookies(source.records, origin: query.origin) if httpCookies.contains(where: { Self.sessionCookieNames.contains($0.name) }) { log("Found \(httpCookies.count) Factory cookies in \(source.label)") log("\(source.label) cookie names: \(self.cookieNames(from: httpCookies))") if let token = httpCookies.first(where: { $0.name == "access-token" })?.value { let hint = token.contains(".") ? "jwt" : "opaque" log("\(source.label) access-token cookie: \(token.count) chars (\(hint))") } if let token = httpCookies.first(where: { self.authSessionCookieNames.contains($0.name) })?.value { let hint = token.contains(".") ? "jwt" : "opaque" log("\(source.label) session cookie: \(token.count) chars (\(hint))") } sessions.append(SessionInfo(cookies: httpCookies, sourceLabel: source.label)) } else { log("\(source.label) cookies found, but no Factory session cookie present") } } return sessions } /// Attempts to import Factory cookies using the standard browser import order. public static func importSession( browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) throws -> SessionInfo { let sessions = try self.importSessions(browserDetection: browserDetection, logger: logger) guard let first = sessions.first else { throw FactoryStatusProbeError.noSessionCookie } return first } /// Check if Factory session cookies are available public static func hasSession(browserDetection: BrowserDetection, logger: ((String) -> Void)? = nil) -> Bool { do { return try !(self.importSessions(browserDetection: browserDetection, logger: logger)).isEmpty } catch { return false } } private static func cookieNames(from cookies: [HTTPCookie]) -> String { let names = Set(cookies.map { "\($0.name)@\($0.domain)" }).sorted() return names.joined(separator: ", ") } } #endif // MARK: - Factory API Models public struct FactoryAuthResponse: Codable, Sendable { public let featureFlags: FactoryFeatureFlags? public let organization: FactoryOrganization? public let userProfile: FactoryUserProfile? } public struct FactoryUserProfile: Codable, Sendable { public let id: String? public let email: String? } public struct FactoryFeatureFlags: Codable, Sendable { public let flags: [String: Bool]? public let configs: [String: AnyCodable]? } public struct FactoryOrganization: Codable, Sendable { public let id: String? public let name: String? public let subscription: FactorySubscription? enum CodingKeys: String, CodingKey { case id case name case subscription } } public struct FactorySubscription: Codable, Sendable { public let factoryTier: String? public let orbSubscription: FactoryOrbSubscription? } public struct FactoryOrbSubscription: Codable, Sendable { public let plan: FactoryPlan? public let status: String? } public struct FactoryPlan: Codable, Sendable { public let name: String? public let id: String? } public struct FactoryUsageResponse: Codable, Sendable { public let usage: FactoryUsageData? public let source: String? public let userId: String? } public struct FactoryUsageData: Codable, Sendable { public let startDate: Int64? public let endDate: Int64? public let standard: FactoryTokenUsage? public let premium: FactoryTokenUsage? } public struct FactoryTokenUsage: Codable, Sendable { public let userTokens: Int64? public let orgTotalTokensUsed: Int64? public let totalAllowance: Int64? public let usedRatio: Double? public let orgOverageUsed: Int64? public let basicAllowance: Int64? public let orgOverageLimit: Int64? } public struct FactoryBillingLimitsResponse: Codable, Sendable { public let usesTokenRateLimitsBilling: Bool public let limits: FactoryTokenRateLimits? public let extraUsageBalanceCents: Int public let overagePreference: String? public let extraUsageAllowed: Bool public let tokenRateLimitsRolloutEligible: Bool enum CodingKeys: String, CodingKey { case usesTokenRateLimitsBilling case limits case extraUsageBalanceCents case overagePreference case extraUsageAllowed case tokenRateLimitsRolloutEligible } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.usesTokenRateLimitsBilling = try container .decodeIfPresent(Bool.self, forKey: .usesTokenRateLimitsBilling) ?? false self.limits = try container.decodeIfPresent(FactoryTokenRateLimits.self, forKey: .limits) self.extraUsageBalanceCents = try container.decodeIfPresent(Int.self, forKey: .extraUsageBalanceCents) ?? 0 self.overagePreference = try container.decodeIfPresent(String.self, forKey: .overagePreference) self.extraUsageAllowed = try container.decodeIfPresent(Bool.self, forKey: .extraUsageAllowed) ?? false self.tokenRateLimitsRolloutEligible = try container .decodeIfPresent(Bool.self, forKey: .tokenRateLimitsRolloutEligible) ?? false } } public struct FactoryTokenRateLimits: Codable, Sendable { public let standard: FactoryLimitPool public let core: FactoryLimitPool? } public struct FactoryLimitPool: Codable, Sendable { public let fiveHour: FactoryBillingWindow public let weekly: FactoryBillingWindow public let monthly: FactoryBillingWindow public var hasUsageData: Bool { [self.fiveHour, self.weekly, self.monthly].contains { $0.usedPercent > 0 || $0.windowEnd != nil || $0.secondsRemaining != nil } } } public struct FactoryBillingWindow: Codable, Sendable { public let usedPercent: Double public let windowEnd: FlexibleFactoryDate? public let secondsRemaining: Double? public func resetAt(now: Date) -> Date? { if let secondsRemaining, secondsRemaining > 0 { return now.addingTimeInterval(secondsRemaining) } guard let windowEnd = self.windowEnd?.date, windowEnd > now else { return nil } return windowEnd } public func effectiveUsedPercent(now: Date) -> Double { // Factory can leave stale values after short rolling windows expire. The web UI treats // that state as reset, so mirror it here instead of showing expired usage. if self.resetAt(now: now) == nil, self.windowEnd != nil, self.secondsRemaining == nil { return 0 } return min(100, max(0, self.usedPercent)) } public func rateWindow(windowMinutes: Int?, title: String, now: Date) -> RateWindow { let reset = self.resetAt(now: now) return RateWindow( usedPercent: self.effectiveUsedPercent(now: now), windowMinutes: windowMinutes, resetsAt: reset, resetDescription: reset.map { FactoryStatusSnapshot.formatResetDate($0) }) } } public struct FlexibleFactoryDate: Codable, Sendable { public let date: Date public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let seconds = try? container.decode(Double.self) { self.date = Date(timeIntervalSince1970: seconds > 1e12 ? seconds / 1000.0 : seconds) return } let string = try container.decode(String.self) if let numeric = Double(string) { self.date = Date(timeIntervalSince1970: numeric > 1e12 ? numeric / 1000.0 : numeric) return } let fractional = ISO8601DateFormatter() fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] if let parsed = fractional.date(from: string) ?? ISO8601DateFormatter().date(from: string) { self.date = parsed return } throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid Factory date") } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.date) } } /// Helper for encoding arbitrary JSON public struct AnyCodable: Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { return } _ = try? container.decode([String: AnyCodable].self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encodeNil() } } // MARK: - Factory Status Snapshot public struct FactoryStatusSnapshot: Sendable { /// Standard token usage (user) public let standardUserTokens: Int64 /// Standard token usage (org total) public let standardOrgTokens: Int64 /// Standard token allowance public let standardAllowance: Int64 /// Standard usage ratio from API (0.0-1.0), preferred over manual calculation /// Falls back to percent-scale (0.0-100.0) when allowance is unavailable. public let standardUsedRatio: Double? /// Premium token usage (user) public let premiumUserTokens: Int64 /// Premium token usage (org total) public let premiumOrgTokens: Int64 /// Premium token allowance public let premiumAllowance: Int64 /// Premium usage ratio from API (0.0-1.0), preferred over manual calculation /// Falls back to percent-scale (0.0-100.0) when allowance is unavailable. public let premiumUsedRatio: Double? /// Billing period start public let periodStart: Date? /// Billing period end public let periodEnd: Date? /// Plan name public let planName: String? /// Factory tier (enterprise, team, etc.) public let tier: String? /// Organization name public let organizationName: String? /// User email public let accountEmail: String? /// User ID public let userId: String? /// Raw JSON for debugging public let rawJSON: String? /// New Factory token-rate-limits billing payload, when enabled for the account. public let tokenRateLimits: FactoryTokenRateLimits? public let extraUsageBalanceCents: Int? public let overagePreference: String? public init( standardUserTokens: Int64, standardOrgTokens: Int64, standardAllowance: Int64, standardUsedRatio: Double? = nil, premiumUserTokens: Int64, premiumOrgTokens: Int64, premiumAllowance: Int64, premiumUsedRatio: Double? = nil, periodStart: Date?, periodEnd: Date?, planName: String?, tier: String?, organizationName: String?, accountEmail: String?, userId: String?, rawJSON: String?, tokenRateLimits: FactoryTokenRateLimits? = nil, extraUsageBalanceCents: Int? = nil, overagePreference: String? = nil) { self.standardUserTokens = standardUserTokens self.standardOrgTokens = standardOrgTokens self.standardAllowance = standardAllowance self.standardUsedRatio = standardUsedRatio self.premiumUserTokens = premiumUserTokens self.premiumOrgTokens = premiumOrgTokens self.premiumAllowance = premiumAllowance self.premiumUsedRatio = premiumUsedRatio self.periodStart = periodStart self.periodEnd = periodEnd self.planName = planName self.tier = tier self.organizationName = organizationName self.accountEmail = accountEmail self.userId = userId self.rawJSON = rawJSON self.tokenRateLimits = tokenRateLimits self.extraUsageBalanceCents = extraUsageBalanceCents self.overagePreference = overagePreference } /// Convert to UsageSnapshot for the common provider interface public func toUsageSnapshot() -> UsageSnapshot { if let tokenRateLimits { return self.tokenRateLimitsUsageSnapshot(from: tokenRateLimits) } // Primary: Standard tokens used (as percentage of allowance, capped reasonably) let standardPercent = self.calculateUsagePercent( used: self.standardUserTokens, allowance: self.standardAllowance, apiRatio: self.standardUsedRatio) let primary = RateWindow( usedPercent: standardPercent, windowMinutes: nil, resetsAt: self.periodEnd, resetDescription: self.periodEnd.map { Self.formatResetDate($0) }) // Secondary: Premium tokens used let premiumPercent = self.calculateUsagePercent( used: self.premiumUserTokens, allowance: self.premiumAllowance, apiRatio: self.premiumUsedRatio) let secondary = RateWindow( usedPercent: premiumPercent, windowMinutes: nil, resetsAt: self.periodEnd, resetDescription: self.periodEnd.map { Self.formatResetDate($0) }) // Format login method as tier + plan let loginMethod: String? = { var parts: [String] = [] if let tier = self.tier, !tier.isEmpty { parts.append("Factory \(tier.capitalized)") } if let plan = self.planName, !plan.isEmpty, !plan.lowercased().contains("factory") { parts.append(plan) } return parts.isEmpty ? nil : parts.joined(separator: " - ") }() let identity = ProviderIdentitySnapshot( providerID: .factory, accountEmail: self.accountEmail, accountOrganization: self.organizationName, loginMethod: loginMethod) return UsageSnapshot( primary: primary, secondary: secondary, tertiary: nil, providerCost: nil, updatedAt: Date(), identity: identity) } private func tokenRateLimitsUsageSnapshot(from limits: FactoryTokenRateLimits) -> UsageSnapshot { let now = Date() let primary = limits.standard.fiveHour.rateWindow(windowMinutes: 5 * 60, title: "5h", now: now) let secondary = limits.standard.weekly.rateWindow(windowMinutes: 7 * 24 * 60, title: "7-day", now: now) let tertiary = limits.standard.monthly.rateWindow(windowMinutes: nil, title: "Monthly", now: now) let coreWindows: [NamedRateWindow]? = if let core = limits.core, core.hasUsageData { [ NamedRateWindow( id: "factory-core-5h", title: "Core 5h", window: core.fiveHour.rateWindow(windowMinutes: 5 * 60, title: "Core 5h", now: now)), NamedRateWindow( id: "factory-core-7d", title: "Core 7-day", window: core.weekly.rateWindow(windowMinutes: 7 * 24 * 60, title: "Core 7-day", now: now)), NamedRateWindow( id: "factory-core-monthly", title: "Core Monthly", window: core.monthly.rateWindow(windowMinutes: nil, title: "Core Monthly", now: now)), ] } else { nil } let loginMethod: String? = {