feat(cli): live Z.ai GLM Coding Plan quota in codeburn quota

Ported from the menubar's ZaiSubscriptionService, so the Windows Capacity
Dock and the settings pane can read Z.ai capacity from the CLI the same way
the Mac reads it natively.

Credential order mirrors the menubar: a key the user supplied first (a
Keychain entry there, ZAI_API_KEY here), then the Z.ai login the Pi CLI
already keeps in ~/.pi/agent/auth.json. The key is used for one request and
never written anywhere.

Z.ai answers HTTP 200 with an authentication code in the body, so the decoder
reports that as a rejection rather than as an unreadable response, and it
keeps reading the older string-typed limit fields.
This commit is contained in:
iamtoruk 2026-09-01 16:57:54 -07:00
parent 2106766a00
commit cace8f2a71
4 changed files with 335 additions and 1 deletions

View file

@ -14,6 +14,7 @@ import { fetchCursorQuota } from './cursor.js'
import { fetchGeminiQuota } from './gemini.js'
import { fetchKimiQuota } from './kimi.js'
import type { ProviderName, QuotaProvider } from './types.js'
import { fetchZaiQuota } from './zai.js'
export type QuotaCommandWindow = { label: string; usedPct: number; resetsAt?: string }
@ -40,6 +41,7 @@ const READERS: { id: ProviderName; name: string; read: ProviderReader }[] = [
{ id: 'antigravity', name: 'Antigravity', read: () => fetchAntigravityQuota() },
{ id: 'kimi', name: 'Kimi', read: async signal => (await fetchKimiQuota({ signal })).quota },
{ id: 'cursor', name: 'Cursor', read: async signal => (await fetchCursorQuota({ signal })).quota },
{ id: 'zai', name: 'Z.ai', read: async signal => (await fetchZaiQuota({ signal })).quota },
]
const DEFAULT_TIMEOUT_MS = 5_000

View file

