Skip to content
Open
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
8 changes: 7 additions & 1 deletion TokenStepSwift/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ let package = Package(
.executable(name: "TokenStepSwift", targets: ["TokenStepSwift"])
],
targets: [
.target(
name: "ZstdDecompressor",
path: "Vendor/ZstdDecompressor",
sources: ["zstddeclib.c"],
publicHeadersPath: "."
),
// TokenStepHelper is bundled by script/build_swiftui_and_run.sh because it
// intentionally shares internal app sources that SwiftPM cannot own twice.
.executableTarget(name: "TokenStepSwift"),
.executableTarget(name: "TokenStepSwift", dependencies: ["ZstdDecompressor"]),
.testTarget(
name: "TokenStepSwiftTests",
dependencies: ["TokenStepSwift"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,29 @@ enum AgentSourceRegistry {
aliases: [],
rankClientKeys: ["workbuddy"]
),
AgentSourceDescriptor(
id: "deepseek-harness",
displayName: "DeepSeek Harness",
tier: .ledger,
colorToken: AgentSourceColorToken(red: 0.82, green: 0.32, blue: 0.58),
isExperimental: true,
probePaths: [
"~/.dsh",
"~/Library/Application Support/@deepseek-ai/dsh-desktop/harness"
],
aliases: [],
rankClientKeys: ["deepseek-harness"]
),
AgentSourceDescriptor(
id: "autoclaw",
displayName: "AutoClaw",
tier: .ledger,
colorToken: AgentSourceColorToken(red: 0.85, green: 0.33, blue: 0.44),
isExperimental: false,
probePaths: ["~/.openclaw-autoclaw"],
aliases: ["OpenClaw"],
rankClientKeys: ["autoclaw"]
),
AgentSourceDescriptor(
id: "cursor",
displayName: "Cursor",
Expand Down Expand Up @@ -170,6 +193,8 @@ enum AgentSourceRegistry {
"Hermes",
"Hermes Agent",
"WorkBuddy",
"DeepSeek Harness",
"AutoClaw",
"Codex via CC Switch",
"Claude Code via CC Switch"
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ enum CodexQuotaService {
throw error
}

let _ = responseSemaphore.wait(timeout: .now() + 4)
// codex app-server can take ~8s to answer after a cold start.
let _ = responseSemaphore.wait(timeout: .now() + 12)
process.terminate()

let exitSemaphore = DispatchSemaphore(value: 0)
Expand Down Expand Up @@ -150,7 +151,8 @@ enum CodexQuotaService {
"id": requestID
]

for request in [initialize, quota] {
let initialized: [String: Any] = ["method": "initialized"]
for request in [initialize, initialized, quota] {
let data = try JSONSerialization.data(withJSONObject: request)
try write(data, to: handle)
try write(Data("\n".utf8), to: handle)
Expand Down Expand Up @@ -190,7 +192,10 @@ enum CodexQuotaService {

private static func appServerEnvironment() -> [String: String] {
var environment = ProcessInfo.processInfo.environment
let defaultPath = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
let home = FileManager.default.homeDirectoryForCurrentUser.path
// GUI launches inherit launchd's minimal PATH, so also cover user-local
// install locations such as npm -g prefixes and Homebrew.
let defaultPath = "\(home)/.local/bin:\(home)/.npm-global/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
if let existing = environment["PATH"], !existing.isEmpty {
environment["PATH"] = "\(defaultPath):\(existing)"
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import Foundation
import ZstdDecompressor

struct DeepSeekHarnessDecodeResult: Equatable {
var completeFrames: Int
var lineCount: Int
var partialTail: Bool
}

enum DeepSeekHarnessDecodeError: Error, LocalizedError {
case cannotOpen(URL)
case invalidCompressedData(String)
case invalidUTF8Line

var errorDescription: String? {
switch self {
case .cannotOpen(let url): return "Unable to open Harness session: \(url.lastPathComponent)"
case .invalidCompressedData(let message): return "Invalid Harness Zstandard data: \(message)"
case .invalidUTF8Line: return "Harness session contains a non-UTF-8 JSONL line"
}
}
}

enum DeepSeekHarnessDecoder {
private static let inputChunkSize = 128 * 1024
private static let newline = Data([0x0A])

static func decode(
fileURL: URL,
onLine: (Data) throws -> Void
) throws -> DeepSeekHarnessDecodeResult {
guard let handle = try? FileHandle(forReadingFrom: fileURL) else {
throw DeepSeekHarnessDecodeError.cannotOpen(fileURL)
}
defer { try? handle.close() }

guard let stream = ZSTD_createDStream() else {
throw DeepSeekHarnessDecodeError.invalidCompressedData("decoder allocation failed")
}
defer { _ = ZSTD_freeDStream(stream) }
let initCode = ZSTD_initDStream(stream)
guard ZSTD_isError(initCode) == 0 else {
throw DeepSeekHarnessDecodeError.invalidCompressedData(errorName(initCode))
}

let outputSize = max(Int(ZSTD_DStreamOutSize()), 32 * 1024)
var lineBuffer = Data()
var completeFrames = 0
var lineCount = 0
var partialTail = false
var sawInput = false
var waitingForFrame = false

func emitLines(finalFrameComplete: Bool) throws {
while let range = lineBuffer.range(of: newline) {
let line = lineBuffer.subdata(in: lineBuffer.startIndex..<range.lowerBound)
lineBuffer.removeSubrange(lineBuffer.startIndex...range.upperBound - 1)
guard !line.isEmpty else { continue }
guard String(data: line, encoding: .utf8) != nil else {
throw DeepSeekHarnessDecodeError.invalidUTF8Line
}
try onLine(line)
lineCount += 1
}
if finalFrameComplete, !lineBuffer.isEmpty {
guard String(data: lineBuffer, encoding: .utf8) != nil else {
throw DeepSeekHarnessDecodeError.invalidUTF8Line
}
try onLine(lineBuffer)
lineBuffer.removeAll(keepingCapacity: true)
lineCount += 1
}
}

while true {
let compressed = try handle.read(upToCount: inputChunkSize) ?? Data()
if compressed.isEmpty { break }
sawInput = true
let input = compressed
try input.withUnsafeBytes { inputBytes in
guard let source = inputBytes.baseAddress else { return }
var inputBuffer = ZSTD_inBuffer(src: source, size: input.count, pos: 0)
while inputBuffer.pos < inputBuffer.size {
var output = Data(count: outputSize)
let outputCapacity = output.count
var outputCount = 0
var code: size_t = 0
output.withUnsafeMutableBytes { outputBytes in
guard let destination = outputBytes.baseAddress else { return }
var outputBuffer = ZSTD_outBuffer(dst: destination, size: outputCapacity, pos: 0)
code = ZSTD_decompressStream(stream, &outputBuffer, &inputBuffer)
outputCount = outputBuffer.pos
}
if ZSTD_isError(code) != 0 {
throw DeepSeekHarnessDecodeError.invalidCompressedData(errorName(code))
}
if outputCount > 0 {
lineBuffer.append(output.prefix(outputCount))
}
if code == 0 {
completeFrames += 1
waitingForFrame = false
try emitLines(finalFrameComplete: true)
let resetCode = ZSTD_initDStream(stream)
guard ZSTD_isError(resetCode) == 0 else {
throw DeepSeekHarnessDecodeError.invalidCompressedData(errorName(resetCode))
}
} else {
waitingForFrame = true
try emitLines(finalFrameComplete: false)
}
if inputBuffer.pos == inputBuffer.size { break }
}
}
}

if waitingForFrame {
var emptyInput = ZSTD_inBuffer(src: nil, size: 0, pos: 0)
for _ in 0..<4 {
var output = Data(count: outputSize)
let outputCapacity = output.count
var outputCount = 0
var code: size_t = 0
output.withUnsafeMutableBytes { outputBytes in
guard let destination = outputBytes.baseAddress else { return }
var outputBuffer = ZSTD_outBuffer(dst: destination, size: outputCapacity, pos: 0)
code = ZSTD_decompressStream(stream, &outputBuffer, &emptyInput)
outputCount = outputBuffer.pos
}
if ZSTD_isError(code) != 0 {
throw DeepSeekHarnessDecodeError.invalidCompressedData(errorName(code))
}
if outputCount > 0 {
lineBuffer.append(output.prefix(outputCount))
try emitLines(finalFrameComplete: false)
}
if code == 0 {
completeFrames += 1
waitingForFrame = false
try emitLines(finalFrameComplete: true)
break
}
if outputCount == 0 { break }
}
partialTail = waitingForFrame && sawInput
}
try emitLines(finalFrameComplete: !waitingForFrame)
return DeepSeekHarnessDecodeResult(
completeFrames: completeFrames,
lineCount: lineCount,
partialTail: partialTail
)
}

private static func errorName(_ code: size_t) -> String {
String(cString: ZSTD_getErrorName(code))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,17 @@ enum GLMQuotaService {

private static var endpoints: [URL] {
[
"https://api.z.ai/api/monitor/usage/quota/limit",
"https://open.bigmodel.cn/api/paas/v4/usage",
"https://open.bigmodel.cn/api/biz/v1/subscription/usage",
"https://api.z.ai/api/coding/usage"
].compactMap(URL.init(string:))
}

static func windows(from payload: Any) -> [QuotaWindow] {
let object = unwrap(payload)
if let limitWindows = limitWindows(from: object) {
return limitWindows
}
var windows: [QuotaWindow] = []
let candidates: [(Any?, QuotaWindowKind)] = [
(object["token_window"] ?? object["tokenWindow"], .tokenWindow),
Expand All @@ -77,6 +80,75 @@ enum GLMQuotaService {
return windows
}

private static func limitWindows(from object: [String: Any]) -> [QuotaWindow]? {
guard let limits = object["limits"] as? [[String: Any]], !limits.isEmpty else {
return nil
}
var tokenLimits: [(percent: Double, resetsAt: Date?)] = []
var monthlyUsage: Double?
var monthlyResetsAt: Date?
for limit in limits {
let type = (limit["type"] as? String) ?? ""
let percentage = QuotaJSON.number(limit["percentage"])
switch type {
case "TOKENS_LIMIT":
if let percentage {
let resetMillis = QuotaJSON.number(limit["nextResetTime"])
let resetDate = resetMillis.map { Date(timeIntervalSince1970: $0 / 1000) }
tokenLimits.append((percentage, resetDate))
if (limit["unit"] as? Int) == 6 {
monthlyUsage = percentage
monthlyResetsAt = resetDate
}
}
case "TIME_LIMIT":
if let usageDetails = limit["usageDetails"] as? [[String: Any]] {
// Z.ai auxiliary tool calls are not model tokens; ignore them.
_ = usageDetails
}
default:
break
}
}
guard !tokenLimits.isEmpty else { return nil }
var windows: [QuotaWindow] = []
if let first = tokenLimits.first {
windows.append(
QuotaWindow(
kind: .fiveHour,
usedPercent: min(max(first.percent, 0), 100),
remaining: nil,
total: nil,
resetsAt: first.resetsAt
)
)
}
if tokenLimits.count > 1 {
let second = tokenLimits[1].percent
windows.append(
QuotaWindow(
kind: .sevenDay,
usedPercent: min(max(second, 0), 100),
remaining: nil,
total: nil,
resetsAt: tokenLimits[1].resetsAt
)
)
}
if let monthlyUsage {
windows.append(
QuotaWindow(
kind: .monthlyCredits,
usedPercent: min(max(monthlyUsage, 0), 100),
remaining: nil,
total: nil,
resetsAt: monthlyResetsAt
)
)
}
return windows
}

private static func unwrap(_ payload: Any) -> [String: Any] {
if let object = payload as? [String: Any] {
if let data = object["data"] as? [String: Any] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,22 @@ enum QuotaRefreshCoordinator {

static func read(_ provider: QuotaProviderID) -> ProviderQuota {
do {
let quota: ProviderQuota
switch provider {
case .codex:
return try CodexQuotaService.read().asProviderQuota(.codex)
quota = try CodexQuotaService.read().asProviderQuota(.codex)
case .claude:
return try ClaudeQuotaService.read().asProviderQuota(.claude)
quota = try ClaudeQuotaService.read().asProviderQuota(.claude)
case .cursor:
return try CursorQuotaService.read()
quota = try CursorQuotaService.read()
case .glm:
return try GLMQuotaService.read()
quota = try GLMQuotaService.read()
case .kimi:
return try KimiQuotaService.read()
quota = try KimiQuotaService.read()
case .grok:
return try GrokQuotaService.read()
quota = try GrokQuotaService.read()
}
return quota
} catch {
return ProviderQuota.unavailable(
provider,
Expand Down
Loading