Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/CodeCaps/SettingsViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
]
}
Expand Down
5 changes: 4 additions & 1 deletion Sources/QuotaCore/LocalQuotaReaderRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions Sources/QuotaCore/QuotaModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

Expand Down
2 changes: 1 addition & 1 deletion Sources/QuotaCore/QuotaReaderPreferences.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
73 changes: 68 additions & 5 deletions Sources/QuotaCore/TokenPlanQuotaReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,22 +61,47 @@ 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 {
return LocalQuotaResult(issues: [id: "Install the official Bailian CLI and sign in to its console."])
}
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."])
}
}

Expand Down Expand Up @@ -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
Expand Down
32 changes: 31 additions & 1 deletion Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"))
Expand Down
26 changes: 24 additions & 2 deletions docs/TOKEN-PLAN-SOURCES.md
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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
Expand All @@ -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.
Loading