@ -5,7 +5,7 @@ export type QuotaWindow = {
}
export type QuotaProvider = {
provider: 'claude' | 'codex' | 'gemini' | 'copilot' | 'antigravity' | 'kimi' | 'cursor'
provider: 'claude' | 'codex' | 'gemini' | 'copilot' | 'antigravity' | 'kimi' | 'cursor' | 'zai'
connection: 'connected' | 'disconnected' | 'accessDenied' | 'loading' | 'stale' | 'transientFailure' | 'terminalFailure'
primary: QuotaWindow | null
details: QuotaWindow[]

191
src/quota/zai.ts Normal file
View file

@ -0,0 +1,191 @@
// Live GLM Coding Plan quota via Z.ai's own usage endpoint (ported from the
// menubar's ZaiSubscriptionService.swift):
//
// - GET https://api.z.ai/api/monitor/usage/quota/limit
// The API key goes in a bare Authorization header, not as a bearer.
//
// Credential, in the order the menubar tries them: a key the user supplied
// (there it is a Keychain entry, here the ZAI_API_KEY environment variable),
// then the Z.ai login the Pi CLI already holds in ~/.pi/agent/auth.json.
// Read-only; the key is used for one request and never persisted or logged.
import os from 'node:os'
import path from 'node:path'
import { quotaRequestSignal, readSecureFile, sanitizeError } from './security.js'
import type { QuotaProvider, QuotaWindow } from './types.js'
const USAGE_ENDPOINT = 'https://api.z.ai/api/monitor/usage/quota/limit'
const SOURCE_FOOTER = ['Source: Z.ai Coding Plan']
const REJECTED_FOOTER = ['Z.ai rejected this API key.']
const RATE_LIMITED_FOOTER = ['Z.ai rate-limited the quota request.']
const UNAVAILABLE_FOOTER = ['Z.ai is temporarily unavailable.']
const PARSE_FOOTER = ['Z.ai returned an unrecognized quota response.']
export type ZaiDeps = {
fetch: typeof fetch
/** The Pi CLI's own login store. */
credentialPath: string
readFile: typeof readSecureFile
env: NodeJS.ProcessEnv
}
function defaultDeps(): ZaiDeps {
return {
fetch: globalThis.fetch,
credentialPath: path.join(os.homedir(), '.pi', 'agent', 'auth.json'),
readFile: readSecureFile,
env: process.env,
}
}
function empty(connection: QuotaProvider['connection'], footerLines: string[] = []): QuotaProvider {
return { provider: 'zai', connection, primary: null, details: [], planLabel: null, footerLines }
}
function nonEmpty(value: unknown): string | null {
if (typeof value !== 'string') return null
const trimmed = value.trim()
return trimmed.length > 0 ? trimmed : null
}
/** Numbers have shipped as JSON numbers and as strings. */
function num(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
return null
}
async function apiKey(deps: ZaiDeps): Promise<string | null> {
const supplied = nonEmpty(deps.env['ZAI_API_KEY'])
if (supplied) return supplied
try {
const raw = await deps.readFile(deps.credentialPath, 64 * 1024)
if (!raw) return null
const auth = JSON.parse(raw) as Record<string, unknown>
const entry = auth['zai']
return entry && typeof entry === 'object' ? nonEmpty((entry as Record<string, unknown>)['key']) : null
} catch {
// A malformed or unreadable login file is the same as no login at all.
return null
}
}
/** Reset stamps arrive as ISO-8601, epoch seconds, or epoch milliseconds. */
function resetsAt(value: unknown): string | null {
const epoch = num(value)
if (epoch !== null) {
const seconds = epoch < 1_000_000_000_000 ? epoch : epoch / 1000
return new Date(seconds * 1000).toISOString()
}
const raw = nonEmpty(value)
if (!raw) return null
const parsed = Date.parse(raw)
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null
}
/** Z.ai encodes the window as a unit enum plus a count; only the two the plan
* actually meters (5-hour and weekly) have a label. */
function windowLabel(unit: number | null, count: number | null): string | null {
if (unit === 3 && count === 5) return '5-hour'
if (unit === 6 && count === 1) return 'Weekly'
return null
}
/** "coding_pro" → "Coding Pro"; missing or blank → null. */
function planLabel(value: unknown): string | null {
const raw = nonEmpty(value)
if (!raw) return null
return raw.replace(/_/g, ' ').toLowerCase().replace(/(^|\s)\w/g, match => match.toUpperCase())
}
export type ZaiDecoded = QuotaProvider | 'rejected' | null
/** `'rejected'` when the body carries an auth error despite the HTTP status,
* `null` when it carries no usable window. */
export function decodeZaiUsage(body: unknown): ZaiDecoded {
if (!body || typeof body !== 'object') return null
const root = body as Record<string, any>
const code = num(root.code)
if (code === 401 || code === 403) return 'rejected'
if (root.success === false) return null
const payload = (root.data && typeof root.data === 'object' ? root.data : root) as Record<string, any>
if (!Array.isArray(payload.limits)) return null
let fiveHour: QuotaWindow | null = null
let weekly: QuotaWindow | null = null
for (const raw of payload.limits) {
if (!raw || typeof raw !== 'object') continue
const limit = raw as Record<string, unknown>
if (limit.type !== 'CREDIT_LIMIT' && limit.type !== 'TOKENS_LIMIT') continue
const label = windowLabel(num(limit.unit), num(limit.number))
if (label === null) continue
let usedPercent = num(limit.percentage)
if (usedPercent === null) {
const current = num(limit.currentValue)
const total = num(limit.usage)
if (current !== null && total !== null && total > 0) usedPercent = current / total * 100
}
if (usedPercent === null) continue
const window: QuotaWindow = {
label,
percent: Math.min(1, Math.max(0, usedPercent / 100)),
resetsAt: resetsAt(limit.nextResetTime),
}
if (label === 'Weekly') weekly = window
else fiveHour = window
}
const details = [fiveHour, weekly].filter((row): row is QuotaWindow => row !== null)
if (details.length === 0) return null
return {
provider: 'zai', connection: 'connected',
primary: weekly ?? fiveHour,
details,
planLabel: planLabel(payload.level),
footerLines: SOURCE_FOOTER,
}
}
export type ZaiResult = { quota: QuotaProvider; retryAfterSeconds?: number }
export async function fetchZaiQuota(options: Partial<ZaiDeps> & { signal?: AbortSignal } = {}): Promise<ZaiResult> {
const deps = { ...defaultDeps(), ...options }
try {
const key = await apiKey(deps)
if (!key) return { quota: empty('disconnected') }
const response = await deps.fetch(USAGE_ENDPOINT, {
method: 'GET', signal: quotaRequestSignal(options.signal),
headers: {
Accept: 'application/json',
'Accept-Language': 'en-US,en',
Authorization: key,
'User-Agent': 'CodeBurn',
},
})
if (response.status === 401 || response.status === 403) return { quota: empty('terminalFailure', REJECTED_FOOTER) }
if (response.status === 429) {
const raw = response.headers.get('Retry-After')
const seconds = raw === null ? NaN : Number(raw)
return {
quota: { ...empty('transientFailure', RATE_LIMITED_FOOTER), rateLimited: true },
retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60),
}
}
if (response.status >= 500) return { quota: empty('transientFailure', UNAVAILABLE_FOOTER) }
if (!response.ok) return { quota: empty('transientFailure', PARSE_FOOTER) }
// Never log the body - it carries account data.
const decoded = decodeZaiUsage(await response.json())
if (decoded === 'rejected') return { quota: empty('terminalFailure', REJECTED_FOOTER) }
return { quota: decoded ?? empty('transientFailure', PARSE_FOOTER) }
} catch (error) {
console.warn(`Z.ai quota unavailable: ${sanitizeError(error)}`)
return { quota: empty('transientFailure') }
}
}

