From a7f57de23465f0d9f1889f169d4358a04210606a Mon Sep 17 00:00:00 2001 From: "swu-jet[bot]" <344783289+swu-jet[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:13:48 +0000 Subject: [PATCH] [JET] Monitor Alibaba Coding Plan for Qwen Code --- Sources/CodeCaps/SettingsViews.swift | 1 + .../QuotaCore/LocalQuotaReaderRegistry.swift | 5 +- Sources/QuotaCore/QuotaModels.swift | 1 + .../QuotaCore/QuotaReaderPreferences.swift | 2 +- Sources/QuotaCore/TokenPlanQuotaReader.swift | 73 +++++++++++++++++-- .../TokenPlanQuotaReaderTests.swift | 32 +++++++- docs/TOKEN-PLAN-SOURCES.md | 26 ++++++- 7 files changed, 130 insertions(+), 10 deletions(-) diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 2c4ef1cc..7466927a 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -1021,6 +1021,7 @@ struct ReaderStatus { ReaderStatus(providerKey: "kimi", label: "Kimi", source: "Kimi Code credentials", optionalReaderID: "kimi"), ReaderStatus(providerKey: "zcode", label: "Z.ai / ZCode", source: "ZCode credentials", optionalReaderID: "zcode"), ReaderStatus(providerKey: "alibaba-token-plan", label: "Alibaba Token Plan", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-token-plan"), + ReaderStatus(providerKey: "alibaba-coding-plan", label: "Alibaba Coding Plan (Qwen Code)", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-coding-plan"), ReaderStatus(providerKey: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", source: "MiMo Token Plan key", optionalReaderID: "mimo-token-plan"), ] } diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index e88032ef..a2ad0883 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -120,7 +120,10 @@ public struct LocalQuotaReaderRegistry: Sendable { ZCodeQuotaReader(credential: zCodeCredentialProvider) }, LocalQuotaReaderRegistration(id: "alibaba-token-plan", label: "Alibaba Token Plan", isOptional: true) { - AlibabaTokenPlanReader() + BailianPlanQuotaReader(plan: .tokenPlan) + }, + LocalQuotaReaderRegistration(id: "alibaba-coding-plan", label: "Alibaba Coding Plan", isOptional: true) { + BailianPlanQuotaReader(plan: .codingPlan) }, LocalQuotaReaderRegistration(id: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", isOptional: true) { MiMoTokenPlanReader(credential: mimoCredentialProvider) diff --git a/Sources/QuotaCore/QuotaModels.swift b/Sources/QuotaCore/QuotaModels.swift index f69ee650..fae9140a 100644 --- a/Sources/QuotaCore/QuotaModels.swift +++ b/Sources/QuotaCore/QuotaModels.swift @@ -1140,6 +1140,7 @@ enum QuotaProviders { // users who have not opted into their local readers. static let optionalTokenPlanLabels: [String: String] = [ "alibaba-token-plan": "Alibaba Token Plan", + "alibaba-coding-plan": "Alibaba Coding Plan", "mimo-token-plan": "Xiaomi MiMo Token Plan", ] diff --git a/Sources/QuotaCore/QuotaReaderPreferences.swift b/Sources/QuotaCore/QuotaReaderPreferences.swift index b6f7c109..62e098be 100644 --- a/Sources/QuotaCore/QuotaReaderPreferences.swift +++ b/Sources/QuotaCore/QuotaReaderPreferences.swift @@ -12,7 +12,7 @@ public struct QuotaReaderPreferences: Codable, Equatable, Sendable { } public func isEnabled(_ readerID: String) -> Bool { - enabledByReaderID[readerID] ?? !["alibaba-token-plan", "mimo-token-plan"].contains(readerID) + enabledByReaderID[readerID] ?? !["alibaba-token-plan", "alibaba-coding-plan", "mimo-token-plan"].contains(readerID) } public mutating func setEnabled(_ enabled: Bool, for readerID: String) { diff --git a/Sources/QuotaCore/TokenPlanQuotaReader.swift b/Sources/QuotaCore/TokenPlanQuotaReader.swift index e3680ae0..bbc39ebb 100644 --- a/Sources/QuotaCore/TokenPlanQuotaReader.swift +++ b/Sources/QuotaCore/TokenPlanQuotaReader.swift @@ -61,9 +61,30 @@ struct MiMoTokenPlanReader: LocalQuotaReading { } } -struct AlibabaTokenPlanReader: LocalQuotaReading { +enum BailianQuotaPlan: Sendable { + case tokenPlan, codingPlan + + var command: String { + switch self { + case .tokenPlan: "token-plan" + case .codingPlan: "coding-plan" + } + } + + var id: String { "alibaba-" + command } + var title: String { + switch self { + case .tokenPlan: "Alibaba Token Plan" + case .codingPlan: "Alibaba Coding Plan" + } + } +} + +struct BailianPlanQuotaReader: LocalQuotaReading { + let plan: BailianQuotaPlan + func read() async -> LocalQuotaResult { - let id = "alibaba-token-plan" + let id = plan.id let home = FileManager.default.homeDirectoryForCurrentUser let paths = [home.appendingPathComponent(".local/bin/bl").path, "/opt/homebrew/bin/bl", "/usr/local/bin/bl"] guard let path = paths.first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else { @@ -71,12 +92,16 @@ struct AlibabaTokenPlanReader: LocalQuotaReading { } do { let data = try await BoundedQuotaProcess().run( - path: path, arguments: ["usage", "token-plan", "--output", "json"], + path: path, arguments: ["usage", plan.command, "--output", "json"], home: home, timeout: 15, maxBytes: 32_768) - let windows = TokenPlanQuotaParser.alibaba(data, now: Date()) + let now = Date() + let windows = switch plan { + case .tokenPlan: TokenPlanQuotaParser.alibaba(data, now: now) + case .codingPlan: TokenPlanQuotaParser.alibabaCoding(data, now: now) + } if !windows.isEmpty { return LocalQuotaResult(windows: windows) } } catch {} - return LocalQuotaResult(issues: [id: "Bailian did not report a current Token Plan quota. Check its console login."]) + return LocalQuotaResult(issues: [id: "Bailian did not report a current \(plan.title) quota. Check its console login and subscription."]) } } @@ -150,6 +175,44 @@ enum TokenPlanQuotaParser { } } + /// Bailian Coding Plan emits nested windows with request counts, unlike the + /// Token Plan's flat fractional percentages. Missing windows do not become quota. + static func alibabaCoding(_ data: Data, now: Date) -> [QuotaWindow] { + guard let payload = try? JSONDecoder().decode([String: CodingPlanWindow].self, from: data) else { return [] } + let plan = BailianQuotaPlan.codingPlan + let kinds = [("per5Hour", "5 hours", "5h"), ("perWeek", "Weekly", "weekly"), + ("perBillMonth", "Monthly", "monthly")] + return kinds.compactMap { key, label, period in + guard let quota = payload[key]?.values, + let used = quota["usedQuota"]?.number, used.isFinite, used >= 0, + let total = quota["totalQuota"]?.number, total.isFinite, total > 0 else { return nil } + let reset: String? + if let raw = quota["resetTime"] { + guard let ms = raw.number, ms.isFinite, ms > 0, ms < 10_000_000_000_000 else { return nil } + let date = Date(timeIntervalSince1970: ms / 1_000) + guard date > now else { return nil } + reset = iso(date) + } else { + reset = nil + } + let balance = max(0, total - used) + let remaining = 100 * (balance / total) + return QuotaWindow( + id: plan.id + ":" + key, provider: plan.id, providerKey: plan.id, providerLabel: plan.title, + label: label, remainingPercent: remaining, absoluteRemaining: balance, absoluteLimit: total, + quotaUnit: "requests", isExhausted: remaining == 0, resetAt: reset, window: period, + status: .derived(remainingPercent: remaining), occurredAt: iso(now), source: "bailian-cli") + } + } + + private struct CodingPlanWindow: Decodable { + let values: [String: JSONValue]? + + init(from decoder: Decoder) throws { + values = try? decoder.singleValueContainer().decode([String: JSONValue].self) + } + } + private struct JSONValue: Decodable { enum Value: Equatable { case boolean(Bool), number(Double), other } let value: Value diff --git a/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift b/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift index 3507eb74..f5d6b2a2 100644 --- a/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift @@ -55,6 +55,7 @@ final class TokenPlanQuotaReaderTests: XCTestCase { func testTokenPlanLabelsAndFleetFallbackDoNotCreateAlwaysVisibleProviders() { let labels = [ "alibaba-token-plan": "Alibaba Token Plan", + "alibaba-coding-plan": "Alibaba Coding Plan", "mimo-token-plan": "Xiaomi MiMo Token Plan", ] let windows = labels.keys.sorted().map { key in @@ -69,12 +70,41 @@ final class TokenPlanQuotaReaderTests: XCTestCase { XCTAssertEqual(Set(fallback.fallback.map(\.canonicalProviderKey)), Set(labels.keys)) let withLocalRead = QuotaLocalScope.fleetFallback( fleet: windows, adopted: [], localProviders: ["mimo-token-plan"]) - XCTAssertEqual(withLocalRead.fallback.map(\.canonicalProviderKey), ["alibaba-token-plan"]) + XCTAssertEqual(Set(withLocalRead.fallback.map(\.canonicalProviderKey)), ["alibaba-token-plan", "alibaba-coding-plan"]) + } + + func testAlibabaCodingPlanUsesDistinctReportedRequestWindows() { + let data = Data(#"{"instanceType":"pro","per5Hour":{"usedQuota":25,"totalQuota":100,"percentage":0.25,"resetTime":1800018000000},"perWeek":{},"perBillMonth":{"usedQuota":1010,"totalQuota":1000,"percentage":1.01}}"#.utf8) + let windows = TokenPlanQuotaParser.alibabaCoding(data, now: now) + XCTAssertEqual(windows.map(\.canonicalProviderKey), ["alibaba-coding-plan", "alibaba-coding-plan"]) + XCTAssertEqual(windows.map(\.label), ["5 hours", "Monthly"]) + XCTAssertEqual(windows.first?.remainingPercent, 75) + XCTAssertEqual(windows.first?.absoluteRemaining, 75) + XCTAssertEqual(windows.first?.absoluteLimit, 100) + XCTAssertEqual(windows.first?.quotaUnit, "requests") + XCTAssertNotNil(windows.first?.resetAt) + XCTAssertEqual(windows.last?.status, .exhausted) + XCTAssertNil(windows.last?.resetAt) + XCTAssertTrue(TokenPlanQuotaParser.alibaba(data, now: now).isEmpty) + } + + func testAlibabaCodingPlanRejectsMissingMalformedOrExpiredWindows() { + for raw in [ + #"{}"#, + #"{"per5HourPercentage":0.5}"#, + #"{"per5Hour":{"usedQuota":true,"totalQuota":100}}"#, + #"{"perWeek":{"usedQuota":1,"totalQuota":0}}"#, + #"{"perWeek":{"usedQuota":1,"totalQuota":100,"resetTime":1790000000000}}"#, + #"{"perBillMonth":{"usedQuota":9,"totalQuota":100,"resetTime":"invalid"}}"#, + ] { + XCTAssertTrue(TokenPlanQuotaParser.alibabaCoding(Data(raw.utf8), now: now).isEmpty) + } } func testNewReadersAreOptInWithoutChangingExistingDefaults() { let prefs = QuotaReaderPreferences() XCTAssertFalse(prefs.isEnabled("alibaba-token-plan")) + XCTAssertFalse(prefs.isEnabled("alibaba-coding-plan")) XCTAssertFalse(prefs.isEnabled("mimo-token-plan")) XCTAssertTrue(prefs.isEnabled("zcode")) XCTAssertTrue(QuotaReaderPreferences(enabledByReaderID: ["mimo-token-plan": true]).isEnabled("mimo-token-plan")) diff --git a/docs/TOKEN-PLAN-SOURCES.md b/docs/TOKEN-PLAN-SOURCES.md index 7602b889..acecafc6 100644 --- a/docs/TOKEN-PLAN-SOURCES.md +++ b/docs/TOKEN-PLAN-SOURCES.md @@ -1,4 +1,4 @@ -# Alibaba and Xiaomi MiMo Token Plan quota sources +# Alibaba, Qwen Code, and Xiaomi MiMo quota sources In **Settings → Sources & Fleet**, enable Alibaba Token Plan after installing the [official Bailian CLI](https://www.alibabacloud.com/help/en/model-studio/cli/installation) @@ -8,6 +8,28 @@ and signing in to the appropriate console site. Check A successful command without usage windows is unavailable, not a full allowance. Availability depends on the console site and plan; no browser profile is read. +## Qwen Code subscriptions + +Qwen Code is a client; select the source for the plan you used under `/auth`. + +- **Alibaba ModelStudio → Token Plan:** Enable the existing **Alibaba Token Plan** + source above. Using it from Qwen Code does not create a separate quota. +- **Alibaba ModelStudio → Coding Plan:** Enable **Alibaba Coding Plan (Qwen Code)**. + Check `bl usage coding-plan --output json` after signing in on the matching + Bailian console site. CodeCaps shows only the reported five-hour, weekly, and + monthly request windows and their reset times. This is a separate meter from + the Alibaba Token Plan. +- **Qwen Account with Subscription (Plus/Pro):** Qwen Code's + [subscription design](https://github.com/QwenLM/qwen-code/blob/main/docs/design/qwen-subscription.md) + describes `/usage` as local statistics, not remaining subscription quota. + CodeCaps does not use these statistics as a quota meter. +- **QwenCloud → Token Plan:** QwenCloud publishes + [console usage instructions](https://docs.qwencloud.com/token-plan/token-plan-usage-quota). + There is no CodeCaps reader for this separate source. Do not use the Alibaba + meter as a proxy for QwenCloud credits or submit inference to estimate them. + +## Xiaomi MiMo Token Plan + For Xiaomi, choose the region shown on the MiMo Token Plan dashboard and save the individual plan key in CodeCaps. CodeCaps keeps that key in the local macOS Keychain, checks only the matching Xiaomi region’s @@ -16,6 +38,6 @@ performs inference. Team and pay-as-you-go keys are not supported. The poll preserves Xiaomi’s reported credit balance and exact billing-cycle end rather than assuming it is monthly. Do not paste the key into a support report. -Use both with signed-in test subscriptions to verify the Mac settings and quota +Use these with signed-in test subscriptions to verify the Mac settings and quota meters. The fixtures do not prove any specific account or region is eligible. The iPhone companion still uses synced snapshots, not these local collectors.