diff --git a/src/quota/index.ts b/src/quota/index.ts index 3b783e7f..271fd51c 100644 --- a/src/quota/index.ts +++ b/src/quota/index.ts @@ -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 diff --git a/src/quota/types.ts b/src/quota/types.ts index 4cd6047e..1352d355 100644 --- a/src/quota/types.ts +++ b/src/quota/types.ts @@ -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[] diff --git a/src/quota/zai.ts b/src/quota/zai.ts new file mode 100644 index 00000000..e4c48c7f --- /dev/null +++ b/src/quota/zai.ts @@ -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 { + 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 + const entry = auth['zai'] + return entry && typeof entry === 'object' ? nonEmpty((entry as Record)['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 + 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 + 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 + 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 & { signal?: AbortSignal } = {}): Promise { + 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') } + } +} diff --git a/tests/quota-zai.test.ts b/tests/quota-zai.test.ts new file mode 100644 index 00000000..eb99ef07 --- /dev/null +++ b/tests/quota-zai.test.ts @@ -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 = {}): 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[] = [] + 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) + 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[] = [] + const result = await fetchZaiQuota({ + env: {}, + credentialPath, + fetch: (async (_url: string, init: RequestInit) => { + seen.push(init.headers as Record) + 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 = {}) => 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.']) + }) +})