Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Add machine capabilities, placement and subscription meters to the CLI

bubu-dudu3d5dcecc1465
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 7c9646ee6..00f20fe49 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -463,7 +463,12 @@ Machine:
writes and ~/.ssh (policy: ~/.harness/cli/data/action-policy.json)
harness spend status|set --agent-usd=N --day-usd=N|on|off
per-agent and per-day spend caps; a pane over its cap is held (off by default)
- harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
+ harness capabilities this computer's GPU, load, power, heat, lid and toolchains
+ harness placement [--gpu] [--min-vram=MB] [--interactive]
+ whether this computer should take a job like that
+ harness subs [--force] | subs set <claude|codex|grok|kimi> <on|off>
+ each AI plan's weekly use, banked against an even pace, and which to use next
+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
harness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)
harness new [agent] [@machine] [folder|name] [-- task]
make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`
@@ -4241,6 +4246,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
onCommandBar: commandBarService,
onAttention: () => fleetControl.attentionPayload(),
+ onSubscriptions: () => fleetControl.subs.collect(),
onStopAll: (except) => fleetControl.stopAll(except),
onFleet: (action, args) => fleetControl.command(action, args),
onAutonomousDeviceRequest: async (method, target, body) => {
@@ -8003,6 +8009,16 @@ async function fleetCommand(cmd: string, args: string[], flags: string[]): Promi
if (action === 'spend-on') { action = 'spend-set'; body = { enabled: true } }
break
}
+ case 'capabilities': break
+ case 'placement': body = { needsGpu: flags.includes('--gpu'), interactive: flags.includes('--interactive'), minFreeVramMb: num('min-vram') ?? undefined }; break
+ case 'subs': {
+ // harness subs [--json] [--force] | harness subs set <claude|codex|grok|kimi> <on|off>
+ if (args[0] === 'set') {
+ if (!args[1] || !['on', 'off'].includes(args[2] ?? '')) { console.error('Usage: harness subs set <claude|codex|grok|kimi> <on|off>'); process.exit(1) }
+ action = 'subs-set'; body = { id: args[1], enabled: args[2] }
+ } else body = { force: flags.includes('--force') }
+ break
+ }
default: action = args[0] ?? ''; body = {}; if (!action) { console.error('Usage: harness fleet <action> [--key=value ...]'); process.exit(1) }
for (const f of flags) { const m = /^--([a-zA-Z-]+)=(.*)$/.exec(f); if (m) body[m[1]!] = m[2] }
}
@@ -8027,6 +8043,10 @@ async function fleetCommand(cmd: string, args: string[], flags: string[]): Promi
for (const a of r.agents) console.log(` ${a.glyph} ${a.name.padEnd(28)} ${a.engine.padEnd(10)} ${a.label}${a.detail ? ` ${a.detail}` : ''}`)
return
}
+ if ((action === 'subs' || action === 'subs-set') && result && typeof result === 'object' && Array.isArray((result as { lines?: unknown }).lines)) {
+ for (const line of (result as { lines: string[] }).lines) console.log(line)
+ return
+ }
console.log(typeof result === 'string' ? result : JSON.stringify(result, null, 2))
}
@@ -9255,7 +9275,7 @@ switch (cmd) {
case 'reset':
resetCommand().catch(onError)
break
- case 'attention': case 'stop-all': case 'gate': case 'spend': case 'fleet':
+ case 'attention': case 'stop-all': case 'gate': case 'spend': case 'capabilities': case 'placement': case 'subs': case 'fleet':
fleetCommand(cmd, args, flags).catch(onError)
break
case 'status':
diff --git a/cli/src/fleet/control.ts b/cli/src/fleet/control.ts
index 5b7439aa5..979e6f3eb 100644
--- a/cli/src/fleet/control.ts
+++ b/cli/src/fleet/control.ts
@@ -9,6 +9,8 @@
* stop-all cancel every agent turn on this machine (`POST /api/stop-all`, `harness stop-all`)
* gate tool-start → policy verdict (Claude PreToolUse permissionDecision), `harness gate`
* spend submit → pause when caps are hit; ledger persisted per day, `harness spend`
+ * caps GPU, load, power, heat, lid, toolchains; whether this machine should take a job
+ * subs every AI plan's weekly use against an even pace, `harness subs`, `GET /api/subscriptions`
* commands the `harness <command>` local API behind `POST /api/fleet`
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
@@ -18,6 +20,9 @@ import { AttentionTracker, summarizeAttention, type AttentionRow } from '../lib/
import { DEFAULT_POLICY, evaluateToolCall, parsePolicy, type ActionPolicy, type GateVerdict } from '../lib/actionPolicy.js'
import { DEFAULT_CAPS, decideSpend, emptyLedger, parseCaps, recordUsage, type BrakeVerdict, type SpendCaps, type SpendLedger } from '../lib/spendBrake.js'
import { gateHookInstalled, installGateHook, uninstallGateHook } from '../lib/hooks.js'
+import { decidePlacement, describeCapabilities, readMachineCapabilities, type MachineCapabilities, type PlacementRequest } from '../lib/machineCapabilities.js'
+import { describeSubscriptions, SubscriptionsService, type ProviderId } from './subscriptions/index.js'
+import { nodeSubscriptionsDeps } from './subscriptions/nodeDeps.js'
export interface FleetSessionLike {
agentId: string
@@ -63,6 +68,10 @@ export class FleetControl {
private policy: ActionPolicy
private caps: SpendCaps
private ledger: SpendLedger
+ private capsCache: { at: number; value: MachineCapabilities } | null = null
+ /** Subscription meters (ported from Burn Bar): weekly used, banked, reset, next plan to use. */
+ readonly subs: SubscriptionsService
+ private subsTimer: NodeJS.Timeout | null = null
constructor(protected readonly deps: FleetControlDeps) {
this.now = deps.now ?? Date.now
@@ -73,6 +82,24 @@ export class FleetControl {
this.caps = this.loadCaps()
this.ledger = readJson<SpendLedger>(this.file('spend-ledger.json')) ?? emptyLedger(this.now())
this.attention.onChange(() => this.pushAttention())
+ // Subscription meters: one pass a minute (each network provider is asked at most every 4 min), so
+ // the attention payload's compact block stays fresh for the bar; HARNESS_SUBS_WATCH=0 turns it off.
+ this.subs = new SubscriptionsService(nodeSubscriptionsDeps(this.dataDir))
+ if (process.env.HARNESS_SUBS_WATCH !== '0' && !process.env.VITEST) {
+ this.subsTimer = setInterval(() => { void this.pollSubscriptions() }, Number(process.env.HARNESS_SUBS_MS) || 60_000)
+ this.subsTimer.unref()
+ setTimeout(() => { void this.pollSubscriptions() }, 2_000).unref()
+ }
+ }
+
+ /** Collect every enabled subscription. Never throws. */
+ async pollSubscriptions(force = false): Promise<unknown> {
+ try {
+ return await this.subs.collect(force)
+ } catch (e) {
+ console.log(`[subs] collect failed: ${e instanceof Error ? e.message : String(e)}`)
+ return null
+ }
}
protected file(name: string): string { return join(this.dataDir, name) }
@@ -93,7 +120,7 @@ export class FleetControl {
const spend = spent ? { usd: Number(spent.usd.toFixed(2)), tokens: spent.input + spent.output, fraction: cap ? Math.min(1.5, spent.usd / cap) : null } : null
return { ...row, lane: lanes.find((l) => { try { return new RegExp(l.agent, 'i').test(row.name) } catch { return false } })?.name ?? null, spend }
})
- return { machineId: this.deps.machineId(), hostname: this.deps.machineName(), at: this.now(), summary: summarizeAttention(agents), agents }
+ return { machineId: this.deps.machineId(), hostname: this.deps.machineName(), at: this.now(), summary: summarizeAttention(agents), agents, subscriptions: this.subs?.compact() ?? null }
}
/** Every local window hears each real transition; the bar widget polls `GET /api/attention` instead. */
@@ -171,6 +198,19 @@ export class FleetControl {
return this.caps
}
+ // ── machine capabilities ───────────────────────────────────────────────────────────────────────
+
+ async capabilities(maxAgeMs = 30_000): Promise<MachineCapabilities> {
+ if (this.capsCache && this.now() - this.capsCache.at < maxAgeMs) return this.capsCache.value
+ const value = await readMachineCapabilities()
+ this.capsCache = { at: this.now(), value }
+ return value
+ }
+
+ placement(req: PlacementRequest): Promise<{ ok: boolean; reasons: string[]; caps: string }> {
+ return this.capabilities().then((caps) => ({ ...decidePlacement(caps, req), caps: describeCapabilities(caps) }))
+ }
+
// ── panic stop ─────────────────────────────────────────────────────────────────────────────────
async stopAll(exceptAgentId: string | null): Promise<{ cancelled: string[] }> {
@@ -206,6 +246,15 @@ export class FleetControl {
if (typeof args.enabled === 'boolean') patch.enabled = args.enabled
return { caps: this.spendSet(patch) }
}
+ case 'capabilities': return { ...(await this.capabilities(0)), line: describeCapabilities(await this.capabilities()) }
+ case 'placement': return this.placement(args as PlacementRequest)
+ case 'subs': { const r = await this.subs.collect(args.force === true || args.force === 'true'); return { ...r, lines: describeSubscriptions(r) } }
+ case 'subs-set': {
+ const on = args.enabled === true || args.enabled === 'on' || args.enabled === 'true'
+ await this.subs.setEnabled(str('id') as ProviderId, on)
+ const r = await this.subs.collect(true)
+ return { ...r, lines: describeSubscriptions(r) }
+ }
default: throw new Error(`unknown fleet action: ${action}`)
}
}
diff --git a/cli/src/fleet/subscriptions/index.spec.ts b/cli/src/fleet/subscriptions/index.spec.ts
new file mode 100644
index 000000000..2b8fb80bc
--- /dev/null
+++ b/cli/src/fleet/subscriptions/index.spec.ts
@@ -0,0 +1,122 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+import { describe, expect, it } from 'vitest'
+import { describeSubscriptions, SubscriptionsService, type SubscriptionsDeps } from './index.js'
+import type { ProviderReading } from './providers.js'
+
+const HOUR = 3_600_000
+const DAY = 86_400_000
+const NOW = Date.UTC(2026, 8, 30, 12)
+
+function reading(id: ProviderReading['id'], over: Partial<ProviderReading> = {}): ProviderReading {
+ return { id, name: id[0]!.toUpperCase() + id.slice(1), state: 'ok', plan: '', limits: [], snapshot: false, measuredAt: NOW, status: '', help: '', ...over }
+}
+/** A week that is `gone` of the way through with `used` spent. */
+const week = (used: number, gone: number) => ({ label: 'Weekly (7-day)', percent: used, resetsAt: new Date(NOW + 7 * DAY * (1 - gone)).toISOString() })
+
+function service(readings: Partial<Record<ProviderReading['id'], ProviderReading>>, files: Record<string, string> = {}) {
+ let now = NOW
+ const deps: SubscriptionsDeps = {
+ dataDir: '/d',
+ now: () => now,
+ readers: {
+ claude: async () => readings.claude ?? reading('claude', { state: 'not-detected' }),
+ codex: async () => readings.codex ?? reading('codex', { state: 'not-detected' }),
+ grok: async () => readings.grok ?? reading('grok', { state: 'not-detected' }),
+ kimi: async () => readings.kimi ?? reading('kimi', { state: 'not-detected' }),
+ },
+ readFile: async (p) => files[p] ?? null,
+ writeFile: async (p, d) => { files[p] = d },
+ }
+ return { svc: new SubscriptionsService(deps), files, tick: (ms: number) => { now += ms } }
+}
+
+describe('the subscriptions payload', () => {
+ it('lists all four providers, not-detected ones included, and never the local GPU', async () => {
+ const { svc } = service({})
+ const p = await svc.collect()
+ expect(p.subs.map((s) => s.id)).toEqual(['claude', 'codex', 'grok', 'kimi'])
+ expect(p.subs.every((s) => s.state === 'not-detected' && s.primary === null)).toBe(true)
+ expect(p.guide.pick).toBe('')
+ expect(JSON.stringify(p)).not.toMatch(/"local"/)
+ })
+
+ it('weekly used, signed banked, reset and pace sentence on the card', async () => {
+ const { svc } = service({ claude: reading('claude', { plan: 'Max 20x', limits: [{ label: 'Session (5-hour)', percent: 0.07, resetsAt: new Date(NOW + HOUR).toISOString() }, week(0.3, 0.5)] }) })
+ const c = (await svc.collect()).subs[0]!
+ expect(c.primary!.label).toBe('Weekly (7-day)')
+ expect(c.primary!.used).toBeCloseTo(0.3, 6)
+ expect(c.primary!.bankedSigned).toBeCloseTo(0.2, 3)
+ expect(c.primary!.banked).toBeCloseTo(0.2, 3)
+ expect(c.primary!.tone).toBe('banked')
+ expect(c.primary!.sentence).toMatch(/20% banked/)
+ expect(c.primary!.resetsInMs).toBeCloseTo(3.5 * DAY, -4)
+ expect(c.windows).toHaveLength(2)
+ })
+
+ it('over pace: negative banked, amber or red, with a come-back timer', async () => {
+ const { svc } = service({ codex: reading('codex', { limits: [week(0.6, 0.3)] }) })
+ const c = (await svc.collect()).subs[1]!.primary!
+ expect(c.bankedSigned).toBeCloseTo(-0.3, 3)
+ expect(c.tone).toBe('red')
+ expect(c.comeBackMs).toBeGreaterThan(0)
+ expect(c.sentence).toMatch(/over pace/i)
+ expect(c.sentence).toMatch(/back on pace in/)
+ })
+
+ it('a month is judged when there is no week (Kimi)', async () => {
+ const { svc } = service({ kimi: reading('kimi', { limits: [{ label: 'Session (5-hour)', percent: 0.09, resetsAt: new Date(NOW + HOUR).toISOString() }, { label: 'Monthly (total)', percent: 0.07, resetsAt: new Date(NOW + 19 * DAY).toISOString() }] }) })
+ expect((await svc.collect()).subs[3]!.primary!.label).toBe('Monthly (total)')
+ })
+
+ it('names the next sub when there is a real choice', async () => {
+ const { svc } = service({ claude: reading('claude', { limits: [week(0.6, 0.3)] }), grok: reading('grok', { snapshot: true, limits: [week(0.02, 0.51)] }) })
+ const p = await svc.collect()
+ expect(p.guide.pick).toBe('grok')
+ expect(p.guide.verdict).toMatch(/Grok/)
+ expect(p.subs.find((s) => s.id === 'grok')!.isPick).toBe(true)
+ })
+
+ it('a disabled sub is left out of the verdict and never read', async () => {
+ let read = 0
+ const { svc } = service({ grok: reading('grok', { limits: [week(0.02, 0.51)] }) })
+ const orig = (svc as unknown as { deps: SubscriptionsDeps }).deps.readers.grok
+ ;(svc as unknown as { deps: SubscriptionsDeps }).deps.readers.grok = async (d) => { read++; return orig(d) }
+ await svc.setEnabled('grok', false)
+ const p = await svc.collect()
+ expect(read).toBe(0)
+ expect(p.subs.find((s) => s.id === 'grok')!.state).toBe('disabled')
+ expect(p.settings.enabled.grok).toBe(false)
+ })
+
+ it('persists settings and rate samples in its own data dir', async () => {
+ const { svc, files, tick } = service({ claude: reading('claude', { limits: [week(0.3, 0.5)] }) })
+ await svc.setEnabled('kimi', false)
+ await svc.collect()
+ tick(10 * 60_000)
+ await svc.collect()
+ expect(JSON.parse(files['/d/subscriptions.json']!).enabled.kimi).toBe(false)
+ expect(files['/d/subscription-samples.jsonl']!.trim().split('\n').length).toBe(2)
+ })
+
+ it('rejects an unknown provider id', async () => {
+ const { svc } = service({})
+ await expect(svc.setEnabled('local' as never, true)).rejects.toThrow(/unknown/)
+ })
+
+ it('describes itself in plain lines for `harness subs`', async () => {
+ const { svc } = service({ claude: reading('claude', { plan: 'Max 20x', limits: [week(0.3, 0.5)] }) })
+ const lines = describeSubscriptions(await svc.collect())
+ expect(lines[0]).toMatch(/Claude/)
+ expect(lines.join('\n')).toMatch(/30% used/)
+ expect(lines.join('\n')).toMatch(/Codex\s+not detected/)
+ })
+
+ it('a compact summary rides on the attention payload', async () => {
+ const { svc } = service({ claude: reading('claude', { limits: [week(0.3, 0.5)] }) })
+ await svc.collect()
+ const c = svc.compact()!
+ expect(c.subs[0]).toMatchObject({ id: 'claude', tone: 'banked' })
+ expect(c.subs).toHaveLength(1)
+ })
+})
diff --git a/cli/src/fleet/subscriptions/index.ts b/cli/src/fleet/subscriptions/index.ts
new file mode 100644
index 000000000..4ee4c2660
--- /dev/null
+++ b/cli/src/fleet/subscriptions/index.ts
@@ -0,0 +1,299 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+/**
+ * Subscriptions: every AI plan on this machine on one screen. Weekly percent used, percent banked
+ * against an even pace, the reset, a come-back timer when over pace, and which plan to use next.
+ *
+ * The math and the provider sources are ported from Burn Bar (https://github.com/nixfred/burnbar, by
+ * nixfred, MIT). Burn Bar does not have to be installed: nothing here calls it or reads its files.
+ *
+ * Served by the daemon as `GET /api/subscriptions`, `POST /api/fleet {action: "subs"}`, a compact
+ * block on the attention payload, and `harness subs [--json]`.
+ * State lives in the daemon's data dir: `subscriptions.json` (which plans are switched on) and
+ * `subscription-samples.jsonl` (the percentages over time, which is what a burn rate is made of).
+ */
+import { guidePick, paceFor, paceLive, parseIsoMs, spanWords, windowId, type Guide, type LimitRow, type Pace, type Sample } from './pace.js'
+import { PROVIDERS, READERS, type ProviderDeps, type ProviderId, type ProviderReading } from './providers.js'
+
+export * from './pace.js'
+export * from './providers.js'
+
+const SAMPLE_MAX_AGE_MS = 40 * 86_400_000
+const SAMPLE_MIN_GAP_MS = 5 * 60_000
+/** Network providers are asked at most this often; Anthropic rate-limits eager pollers. */
+const NETWORK_TTL_MS = 4 * 60_000
+const LOCAL_TTL_MS = 30_000
+/** A snapshot has to be this far ahead before it is advice (Burn Bar's snapshot margin). */
+const SNAPSHOT_MIN_BANK = 0.1
+
+export type CardState = ProviderReading['state'] | 'disabled'
+/** banked = green; on-pace = neutral; amber = over pace; red = well over or spent. */
+export type Tone = 'banked' | 'on-pace' | 'amber' | 'red' | 'unknown'
+
+export interface PrimaryWindow {
+ label: string
+ used: number
+ resetsAt: string
+ resetsInMs: number
+ windowMs: number
+ elapsed: number
+ /** elapsed - used: positive = banked, negative = ahead of the clock (over pace). */
+ bankedSigned: number
+ banked: number
+ bankedMs: number
+ behind: number
+ over: boolean
+ spent: boolean
+ comeBackAt: number
+ comeBackMs: number
+ room: number
+ ratio: number
+ tone: Tone
+ sentence: string
+ pace: Pace
+}
+
+export interface SubscriptionCard {
+ id: ProviderId
+ name: string
+ state: CardState
+ enabled: boolean
+ plan: string
+ snapshot: boolean
+ measuredAt: number
+ status: string
+ help: string
+ primary: PrimaryWindow | null
+ windows: LimitRow[]
+ /** A short window (5-hour session) is nearly full: this plan would stop you right now. */
+ blocked: boolean
+ isPick: boolean
+}
+
+export interface SubscriptionsPayload {
+ at: number
+ subs: SubscriptionCard[]
+ guide: Guide & { verdict: string }
+ settings: SubscriptionSettings
+}
+
+export interface SubscriptionSettings { enabled: Record<ProviderId, boolean> }
+
+export interface SubscriptionsDeps {
+ dataDir: string
+ now(): number
+ readers: Record<ProviderId, (deps: ProviderDeps) => Promise<ProviderReading>>
+ providerDeps?: ProviderDeps
+ readFile(path: string): Promise<string | null>
+ writeFile(path: string, data: string): Promise<void>
+}
+
+const SETTINGS_FILE = 'subscriptions.json'
+const SAMPLES_FILE = 'subscription-samples.jsonl'
+const pct = (n: number): string => `${Math.round(n * 100)}%`
+
+/** The window a plan is judged by: weekly, else the monthly pool, else the first non-session window. */
+export function primaryLimit(rows: LimitRow[]): LimitRow | null {
+ const session = (l: string) => /session|5-hour/i.test(l)
+ return rows.find((r) => /^weekly/i.test(r.label)) ?? rows.find((r) => /monthly \(total\)/i.test(r.label)) ?? rows.find((r) => !session(r.label)) ?? null
+}
+
+function toneOf(live: ReturnType<typeof paceLive>): Tone {
+ if (!live) return 'unknown'
+ if (live.spent) return 'red'
+ if (live.over) return live.elapsed > 0 && live.used / live.elapsed > 1.25 ? 'red' : 'amber'
+ if (live.banked >= 0.005) return 'banked'
+ return 'on-pace'
+}
+
+function sentenceOf(live: NonNullable<ReturnType<typeof paceLive>>): string {
+ const reset = `Resets in ${spanWords(live.leftMs)}.`
+ if (live.spent) return `Spent. Back at the reset in ${spanWords(live.leftMs)}.`
+ if (live.over) return `${pct(live.behind)} over pace. Stop now and you are back on pace in ${spanWords(live.comeBackMs)}. ${reset}`
+ if (live.banked >= 0.005) return `${pct(live.banked)} banked, about ${spanWords(live.bankedMs)} of even pace in hand. ${reset}`
+ return `On pace. ${reset}`
+}
+
+export class SubscriptionsService {
+ private settings: SubscriptionSettings | null = null
+ private samples: Map<string, Sample[]> | null = null
+ private cache = new Map<ProviderId, { at: number; reading: ProviderReading }>()
+ private previousPick = ''
+ private last: SubscriptionsPayload | null = null
+
+ constructor(private readonly deps: SubscriptionsDeps) {}
+
+ private path(name: string): string { return `${this.deps.dataDir.replace(/\/+$/, '')}/${name}` }
+
+ async getSettings(): Promise<SubscriptionSettings> {
+ if (this.settings) return this.settings
+ const enabled = Object.fromEntries(PROVIDERS.map((p) => [p.id, true])) as Record<ProviderId, boolean>
+ try {
+ const raw = JSON.parse((await this.deps.readFile(this.path(SETTINGS_FILE))) ?? '{}') as { enabled?: Record<string, unknown> }
+ for (const p of PROVIDERS) if (typeof raw.enabled?.[p.id] === 'boolean') enabled[p.id] = raw.enabled[p.id] as boolean
+ } catch { /* a bad file keeps the defaults */ }
+ this.settings = { enabled }
+ return this.settings
+ }
+
+ async setEnabled(id: ProviderId, on: boolean): Promise<SubscriptionSettings> {
+ if (!PROVIDERS.some((p) => p.id === id)) throw new Error(`unknown subscription: ${String(id)}`)
+ const s = await this.getSettings()
+ s.enabled[id] = on
+ await this.deps.writeFile(this.path(SETTINGS_FILE), JSON.stringify(s, null, 2))
+ return s
+ }
+
+ private async loadSamples(): Promise<Map<string, Sample[]>> {
+ if (this.samples) return this.samples
+ const out = new Map<string, Sample[]>()
+ const floor = this.deps.now() - SAMPLE_MAX_AGE_MS
+ for (const line of ((await this.deps.readFile(this.path(SAMPLES_FILE))) ?? '').split('\n')) {
+ if (!line.trim()) continue
+ try {
+ const r = JSON.parse(line) as { ts: number; key: string; pct: number; resets: number }
+ if (!(r.ts >= floor) || !(r.pct >= 0 && r.pct <= 1) || typeof r.key !== 'string') continue
+ const list = out.get(r.key) ?? []
+ list.push([Number(r.ts), Number(r.pct), Number(r.resets) || 0])
+ out.set(r.key, list)
+ } catch { /* a malformed line is skipped, never fatal */ }
+ }
+ for (const v of out.values()) v.sort((a, b) => a[0] - b[0])
+ this.samples = out
+ return out
+ }
+
+ private async saveSamples(): Promise<void> {
+ if (!this.samples) return
+ const floor = this.deps.now() - SAMPLE_MAX_AGE_MS
+ const lines: string[] = []
+ for (const [key, pts] of this.samples) for (const [ts, p, resets] of pts) if (ts >= floor) lines.push(JSON.stringify({ ts, key, pct: Math.round(p * 1e6) / 1e6, resets }))
+ await this.deps.writeFile(this.path(SAMPLES_FILE), lines.length ? `${lines.join('\n')}\n` : '')
+ }
+
+ private async read(id: ProviderId, force: boolean): Promise<ProviderReading> {
+ const now = this.deps.now()
+ const hit = this.cache.get(id)
+ const ttl = id === 'claude' || id === 'kimi' ? NETWORK_TTL_MS : LOCAL_TTL_MS
+ if (hit && !force && now - hit.at < ttl) return hit.reading
+ let fresh: ProviderReading
+ try { fresh = await this.deps.readers[id](this.deps.providerDeps as ProviderDeps) } catch (e) {
+ fresh = { id, name: PROVIDERS.find((p) => p.id === id)!.name, state: 'error', plan: '', limits: [], snapshot: false, measuredAt: 0, status: 'reader failed', help: '' }
+ void e
+ }
+ // A failed probe keeps the last good figure rather than blanking it, and says so.
+ if (fresh.state === 'error' && hit?.reading.state === 'ok') fresh = { ...hit.reading, status: `last known; ${fresh.status}` }
+ this.cache.set(id, { at: now, reading: fresh })
+ return fresh
+ }
+
+ /** Read every enabled provider and build the payload. `force` skips the per-provider TTL. */
+ async collect(force = false): Promise<SubscriptionsPayload> {
+ const now = this.deps.now()
+ const settings = await this.getSettings()
+ const samples = await this.loadSamples()
+ let dirty = false
+ const cards: SubscriptionCard[] = []
+ for (const p of PROVIDERS) {
+ const enabled = settings.enabled[p.id]
+ if (!enabled) {
+ cards.push({ id: p.id, name: p.name, state: 'disabled', enabled, plan: '', snapshot: false, measuredAt: 0, status: 'Switched off in settings', help: '', primary: null, windows: [], blocked: false, isPick: false })
+ continue
+ }
+ const r = await this.read(p.id, force)
+ let primary: PrimaryWindow | null = null
+ let blocked = false
+ for (const row of r.limits) {
+ const key = `${p.id}|${row.label.slice(0, 64)}`
+ const resets = windowId(parseIsoMs(row.resetsAt))
+ const pts = samples.get(key) ?? []
+ const paceBlock = paceFor(row, pts, !r.snapshot, now)
+ if (row.percent >= 0 && resets) {
+ const lastPt = pts[pts.length - 1]
+ if (!lastPt || lastPt[2] !== resets || Math.abs(lastPt[1] - row.percent) > 1e-9 || now - lastPt[0] >= SAMPLE_MIN_GAP_MS) {
+ pts.push([now, row.percent, resets])
+ samples.set(key, pts)
+ dirty = true
+ }
+ }
+ if (/session|5-hour/i.test(row.label) && row.percent >= 0 && parseIsoMs(row.resetsAt) > now) {
+ const rate = paceBlock.ratePerHour
+ if (row.percent >= 0.9 || (rate > 0 && (1 - row.percent) / rate < 0.5)) blocked = true
+ }
+ if (row === primaryLimit(r.limits)) {
+ const live = paceLive(row.percent, paceBlock.resetsMs, paceBlock.windowMs, now)
+ if (live) {
+ primary = {
+ label: row.label, used: live.used, resetsAt: row.resetsAt, resetsInMs: live.leftMs, windowMs: live.windowMs,
+ elapsed: live.elapsed, bankedSigned: live.bankedSigned, banked: live.banked, bankedMs: live.bankedMs, behind: live.behind,
+ over: live.over, spent: live.spent, comeBackAt: live.comeBackAt, comeBackMs: live.comeBackMs, room: live.room,
+ ratio: paceBlock.ratio, tone: toneOf(live), sentence: sentenceOf(live), pace: paceBlock,
+ }
+ }
+ }
+ }
+ cards.push({ id: p.id, name: p.name, state: r.state, enabled, plan: r.plan, snapshot: r.snapshot, measuredAt: r.measuredAt, status: r.status, help: r.help, primary, windows: r.limits, blocked, isPick: false })
+ }
+ if (dirty) await this.saveSamples().catch(() => {})
+ const present = cards.filter((c) => c.state !== 'disabled' && c.state !== 'not-detected')
+ const guide = guidePick(present.map((c) => ({
+ id: c.id,
+ live: c.primary ? paceLive(c.primary.used, c.primary.pace.resetsMs, c.primary.windowMs, now) : null,
+ fresh: !!c.primary,
+ blocked: c.blocked,
+ minBank: c.snapshot ? SNAPSHOT_MIN_BANK : undefined,
+ })), this.previousPick)
+ this.previousPick = guide.pick
+ const name = (id: string) => PROVIDERS.find((p) => p.id === id)?.name ?? id
+ let verdict = ''
+ if (guide.pick) {
+ const top = cards.find((c) => c.id === guide.pick)!
+ top.isPick = true
+ verdict = guide.urgent
+ ? `Use ${name(guide.pick)} next: ${pct(1 - top.primary!.used)} unspent and it resets in ${spanWords(top.primary!.resetsInMs)}. Use it or lose it.`
+ : `Use ${name(guide.pick)} next: the most room, ${guide.room.toFixed(1)}x an even pace.`
+ if (guide.next) verdict += ` Then ${name(guide.next)}.`
+ } else if (guide.count < 2) {
+ verdict = guide.count === 1 ? 'One subscription here, so there is nothing to choose between.' : 'No subscriptions detected on this machine.'
+ } else if (guide.rest.length) {
+ const first = guide.rest[0]!
+ verdict = `No plan is clearly ahead. ${name(first.id)} is back on pace first, in ${spanWords(Math.max(0, first.comeBackAt - now))}.`
+ } else {
+ verdict = 'Every plan is on pace; no clear pick.'
+ }
+ this.last = { at: now, subs: cards, guide: { ...guide, verdict }, settings }
+ return this.last
+ }
+
+ /** The last payload, trimmed for the attention frame (the bar and the device). */
+ compact(): { at: number; pick: string; verdict: string; subs: Array<{ id: ProviderId; name: string; used: number; bankedSigned: number; tone: Tone; resetsInMs: number; comeBackMs: number }> } | null {
+ if (!this.last) return null
+ return {
+ at: this.last.at,
+ pick: this.last.guide.pick,
+ verdict: this.last.guide.verdict,
+ subs: this.last.subs.filter((s) => s.primary).map((s) => ({
+ id: s.id, name: s.name, used: s.primary!.used, bankedSigned: s.primary!.bankedSigned, tone: s.primary!.tone,
+ resetsInMs: s.primary!.resetsInMs, comeBackMs: s.primary!.comeBackMs,
+ })),
+ }
+ }
+}
+
+/** Plain lines for `harness subs`. */
+export function describeSubscriptions(p: SubscriptionsPayload): string[] {
+ const lines: string[] = []
+ for (const s of p.subs) {
+ const head = `${s.isPick ? '>' : ' '} ${s.name.padEnd(7)}`
+ if (s.state === 'disabled') { lines.push(`${head} off (harness subs set ${s.id} on)`); continue }
+ if (s.state === 'not-detected') { lines.push(`${head} not detected`); continue }
+ if (!s.primary) { lines.push(`${head} ${s.state}${s.status ? `: ${s.status}` : ''}${s.help ? ` (${s.help})` : ''}`); continue }
+ const w = s.primary
+ const bank = w.bankedSigned >= 0 ? `${pct(w.bankedSigned)} banked` : `${pct(-w.bankedSigned)} over pace`
+ lines.push(`${head} ${s.plan ? `${s.plan} ` : ''}${w.label}: ${pct(w.used)} used, ${bank}, resets in ${spanWords(w.resetsInMs)}${s.snapshot ? ' (snapshot)' : ''}`)
+ lines.push(` ${w.sentence}`)
+ if (s.status) lines.push(` ${s.status}`)
+ }
+ lines.push('', p.guide.verdict)
+ return lines
+}
diff --git a/cli/src/fleet/subscriptions/nodeDeps.ts b/cli/src/fleet/subscriptions/nodeDeps.ts
new file mode 100644
index 000000000..5f44295de
--- /dev/null
+++ b/cli/src/fleet/subscriptions/nodeDeps.ts
@@ -0,0 +1,55 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+/** The real machine behind ProviderDeps and SubscriptionsDeps. Read-only except the daemon's own data dir. */
+import { execFile } from 'node:child_process'
+import { promises as fsp } from 'node:fs'
+import { homedir } from 'node:os'
+import { READERS, type ProviderDeps } from './providers.js'
+import type { SubscriptionsDeps } from './index.js'
+
+export function nodeProviderDeps(): ProviderDeps {
+ return {
+ home: homedir(),
+ platform: process.platform,
+ env: process.env,
+ now: () => Date.now(),
+ readFile: async (p) => { try { return await fsp.readFile(p, 'utf8') } catch { return null } },
+ readTail: async (p, bytes) => {
+ let fh: fsp.FileHandle | null = null
+ try {
+ fh = await fsp.open(p, 'r')
+ const { size } = await fh.stat()
+ const len = Math.min(size, bytes)
+ const buf = Buffer.alloc(len)
+ await fh.read(buf, 0, len, size - len)
+ return buf.toString('utf8')
+ } catch { return null } finally { await fh?.close().catch(() => {}) }
+ },
+ listDir: async (p) => { try { return await fsp.readdir(p) } catch { return [] } },
+ exists: async (p) => { try { await fsp.stat(p); return true } catch { return false } },
+ fetchJson: async (url, headers, timeoutMs) => {
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
+ let body: unknown = null
+ try { body = await res.json() } catch { body = null }
+ return { status: res.status, body }
+ },
+ execFile: (cmd, args, timeoutMs) => new Promise((resolve) => {
+ execFile(cmd, args, { timeout: timeoutMs, encoding: 'utf8', maxBuffer: 256 * 1024 }, (err, stdout) => resolve(err ? null : stdout))
+ }),
+ }
+}
+
+export function nodeSubscriptionsDeps(dataDir: string): SubscriptionsDeps {
+ return {
+ dataDir,
+ now: () => Date.now(),
+ readers: READERS,
+ providerDeps: nodeProviderDeps(),
+ readFile: async (p) => { try { return await fsp.readFile(p, 'utf8') } catch { return null } },
+ writeFile: async (p, d) => {
+ const tmp = `${p}.${process.pid}.tmp`
+ await fsp.writeFile(tmp, d, { mode: 0o600 })
+ await fsp.rename(tmp, p)
+ },
+ }
+}
diff --git a/cli/src/fleet/subscriptions/pace.spec.ts b/cli/src/fleet/subscriptions/pace.spec.ts
new file mode 100644
index 000000000..e295f5ccc
--- /dev/null
+++ b/cli/src/fleet/subscriptions/pace.spec.ts
@@ -0,0 +1,297 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+/**
+ * The pace and banked arithmetic, mirroring Burn Bar's own suites
+ * (github.com/nixfred/burnbar tests/test_pace_math.py and tests/test_guidance.cjs) case for case,
+ * so the port answers every question the original answers, with the same numbers.
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ burndownSeries, clockSpan, guidePick, paceFor, paceLive, recentRatePerHour, SERIES_MAX_POINTS,
+ spanWords, windowId, windowMsFor, type Sample,
+} from './pace.js'
+
+const HOUR = 3_600_000
+const DAY = 86_400_000
+const WEEK = 7 * DAY
+const MONTH = 30 * DAY
+const NOW = 1_789_900_000_000 // 2026-09-20 UTC
+const iso = (ms: number): string => new Date(ms).toISOString()
+const utc = (y: number, m: number, d: number): number => Date.UTC(y, m - 1, d)
+
+describe('window length (burnbar WindowLengthTests)', () => {
+ it('reads the length off the label when the provider states it', () => {
+ expect(windowMsFor('Session (5-hour)', NOW, 0)).toBe(5 * HOUR)
+ expect(windowMsFor('Weekly (7-day)', NOW, 0)).toBe(7 * DAY)
+ })
+ it('a month is the calendar month before the reset, not thirty days', () => {
+ expect(windowMsFor('Monthly (total)', utc(2027, 3, 1), 0)).toBe(28 * DAY)
+ expect(windowMsFor('Monthly (total)', utc(2028, 3, 1), 0)).toBe(29 * DAY)
+ })
+ it('an unlabelled window is measured from the previous reset', () => {
+ expect(windowMsFor('Quota', NOW + DAY, NOW - 2 * DAY)).toBe(3 * DAY)
+ })
+ it('an unlabelled window with no history is unknown, not a guess', () => {
+ expect(windowMsFor('Quota', NOW + DAY, 0)).toBe(0)
+ })
+})
+
+describe('rate (burnbar RateTests)', () => {
+ const rate = (pts: Array<[number, number]>) => recentRatePerHour(pts.map(([t, p]) => [t, p, 1] as Sample))
+ it('a straight line is its slope per hour', () => {
+ expect(rate([[NOW - 2 * HOUR, 0.1], [NOW - HOUR, 0.2], [NOW, 0.3]])).toBeCloseTo(0.1, 6)
+ })
+ it('one sample cannot be a rate', () => { expect(rate([[NOW, 0.4]])).toBeNull() })
+ it('two ticks seconds apart cannot be a rate', () => { expect(rate([[NOW - 5000, 0.4], [NOW, 0.41]])).toBeNull() })
+ it('a percentage that went down is a reset, not a negative burn', () => {
+ expect(rate([[NOW - 2 * HOUR, 0.9], [NOW, 0.05]])).toBeNull()
+ })
+ it('samples older than the rate window are not part of the rate', () => {
+ expect(rate([[NOW - 20 * HOUR, 0], [NOW - HOUR, 0.5], [NOW, 0.6]])).toBeCloseTo(0.1, 6)
+ })
+})
+
+describe('window id (burnbar WindowIdTests)', () => {
+ it('the same window stated with jitter is one window', () => {
+ const base = NOW + 6 * DAY
+ expect(new Set([0, 53, 407, 828, 950].map((ms) => windowId(base + ms))).size).toBe(1)
+ })
+ it('windows a minute apart stay different', () => {
+ expect(windowId(NOW + 6 * DAY)).not.toBe(windowId(NOW + 6 * DAY + 60_000))
+ })
+})
+
+describe('burndown series (burnbar BurndownSeriesTests)', () => {
+ it('is normalised and ends on the present', () => {
+ const resets = windowId(NOW + 3 * DAY)
+ const start = resets - WEEK
+ const s = burndownSeries([[start + DAY, 0.1, resets], [start + 2 * DAY, 0.25, resets]], resets, WEEK, 0.4, NOW)
+ expect(s).toHaveLength(3)
+ expect(s[0]![0]).toBeCloseTo(1 / 7, 3)
+ expect(s[0]![1]).toBeCloseTo(0.1, 5)
+ expect(s[2]![0]).toBeCloseTo((NOW - start) / WEEK, 3)
+ expect(s[2]![1]).toBeCloseTo(0.4, 5)
+ for (const [x, y] of s) { expect(x).toBeGreaterThanOrEqual(0); expect(x).toBeLessThanOrEqual(1); expect(y).toBeLessThanOrEqual(1) }
+ })
+ it('never lets another window leak into this line', () => {
+ const resets = windowId(NOW + 3 * DAY)
+ const s = burndownSeries([[NOW - DAY, 0.9, resets - WEEK], [NOW - HOUR, 0.2, resets]], resets, WEEK, 0.22, NOW)
+ expect(s.map((p) => Math.round(p[1] * 100) / 100)).toEqual([0.2, 0.22])
+ })
+ it('thins a long window rather than shipping it whole', () => {
+ const resets = windowId(NOW + DAY)
+ const start = resets - WEEK
+ const pts: Sample[] = Array.from({ length: 1499 }, (_, i) => [start + (i + 1) * 300_000, (i + 1) / 2000, resets])
+ const s = burndownSeries(pts, resets, WEEK, 0.76, NOW)
+ expect(s.length).toBeLessThanOrEqual(SERIES_MAX_POINTS)
+ expect(s[s.length - 1]![1]).toBeCloseTo(0.76, 5)
+ })
+ it('no samples is still a point the card can draw', () => {
+ const s = burndownSeries([], windowId(NOW + 3 * DAY), WEEK, 0.05, NOW)
+ expect(s).toHaveLength(1)
+ expect(s[0]![1]).toBeCloseTo(0.05, 5)
+ })
+})
+
+describe('pace (burnbar PaceTests and ReviewFixTests)', () => {
+ const row = (pct: number, resets: number, label = 'Weekly (7-day)') => ({ label, percent: pct, resetsAt: iso(resets) })
+ it('on pace is one', () => {
+ const p = paceFor(row(0.5, NOW + 3.5 * DAY), [], true, NOW)
+ expect(p.ratio).toBeCloseTo(1, 3)
+ expect(p.elapsed).toBeCloseTo(0.5, 3)
+ })
+ it('a blown window has no allowance and recovers only at the reset', () => {
+ const resets = windowId(NOW + 6 * DAY)
+ const p = paceFor(row(1, resets), [], true, NOW)
+ expect(p.ratio).toBeGreaterThan(1)
+ expect(p.allowancePerHour).toBe(0)
+ expect(p.backOnPaceAt).toBe(resets)
+ })
+ it('half spent early comes back on pace midway through the window', () => {
+ const resets = windowId(NOW + 6 * DAY)
+ expect(paceFor(row(0.5, resets), [], true, NOW).backOnPaceAt).toBe(resets - 3.5 * DAY)
+ })
+ it('the first moments of a window hold the ratio rather than divide by zero', () => {
+ const p = paceFor(row(0.01, NOW + 7 * DAY - 60_000), [], true, NOW)
+ expect(p.ratio).toBe(-1)
+ expect(p.elapsed).toBeGreaterThanOrEqual(0)
+ })
+ it('a window already past its reset carries no pace', () => {
+ const p = paceFor(row(0.4, NOW - HOUR), [], true, NOW)
+ expect(p.windowMs).toBe(0)
+ expect(p.ratio).toBe(-1)
+ })
+ it('a missing percentage carries no pace', () => {
+ const p = paceFor(row(-1, NOW + DAY), [], true, NOW)
+ expect(p.ratio).toBe(-1)
+ expect(p.allowancePerHour).toBe(-1)
+ })
+ it('a snapshot row gets a ratio but never a rate', () => {
+ const p = paceFor(row(0.3, NOW + 3.5 * DAY), [[NOW - 2 * HOUR, 0.1, 1], [NOW, 0.3, 1]], false, NOW)
+ expect(p.ratio).toBeGreaterThan(0)
+ expect(p.ratePerHour).toBe(-1)
+ expect(p.projected).toBe(-1)
+ })
+ it('at this rate projects past the reset and names the dry moment', () => {
+ const resets = windowId(NOW + 10 * HOUR)
+ const pts: Sample[] = [[NOW - 2 * HOUR, 0.2, resets], [NOW - HOUR, 0.3, resets], [NOW, 0.4, resets]]
+ const p = paceFor(row(0.4, resets), pts, true, NOW)
+ expect(p.ratePerHour).toBeCloseTo(0.1, 6)
+ expect(p.projected).toBeCloseTo(1.4, 2)
+ expect((p.dryAt - NOW) / HOUR).toBeCloseTo(6, 3)
+ })
+ it('a rate that still lands inside the window names no dry moment', () => {
+ const resets = windowId(NOW + 10 * HOUR)
+ const p = paceFor(row(0.12, resets), [[NOW - 2 * HOUR, 0.1, resets], [NOW, 0.12, resets]], true, NOW)
+ expect(p.projected).toBeLessThan(1)
+ expect(p.dryAt).toBe(0)
+ })
+ it('an on-pace sub is not told to stop in a day', () => {
+ const resets = windowId(NOW + 3.5 * DAY)
+ const even = 1 / 7 / 24
+ const p = paceFor(row(0.5, resets), [[NOW - 2 * HOUR, 0.5 - 2 * even, resets], [NOW, 0.5, resets]], true, NOW)
+ expect(p.stopInMs).toBe(-1)
+ })
+ it('a fast burn still gets its stop time', () => {
+ const resets = windowId(NOW + 3.5 * DAY)
+ const p = paceFor(row(0.3, resets), [[NOW - 2 * HOUR, 0.2, resets], [NOW, 0.3, resets]], true, NOW)
+ expect(p.stopInMs).toBeGreaterThan(0)
+ expect(p.stopInMs).toBeLessThan(24 * HOUR)
+ })
+ it('a five-hour window has no daily ceiling', () => {
+ expect(paceFor(row(0.5, NOW + HOUR, 'Session (5-hour)'), [], true, NOW).todayCeiling).toBe(-1)
+ })
+})
+
+const NOW2 = 1_800_000_000_000
+const win = (used: number, gone: number, span = WEEK) => paceLive(used, NOW2 + span * (1 - gone), span, NOW2)
+
+describe('banked and come-back (burnbar test_guidance.cjs)', () => {
+ it('ahead: banked is elapsed minus used, in plan share and in time', () => {
+ const w = win(0.02, 0.51)!
+ expect(w.banked).toBeCloseTo(0.49, 9)
+ expect(w.bankedSigned).toBeCloseTo(0.49, 9)
+ expect(w.bankedMs).toBeCloseTo(0.49 * WEEK, 0)
+ expect(w.behind).toBe(0)
+ expect(w.comeBackAt).toBe(0)
+ expect(w.room).toBeCloseTo(0.98 / 0.49, 9)
+ })
+ it('behind: no banked figure, a negative signed bank, and a moment to come back', () => {
+ const w = win(0.09, 0.05)!
+ expect(w.banked).toBe(0)
+ expect(w.bankedSigned).toBeCloseTo(-0.04, 9)
+ expect(w.behind).toBeCloseTo(0.04, 9)
+ expect(w.comeBackMs).toBeCloseTo(0.04 * WEEK, 0)
+ expect(w.comeBackAt).toBeGreaterThan(NOW2)
+ expect(w.comeBackAt).toBeLessThan(w.resetsMs)
+ })
+ it('time off brings a sub back, and the promised come-back moment is when it flips', () => {
+ const reset = NOW2 + 5 * DAY
+ const before = paceLive(0.3, reset, WEEK, NOW2)!
+ const later = paceLive(0.3, reset, WEEK, NOW2 + 2 * DAY)!
+ expect(before.behind).toBeGreaterThan(0)
+ expect(later.banked).toBeGreaterThan(0.25)
+ expect(paceLive(0.3, reset, WEEK, before.comeBackAt + 1000)!.behind).toBe(0)
+ })
+ it('spent out comes back at the reset, never before', () => {
+ const w = win(1, 0.13)!
+ expect(w.spent).toBe(true)
+ expect(w.comeBackAt).toBe(w.resetsMs)
+ expect(w.room).toBe(0)
+ })
+ it('spent while ahead of the clock still comes back at the reset', () => {
+ const w = win(0.996, 0.999)!
+ expect(w.spent).toBe(true)
+ expect(w.banked).toBe(0)
+ expect(w.comeBackAt).toBe(w.resetsMs)
+ expect(win(0.997, 0.997)!.comeBackAt).toBe(win(0.997, 0.997)!.resetsMs)
+ })
+ it('inside 5% of an even spend is on pace, not over', () => {
+ expect(win(0.5, 0.48)!.over).toBe(false)
+ expect(win(0.09, 0.05)!.over).toBe(true)
+ expect(win(0.004, 0.001)!.over).toBe(false)
+ })
+ it('claims nothing about a window that cannot be read', () => {
+ for (const [p, r, s] of [[-1, NOW2 + DAY, WEEK], [NaN, NOW2 + DAY, WEEK], [0.5, 0, WEEK], [0.5, NOW2 + DAY, 0], [0.5, NOW2 - 1, WEEK]])
+ expect(paceLive(p!, r!, s!, NOW2)).toBeNull()
+ })
+})
+
+const row = (id: string, used: number, gone: number, opts: { span?: number; fresh?: boolean; blocked?: boolean; minBank?: number } = {}) =>
+ ({ id, live: win(used, gone, opts.span ?? WEEK), fresh: opts.fresh ?? true, blocked: opts.blocked ?? false, minBank: opts.minBank })
+
+describe('which sub next (burnbar guidePick)', () => {
+ it('one subscription is never suggested', () => {
+ const g = guidePick([row('kimi', 0.05, 0.6, { span: MONTH })], '')
+ expect(g.count).toBe(1)
+ expect(g.pick).toBe('')
+ })
+ it('with two, the one with room is the right one', () => {
+ const g = guidePick([row('claude', 0.09, 0.05), row('grok', 0.02, 0.51)], '')
+ expect(g.pick).toBe('grok')
+ expect(g.rest.map((r) => r.id)).toEqual(['claude'])
+ })
+ it('with four, a week and a month are ranked on the same scale', () => {
+ const g = guidePick([row('claude', 0.09, 0.05), row('codex', 1, 0.13), row('grok', 0.02, 0.51), row('kimi', 0.05, 0.16, { span: MONTH })], '')
+ expect(g.pick).toBe('grok')
+ expect(g.next).toBe('kimi')
+ expect(g.ahead).toBe(2)
+ expect(g.rest.map((r) => r.id)).toEqual(['claude', 'codex'])
+ })
+ it('use it or lose it: a close reset with budget unspent wins, and says so', () => {
+ const g = guidePick([row('grok', 0.02, 0.51), row('codex', 0.6, 0.95)], '')
+ expect(g.pick).toBe('codex')
+ expect(g.urgent).toBe(true)
+ })
+ it('urgent is about the calendar', () => {
+ const fourDays = 1 - (4 * DAY) / MONTH
+ const g = guidePick([row('kimi', 0.3, fourDays, { span: MONTH }), row('claude', 0.9, 0.5)], '')
+ expect(g.pick).toBe('kimi')
+ expect(g.urgent).toBe(false)
+ const twoDays = 1 - (2 * DAY) / MONTH
+ expect(guidePick([row('kimi', 0.3, twoDays, { span: MONTH }), row('claude', 0.9, 0.5)], '').urgent).toBe(true)
+ expect(guidePick([row('grok', 0.93, 0.97), row('claude', 0.9, 0.5)], '').urgent).toBe(false)
+ })
+ it('a snapshot has to be further ahead before it is suggested', () => {
+ const snap = (bank: number, min: number) => row('grok', 0.5 - bank, 0.5, { minBank: min })
+ expect(guidePick([snap(0.06, 0.1), row('claude', 0.9, 0.5)], '').pick).toBe('')
+ expect(guidePick([snap(0.12, 0.1), row('claude', 0.9, 0.5)], '').pick).toBe('grok')
+ })
+ it('the sub being suggested keeps the job down to half the threshold', () => {
+ const thin = row('kimi', 0.485, 0.5, { span: MONTH })
+ expect(guidePick([thin, row('claude', 0.9, 0.5)], '').pick).toBe('')
+ expect(guidePick([thin, row('claude', 0.9, 0.5)], 'kimi').pick).toBe('kimi')
+ })
+ it('is never a sub that is stale, blocked, spent or unreadable', () => {
+ expect(guidePick([row('claude', 0.5, 0.5), row('grok', 0.02, 0.6, { fresh: false })], '').pick).toBe('')
+ expect(guidePick([row('claude', 0.1, 0.6, { blocked: true }), row('codex', 0.7, 0.5)], '').pick).toBe('')
+ expect(guidePick([{ id: 'claude', live: null, fresh: true, blocked: false }, row('kimi', 0.05, 0.4, { span: MONTH })], '').pick).toBe('kimi')
+ })
+ it('everyone behind: no suggestion, and the first one back is named', () => {
+ const g = guidePick([row('claude', 0.3, 0.1), row('codex', 0.2, 0.15)], '')
+ expect(g.pick).toBe('')
+ expect(g.rest[0]!.id).toBe('codex')
+ })
+ it('a hair of banked budget is not advice', () => {
+ expect(guidePick([row('claude', 0.49, 0.5), row('codex', 0.3, 0.31)], '').pick).toBe('')
+ })
+ it('does not flap between two near-equal subs', () => {
+ const a = row('grok', 0.2, 0.6)
+ const b = row('kimi', 0.19, 0.6, { span: MONTH })
+ expect(guidePick([a, b], '').pick).toBe('kimi')
+ expect(guidePick([a, b], 'grok').pick).toBe('grok')
+ expect(guidePick([a, row('kimi', 0.02, 0.6, { span: MONTH })], 'grok').pick).toBe('kimi')
+ })
+})
+
+describe('spans', () => {
+ it('clocks run, spans read like advice', () => {
+ expect(clockSpan(3 * DAY + 9 * HOUR + 12 * 60e3 + 45e3)).toBe('3d 09:12:45')
+ expect(clockSpan(7 * HOUR + 13 * 60e3 + 22e3)).toBe('7:13:22')
+ expect(clockSpan(-5)).toBe('0:00')
+ expect(spanWords(3 * DAY + 10 * HOUR + 22 * 60e3)).toBe('3d 10h')
+ expect(spanWords(6 * HOUR + 40 * 60e3)).toBe('6h 40m')
+ expect(spanWords(2 * DAY)).toBe('2d')
+ expect(spanWords(20e3)).toBe('under a minute')
+ })
+})
diff --git a/cli/src/fleet/subscriptions/pace.ts b/cli/src/fleet/subscriptions/pace.ts
new file mode 100644
index 000000000..3929abf1f
--- /dev/null
+++ b/cli/src/fleet/subscriptions/pace.ts
@@ -0,0 +1,308 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+/**
+ * Budget pace for a subscription window: am I over, how much have I banked, when can I come back,
+ * and which subscription should I reach for next.
+ *
+ * Ported from Burn Bar (https://github.com/nixfred/burnbar, MIT): `bin/burnbar-collect` (pace_for,
+ * window_ms_for, recent_rate_per_hour, burndown_series, window_id) and `BarWidget.qml` (paceLive,
+ * guidePick, spanWords, clockSpan). The arithmetic is kept identical so the two agree to the number;
+ * Burn Bar itself is not required, called or read.
+ *
+ * On budget means EVEN PACE across the window: a tenth of the way in, a tenth of the plan is a fair
+ * spend. With used fraction p, window length L and time left r:
+ *
+ * elapsed e = (L - r) / L
+ * pace ratio R = p / e 1.0 is exactly on pace, above it is over
+ * banked e - p (signed) positive = unspent share an even pace allowed by now,
+ * negative = how far ahead of the clock the spend is
+ * allowance (1 - p) / r what may still burn per hour and make it to the reset
+ * forecast p + rate * r above 1.0 the window runs dry early
+ * come back at reset - L * (1 - p) the moment the even-pace line catches up, if you stop now
+ * room (1 - p) / (1 - e) same scale for a week and a month; ranks the next sub
+ *
+ * Unknowns are -1 (a figure that cannot be measured) or 0 (a moment that does not apply), never an
+ * invented number. Every percentage is the provider's own.
+ */
+
+export const HOUR_MS = 3_600_000
+export const DAY_MS = 86_400_000
+export const RATE_WINDOW_MS = 120 * 60_000
+export const RATE_MIN_SPAN_MS = 10 * 60_000
+export const DAILY_MIN_WINDOW_MS = 36 * HOUR_MS
+export const SERIES_MAX_POINTS = 48
+
+/** [timestampMs, usedFraction, windowId] */
+export type Sample = [number, number, number]
+
+export interface LimitRow {
+ label: string
+ /** 0..1, or -1 when unknown. */
+ percent: number
+ /** ISO time, or '' when unknown. */
+ resetsAt: string
+ /** Start of the window when the provider states it (Grok does). */
+ startsAt?: string
+}
+
+export interface Pace {
+ windowMs: number
+ resetsMs: number
+ elapsed: number
+ ratio: number
+ allowancePerHour: number
+ ratePerHour: number
+ projected: number
+ dryAt: number
+ backOnPaceAt: number
+ todayCeiling: number
+ stopInMs: number
+ stopAtMs: number
+ series: Array<[number, number]>
+}
+
+export function parseIsoMs(raw: unknown): number {
+ const s = String(raw ?? '').trim()
+ if (!s) return 0
+ const ms = Date.parse(s)
+ return Number.isFinite(ms) ? ms : 0
+}
+
+/** 0..1 or -1. A boolean is never a percentage. */
+export function normPercent(value: unknown): number {
+ if (typeof value === 'boolean' || value === null || value === undefined || value === '') return -1
+ const n = Number(value)
+ if (!Number.isFinite(n) || n < 0 || n > 1) return -1
+ return n
+}
+
+/** Which window instance this is, to the minute: providers restate the same reset with ms jitter. */
+export function windowId(resetsMs: number): number {
+ return Math.floor(resetsMs / 60_000) * 60_000
+}
+
+/** How long a window is: from the label when stated, else the distance from the previous reset. */
+export function windowMsFor(label: string, resetsMs: number, prevResetsMs: number): number {
+ const text = String(label || '').toLowerCase()
+ const m = /(\d+)\s*-\s*(hour|day)/.exec(text)
+ if (m) return Number(m[1]) * (m[2] === 'hour' ? HOUR_MS : DAY_MS)
+ if (text.includes('week')) return 7 * DAY_MS
+ if (text.includes('month')) {
+ if (resetsMs) {
+ // Step back one calendar month from the reset so a February window is February long.
+ const end = new Date(resetsMs)
+ let y = end.getUTCFullYear()
+ let mo = end.getUTCMonth() - 1
+ if (mo < 0) { mo = 11; y -= 1 }
+ const daysIn = new Date(Date.UTC(y, mo + 1, 0)).getUTCDate()
+ const day = Math.min(end.getUTCDate(), daysIn)
+ const start = Date.UTC(y, mo, day, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds())
+ return Math.max(DAY_MS, resetsMs - start)
+ }
+ return 30 * DAY_MS
+ }
+ if (text.includes('session')) return 5 * HOUR_MS
+ if (text.includes('daily') || text.includes('day')) return DAY_MS
+ if (prevResetsMs && resetsMs > prevResetsMs) return resetsMs - prevResetsMs
+ return 0
+}
+
+/** Least-squares slope over the last two hours, as fraction per hour; null when it cannot carry one. */
+export function recentRatePerHour(points: Sample[]): number | null {
+ if (points.length < 2) return null
+ const floor = points[points.length - 1]![0] - RATE_WINDOW_MS
+ const pts = points.filter(([t]) => t >= floor).map(([t, p]) => [t, p] as const)
+ if (pts.length < 2 || pts[pts.length - 1]![0] - pts[0]![0] < RATE_MIN_SPAN_MS) return null
+ for (let i = 1; i < pts.length; i++) if (pts[i]![1] < pts[i - 1]![1] - 1e-9) return null
+ const n = pts.length
+ const mt = pts.reduce((a, [t]) => a + t, 0) / n
+ const mp = pts.reduce((a, [, p]) => a + p, 0) / n
+ const denom = pts.reduce((a, [t]) => a + (t - mt) ** 2, 0)
+ if (denom <= 0) return null
+ const slope = pts.reduce((a, [t, p]) => a + (t - mt) * (p - mp), 0) / denom
+ return Math.max(0, slope * HOUR_MS)
+}
+
+const r5 = (n: number): number => Math.round(n * 1e5) / 1e5
+
+/** This window's samples as [x, y] in 0..1, thinned, always ending on the present. */
+export function burndownSeries(points: Sample[], resets: number, window: number, pctNow: number, now: number): Array<[number, number]> {
+ const start = resets - window
+ let mine = points.filter(([t, , r]) => r === resets && t >= start && t <= now)
+ if (mine.length > SERIES_MAX_POINTS - 1) {
+ const step = mine.length / (SERIES_MAX_POINTS - 1)
+ mine = Array.from({ length: SERIES_MAX_POINTS - 1 }, (_, i) => mine[Math.floor(i * step)]!)
+ }
+ const out: Array<[number, number]> = mine.map(([t, p]) => [r5((t - start) / window), r5(p)])
+ out.push([r5(Math.min(1, Math.max(0, (now - start) / window))), r5(pctNow)])
+ return out
+}
+
+/** The collector-side pace block for one limit row (Burn Bar's pace_for). */
+export function paceFor(row: LimitRow, points: Sample[], live: boolean, now: number): Pace {
+ const out: Pace = {
+ windowMs: 0, resetsMs: 0, elapsed: -1, ratio: -1, allowancePerHour: -1, ratePerHour: -1, projected: -1,
+ dryAt: 0, backOnPaceAt: 0, todayCeiling: -1, stopInMs: -1, stopAtMs: 0, series: [],
+ }
+ const pct = row.percent
+ const resets = windowId(parseIsoMs(row.resetsAt))
+ if (typeof pct !== 'number' || !(pct >= 0) || !resets) return out
+ let prev = 0
+ for (const [, , r] of points) if (r && r < resets) prev = Math.max(prev, r)
+ const starts = parseIsoMs(row.startsAt)
+ let window = starts && starts < resets ? resets - starts : windowMsFor(row.label, resets, prev)
+ const leftMs = resets - now
+ if (window <= 0 || leftMs <= 0) return out
+ window = Math.max(window, 1)
+ out.windowMs = window
+ out.resetsMs = resets
+ out.series = burndownSeries(points, resets, window, pct, now)
+ const elapsed = Math.min(1, Math.max(0, (window - leftMs) / window))
+ out.elapsed = elapsed
+ const hoursLeft = leftMs / HOUR_MS
+ out.allowancePerHour = Math.max(0, (1 - pct) / hoursLeft)
+ // Hold the ratio until the window is one percent old: any spend divides by ~0 before that.
+ if (elapsed >= 0.01) out.ratio = pct / elapsed
+ const rate = live ? recentRatePerHour(points.filter((p) => p[2] === resets)) : null
+ if (rate !== null) {
+ out.ratePerHour = rate
+ out.projected = pct + rate * hoursLeft
+ if (rate > 0 && out.projected > 1) out.dryAt = Math.trunc(now + ((1 - pct) / rate) * HOUR_MS)
+ }
+ if (out.ratio > 1) out.backOnPaceAt = Math.trunc(resets - window * (1 - pct))
+ if (window >= DAILY_MIN_WINDOW_MS && hoursLeft > 0) {
+ const ceiling = Math.max(0, (1 - pct) * Math.min(1, 24 / hoursLeft))
+ out.todayCeiling = ceiling
+ // Only a stop that lands inside the day (and the window) is advice; an on-pace sub lasts ~24h.
+ if (rate !== null && rate > 0.0005) {
+ const hours = ceiling / rate
+ if (hours < 24 && hours * HOUR_MS < leftMs) {
+ out.stopInMs = Math.trunc(hours * HOUR_MS)
+ out.stopAtMs = Math.trunc(now + hours * HOUR_MS)
+ }
+ }
+ }
+ return out
+}
+
+export interface LivePace {
+ used: number
+ elapsed: number
+ leftMs: number
+ windowMs: number
+ resetsMs: number
+ /** Share of the plan an even pace would have used by now and did not; 0 when not ahead. */
+ banked: number
+ /** elapsed - used: positive when banked, negative when over pace. */
+ bankedSigned: number
+ bankedMs: number
+ behind: number
+ over: boolean
+ comeBackAt: number
+ comeBackMs: number
+ room: number
+ spent: boolean
+}
+
+/** Where one window stands right now (Burn Bar's paceLive). Null when the window cannot be read. */
+export function paceLive(percent: number, resetsMs: number, windowMs: number, nowMs: number): LivePace | null {
+ const p0 = Number(percent), reset = Number(resetsMs), span = Number(windowMs), now = Number(nowMs)
+ if (!(p0 >= 0) || !(reset > 0) || !(span > 0) || !(now > 0) || now >= reset) return null
+ const p = Math.min(1, p0)
+ const left = reset - now
+ const e = Math.max(0, Math.min(1, 1 - left / span))
+ const out: LivePace = {
+ used: p, elapsed: e, leftMs: left, windowMs: span, resetsMs: reset, banked: 0, bankedSigned: e - p, bankedMs: 0,
+ behind: 0, over: false, comeBackAt: 0, comeBackMs: 0, room: 0, spent: p >= 0.995,
+ }
+ if (out.spent) {
+ // Decided first: a plan can be spent while still ahead of the clock; it only comes back at the reset.
+ out.behind = Math.max(0, p - e)
+ out.over = true
+ out.comeBackAt = reset
+ out.comeBackMs = left
+ } else if (e > p) {
+ out.banked = e - p
+ out.bankedMs = out.banked * span
+ } else if (p > e) {
+ out.behind = p - e
+ // Over means more than 5% past an even spend and by at least a whole percent of the plan.
+ out.over = out.behind > 0.01 && (e <= 0 || p / e > 1.05)
+ out.comeBackAt = Math.min(reset, reset - span * (1 - p))
+ out.comeBackMs = Math.max(0, out.comeBackAt - now)
+ }
+ out.room = e < 1 ? (1 - p) / (1 - e) : 0
+ return out
+}
+
+export interface GuideRow { id: string; live: LivePace | null; fresh: boolean; blocked: boolean; minBank?: number }
+export interface Guide {
+ count: number
+ pick: string
+ next: string
+ urgent: boolean
+ room: number
+ ahead: number
+ rest: Array<{ id: string; comeBackAt: number; spent: boolean; behind: number }>
+}
+
+/**
+ * Which subscription to reach for next (Burn Bar's guidePick). Only a sub that is ahead is ever
+ * suggested; the most room wins, which becomes earliest-deadline-first as a reset nears with budget
+ * unspent. One sub alone is never suggested. The previous pick sticks until another is clearly better.
+ */
+export function guidePick(rows: GuideRow[], previousId: string): Guide {
+ const MIN_BANK = 0.02, STICK = 1.15
+ const LOSE_IT_MS = 72 * HOUR_MS, LOSE_IT_SHARE = 0.15, LOSE_IT_LEFT = 0.1
+ const out: Guide = { count: 0, pick: '', next: '', urgent: false, room: 0, rest: [], ahead: 0 }
+ const ok: GuideRow[] = []
+ for (const r of rows) {
+ if (!r || !r.id) continue
+ out.count++
+ if (!r.live || !r.fresh) continue
+ if (r.live.over || r.live.spent) out.rest.push({ id: r.id, comeBackAt: r.live.comeBackAt, spent: r.live.spent, behind: r.live.behind })
+ let need = r.minBank && r.minBank > 0 ? r.minBank : MIN_BANK
+ if (r.id === previousId) need *= 0.5
+ if (r.live.spent || r.blocked || !(r.live.banked >= need)) continue
+ ok.push(r)
+ }
+ out.ahead = ok.length
+ out.rest.sort((a, b) => a.comeBackAt - b.comeBackAt)
+ if (out.count < 2 || ok.length === 0) return out
+ ok.sort((a, b) => {
+ if (b.live!.room !== a.live!.room) return b.live!.room - a.live!.room
+ if (b.live!.banked !== a.live!.banked) return b.live!.banked - a.live!.banked
+ return a.live!.leftMs - b.live!.leftMs
+ })
+ if (previousId && previousId !== ok[0]!.id) {
+ const i = ok.findIndex((r, idx) => idx > 0 && r.id === previousId)
+ if (i > 0 && ok[0]!.live!.room < ok[i]!.live!.room * STICK) ok.unshift(ok.splice(i, 1)[0]!)
+ }
+ const top = ok[0]!.live!
+ out.pick = ok[0]!.id
+ out.room = top.room
+ out.urgent = top.leftMs <= Math.min(LOSE_IT_MS, top.windowMs * LOSE_IT_SHARE) && 1 - top.used >= LOSE_IT_LEFT
+ out.next = ok.length > 1 ? ok[1]!.id : ''
+ return out
+}
+
+/** "3d 09:12:45", "7:13:22", "13:05". */
+export function clockSpan(ms: number): string {
+ const total = Math.max(0, Math.floor(Number(ms) / 1000))
+ if (!(total >= 0)) return '0:00'
+ const d = Math.floor(total / 86400), h = Math.floor((total % 86400) / 3600), m = Math.floor((total % 3600) / 60), s = total % 60
+ const two = (n: number) => (n < 10 ? '0' : '') + n
+ if (d > 0) return `${d}d ${two(h)}:${two(m)}:${two(s)}`
+ if (h > 0) return `${h}:${two(m)}:${two(s)}`
+ return `${m}:${two(s)}`
+}
+
+/** "3d 10h", "6h 40m", "45m": two units at most. */
+export function spanWords(ms: number): string {
+ const mins = Math.max(0, Math.round(Number(ms) / 60000))
+ if (!(mins >= 1)) return 'under a minute'
+ const d = Math.floor(mins / 1440), h = Math.floor((mins % 1440) / 60), m = mins % 60
+ if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`
+ if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`
+ return `${m}m`
+}
diff --git a/cli/src/fleet/subscriptions/providers.spec.ts b/cli/src/fleet/subscriptions/providers.spec.ts
new file mode 100644
index 000000000..279cbf810
--- /dev/null
+++ b/cli/src/fleet/subscriptions/providers.spec.ts
@@ -0,0 +1,156 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+import { describe, expect, it } from 'vitest'
+import { readClaude, readCodex, readGrok, readKimi, type ProviderDeps } from './providers.js'
+
+const NOW = Date.UTC(2026, 8, 30, 12)
+const HOME = '/h'
+
+function deps(files: Record<string, string>, over: Partial<ProviderDeps> = {}): ProviderDeps & { calls: Array<{ url: string; headers: Record<string, string> }> } {
+ const calls: Array<{ url: string; headers: Record<string, string> }> = []
+ return {
+ calls,
+ home: HOME,
+ platform: 'linux',
+ env: {},
+ now: () => NOW,
+ readFile: async (p) => (p in files ? files[p]! : null),
+ readTail: async (p, bytes) => (p in files ? files[p]!.slice(-bytes) : null),
+ listDir: async (p) => {
+ const prefix = p.endsWith('/') ? p : `${p}/`
+ const names = new Set<string>()
+ for (const f of Object.keys(files)) if (f.startsWith(prefix)) names.add(f.slice(prefix.length).split('/')[0]!)
+ return [...names]
+ },
+ exists: async (p) => Object.keys(files).some((f) => f === p || f.startsWith(`${p}/`)),
+ fetchJson: async (url, headers) => { calls.push({ url, headers }); return { status: 599, body: null } },
+ execFile: async () => null,
+ ...over,
+ }
+}
+
+describe('provider absent: not detected, never an error', () => {
+ it('claude, codex, grok and kimi on an empty machine', async () => {
+ const d = deps({})
+ for (const r of [await readClaude(d), await readCodex(d), await readGrok(d), await readKimi(d)]) {
+ expect(r.state).toBe('not-detected')
+ expect(r.limits).toEqual([])
+ }
+ expect(d.calls).toHaveLength(0) // nothing leaves the machine when nothing is configured
+ })
+ it('claude installed but not logged in is not configured', async () => {
+ const r = await readClaude(deps({ '/h/.claude/settings.json': '{}' }))
+ expect(r.state).toBe('not-configured')
+ expect(r.help).toMatch(/claude/)
+ })
+})
+
+describe('claude', () => {
+ const creds = JSON.stringify({ claudeAiOauth: { accessToken: 'sk-ant-oat01-SECRETSECRETSECRET', rateLimitTier: 'default_claude_max_20x', subscriptionType: 'max' } })
+ it('reads the OAuth usage endpoint with the local token and maps percent-scale rows', async () => {
+ const d = deps({ '/h/.claude/.credentials.json': creds }, {
+ fetchJson: async (url, headers) => {
+ d.calls.push({ url, headers })
+ return { status: 200, body: { five_hour: { utilization: 7, resets_at: '2026-09-30T15:00:00Z' }, seven_day: { utilization: 32, resets_at: '2026-10-04T10:00:00Z' } } }
+ },
+ })
+ const r = await readClaude(d)
+ expect(d.calls[0]!.url).toBe('https://api.anthropic.com/api/oauth/usage')
+ expect(d.calls[0]!.headers.Authorization).toMatch(/^Bearer /)
+ expect(r.state).toBe('ok')
+ expect(r.plan).toBe('Max 20x')
+ expect(r.limits).toEqual([
+ { label: 'Session (5-hour)', percent: 0.07, resetsAt: '2026-09-30T15:00:00.000Z' },
+ { label: 'Weekly (7-day)', percent: 0.32, resetsAt: '2026-10-04T10:00:00.000Z' },
+ ])
+ expect(JSON.stringify(r)).not.toContain('SECRET')
+ })
+ it('an HTTP error says so and never echoes the token', async () => {
+ const d = deps({ '/h/.claude/.credentials.json': creds }, { fetchJson: async () => ({ status: 429, body: null }) })
+ const r = await readClaude(d)
+ expect(r.state).toBe('error')
+ expect(r.status).toMatch(/429/)
+ expect(JSON.stringify(r)).not.toContain('SECRET')
+ })
+ it('on macOS the token comes from the login keychain, read only', async () => {
+ const seen: string[][] = []
+ const d = deps({ '/h/.claude/x': '' }, {
+ platform: 'darwin',
+ execFile: async (cmd, args) => { seen.push([cmd, ...args]); return creds },
+ fetchJson: async () => ({ status: 200, body: { seven_day: { utilization: 0.5, resets_at: '2026-10-04T10:00:00Z' } } }),
+ })
+ const r = await readClaude(d)
+ expect(seen[0]).toEqual(['security', 'find-generic-password', '-s', 'Claude Code-credentials', '-w'])
+ expect(r.limits[0]!.percent).toBe(0.5)
+ })
+})
+
+describe('codex', () => {
+ const line = (ts: string, rl: unknown) => JSON.stringify({ timestamp: ts, type: 'event_msg', payload: { type: 'token_count', rate_limits: rl } })
+ it('takes the newest rate_limits snapshot from the newest rollout, no network', async () => {
+ const f = '/h/.codex/sessions/2026/09/30/rollout-2026-09-30T10-00-00-abc.jsonl'
+ const old = '/h/.codex/sessions/2026/09/29/rollout-2026-09-29T10-00-00-abc.jsonl'
+ const d = deps({
+ [old]: line('2026-09-29T10:00:00Z', { primary: { used_percent: 1, window_minutes: 10080, resets_at: 1791308664 } }),
+ [f]: [
+ line('2026-09-30T10:00:00Z', { primary: { used_percent: 12, window_minutes: 10080, resets_at: 1791308664 } }),
+ line('2026-09-30T11:00:00Z', { primary: { used_percent: 16, window_minutes: 10080, resets_at: 1791308664 }, secondary: { used_percent: 40, window_minutes: 300, resets_at: 1790780000 }, plan_type: 'pro' }),
+ '{"not json',
+ ].join('\n'),
+ })
+ const r = await readCodex(d)
+ expect(r.state).toBe('ok')
+ expect(r.plan).toBe('pro')
+ expect(r.limits[0]).toEqual({ label: 'Weekly (7-day)', percent: 0.16, resetsAt: new Date(1791308664000).toISOString() })
+ expect(r.limits[1]!.label).toBe('Session (5-hour)')
+ expect(r.measuredAt).toBe(Date.parse('2026-09-30T11:00:00Z'))
+ expect(d.calls).toHaveLength(0)
+ })
+ it('sessions but no snapshot yet is detected with a remedy', async () => {
+ const r = await readCodex(deps({ '/h/.codex/sessions/2026/09/30/rollout-x.jsonl': '{}' }))
+ expect(r.state).toBe('not-configured')
+ })
+})
+
+describe('grok', () => {
+ it('reads the newest billing snapshot, with its own period start', async () => {
+ const snap = (pct: number, end: string) => JSON.stringify({ ts: '2026-09-28T02:03:03.932Z', msg: 'billing: fetched credits config', ctx: { config: { creditUsagePercent: pct, currentPeriod: { start: '2026-09-24T03:10:03Z', end } }, subscriptionTier: 'SuperGrok Plus' } })
+ const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': ['{"msg":"other"}', snap(1, '2026-10-01T03:10:03Z'), snap(3, '2026-10-01T03:10:03Z')].join('\n') }))
+ expect(r.state).toBe('ok')
+ expect(r.snapshot).toBe(true)
+ expect(r.plan).toBe('SuperGrok Plus')
+ expect(r.limits).toEqual([{ label: 'Weekly (7-day)', percent: 0.03, resetsAt: '2026-10-01T03:10:03.000Z', startsAt: '2026-09-24T03:10:03.000Z' }])
+ })
+ it('a snapshot with no percentage is unknown, never a confident zero', async () => {
+ const line = JSON.stringify({ ts: '2026-09-28T02:03:03Z', msg: 'billing: fetched credits config', ctx: { config: { currentPeriod: { end: '2026-10-01T03:10:03Z' } } } })
+ const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': line }))
+ expect(r.limits[0]!.percent).toBe(-1)
+ })
+ it('a window that has reset since the snapshot says so', async () => {
+ const line = JSON.stringify({ ts: '2026-09-20T02:03:03Z', msg: 'billing: fetched credits config', ctx: { config: { creditUsagePercent: 50, currentPeriod: { end: '2026-09-25T03:10:03Z' } } } })
+ const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': line }))
+ expect(r.status).toMatch(/reset/)
+ })
+})
+
+describe('kimi', () => {
+ const usages = { limits: [{ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' }, detail: { limit: '100', used: '9', resetTime: '2026-09-30T08:43:48Z' } }], usages: { limit_5h: { used_ratio: 0, reset_time: '2026-09-30T08:43:47Z' }, limit_month_total: { used_ratio: 0.0711, reset_time: '2026-10-19T00:00:00Z' }, limit_month_code: { used_ratio: 0, reset_time: '2026-10-19T00:00:00Z' } } }
+ it('uses KIMI_API_KEY from ~/.env and maps the request window and month', async () => {
+ const d = deps({ '/h/.env': '# x\nKIMI_API_KEY="kimi-secret-key-value"\nOTHER=1\n' }, {
+ fetchJson: async (url, headers) => { d.calls.push({ url, headers }); return { status: 200, body: usages } },
+ })
+ const r = await readKimi(d)
+ expect(d.calls[0]!.url).toBe('https://api.kimi.com/coding/v1/usages')
+ expect(r.state).toBe('ok')
+ expect(r.limits.map((l) => l.label)).toEqual(['Session (5-hour)', 'Monthly (total)', 'Monthly (code)'])
+ expect(r.limits[0]!.percent).toBeCloseTo(0.09, 9)
+ expect(r.limits[1]!.percent).toBeCloseTo(0.0711, 9)
+ expect(JSON.stringify(r)).not.toContain('kimi-secret')
+ })
+ it('refuses a non-https base URL rather than sending the key in clear', async () => {
+ const d = deps({}, { env: { KIMI_API_KEY: 'k', KIMI_BASE_URL: 'http://evil.example' } })
+ const r = await readKimi(d)
+ expect(r.state).toBe('error')
+ expect(d.calls).toHaveLength(0)
+ })
+})
diff --git a/cli/src/fleet/subscriptions/providers.ts b/cli/src/fleet/subscriptions/providers.ts
new file mode 100644
index 000000000..2d150aee6
--- /dev/null
+++ b/cli/src/fleet/subscriptions/providers.ts
@@ -0,0 +1,316 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+/**
+ * One reader per subscription provider. Each answers the same question, "what does this plan's own
+ * meter say right now", from the one source that provider really publishes, and says plainly when the
+ * provider is not on this machine at all.
+ *
+ * Sources, ported from Burn Bar (https://github.com/nixfred/burnbar) and the collectors it reads, but
+ * reimplemented here so neither Burn Bar nor Omarchy has to be installed (Linux or macOS):
+ *
+ * Claude GET https://api.anthropic.com/api/oauth/usage with the Claude Code login's own OAuth token,
+ * read from ~/.claude/.credentials.json (or $CLAUDE_CONFIG_DIR), or on macOS from the login
+ * keychain item "Claude Code-credentials" via `security find-generic-password -w`.
+ * Codex no network: the newest `rate_limits` snapshot Codex itself writes into its session rollouts
+ * under ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (or $CODEX_HOME).
+ * Grok no network: the newest "billing: fetched credits config" line in ~/.grok/logs/unified.jsonl
+ * (or $GROK_HOME). A snapshot: Grok writes it when Grok starts, not on every use.
+ * Kimi GET {KIMI_BASE_URL or https://api.kimi.com/coding/v1}/usages with KIMI_API_KEY from the
+ * environment or a KIMI_API_KEY= line in ~/.env.
+ *
+ * Every credential read is local and read-only. A token only ever goes into the Authorization header of
+ * its own provider's HTTPS request: it is never returned, logged, or put on a command line.
+ */
+import { normPercent, parseIsoMs, type LimitRow } from './pace.js'
+
+export type ProviderId = 'claude' | 'codex' | 'grok' | 'kimi'
+export const PROVIDERS: ReadonlyArray<{ id: ProviderId; name: string }> = [
+ { id: 'claude', name: 'Claude' },
+ { id: 'codex', name: 'Codex' },
+ { id: 'grok', name: 'Grok' },
+ { id: 'kimi', name: 'Kimi' },
+]
+
+export type ReadingState = 'ok' | 'not-detected' | 'not-configured' | 'error'
+
+export interface ProviderReading {
+ id: ProviderId
+ name: string
+ state: ReadingState
+ plan: string
+ limits: LimitRow[]
+ /** A snapshot cannot be re-measured on demand (Grok): it needs a bigger margin before it is advice. */
+ snapshot: boolean
+ measuredAt: number
+ /** One short line for the card: why a figure is missing, or its age. Never contains a secret. */
+ status: string
+ /** The remedy, when there is one. */
+ help: string
+}
+
+export interface ProviderDeps {
+ home: string
+ platform: NodeJS.Platform
+ env: Record<string, string | undefined>
+ now(): number
+ /** Whole file as text, or null when missing or unreadable. */
+ readFile(path: string): Promise<string | null>
+ /** The last `bytes` of a file as text, or null. */
+ readTail(path: string, bytes: number): Promise<string | null>
+ /** Entry names, or [] when missing. */
+ listDir(path: string): Promise<string[]>
+ exists(path: string): Promise<boolean>
+ fetchJson(url: string, headers: Record<string, string>, timeoutMs: number): Promise<{ status: number; body: unknown }>
+ /** stdout, or null on any failure. Used only for the macOS keychain read. */
+ execFile(cmd: string, args: string[], timeoutMs: number): Promise<string | null>
+}
+
+const nameOf = (id: ProviderId): string => PROVIDERS.find((p) => p.id === id)!.name
+const reading = (id: ProviderId, state: ReadingState, extra: Partial<ProviderReading> = {}): ProviderReading =>
+ ({ id, name: nameOf(id), state, plan: '', limits: [], snapshot: false, measuredAt: 0, status: '', help: '', ...extra })
+const join = (...parts: string[]): string => parts.join('/').replace(/\/+/g, '/')
+const isoOrEmpty = (v: unknown): string => { const ms = resetMs(v); return ms ? new Date(ms).toISOString() : '' }
+
+/** A reset as epoch seconds, epoch ms, or ISO text. */
+function resetMs(v: unknown): number {
+ if (v === null || v === undefined || v === '') return 0
+ if (typeof v === 'number' || /^\d+$/.test(String(v).trim())) {
+ const n = Number(v)
+ if (!Number.isFinite(n) || n <= 0) return 0
+ return n < 1e12 ? n * 1000 : n
+ }
+ return parseIsoMs(v)
+}
+
+function asObj(v: unknown): Record<string, unknown> | null {
+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
+}
+
+// ── Claude ───────────────────────────────────────────────────────────────────────────────────────
+
+export const CLAUDE_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
+
+function claudePlan(tier: string, sub: string): string {
+ const m = /max_(\d+x)/i.exec(tier)
+ if (m) return `Max ${m[1]}`
+ return sub ? sub[0]!.toUpperCase() + sub.slice(1) : ''
+}
+
+export async function readClaude(deps: ProviderDeps): Promise<ProviderReading> {
+ const dir = deps.env.CLAUDE_CONFIG_DIR || join(deps.home, '.claude')
+ let raw = await deps.readFile(join(dir, '.credentials.json'))
+ if (!raw && deps.platform === 'darwin') raw = await deps.execFile('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], 5000)
+ let login: Record<string, unknown> | null = null
+ try { login = asObj(asObj(JSON.parse(raw ?? 'null'))?.claudeAiOauth) } catch { login = null }
+ const token = typeof login?.accessToken === 'string' ? login.accessToken : ''
+ if (!token) {
+ if (!(await deps.exists(dir))) return reading('claude', 'not-detected')
+ return reading('claude', 'not-configured', { status: 'No Claude Code login found', help: 'Run `claude` and sign in with a Claude subscription' })
+ }
+ const plan = claudePlan(String(login?.rateLimitTier ?? ''), String(login?.subscriptionType ?? ''))
+ let res: { status: number; body: unknown }
+ try {
+ res = await deps.fetchJson(CLAUDE_USAGE_URL, { Authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', Accept: 'application/json' }, 10_000)
+ } catch { res = { status: 0, body: null } }
+ if (res.status !== 200) {
+ const why = res.status === 0 || res.status >= 599 ? 'could not reach Anthropic' : `usage endpoint returned ${res.status}`
+ return reading('claude', 'error', { plan, status: `Claude ${why}`, help: res.status === 401 ? 'Run `claude` and sign in again' : '' })
+ }
+ const body = asObj(res.body) ?? {}
+ const weekly = asObj(body.seven_day_oauth_apps) ?? asObj(body.seven_day)
+ const session = asObj(body.five_hour)
+ // One payload speaks one convention: any value >= 1 means the whole payload is percent-scaled.
+ const rawVals = [session?.utilization, weekly?.utilization].map((v) => Number(v))
+ const percentScale = rawVals.some((v) => v >= 1)
+ const norm = (v: unknown): number => {
+ const n = Number(v)
+ if (!(n >= 0)) return -1
+ return Math.min(1, percentScale || n > 1 ? n / 100 : n)
+ }
+ const limits: LimitRow[] = []
+ if (session && norm(session.utilization) >= 0) limits.push({ label: 'Session (5-hour)', percent: norm(session.utilization), resetsAt: isoOrEmpty(session.resets_at) })
+ if (weekly && norm(weekly.utilization) >= 0) limits.push({ label: 'Weekly (7-day)', percent: norm(weekly.utilization), resetsAt: isoOrEmpty(weekly.resets_at) })
+ if (!limits.length) return reading('claude', 'error', { plan, status: 'Anthropic returned no limits' })
+ return reading('claude', 'ok', { plan, limits, measuredAt: deps.now() })
+}
+
+// ── Codex ────────────────────────────────────────────────────────────────────────────────────────
+
+const CODEX_TAIL_BYTES = 512 * 1024
+const CODEX_FILES_TO_TRY = 6
+
+function codexLabel(mins: number): string {
+ if (mins === 10080) return 'Weekly (7-day)'
+ if (mins === 300) return 'Session (5-hour)'
+ if (mins && mins % 1440 === 0) return `${mins / 1440}-day window`
+ if (mins && mins % 60 === 0) return `${mins / 60}-hour window`
+ return mins ? `${mins}m window` : 'Limit'
+}
+
+/** The newest rollout files, newest first, walking YYYY/MM/DD in descending order. */
+async function newestRollouts(deps: ProviderDeps, root: string, want: number): Promise<string[]> {
+ const out: string[] = []
+ const desc = (xs: string[]) => xs.filter((x) => /^\d+$/.test(x)).sort((a, b) => Number(b) - Number(a))
+ for (const y of desc(await deps.listDir(root))) {
+ for (const m of desc(await deps.listDir(join(root, y)))) {
+ for (const d of desc(await deps.listDir(join(root, y, m)))) {
+ const files = (await deps.listDir(join(root, y, m, d))).filter((f) => f.startsWith('rollout-') && f.endsWith('.jsonl')).sort().reverse()
+ for (const f of files) { out.push(join(root, y, m, d, f)); if (out.length >= want) return out }
+ }
+ }
+ }
+ return out
+}
+
+export async function readCodex(deps: ProviderDeps): Promise<ProviderReading> {
+ const home = deps.env.CODEX_HOME || join(deps.home, '.codex')
+ const root = join(home, 'sessions')
+ if (!(await deps.exists(root))) return reading('codex', 'not-detected')
+ // Rollout names sort by start time, but a long session keeps writing into an older file, so the
+ // newest few are all read and the snapshot with the latest timestamp wins.
+ let best: { at: number; rl: Record<string, unknown> } | null = null
+ for (const file of await newestRollouts(deps, root, CODEX_FILES_TO_TRY)) {
+ const text = await deps.readTail(file, CODEX_TAIL_BYTES)
+ if (!text) continue
+ const lines = text.split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const line = lines[i]!
+ if (!line.includes('"rate_limits"')) continue
+ let obj: Record<string, unknown> | null
+ try { obj = asObj(JSON.parse(line)) } catch { continue }
+ const rl = asObj(asObj(obj?.payload)?.rate_limits) ?? asObj(obj?.rate_limits)
+ if (!rl || !asObj(rl.primary)) continue
+ const at = parseIsoMs(obj?.timestamp)
+ if (!best || at > best.at) best = { at, rl }
+ break
+ }
+ }
+ if (!best) return reading('codex', 'not-configured', { status: 'No Codex rate-limit snapshot yet', help: 'Run one Codex turn signed in with a ChatGPT plan' })
+ const limits: LimitRow[] = []
+ for (const key of ['primary', 'secondary']) {
+ const w = asObj(best.rl[key])
+ if (!w || w.used_percent === undefined || w.used_percent === null) continue
+ let resets = resetMs(w.resets_at)
+ // Older Codex builds wrote a relative reset; anchor it to the line's own timestamp.
+ if (!resets && Number(w.resets_in_seconds) > 0 && best.at) resets = best.at + Number(w.resets_in_seconds) * 1000
+ limits.push({ label: codexLabel(Number(w.window_minutes) || 0), percent: normPercent(Number(w.used_percent) / 100), resetsAt: resets ? new Date(resets).toISOString() : '' })
+ }
+ // Weekly first, so the card judges the plan by its week.
+ limits.sort((a, b) => (/^weekly/i.test(b.label) ? 1 : 0) - (/^weekly/i.test(a.label) ? 1 : 0))
+ const plan = typeof best.rl.plan_type === 'string' ? best.rl.plan_type : ''
+ const open = limits.some((l) => parseIsoMs(l.resetsAt) > deps.now())
+ return reading('codex', 'ok', {
+ plan, limits, measuredAt: best.at,
+ status: open ? '' : 'Codex window has reset since the last turn; run Codex to refresh',
+ })
+}
+
+// ── Grok ─────────────────────────────────────────────────────────────────────────────────────────
+
+const GROK_TAIL_BYTES = 8 * 1024 * 1024
+const GROK_MARK = 'billing: fetched credits config'
+
+export async function readGrok(deps: ProviderDeps): Promise<ProviderReading> {
+ const home = deps.env.GROK_HOME || join(deps.home, '.grok')
+ if (!(await deps.exists(home))) return reading('grok', 'not-detected')
+ const text = await deps.readTail(join(home, 'logs', 'unified.jsonl'), GROK_TAIL_BYTES)
+ let latest: { config: Record<string, unknown>; tier: string; at: number } | null = null
+ for (const line of (text ?? '').split('\n')) {
+ if (!line.includes(GROK_MARK)) continue
+ let e: Record<string, unknown> | null
+ try { e = asObj(JSON.parse(line)) } catch { continue }
+ if (!e || e.msg !== GROK_MARK) continue
+ const ctx = asObj(e.ctx)
+ const config = asObj(ctx?.config)
+ if (!config) continue
+ latest = { config, tier: typeof ctx?.subscriptionTier === 'string' ? ctx.subscriptionTier : '', at: parseIsoMs(e.ts) }
+ }
+ if (!latest) return reading('grok', 'not-configured', { snapshot: true, status: 'No Grok billing snapshot yet', help: 'Start Grok once while signed in' })
+ const period = asObj(latest.config.currentPeriod) ?? {}
+ const end = isoOrEmpty(period.end ?? latest.config.billingPeriodEnd)
+ const start = isoOrEmpty(period.start ?? latest.config.billingPeriodStart)
+ const raw = latest.config.creditUsagePercent
+ // Grok logs 0..100. A config without the figure is unknown, not a confident 0%.
+ const percent = raw === undefined || raw === null || typeof raw === 'boolean' ? -1 : normPercent(Number(raw) / 100)
+ const row: LimitRow = { label: 'Weekly (7-day)', percent, resetsAt: end }
+ if (start) row.startsAt = start
+ const open = !end || parseIsoMs(end) > deps.now()
+ return reading('grok', 'ok', {
+ plan: latest.tier, limits: [row], snapshot: true, measuredAt: latest.at,
+ status: open ? '' : 'Grok window has reset since the last snapshot; start Grok to refresh',
+ })
+}
+
+// ── Kimi ─────────────────────────────────────────────────────────────────────────────────────────
+
+export const KIMI_DEFAULT_BASE = 'https://api.kimi.com/coding/v1'
+
+/** KEY from the environment, else a KEY= line in ~/.env. Only the named keys are ever looked at. */
+async function envOrDotenv(deps: ProviderDeps, key: string): Promise<string> {
+ const v = (deps.env[key] ?? '').trim()
+ if (v) return v
+ const text = await deps.readFile(join(deps.home, '.env'))
+ for (const raw of (text ?? '').split('\n')) {
+ const line = raw.trim().replace(/^export\s+/, '')
+ if (line.startsWith(`${key}=`)) return line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '')
+ }
+ return ''
+}
+
+function kimiWindowLabel(w: Record<string, unknown> | null): string {
+ let n = Number(w?.duration) || 0
+ let unit = String(w?.timeUnit ?? '').replace('TIME_UNIT_', '').toLowerCase()
+ if (n <= 0 || !unit) return ''
+ if (unit === 'minute' && n % 60 === 0) { n /= 60; unit = 'hour' }
+ return `${n}-${unit}`
+}
+
+/** Burn Bar's rows from Kimi's /usages: the request window binds the session; the month is the budget. */
+export function kimiLimitsFromUsages(raw: unknown): LimitRow[] {
+ const body = asObj(raw) ?? {}
+ const out: LimitRow[] = []
+ const seen = new Set<string>()
+ for (const entry of Array.isArray(body.limits) ? body.limits : []) {
+ const e = asObj(entry)
+ const label = kimiWindowLabel(asObj(e?.window))
+ const detail = asObj(e?.detail) ?? {}
+ const limit = Number(detail.limit) || 0
+ const used = Number(detail.used) || 0
+ if (!label || limit <= 0) continue
+ seen.add(label)
+ out.push({ label: `Session (${label})`, percent: Math.max(0, Math.min(1, used / limit)), resetsAt: isoOrEmpty(detail.resetTime) })
+ }
+ const names: Array<[string, string, string]> = [['limit_5h', 'Session (5-hour)', '5-hour'], ['limit_month_total', 'Monthly (total)', ''], ['limit_month_code', 'Monthly (code)', '']]
+ const usages = asObj(body.usages) ?? {}
+ for (const [key, label, span] of names) {
+ const e = asObj(usages[key])
+ if (!e || (span && seen.has(span))) continue
+ const ratio = Number(e.used_ratio)
+ if (!Number.isFinite(ratio)) continue
+ out.push({ label, percent: Math.max(0, Math.min(1, ratio)), resetsAt: isoOrEmpty(e.reset_time) })
+ }
+ return out
+}
+
+export async function readKimi(deps: ProviderDeps): Promise<ProviderReading> {
+ const key = await envOrDotenv(deps, 'KIMI_API_KEY')
+ if (!key) return reading('kimi', 'not-detected')
+ const base = ((await envOrDotenv(deps, 'KIMI_BASE_URL')) || KIMI_DEFAULT_BASE).replace(/\/+$/, '')
+ // The key never travels in clear text, except to this machine itself.
+ if (!/^https:\/\//.test(base) && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${base}/`)) {
+ return reading('kimi', 'error', { status: 'KIMI_BASE_URL must be https', help: 'Fix KIMI_BASE_URL' })
+ }
+ let res: { status: number; body: unknown }
+ try { res = await deps.fetchJson(`${base}/usages`, { Authorization: `Bearer ${key}`, Accept: 'application/json' }, 8000) } catch { res = { status: 0, body: null } }
+ if (res.status !== 200) {
+ const why = res.status === 0 || res.status >= 599 ? 'could not reach Kimi' : `usages endpoint returned ${res.status}`
+ return reading('kimi', 'error', { status: `Kimi ${why}`, help: res.status === 401 ? 'Check KIMI_API_KEY' : '' })
+ }
+ const limits = kimiLimitsFromUsages(res.body)
+ if (!limits.length) return reading('kimi', 'error', { status: 'Kimi returned no limits' })
+ return reading('kimi', 'ok', { limits, measuredAt: deps.now() })
+}
+
+export const READERS: Record<ProviderId, (deps: ProviderDeps) => Promise<ProviderReading>> = {
+ claude: readClaude, codex: readCodex, grok: readGrok, kimi: readKimi,
+}
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 4530b007b..987044f48 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -833,3 +833,13 @@ describe('fleet controls: /api/attention, /api/stop-all, /api/fleet', () => {
expect((await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({}) })).status).toBe(400)
})
})
+
+describe('fleet controls: /api/subscriptions', () => {
+ it('serves the plans when wired, and says unavailable otherwise', async () => {
+ const { base } = await start({ onSubscriptions: async () => ({ subs: [{ id: 'claude', used: 0.4 }] }) })
+ expect(await (await fetch(`${base}/api/subscriptions?force=0`)).json()).toEqual({ subs: [{ id: 'claude', used: 0.4 }] })
+ server?.close()
+ const bare = await start()
+ expect((await fetch(`${bare.base}/api/subscriptions`)).status).toBe(503)
+ })
+})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 9e8c24336..162a391f5 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -119,6 +119,8 @@ export interface HookServerHandlers {
}) => void | GateVerdict | Promise<void | GateVerdict>
/** GET /api/attention: every agent's attention state for the bar widget and other local readers. */
onAttention?: () => unknown
+ /** GET /api/subscriptions: every plan's weekly used, banked, reset and the next-plan verdict. */
+ onSubscriptions?: () => Promise<unknown>
/** POST /api/stop-all: cancel every agent's turn except one (the panic stop). */
onStopAll?: (exceptAgentId: string | null) => Promise<{ cancelled: string[] }>
/** POST /api/fleet {action, ...args}: the local command surface behind the fleet `harness` commands. */
@@ -512,6 +514,11 @@ export function startHookServer(
if (req.method === 'GET' && url === '/api/attention') {
json(200, handlers.onAttention ? handlers.onAttention() : { agents: [] }); return
}
+ if (req.method === 'GET' && (url === '/api/subscriptions' || url.startsWith('/api/subscriptions?'))) {
+ if (!handlers.onSubscriptions) { json(503, { error: 'UNAVAILABLE' }); return }
+ try { json(200, await handlers.onSubscriptions()) } catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }
+ return
+ }
// Panic stop: every agent's turn is cancelled except the one named. Mutating, so the same
// same-origin guard as the other local mutations.
if (req.method === 'POST' && url === '/api/stop-all') {
diff --git a/cli/src/lib/machineCapabilities.spec.ts b/cli/src/lib/machineCapabilities.spec.ts
new file mode 100644
index 000000000..fc8f2de66
--- /dev/null
+++ b/cli/src/lib/machineCapabilities.spec.ts
@@ -0,0 +1,109 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+import { describe, expect, it } from 'vitest'
+import {
+ decidePlacement, describeCapabilities, parseNvidiaSmi, readMachineCapabilities,
+ type CapabilityReaders, type MachineCapabilities,
+} from './machineCapabilities.js'
+
+function readers(over: Partial<CapabilityReaders> & { files?: Record<string, string>; dirs?: Record<string, string[]> } = {}): CapabilityReaders {
+ const files = over.files ?? {}
+ const dirs = over.dirs ?? {}
+ return {
+ nvidiaSmi: over.nvidiaSmi ?? (async () => { throw new Error('no nvidia-smi') }),
+ readFile: over.readFile ?? (async (p) => { if (p in files) return files[p]!; throw new Error('ENOENT ' + p) }),
+ listDir: over.listDir ?? (async (p) => { if (p in dirs) return dirs[p]!; throw new Error('ENOENT ' + p) }),
+ which: over.which ?? (async (c) => c === 'git'),
+ hostname: over.hostname ?? (() => 'testbox'),
+ loadavg: over.loadavg ?? (() => [0.5, 0.4, 0.3]),
+ cores: over.cores ?? (() => 8),
+ now: over.now ?? (() => 1700000000000),
+ }
+}
+
+describe('parseNvidiaSmi', () => {
+ it('parses one line per card and tolerates blanks', () => {
+ const out = parseNvidiaSmi('NVIDIA GeForce RTX 5070 Laptop GPU, 12227, 1834, 7\n\n')
+ expect(out).toEqual([{ name: 'NVIDIA GeForce RTX 5070 Laptop GPU', vramTotalMb: 12227, vramUsedMb: 1834, utilizationPct: 7 }])
+ })
+ it('returns an empty list for empty output', () => {
+ expect(parseNvidiaSmi('')).toEqual([])
+ })
+})
+
+describe('readMachineCapabilities', () => {
+ it('reads GPU, power, thermal, lid and toolchains from injected readers', async () => {
+ const caps = await readMachineCapabilities(readers({
+ nvidiaSmi: async () => 'RTX 4050, 6141, 512, 3',
+ dirs: { '/sys/class/power_supply': ['AC', 'BAT1'], '/sys/class/thermal': ['thermal_zone0', 'cooling_device0'], '/proc/acpi/button/lid': ['LID0'] },
+ files: {
+ '/sys/class/power_supply/AC/type': 'Mains\n', '/sys/class/power_supply/AC/online': '0\n',
+ '/sys/class/power_supply/BAT1/type': 'Battery\n', '/sys/class/power_supply/BAT1/capacity': '42\n', '/sys/class/power_supply/BAT1/status': 'Discharging\n',
+ '/sys/class/thermal/thermal_zone0/temp': '67000\n',
+ '/proc/acpi/button/lid/LID0/state': 'state: closed\n',
+ },
+ }))
+ expect(caps.gpus[0]?.vramUsedMb).toBe(512)
+ expect(caps.power).toEqual({ onAc: false, batteryPct: 42 })
+ expect(caps.thermal.maxC).toBe(67)
+ expect(caps.lid).toBe('closed')
+ expect(caps.toolchains.git).toBe(true)
+ expect(caps.toolchains.flutter).toBe(false)
+ expect(caps.hostname).toBe('testbox')
+ })
+ it('degrades to no GPU, AC, unknown lid on a headless box without sysfs entries', async () => {
+ const caps = await readMachineCapabilities(readers())
+ expect(caps.gpus).toEqual([])
+ expect(caps.power).toEqual({ onAc: true, batteryPct: null })
+ expect(caps.thermal.maxC).toBeNull()
+ expect(caps.lid).toBe('unknown')
+ })
+})
+
+const base: MachineCapabilities = {
+ at: 0, hostname: 'gus', cpu: { cores: 24, load1: 2, load5: 2 },
+ gpus: [{ name: 'RTX 5070', vramTotalMb: 12227, vramUsedMb: 2000, utilizationPct: 5 }],
+ power: { onAc: true, batteryPct: 100 }, thermal: { maxC: 55 }, lid: 'open',
+ toolchains: { git: true, node: true, flutter: false },
+}
+
+describe('decidePlacement', () => {
+ it('accepts an empty request on a healthy machine', () => {
+ expect(decidePlacement(base, {})).toEqual({ ok: true, reasons: [] })
+ })
+ it('refuses GPU work on a busy card and says why', () => {
+ const busy = { ...base, gpus: [{ ...base.gpus[0]!, utilizationPct: 85 }] }
+ const d = decidePlacement(busy, { needsGpu: true })
+ expect(d.ok).toBe(false)
+ expect(d.reasons).toEqual(['GPU busy at 85%'])
+ })
+ it('refuses when free VRAM is under the minimum', () => {
+ const d = decidePlacement(base, { needsGpu: true, minFreeVramMb: 11000 })
+ expect(d.reasons[0]).toMatch(/10227 MB free, needs 11000 MB/)
+ })
+ it('refuses GPU work where there is no GPU', () => {
+ expect(decidePlacement({ ...base, gpus: [] }, { needsGpu: true }).reasons).toEqual(['no GPU on this machine'])
+ })
+ it('refuses batch work on battery unless allowed, and a closed lid on a laptop', () => {
+ const laptop = { ...base, power: { onAc: false, batteryPct: 30 }, lid: 'closed' as const }
+ expect(decidePlacement(laptop, {}).reasons).toEqual(['on battery', 'lid closed on a laptop'])
+ expect(decidePlacement(laptop, { allowOnBattery: true, allowLidClosed: true }).ok).toBe(true)
+ })
+ it('lets interactive work through a closed lid (external monitor) but not battery', () => {
+ const laptop = { ...base, power: { onAc: false, batteryPct: 30 }, lid: 'closed' as const }
+ expect(decidePlacement(laptop, { interactive: true }).reasons).toEqual(['on battery'])
+ })
+ it('flags CPU overload, heat and missing toolchains', () => {
+ const hot = { ...base, cpu: { cores: 4, load1: 9, load5: 8 }, thermal: { maxC: 95 } }
+ const d = decidePlacement(hot, { toolchains: ['flutter', 'git'] })
+ expect(d.reasons).toEqual(['CPU load 9.0 over 4 cores', 'thermal 95C', 'missing flutter'])
+ })
+})
+
+describe('describeCapabilities', () => {
+ it('renders one line', () => {
+ expect(describeCapabilities(base)).toBe('gus: RTX 5070 10227/12227MB free 5%, load 2.0/24, AC 55C, lid open')
+ expect(describeCapabilities({ ...base, gpus: [], power: { onAc: false, batteryPct: 12 }, thermal: { maxC: null } }))
+ .toBe('gus: no GPU, load 2.0/24, battery 12%, lid open')
+ })
+})
diff --git a/cli/src/lib/machineCapabilities.ts b/cli/src/lib/machineCapabilities.ts
new file mode 100644
index 000000000..081291baa
--- /dev/null
+++ b/cli/src/lib/machineCapabilities.ts
@@ -0,0 +1,168 @@
+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
+
+import { execFile } from 'node:child_process'
+import { promises as fs } from 'node:fs'
+import { cpus, loadavg } from 'node:os'
+
+/**
+ * What this machine can take right now: GPU memory and load, CPU load, power source, thermal
+ * headroom, lid state and which toolchains are on PATH. Read on demand, never cached for long,
+ * because the whole point is to refuse work on a card that just got busy or a laptop that just
+ * went to battery. Every reader is injectable so the placement rules are testable without a GPU.
+ */
+export interface GpuCapability {
+ name: string
+ vramTotalMb: number
+ vramUsedMb: number
+ utilizationPct: number
+}
+
+export interface MachineCapabilities {
+ at: number
+ hostname: string
+ cpu: { cores: number; load1: number; load5: number }
+ gpus: GpuCapability[]
+ power: { onAc: boolean; batteryPct: number | null }
+ thermal: { maxC: number | null }
+ lid: 'open' | 'closed' | 'unknown'
+ toolchains: Record<string, boolean>
+}
+
+export interface CapabilityReaders {
+ nvidiaSmi: () => Promise<string>
+ readFile: (path: string) => Promise<string>
+ listDir: (path: string) => Promise<string[]>
+ which: (cmd: string) => Promise<boolean>
+ hostname: () => string
+ loadavg: () => number[]
+ cores: () => number
+ now: () => number
+}
+
+export const TOOLCHAINS_TO_PROBE = ['node', 'python3', 'git', 'gh', 'tmux', 'flutter', 'qs', 'docker', 'cargo', 'bun', 'uv']
+
+const run = (cmd: string, args: string[], timeout = 3000): Promise<string> =>
+ new Promise((resolve, reject) => {
+ execFile(cmd, args, { timeout, maxBuffer: 1 << 20 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout))))
+ })
+
+export const systemReaders: CapabilityReaders = {
+ nvidiaSmi: () => run('nvidia-smi', ['--query-gpu=name,memory.total,memory.used,utilization.gpu', '--format=csv,noheader,nounits']),
+ readFile: (p) => fs.readFile(p, 'utf8'),
+ listDir: (p) => fs.readdir(p),
+ which: async (cmd) => { try { await run('sh', ['-c', `command -v ${cmd}`]); return true } catch { return false } },
+ hostname: () => process.env.HOSTNAME ?? require('node:os').hostname(),
+ loadavg,
+ cores: () => cpus().length,
+ now: () => Date.now(),
+}
+
+export function parseNvidiaSmi(csv: string): GpuCapability[] {
+ return csv.split('\n').map((l) => l.trim()).filter(Boolean).map((line) => {
+ const [name = '', total = '0', used = '0', util = '0'] = line.split(',').map((s) => s.trim())
+ return { name, vramTotalMb: Number(total) || 0, vramUsedMb: Number(used) || 0, utilizationPct: Number(util) || 0 }
+ })
+}
+
+async function readPower(r: CapabilityReaders): Promise<MachineCapabilities['power']> {
+ let onAc = true
+ let batteryPct: number | null = null
+ let supplies: string[] = []
+ try { supplies = await r.listDir('/sys/class/power_supply') } catch { return { onAc, batteryPct } }
+ for (const s of supplies) {
+ const base = `/sys/class/power_supply/${s}`
+ let type = ''
+ try { type = (await r.readFile(`${base}/type`)).trim() } catch { continue }
+ if (type === 'Mains') {
+ try { onAc = (await r.readFile(`${base}/online`)).trim() === '1' } catch { /* keep default */ }
+ } else if (type === 'Battery') {
+ try { batteryPct = Number((await r.readFile(`${base}/capacity`)).trim()) } catch { /* unknown */ }
+ // A battery that is discharging means no mains, even when no Mains supply is exposed.
+ try { if ((await r.readFile(`${base}/status`)).trim() === 'Discharging') onAc = false } catch { /* ignore */ }
+ }
+ }
+ return { onAc, batteryPct }
+}
+
+async function readThermal(r: CapabilityReaders): Promise<number | null> {
+ let zones: string[] = []
+ try { zones = await r.listDir('/sys/class/thermal') } catch { return null }
+ let max: number | null = null
+ for (const z of zones) {
+ if (!z.startsWith('thermal_zone')) continue
+ try {
+ const milli = Number((await r.readFile(`/sys/class/thermal/${z}/temp`)).trim())
+ if (Number.isFinite(milli)) max = Math.max(max ?? -Infinity, milli / 1000)
+ } catch { /* zone without a reading */ }
+ }
+ return max
+}
+
+async function readLid(r: CapabilityReaders): Promise<MachineCapabilities['lid']> {
+ let lids: string[] = []
+ try { lids = await r.listDir('/proc/acpi/button/lid') } catch { return 'unknown' }
+ for (const l of lids) {
+ try {
+ const state = await r.readFile(`/proc/acpi/button/lid/${l}/state`)
+ if (/closed/i.test(state)) return 'closed'
+ if (/open/i.test(state)) return 'open'
+ } catch { /* next lid */ }
+ }
+ return 'unknown'
+}
+
+export async function readMachineCapabilities(r: CapabilityReaders = systemReaders): Promise<MachineCapabilities> {
+ let gpus: GpuCapability[] = []
+ try { gpus = parseNvidiaSmi(await r.nvidiaSmi()) } catch { gpus = [] }
+ const [power, maxC, lid] = await Promise.all([readPower(r), readThermal(r), readLid(r)])
+ const toolchains: Record<string, boolean> = {}
+ await Promise.all(TOOLCHAINS_TO_PROBE.map(async (t) => { toolchains[t] = await r.which(t) }))
+ const [load1 = 0, load5 = 0] = r.loadavg()
+ return { at: r.now(), hostname: r.hostname(), cpu: { cores: r.cores(), load1, load5 }, gpus, power, thermal: { maxC }, lid, toolchains }
+}
+
+/** What a job asks of a machine. Everything optional: an empty request fits anywhere that is up. */
+export interface PlacementRequest {
+ needsGpu?: boolean
+ minFreeVramMb?: number
+ interactive?: boolean
+ allowOnBattery?: boolean
+ allowLidClosed?: boolean
+ maxLoadPerCore?: number
+ toolchains?: string[]
+}
+
+export interface PlacementDecision { ok: boolean; reasons: string[] }
+
+export const GPU_BUSY_UTILIZATION_PCT = 60
+export const HOT_C = 90
+
+/** Pure rule check: refuse work the machine should not take, and say exactly why. */
+export function decidePlacement(caps: MachineCapabilities, req: PlacementRequest): PlacementDecision {
+ const reasons: string[] = []
+ if (req.needsGpu) {
+ if (caps.gpus.length === 0) reasons.push('no GPU on this machine')
+ else {
+ const best = caps.gpus.reduce((a, b) => (b.vramTotalMb - b.vramUsedMb > a.vramTotalMb - a.vramUsedMb ? b : a))
+ const free = best.vramTotalMb - best.vramUsedMb
+ if (req.minFreeVramMb !== undefined && free < req.minFreeVramMb) reasons.push(`GPU has ${free} MB free, needs ${req.minFreeVramMb} MB`)
+ if (best.utilizationPct >= GPU_BUSY_UTILIZATION_PCT) reasons.push(`GPU busy at ${best.utilizationPct}%`)
+ }
+ }
+ if (!req.allowOnBattery && !caps.power.onAc) reasons.push('on battery')
+ if (!req.allowLidClosed && !req.interactive && caps.lid === 'closed' && caps.power.batteryPct !== null) reasons.push('lid closed on a laptop')
+ const perCore = caps.cpu.cores > 0 ? caps.cpu.load1 / caps.cpu.cores : 0
+ const maxLoad = req.maxLoadPerCore ?? 1.5
+ if (perCore > maxLoad) reasons.push(`CPU load ${caps.cpu.load1.toFixed(1)} over ${caps.cpu.cores} cores`)
+ if (caps.thermal.maxC !== null && caps.thermal.maxC >= HOT_C) reasons.push(`thermal ${caps.thermal.maxC.toFixed(0)}C`)
+ for (const t of req.toolchains ?? []) if (!caps.toolchains[t]) reasons.push(`missing ${t}`)
+ return { ok: reasons.length === 0, reasons }
+}
+
+/** Compact one-line summary for logs, the device and the bar. */
+export function describeCapabilities(c: MachineCapabilities): string {
+ const gpu = c.gpus[0] ? `${c.gpus[0].name} ${c.gpus[0].vramTotalMb - c.gpus[0].vramUsedMb}/${c.gpus[0].vramTotalMb}MB free ${c.gpus[0].utilizationPct}%` : 'no GPU'
+ const power = c.power.onAc ? 'AC' : `battery ${c.power.batteryPct ?? '?'}%`
+ const heat = c.thermal.maxC === null ? '' : ` ${c.thermal.maxC.toFixed(0)}C`
+ return `${c.hostname}: ${gpu}, load ${c.cpu.load1.toFixed(1)}/${c.cpu.cores}, ${power}${heat}, lid ${c.lid}`
+}