Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(usage): add the Grok and Kimi providers (#11)
eneskircaa2353f22f7af
diff --git a/src/core/usage/grok-usage.test.ts b/src/core/usage/grok-usage.test.tsnew file mode 100644index 000000000..ebe815d4a--- /dev/null+++ b/src/core/usage/grok-usage.test.ts@@ -0,0 +1,170 @@+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ mapGrokLimits,+ mapGrokWeekly,+ mapGrokMonthly,+ grokConfigOf,+ parseMoney,+ pickGrokAuth,+ readGrokAuth,+ fetchGrokUsage,+ grokHome+} from './grok-usage'+import { limitLabel } from '../../shared/usage-limits'++/**+ * NOTE: not captured from a live account — no Grok credentials were available on the machine+ * this was written on. Follows the field contract orca's fetcher documents; numbers illustrative.+ */+const PERIOD = {+ billingPeriodStart: '2026-07-13T00:00:00Z',+ billingPeriodEnd: '2026-07-20T00:00:00Z',+ currentPeriod: {+ type: 'USAGE_PERIOD_TYPE_WEEKLY',+ start: '2026-07-13T00:00:00Z',+ end: '2026-07-20T00:00:00Z'+ }+}++describe('mapGrokWeekly', () => {+ it('maps the credit allowance', () => {+ const l = mapGrokWeekly({ ...PERIOD, creditUsagePercent: 40 })+ expect(l).toMatchObject({ kind: 'weekly_all', usedPercent: 40, windowMinutes: 10_080 })+ expect(l?.resetsAt).toBe(Date.parse('2026-07-20T00:00:00Z'))+ })++ it('reads an omitted percentage as 0% when the period proves it is weekly', () => {+ // Grok drops protobuf default values, so an untouched allowance arrives as an ABSENT field.+ // Matching billing bounds are what make "0% used" distinguishable from "no such limit".+ expect(mapGrokWeekly(PERIOD)?.usedPercent).toBe(0)+ })++ it('does NOT invent 0% when the period is not a confirmed weekly one', () => {+ // A monthly unified-billing response can carry a weekly currentPeriod whose bounds differ;+ // treating that omission as 0% would show a full allowance the account may not have.+ expect(+ mapGrokWeekly({+ billingPeriodStart: '2026-07-01T00:00:00Z',+ billingPeriodEnd: '2026-08-01T00:00:00Z',+ currentPeriod: {+ type: 'USAGE_PERIOD_TYPE_WEEKLY',+ start: '2026-07-13T00:00:00Z',+ end: '2026-07-20T00:00:00Z'+ }+ })+ ).toBeNull()+ })++ it('clamps an out-of-range percentage', () => {+ expect(mapGrokWeekly({ creditUsagePercent: 250 })?.usedPercent).toBe(100)+ })+})++describe('mapGrokMonthly', () => {+ it('derives a percentage from spend against the budget', () => {+ const l = mapGrokMonthly({ ...PERIOD, monthlyLimit: { val: '200' }, used: { val: '50' } })+ expect(l).toMatchObject({ kind: 'monthly_spend', usedPercent: 25, windowMinutes: 43_200 })+ })++ it('accepts money values as numbers or strings', () => {+ expect(parseMoney({ val: '12.5' })).toBe(12.5)+ expect(parseMoney({ val: 12.5 })).toBe(12.5)+ expect(parseMoney({ val: 'free' })).toBeNull()+ expect(parseMoney(undefined)).toBeNull()+ })++ it('refuses to divide by a zero or missing budget', () => {+ expect(mapGrokMonthly({ monthlyLimit: { val: 0 }, used: { val: 10 } })).toBeNull()+ expect(mapGrokMonthly({ used: { val: 10 } })).toBeNull()+ })+})++describe('grokConfigOf', () => {+ it('reads figures from the top level or from a nested config block', () => {+ expect(grokConfigOf({ creditUsagePercent: 10 }).creditUsagePercent).toBe(10)+ expect(grokConfigOf({ config: { creditUsagePercent: 10 } }).creditUsagePercent).toBe(10)+ })++ it('survives a junk body', () => {+ expect(grokConfigOf(null)).toEqual({})+ expect(grokConfigOf('nope')).toEqual({})+ })+})++describe('mapGrokLimits', () => {+ it('emits both windows when the plan has both', () => {+ const limits = mapGrokLimits({+ ...PERIOD,+ creditUsagePercent: 30,+ monthlyLimit: { val: 100 },+ used: { val: 10 }+ })+ expect(limits.map((l) => l.kind)).toEqual(['weekly_all', 'monthly_spend'])+ })++ it('labels the spend window readably', () => {+ expect(limitLabel('monthly_spend', null)).toBe('Monthly Spend')+ })++ it('reports no severity, leaving colour to the percentage thresholds', () => {+ for (const l of mapGrokLimits({ ...PERIOD, creditUsagePercent: 95 })) {+ expect(l.severity).toBeNull()+ }+ })+})++describe('pickGrokAuth', () => {+ it('prefers the xAI issuer when several are present', () => {+ expect(+ pickGrokAuth({+ 'https://other.example': { key: 'wrong' },+ 'https://auth.x.ai': { key: 'right', user_id: 'u1' }+ })+ ).toEqual({ key: 'right', userId: 'u1' })+ })++ it('falls back to an entry with a key rather than assuming a single issuer', () => {+ expect(pickGrokAuth({ 'https://other.example': { key: 'only' } }).key).toBe('only')+ })++ it('ignores entries without a key', () => {+ expect(pickGrokAuth({ a: { user_id: 'x' }, b: { key: 'k' } }).key).toBe('k')+ })++ it('returns nulls for junk', () => {+ expect(pickGrokAuth(null)).toEqual({ key: null, userId: null })+ expect(pickGrokAuth({})).toEqual({ key: null, userId: null })+ })+})++describe('fetchGrokUsage', () => {+ it('reports unavailable when not signed in, without touching the network', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-'))+ await expect(fetchGrokUsage(dir)).resolves.toMatchObject({+ provider: 'grok',+ status: 'unavailable',+ limits: []+ })+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('tolerates a malformed auth.json', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-'))+ fs.writeFileSync(path.join(dir, 'auth.json'), '{{{')+ await expect(readGrokAuth(dir)).resolves.toEqual({ key: null, userId: null })+ fs.rmSync(dir, { recursive: true, force: true })+ })+})++describe('grokHome', () => {+ it('honours GROK_HOME', () => {+ const prev = process.env.GROK_HOME+ process.env.GROK_HOME = '/tmp/custom-grok'+ expect(grokHome()).toBe('/tmp/custom-grok')+ if (prev === undefined) delete process.env.GROK_HOME+ else process.env.GROK_HOME = prev+ })+})diff --git a/src/core/usage/grok-usage.ts b/src/core/usage/grok-usage.tsnew file mode 100644index 000000000..a4ae5c5da--- /dev/null+++ b/src/core/usage/grok-usage.ts@@ -0,0 +1,185 @@+// Grok (xAI) subscription usage, via the CLI chat proxy's billing endpoint.+//+// Grok is billing-shaped rather than window-shaped: a plan exposes a weekly credit allowance+// and/or a monthly money budget, so the two limits here are derived from billing figures rather+// than read off rate-limit windows. Read-only — we never write `auth.json`.+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import type { ProviderUsage, UsageLimit } from '../../shared/types'++const DEFAULT_PROXY_BASE = 'https://cli-chat-proxy.grok.com/v1'+const FETCH_TIMEOUT_MS = 8000+const WEEKLY_WINDOW_MINUTES = 10_080+const MONTHLY_WINDOW_MINUTES = 43_200++/** Grok's own issuer. An `auth.json` can hold several entries; this one is the CLI's. */+const XAI_ISSUER = 'auth.x.ai'++function proxyBase(): string {+ return process.env.GROK_CLI_CHAT_PROXY_BASE_URL?.trim().replace(/\/$/, '') || DEFAULT_PROXY_BASE+}++export function grokHome(): string {+ return process.env.GROK_HOME?.trim() || path.join(os.homedir(), '.grok')+}++interface GrokAuth {+ key: string | null+ userId: string | null+}++/**+ * Read the CLI's API key. `auth.json` maps issuer → entry, and an account can carry entries for+ * more than one issuer, so prefer xAI's own and fall back to the first entry that has a key+ * rather than assuming there is exactly one.+ */+export function pickGrokAuth(parsed: unknown): GrokAuth {+ if (!parsed || typeof parsed !== 'object') return { key: null, userId: null }+ const entries = Object.entries(parsed as Record<string, any>).filter(+ ([, v]) => v && typeof v === 'object' && typeof v.key === 'string' && v.key+ )+ if (entries.length === 0) return { key: null, userId: null }+ const preferred =+ entries.find(([issuer]) => issuer.includes(XAI_ISSUER)) ??+ entries.find(([, v]) => typeof v.oidc_client_id === 'string' && v.oidc_client_id) ??+ entries[0]+ const [, entry] = preferred!+ return {+ key: entry.key,+ userId: typeof entry.user_id === 'string' ? entry.user_id : null+ }+}++export async function readGrokAuth(home = grokHome()): Promise<GrokAuth> {+ try {+ return pickGrokAuth(JSON.parse(await fs.readFile(path.join(home, 'auth.json'), 'utf-8')))+ } catch {+ return { key: null, userId: null }+ }+}++/** Money values arrive as `{ val }`, and `val` is a string on some plans and a number on others. */+export function parseMoney(value: unknown): number | null {+ const raw = (value as any)?.val+ const num = typeof raw === 'string' ? Number.parseFloat(raw) : raw+ return typeof num === 'number' && Number.isFinite(num) ? num : null+}++function periodEnd(config: Record<string, any>): number | null {+ const end = config.currentPeriod?.end ?? config.billingPeriodEnd+ if (typeof end !== 'string') return null+ const t = Date.parse(end)+ return Number.isFinite(t) ? t : null+}++function timestampsMatch(a: unknown, b: unknown): boolean {+ return typeof a === 'string' && typeof b === 'string' && Date.parse(a) === Date.parse(b)+}++/**+ * Weekly credit allowance.+ *+ * The zero case needs care: Grok omits `creditUsagePercent` when it is zero (protobuf drops+ * default values), so an untouched allowance and an absent one look identical. They are only+ * distinguishable when the current period is explicitly weekly AND its bounds match the billing+ * period — then the omission provably means 0% used, not "no such limit".+ */+export function mapGrokWeekly(config: Record<string, any>): UsageLimit | null {+ const confirmedWeekly =+ config.currentPeriod?.type === 'USAGE_PERIOD_TYPE_WEEKLY' &&+ timestampsMatch(config.currentPeriod?.start, config.billingPeriodStart) &&+ timestampsMatch(config.currentPeriod?.end, config.billingPeriodEnd)++ const raw = config.creditUsagePercent === undefined && confirmedWeekly ? 0 : config.creditUsagePercent+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return null++ return {+ kind: 'weekly_all',+ group: 'weekly',+ usedPercent: Math.min(100, Math.max(0, raw)),+ severity: null,+ resetsAt: periodEnd(config),+ windowMinutes: WEEKLY_WINDOW_MINUTES,+ scopeLabel: null,+ isActive: false+ }+}++/** Monthly included budget, as a share of spend rather than of requests. */+export function mapGrokMonthly(config: Record<string, any>): UsageLimit | null {+ const limit = parseMoney(config.monthlyLimit)+ const used = parseMoney(config.used)+ if (limit === null || used === null || limit <= 0) return null+ return {+ kind: 'monthly_spend',+ group: 'monthly',+ usedPercent: Math.min(100, Math.max(0, (used / limit) * 100)),+ severity: null,+ resetsAt: periodEnd(config),+ windowMinutes: MONTHLY_WINDOW_MINUTES,+ scopeLabel: null,+ isActive: false+ }+}++/** The figures live at the top level on some responses and under `config` on others. */+export function grokConfigOf(body: unknown): Record<string, any> {+ if (!body || typeof body !== 'object') return {}+ const b = body as Record<string, any>+ return b.config && typeof b.config === 'object' ? { ...b, ...b.config } : b+}++export function mapGrokLimits(body: unknown): UsageLimit[] {+ const config = grokConfigOf(body)+ return [mapGrokWeekly(config), mapGrokMonthly(config)].filter((l): l is UsageLimit => l !== null)+}++function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {+ return { provider: 'grok', limits, account: null, updatedAt: Date.now(), status }+}++async function getBilling(url: string, auth: GrokAuth): Promise<unknown | null> {+ const headers: Record<string, string> = {+ authorization: `Bearer ${auth.key}`,+ accept: 'application/json'+ }+ // The CLI sends a second auth header whose value it takes from the environment; forward it+ // when present rather than inventing one.+ const tokenAuth = process.env.GROK_CLI_AUTH_HEADER?.trim()+ if (tokenAuth) headers['x-xai-token-auth'] = tokenAuth+ if (auth.userId) headers['x-userid'] = auth.userId++ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ const res = await fetch(url, { headers, signal: ctrl.signal }).finally(() => clearTimeout(t))+ if (!res.ok) return null+ return res.json()+}++/**+ * Grok usage. Two views: the credits view carries `creditUsagePercent`, but unified-billing+ * accounts omit it and expose only the monthly budget — so when the credits view yields nothing+ * usable, the default view is consulted before giving up. Never rejects.+ */+export async function fetchGrokUsage(home = grokHome()): Promise<ProviderUsage> {+ try {+ const auth = await readGrokAuth(home)+ if (!auth.key) return snapshot([], 'unavailable')++ const base = proxyBase()+ const credits = await getBilling(`${base}/billing?format=credits`, auth)+ const fromCredits = credits ? mapGrokLimits(credits) : []+ if (fromCredits.length > 0) return snapshot(fromCredits, 'ok')++ const dflt = await getBilling(`${base}/billing`, auth)+ const fromDefault = dflt ? mapGrokLimits(dflt) : []+ if (fromDefault.length > 0) return snapshot(fromDefault, 'ok')++ // Both views answered but neither carried a quota: the account genuinely has none to show.+ if (credits !== null || dflt !== null) return snapshot([], 'unavailable')+ return snapshot([], 'error')+ } catch {+ return snapshot([], 'error')+ }+}diff --git a/src/core/usage/kimi-usage.test.ts b/src/core/usage/kimi-usage.test.tsnew file mode 100644index 000000000..5ac338c7e--- /dev/null+++ b/src/core/usage/kimi-usage.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ mapKimiLimits,+ mapKimiDetail,+ windowToMinutes,+ readKimiToken,+ fetchKimiUsage,+ kimiHome+} from './kimi-usage'++/**+ * NOTE: not captured from a live account — no Kimi credentials were available on the machine+ * this was written on. Follows the field contract orca's fetcher documents.+ */+const RESPONSE = {+ usage: { limit: '1000', used: '250', resetTime: '2026-07-26T00:00:00Z' },+ limits: [+ {+ window: { duration: 5, timeUnit: 'HOURS' },+ detail: { limit: 100, used: 30, resetTime: '2026-07-19T20:00:00Z' }+ }+ ]+}++describe('windowToMinutes', () => {+ it('converts each unit', () => {+ expect(windowToMinutes({ duration: 5, timeUnit: 'HOURS' })).toBe(300)+ expect(windowToMinutes({ duration: 90, timeUnit: 'MINUTES' })).toBe(90)+ expect(windowToMinutes({ duration: 7, timeUnit: 'DAYS' })).toBe(10_080)+ expect(windowToMinutes({ duration: 120, timeUnit: 'SECONDS' })).toBe(2)+ })++ it('treats an unrecognized unit as minutes rather than dropping the window', () => {+ expect(windowToMinutes({ duration: 42, timeUnit: 'FORTNIGHTS' })).toBe(42)+ })++ it('returns null without a duration', () => {+ expect(windowToMinutes({ timeUnit: 'HOURS' })).toBeNull()+ expect(windowToMinutes(undefined)).toBeNull()+ })+})++describe('mapKimiDetail', () => {+ it('turns counts into a percentage', () => {+ expect(mapKimiDetail({ limit: 200, used: 50 }, 'session', 'session', 300)?.usedPercent).toBe(25)+ })++ it('accepts counts as strings', () => {+ expect(mapKimiDetail({ limit: '200', used: '50' }, 'session', 'session', 300)?.usedPercent).toBe(25)+ })++ it('derives used from remaining when the plan reports only remaining', () => {+ // Dropping the window instead would hide a quota the account actually has.+ expect(mapKimiDetail({ limit: 200, remaining: 150 }, 'session', 'session', 300)?.usedPercent).toBe(25)+ })++ it('refuses to divide by a zero or missing limit', () => {+ expect(mapKimiDetail({ limit: 0, used: 5 }, 'session', 'session', 300)).toBeNull()+ expect(mapKimiDetail({ used: 5 }, 'session', 'session', 300)).toBeNull()+ })++ it('returns null when neither used nor remaining is present', () => {+ expect(mapKimiDetail({ limit: 100 }, 'session', 'session', 300)).toBeNull()+ })++ it('parses resetTime or resetAt, and survives neither', () => {+ expect(mapKimiDetail({ limit: 1, used: 0, resetAt: '2026-07-19T20:00:00Z' }, 'k', 'g', 60)?.resetsAt)+ .toBe(Date.parse('2026-07-19T20:00:00Z'))+ expect(mapKimiDetail({ limit: 1, used: 0 }, 'k', 'g', 60)?.resetsAt).toBeNull()+ })++ it('clamps a count that exceeds its limit', () => {+ expect(mapKimiDetail({ limit: 10, used: 50 }, 'k', 'g', 60)?.usedPercent).toBe(100)+ })+})++describe('mapKimiLimits', () => {+ it('emits the weekly quota and every rolling window', () => {+ const limits = mapKimiLimits(RESPONSE)+ expect(limits.map((l) => l.kind)).toEqual(['weekly_all', 'session'])+ expect(limits[0].usedPercent).toBe(25)+ expect(limits[1].usedPercent).toBe(30)+ expect(limits[1].windowMinutes).toBe(300)+ })++ it('keeps EVERY rolling window rather than picking the one nearest 5h', () => {+ // Orca picks one because its shape has a single session slot; ours carries a list, so a plan+ // with both an hourly and a 5-hourly cap must show both.+ const limits = mapKimiLimits({+ limits: [+ { window: { duration: 1, timeUnit: 'HOURS' }, detail: { limit: 10, used: 1 } },+ { window: { duration: 5, timeUnit: 'HOURS' }, detail: { limit: 100, used: 40 } }+ ]+ })+ expect(limits).toHaveLength(2)+ expect(limits.map((l) => l.windowMinutes)).toEqual([60, 300])+ })++ it('skips malformed entries', () => {+ const limits = mapKimiLimits({+ limits: [null, { detail: { limit: 0, used: 1 } }, { window: {}, detail: { limit: 4, used: 1 } }]+ })+ expect(limits).toHaveLength(1)+ expect(limits[0].windowMinutes).toBeNull()+ })++ it('reports no severity', () => {+ for (const l of mapKimiLimits(RESPONSE)) expect(l.severity).toBeNull()+ })++ it('returns nothing for a junk body', () => {+ expect(mapKimiLimits(null)).toEqual([])+ expect(mapKimiLimits({})).toEqual([])+ })+})++describe('readKimiToken', () => {+ it('reads the access token from the credentials file', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-'))+ fs.mkdirSync(path.join(dir, 'credentials'))+ fs.writeFileSync(+ path.join(dir, 'credentials', 'kimi-code.json'),+ JSON.stringify({ access_token: 'tok' })+ )+ await expect(readKimiToken(dir)).resolves.toBe('tok')+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('returns null for a missing file rather than throwing', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-'))+ await expect(readKimiToken(dir)).resolves.toBeNull()+ fs.rmSync(dir, { recursive: true, force: true })+ })+})++describe('fetchKimiUsage', () => {+ it('reports unavailable when not signed in, without touching the network', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-'))+ await expect(fetchKimiUsage(dir)).resolves.toMatchObject({+ provider: 'kimi',+ status: 'unavailable',+ limits: []+ })+ fs.rmSync(dir, { recursive: true, force: true })+ })+})++describe('kimiHome', () => {+ it('honours KIMI_CODE_HOME', () => {+ const prev = process.env.KIMI_CODE_HOME+ process.env.KIMI_CODE_HOME = '/tmp/custom-kimi'+ expect(kimiHome()).toBe('/tmp/custom-kimi')+ if (prev === undefined) delete process.env.KIMI_CODE_HOME+ else process.env.KIMI_CODE_HOME = prev+ })+})diff --git a/src/core/usage/kimi-usage.ts b/src/core/usage/kimi-usage.tsnew file mode 100644index 000000000..a7b6f5741--- /dev/null+++ b/src/core/usage/kimi-usage.ts@@ -0,0 +1,146 @@+// Kimi Code subscription usage.+//+// Strictly read-only, and here that is load-bearing rather than a house style: the access token+// in `~/.kimi-code/credentials/kimi-code.json` has a ~15-minute TTL and the Kimi CLI rotates the+// refresh token alongside it. Writing that file — or spending its refresh token — would log out+// a live `kimi` session.+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import type { ProviderUsage, UsageLimit } from '../../shared/types'++const DEFAULT_BASE_URL = 'https://api.kimi.com/coding/v1'+const FETCH_TIMEOUT_MS = 8000+const WEEKLY_WINDOW_MINUTES = 10_080++export function kimiHome(): string {+ return process.env.KIMI_CODE_HOME?.trim() || path.join(os.homedir(), '.kimi-code')+}++function baseUrl(): string {+ return process.env.KIMI_CODE_BASE_URL?.trim().replace(/\/$/, '') || DEFAULT_BASE_URL+}++export async function readKimiToken(home = kimiHome()): Promise<string | null> {+ try {+ const raw = await fs.readFile(path.join(home, 'credentials', 'kimi-code.json'), 'utf-8')+ const j = JSON.parse(raw) as Record<string, any>+ const token = j.access_token ?? j.accessToken+ return typeof token === 'string' && token ? token : null+ } catch {+ return null+ }+}++/** Counts arrive as strings on some responses and numbers on others. */+function toInt(value: unknown): number | null {+ if (typeof value === 'number') return Number.isFinite(value) ? value : null+ if (typeof value === 'string') {+ const n = Number(value)+ return Number.isFinite(n) ? n : null+ }+ return null+}++/** `{ duration, timeUnit }` → minutes. An unrecognized unit is treated as minutes. */+export function windowToMinutes(window: unknown): number | null {+ const w = (window ?? {}) as Record<string, any>+ const duration = toInt(w.duration)+ if (duration === null) return null+ const unit = String(w.timeUnit ?? '').toUpperCase()+ if (unit.includes('SECOND')) return Math.round(duration / 60)+ if (unit.includes('MINUTE')) return duration+ if (unit.includes('HOUR')) return duration * 60+ if (unit.includes('DAY')) return duration * 60 * 24+ return duration+}++/**+ * One quota block → a limit. Kimi reports counts, not percentages, and gives `used` on some+ * plans and `remaining` on others — derive the missing one rather than dropping the window.+ */+export function mapKimiDetail(+ detail: unknown,+ kind: string,+ group: string,+ windowMinutes: number | null+): UsageLimit | null {+ if (!detail || typeof detail !== 'object') return null+ const d = detail as Record<string, any>+ const limit = toInt(d.limit)+ let used = toInt(d.used)+ if (used === null) {+ const remaining = toInt(d.remaining)+ if (remaining !== null && limit !== null) used = limit - remaining+ }+ if (limit === null || limit <= 0 || used === null) return null++ const reset = d.resetTime ?? d.resetAt+ const resetsAt = typeof reset === 'string' ? Date.parse(reset) || null : null++ return {+ kind,+ group,+ usedPercent: Math.min(100, Math.max(0, (used / limit) * 100)),+ severity: null,+ resetsAt,+ windowMinutes,+ scopeLabel: null,+ isActive: false+ }+}++/**+ * The top-level `usage` block is the weekly quota; entries in `limits[]` are shorter rolling+ * windows.+ *+ * Orca picks the single `limits[]` entry closest to 5h because its shape has one `session` slot+ * to fill. Ours carries a list, so every window is emitted — a plan with both an hourly and a+ * 5-hourly cap shows both instead of silently discarding one.+ */+export function mapKimiLimits(body: unknown): UsageLimit[] {+ if (!body || typeof body !== 'object') return []+ const b = body as Record<string, any>+ const out: UsageLimit[] = []++ const weekly = mapKimiDetail(b.usage, 'weekly_all', 'weekly', WEEKLY_WINDOW_MINUTES)+ if (weekly) out.push(weekly)++ const entries = Array.isArray(b.limits) ? b.limits : []+ for (const entry of entries) {+ if (!entry || typeof entry !== 'object') continue+ const minutes = windowToMinutes((entry as any).window)+ const mapped = mapKimiDetail((entry as any).detail, 'session', 'session', minutes)+ if (mapped) out.push(mapped)+ }+ return out+}++function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {+ return { provider: 'kimi', limits, account: null, updatedAt: Date.now(), status }+}++/** Kimi usage. Never rejects. */+export async function fetchKimiUsage(home = kimiHome()): Promise<ProviderUsage> {+ try {+ const token = await readKimiToken(home)+ if (!token) return snapshot([], 'unavailable')++ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ const res = await fetch(`${baseUrl()}/usages`, {+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },+ signal: ctrl.signal+ }).finally(() => clearTimeout(t))++ // The token lives ~15 minutes and only the CLI renews it, so an expired one is "nothing to+ // show" rather than an error — exactly the Gemini situation.+ if (res.status === 401 || res.status === 403) return snapshot([], 'unavailable')+ if (!res.ok) return snapshot([], 'error')++ const limits = mapKimiLimits(await res.json())+ return snapshot(limits, limits.length > 0 ? 'ok' : 'unavailable')+ } catch {+ return snapshot([], 'error')+ }+}diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex 7f4d510db..0c8035904 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -21,6 +21,8 @@ import { findLimit } from '../../shared/usage-limits'import { mapUsageLimits } from './claude-usage-map'import { fetchCodexUsage } from './codex-usage'import { fetchGeminiUsage } from './gemini-usage'+import { fetchGrokUsage } from './grok-usage'+import { fetchKimiUsage } from './kimi-usage'import { usageCredsPaths } from '../claude-accounts-core'import { claudeConfigDirFor } from '../claude-config-dir'import { platform } from '../platform'@@ -46,7 +48,9 @@ interface OAuthCreds {*/const OTHER_PROVIDERS: { id: string; fetch: () => Promise<ProviderUsage> }[] = [{ id: 'codex', fetch: fetchCodexUsage },- { id: 'gemini', fetch: fetchGeminiUsage }+ { id: 'gemini', fetch: fetchGeminiUsage },+ { id: 'grok', fetch: fetchGrokUsage },+ { id: 'kimi', fetch: fetchKimiUsage }]/** Parse a credentials JSON blob; tokens may sit at top level or under `claudeAiOauth`. */diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex d0cfd5383..5d66a42d8 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -3,7 +3,13 @@ import type { ClaudeUsage, ProviderUsage, UsageLimit } from '@shared/types'import { AGENT_CONFIG } from '@shared/agents/config'import { useSettings } from '../state/settings'import { formatResetCountdown, formatTimeAgo, severityColor } from '../lib/usageFormat'-import { limitKey, limitLabel, limitShortLabel, primaryLimit } from '@shared/usage-limits'+import {+ limitKey,+ limitLabel,+ limitShortLabel,+ primaryLimit,+ providerLabel+} from '@shared/usage-limits'import { systemAccountDisplay } from '../state/workspace'/**@@ -59,9 +65,10 @@ function AccountUsageBlock({ label, email, u }: { label: string; email?: string;*/function ProviderBlock({ u }: { u: ProviderUsage }) {if (u.status === 'unavailable') return null- // AGENT_CONFIG is keyed by the builtin ids; `provider` is an open string, so a provider that- // is not a builtin agent (a billing-only one) falls back to its own id rather than blanking.- const label = (AGENT_CONFIG as Record<string, { label?: string } | undefined>)[u.provider]?.label ?? u.provider+ // AGENT_CONFIG is keyed by the builtin ids; `provider` is an open string, so a billing-only+ // provider (Grok, Kimi, …) has no entry and falls through to the shared label table.+ const agentLabel = (AGENT_CONFIG as Record<string, { label?: string } | undefined>)[u.provider]?.label+ const label = providerLabel(u.provider, agentLabel)return (<div className="usage-account"><div className="usage-account__label">{label}</div>diff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.tsindex 365879709..391ebb4e3 100644--- a/src/shared/usage-limits.ts+++ b/src/shared/usage-limits.ts@@ -54,3 +54,24 @@ export function findLimit(limits: UsageLimit[], kind: string): UsageLimit | nullexport function limitKey(limit: UsageLimit): string {return `${limit.kind}:${limit.scopeLabel ?? ''}`}++/**+ * Display names for usage providers that are NOT builtin agents — Grok, Kimi and the rest are+ * billing relationships we can read, not CLIs nodeterm spawns, so they have no AGENT_CONFIG+ * entry to borrow a label from.+ */+const PROVIDER_LABELS: Record<string, string> = {+ grok: 'Grok',+ kimi: 'Kimi',+ minimax: 'MiniMax',+ opencode: 'opencode'+}++/**+ * Label a provider for the popover. Prefers the builtin agent's own label (passed in by the+ * renderer, which is where AGENT_CONFIG lives), then the table above, then the raw id — so a+ * provider added to the registry always renders as something rather than a blank heading.+ */+export function providerLabel(provider: string, agentLabel?: string): string {+ return agentLabel ?? PROVIDER_LABELS[provider] ?? provider+}