141
tests/quota-zai.test.ts Normal file
View file

@ -0,0 +1,141 @@
// Fixture-driven coverage for the Z.ai quota adapter, ported from the
// menubar's ZaiQuotaTests. Keys are synthetic and the Pi login is a temp file.
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { decodeZaiUsage, fetchZaiQuota } from '../src/quota/zai.js'
const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch
const SYNTHETIC_KEY = 'synthetic-zai-test-key'
const successBody = {
code: 200,
data: {
level: 'pro',
limits: [
{ type: 'CREDIT_LIMIT', unit: 3, number: 5, usage: 12000, currentValue: 360, percentage: 3, nextResetTime: 1_800_000_000_000 },
{ type: 'CREDIT_LIMIT', unit: 6, number: 1, usage: 60000, currentValue: 10800, percentage: 18, nextResetTime: 1_800_500_000_000 },
],
},
}
function jsonResponse(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } })
}
let root: string
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'codeburn-zai-quota-'))
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
describe('Z.ai quota decoding', () => {
it('maps the credit windows with the plan level', () => {
const quota = decodeZaiUsage(successBody)
expect(quota).not.toBe('rejected')
if (quota === null || quota === 'rejected') throw new Error('expected a decoded provider')
expect(quota.connection).toBe('connected')
expect(quota.planLabel).toBe('Pro')
expect(quota.details.map(row => row.label)).toEqual(['5-hour', 'Weekly'])
expect(quota.details.map(row => row.percent)).toEqual([0.03, 0.18])
expect(quota.primary).toEqual({ label: 'Weekly', percent: 0.18, resetsAt: '2027-01-21T02:53:20.000Z' })
expect(quota.footerLines).toEqual(['Source: Z.ai Coding Plan'])
})
it('still reads string-typed token windows and derives the percentage', () => {
const quota = decodeZaiUsage({
data: { limits: [{ type: 'TOKENS_LIMIT', unit: '3', number: '5', usage: '2000', currentValue: '500', nextResetTime: '1800000000' }] },
})
if (quota === null || quota === 'rejected') throw new Error('expected a decoded provider')
expect(quota.details).toEqual([{ label: '5-hour', percent: 0.25, resetsAt: '2027-01-15T08:00:00.000Z' }])
})
it('reads an authentication code in the body as a rejection', () => {
for (const code of [401, 403]) {
expect(decodeZaiUsage({ code, msg: 'token expired or incorrect', success: false })).toBe('rejected')
}
})
it('rejects a payload with no usable window', () => {
expect(decodeZaiUsage({ code: 500, success: false })).toBeNull()
expect(decodeZaiUsage({ data: {} })).toBeNull()
expect(decodeZaiUsage({ data: { limits: [] } })).toBeNull()
expect(decodeZaiUsage({ data: { limits: [{ type: 'CREDIT_LIMIT', unit: 3, number: 5 }] } })).toBeNull()
expect(decodeZaiUsage({ data: { limits: [{ type: 'CREDIT_LIMIT', unit: 9, number: 2, percentage: 5 }] } })).toBeNull()
})
})
describe('Z.ai credential discovery', () => {
it('prefers a supplied key and sends it as a bare authorization header', async () => {
const seen: Record<string, string>[] = []
const result = await fetchZaiQuota({
env: { ZAI_API_KEY: ` ${SYNTHETIC_KEY} ` },
credentialPath: path.join(root, 'missing.json'),
fetch: (async (url: string, init: RequestInit) => {
expect(url).toBe('https://api.z.ai/api/monitor/usage/quota/limit')
seen.push(init.headers as Record<string, string>)
return jsonResponse(successBody)
}) as unknown as typeof fetch,
})
expect(result.quota.connection).toBe('connected')
expect(seen[0]!['Authorization']).toBe(SYNTHETIC_KEY)
})
it('falls back to the Pi login on disk', async () => {
const credentialPath = path.join(root, '.pi', 'agent', 'auth.json')
await mkdir(path.dirname(credentialPath), { recursive: true })
await writeFile(credentialPath, JSON.stringify({ zai: { key: 'pi-zai-key' } }), 'utf8')
const seen: Record<string, string>[] = []
const result = await fetchZaiQuota({
env: {},
credentialPath,
fetch: (async (_url: string, init: RequestInit) => {
seen.push(init.headers as Record<string, string>)
return jsonResponse(successBody)
}) as unknown as typeof fetch,
})
expect(result.quota.connection).toBe('connected')
expect(seen[0]!['Authorization']).toBe('pi-zai-key')
})
it('reports disconnected with no key anywhere and never fetches', async () => {
const result = await fetchZaiQuota({ env: {}, credentialPath: path.join(root, 'missing.json'), fetch: neverFetch })
expect(result.quota.connection).toBe('disconnected')
})
})
describe('Z.ai HTTP failures', () => {
it('keeps the terminal and retryable classifications', async () => {
const respond = async (status: number, headers: Record<string, string> = {}) => fetchZaiQuota({
env: { ZAI_API_KEY: SYNTHETIC_KEY },
fetch: (async () => jsonResponse({}, status, headers)) as unknown as typeof fetch,
})
expect((await respond(401)).quota.connection).toBe('terminalFailure')
expect((await respond(403)).quota.footerLines).toEqual(['Z.ai rejected this API key.'])
const limited = await respond(429, { 'Retry-After': '90' })
expect(limited.quota.rateLimited).toBe(true)
expect(limited.retryAfterSeconds).toBe(90)
expect((await respond(503)).quota.footerLines).toEqual(['Z.ai is temporarily unavailable.'])
expect((await respond(404)).quota.footerLines).toEqual(['Z.ai returned an unrecognized quota response.'])
})
it('turns a body-level authentication failure into a terminal state', async () => {
const result = await fetchZaiQuota({
env: { ZAI_API_KEY: SYNTHETIC_KEY },
fetch: (async () => jsonResponse({ code: 401, success: false })) as unknown as typeof fetch,
})
expect(result.quota.connection).toBe('terminalFailure')
expect(result.quota.footerLines).toEqual(['Z.ai rejected this API key.'])
})
})