From 85304dbe307297d80f299bb012e58a6c52c1b37d Mon Sep 17 00:00:00 2001 From: BlairWelsh Date: Tue, 14 Apr 2026 13:33:06 +0100 Subject: [PATCH] feat: add multi-currency support Display costs in any of 162 ISO 4217 currencies. Exchange rates are fetched from frankfurter.app (ECB-backed, free, no API key) and cached for 24h alongside the existing LiteLLM pricing cache. Currency symbols and decimal rules come from Node's built-in Intl API rather than hardcoded tables. New command: codeburn config currency Reset: codeburn config currency --reset Config stored at ~/.config/codeburn/config.json. All internal calculations remain in USD -- conversion is display-only. --- src/cli.ts | 76 +++++++++++++++++- src/config.ts | 47 +++++++++++ src/currency.ts | 203 ++++++++++++++++++++++++++++++++++++++++++++++++ src/export.ts | 12 +-- src/format.ts | 10 +-- 5 files changed, 337 insertions(+), 11 deletions(-) create mode 100644 src/config.ts create mode 100644 src/currency.ts diff --git a/src/cli.ts b/src/cli.ts index bf3eaf6b..6e983e61 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -7,6 +7,8 @@ import { installMenubar, renderMenubarFormat, type PeriodData, type ProviderCost import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import { renderDashboard } from './dashboard.js' import { providers } from './providers/index.js' +import { readConfig, saveConfig, getConfigFilePath } from './config.js' +import { loadCurrency, getCurrency, isValidCurrencyCode } from './currency.js' function getDateRange(period: string): { range: DateRange; label: string } { const now = new Date() @@ -56,6 +58,12 @@ const program = new Command() .description('See where your AI coding tokens go - by task, tool, model, and project') .version('0.4.0') +// Load currency config before any command runs. +// If no currency is configured, this is a no-op and everything stays USD. +program.hook('preAction', async () => { + await loadCurrency() +}) + program .command('report', { isDefault: true }) .description('Interactive usage dashboard') @@ -130,7 +138,12 @@ program if (opts.format === 'json') { const todayData = buildPeriodData('today', await parseAllSessions(getDateRange('today').range, pf)) const monthData = buildPeriodData('month', await parseAllSessions(getDateRange('month').range, pf)) - console.log(JSON.stringify({ today: { cost: todayData.cost, calls: todayData.calls }, month: { cost: monthData.cost, calls: monthData.calls } })) + const { code, rate } = getCurrency() + console.log(JSON.stringify({ + currency: code, + today: { cost: Math.round(todayData.cost * rate * 100) / 100, calls: todayData.calls }, + month: { cost: Math.round(monthData.cost * rate * 100) / 100, calls: monthData.calls }, + })) return } @@ -203,4 +216,65 @@ program console.log(result) }) +// --- Config commands --- + +const configCmd = program + .command('config') + .description('View or set configuration') + +configCmd + .command('currency [code]') + .description('Set display currency (e.g. codeburn config currency AUD)') + .option('--symbol ', 'Override the currency symbol') + .option('--reset', 'Reset to USD (removes currency config)') + .action(async (code?: string, opts?: { symbol?: string; reset?: boolean }) => { + // Reset: remove currency from config + if (opts?.reset) { + const config = await readConfig() + delete config.currency + await saveConfig(config) + console.log('\n Currency reset to USD.\n') + return + } + + // Show: display current setting + if (!code) { + const { code: activeCode, rate, symbol } = getCurrency() + if (activeCode === 'USD' && rate === 1) { + console.log('\n Currency: USD (default)') + console.log(` Config: ${getConfigFilePath()}\n`) + } else { + console.log(`\n Currency: ${activeCode}`) + console.log(` Symbol: ${symbol}`) + console.log(` Rate: 1 USD = ${rate} ${activeCode}`) + console.log(` Config: ${getConfigFilePath()}\n`) + } + return + } + + // Set: validate and save + const upperCode = code.toUpperCase() + if (!isValidCurrencyCode(upperCode)) { + console.error(`\n "${code}" is not a valid ISO 4217 currency code.\n`) + process.exitCode = 1 + return + } + + const config = await readConfig() + config.currency = { + code: upperCode, + ...(opts?.symbol ? { symbol: opts.symbol } : {}), + } + await saveConfig(config) + + // Load the currency to fetch the rate and confirm it works + await loadCurrency() + const { rate, symbol } = getCurrency() + + console.log(`\n Currency set to ${upperCode}.`) + console.log(` Symbol: ${symbol}`) + console.log(` Rate: 1 USD = ${rate} ${upperCode}`) + console.log(` Config saved to ${getConfigFilePath()}\n`) + }) + program.parse() diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 00000000..15094988 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,47 @@ +/** + * Generic config file management for ~/.config/codeburn/config.json. + * + * This module handles reading and writing the config file only. + * Feature-specific logic (e.g. currency) lives in its own module + * and imports from here. + */ + +import { readFile, writeFile, mkdir } from 'fs/promises' +import { join } from 'path' +import { homedir } from 'os' + +export type CodeburnConfig = { + currency?: { + code: string + symbol?: string // optional override, otherwise resolved via Intl + } +} + +function getConfigDir(): string { + return join(homedir(), '.config', 'codeburn') +} + +function getConfigPath(): string { + return join(getConfigDir(), 'config.json') +} + +/** Reads the config file. Returns an empty object if the file is missing or invalid. */ +export async function readConfig(): Promise { + try { + const raw = await readFile(getConfigPath(), 'utf-8') + return JSON.parse(raw) as CodeburnConfig + } catch { + return {} + } +} + +/** Writes the config to disk, creating ~/.config/codeburn/ if needed. */ +export async function saveConfig(config: CodeburnConfig): Promise { + await mkdir(getConfigDir(), { recursive: true }) + await writeFile(getConfigPath(), JSON.stringify(config, null, 2) + '\n', 'utf-8') +} + +/** Returns the absolute path to the config file (for display in CLI output). */ +export function getConfigFilePath(): string { + return getConfigPath() +} diff --git a/src/currency.ts b/src/currency.ts new file mode 100644 index 00000000..cfb27807 --- /dev/null +++ b/src/currency.ts @@ -0,0 +1,203 @@ +/** + * Currency conversion and formatting. + * + * All internal cost data is USD (from Anthropic API pricing). This module + * handles converting and formatting those values for display in the user's + * preferred currency. + * + * Currency symbols and decimal rules come from Node's built-in Intl API + * (ISO 4217), so no hardcoded tables or external dependencies are needed. + * + * Exchange rates are fetched from frankfurter.app (free, no API key, ECB-backed) + * and cached for 24 hours at ~/.cache/codeburn/exchange-rate.json -- the same + * pattern used for LiteLLM pricing in models.ts. + */ + +import { readFile, writeFile, mkdir } from 'fs/promises' +import { join } from 'path' +import { homedir } from 'os' + +import { readConfig } from './config.js' + +type CurrencyState = { + code: string + rate: number + symbol: string +} + +const CACHE_TTL_MS = 24 * 60 * 60 * 1000 +const FRANKFURTER_URL = 'https://api.frankfurter.app/latest?from=USD&to=' + +// Default state: USD passthrough (rate=1, no conversion applied). +// Overwritten by loadCurrency() if the user has configured a currency. +let active: CurrencyState = { code: 'USD', rate: 1, symbol: '$' } + +// --------------------------------------------------------------------------- +// Intl-based currency helpers +// --------------------------------------------------------------------------- +// Node's Intl API knows all 162 ISO 4217 currencies: symbols, decimal places, +// and code validation. Using it avoids hardcoded lookup tables that go stale. + +/** + * Validates a currency code against ISO 4217. + * Used by the CLI command to reject invalid input before saving config. + */ +export function isValidCurrencyCode(code: string): boolean { + try { + new Intl.NumberFormat('en', { style: 'currency', currency: code }) + return true + } catch { + return false + } +} + +/** + * Resolves the display symbol for a currency code via Intl. + * Uses 'symbol' display (not 'narrowSymbol') so that dollar-based currencies + * get distinguishing prefixes: AUD -> "A$", CAD -> "CA$", USD -> "$". + */ +function resolveSymbol(code: string): string { + const parts = new Intl.NumberFormat('en', { + style: 'currency', + currency: code, + currencyDisplay: 'symbol', + }).formatToParts(0) + return parts.find(p => p.type === 'currency')?.value ?? code +} + +/** + * Returns the standard number of decimal places for a currency. + * Most currencies return 2 (USD, EUR, GBP). JPY and KRW return 0. + * Drives rounding in both formatCost() and convertCost(). + */ +function getFractionDigits(code: string): number { + return new Intl.NumberFormat('en', { + style: 'currency', + currency: code, + }).resolvedOptions().maximumFractionDigits +} + +// --------------------------------------------------------------------------- +// Exchange rate fetching and caching +// --------------------------------------------------------------------------- +// Mirrors the cache pattern in models.ts (loadPricing / loadCachedPricing): +// try cache first, fetch on miss, fall back to defaults on failure. + +function getCacheDir(): string { + return join(homedir(), '.cache', 'codeburn') +} + +function getRateCachePath(): string { + return join(getCacheDir(), 'exchange-rate.json') +} + +async function fetchRate(code: string): Promise { + const response = await fetch(`${FRANKFURTER_URL}${code}`) + if (!response.ok) throw new Error(`HTTP ${response.status}`) + const data = await response.json() as { rates: Record } + const rate = data.rates[code] + if (!rate) throw new Error(`No rate returned for ${code}`) + return rate +} + +async function loadCachedRate(code: string): Promise { + try { + const raw = await readFile(getRateCachePath(), 'utf-8') + const cached = JSON.parse(raw) as { timestamp: number; code: string; rate: number } + // Invalidate if the user switched currencies or the cache expired + if (cached.code !== code) return null + if (Date.now() - cached.timestamp > CACHE_TTL_MS) return null + return cached.rate + } catch { + return null + } +} + +async function cacheRate(code: string, rate: number): Promise { + await mkdir(getCacheDir(), { recursive: true }) + await writeFile(getRateCachePath(), JSON.stringify({ timestamp: Date.now(), code, rate })) +} + +async function getExchangeRate(code: string): Promise { + if (code === 'USD') return 1 + + const cached = await loadCachedRate(code) + if (cached) return cached + + try { + const rate = await fetchRate(code) + await cacheRate(code, rate) + return rate + } catch { + // API unreachable and no cache -- fall back to no conversion. + // The tool still works, it just shows USD values. + return 1 + } +} + +// --------------------------------------------------------------------------- +// Lifecycle +// --------------------------------------------------------------------------- + +/** + * Loads currency config and fetches the exchange rate. + * Called once at CLI startup via a Commander preAction hook in cli.ts. + * If no currency is configured, this is a no-op and everything stays USD. + */ +export async function loadCurrency(): Promise { + const config = await readConfig() + if (!config.currency) return + + const code = config.currency.code.toUpperCase() + const rate = await getExchangeRate(code) + const symbol = config.currency.symbol ?? resolveSymbol(code) + + active = { code, rate, symbol } +} + +// --------------------------------------------------------------------------- +// Accessors -- used by format.ts, export.ts, cli.ts, and dashboard/menubar +// --------------------------------------------------------------------------- + +/** Returns the active currency state (code, rate, and symbol). */ +export function getCurrency(): CurrencyState { + return active +} + +/** Returns a dynamic column header like "Cost (AUD)" for use in CSV/JSON exports. */ +export function getCostColumnHeader(): string { + return `Cost (${active.code})` +} + +/** + * Converts a USD cost to the active currency, rounded to the correct + * number of decimal places. Used in exports where a raw number is needed + * rather than a formatted string. + */ +export function convertCost(costUSD: number): number { + const digits = getFractionDigits(active.code) + const factor = 10 ** digits + return Math.round(costUSD * active.rate * factor) / factor +} + +/** + * Formats a USD cost for display in the active currency. + * + * Uses adaptive precision so small values stay readable: + * >= 1 -> 2 decimal places (A$4.59) + * >= 0.01 -> 3 decimal places (A$0.123) + * < 0.01 -> 4 decimal places (A$0.0034) + * + * Zero-decimal currencies (JPY, KRW) are rounded to whole numbers. + */ +export function formatCost(costUSD: number): string { + const { rate, symbol, code } = active + const cost = costUSD * rate + const digits = getFractionDigits(code) + + if (digits === 0) return `${symbol}${Math.round(cost)}` + + if (cost >= 1) return `${symbol}${cost.toFixed(2)}` + if (cost >= 0.01) return `${symbol}${cost.toFixed(3)}` + return `${symbol}${cost.toFixed(4)}` +} diff --git a/src/export.ts b/src/export.ts index 57af0d72..5239ee0a 100644 --- a/src/export.ts +++ b/src/export.ts @@ -1,6 +1,8 @@ import { writeFile } from 'fs/promises' import { resolve } from 'path' + import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js' +import { getCostColumnHeader, convertCost } from './currency.js' function escCsv(s: string): string { if (s.includes(',') || s.includes('"') || s.includes('\n')) { @@ -32,7 +34,7 @@ function buildDailyRows(projects: ProjectSummary[]): Array ({ Date: date, - 'Cost (USD)': Math.round(d.cost * 100) / 100, + [getCostColumnHeader()]: convertCost(d.cost), 'API Calls': d.calls, 'Input Tokens': d.input, 'Output Tokens': d.output, @@ -56,7 +58,7 @@ function buildActivityRows(projects: ProjectSummary[]): Array b.cost - a.cost) .map(([cat, d]) => ({ Activity: CATEGORY_LABELS[cat as TaskCategory] ?? cat, - 'Cost (USD)': Math.round(d.cost * 100) / 100, + [getCostColumnHeader()]: convertCost(d.cost), Turns: d.turns, })) } @@ -78,7 +80,7 @@ function buildModelRows(projects: ProjectSummary[]): Array b.cost - a.cost) .map(([model, d]) => ({ Model: model, - 'Cost (USD)': Math.round(d.cost * 100) / 100, + [getCostColumnHeader()]: convertCost(d.cost), 'API Calls': d.calls, 'Input Tokens': d.input, 'Output Tokens': d.output, @@ -116,7 +118,7 @@ function buildBashRows(projects: ProjectSummary[]): Array> { return projects.map(p => ({ Project: p.projectPath, - 'Cost (USD)': Math.round(p.totalCostUSD * 100) / 100, + [getCostColumnHeader()]: convertCost(p.totalCostUSD), 'API Calls': p.totalApiCalls, Sessions: p.sessions.length, })) @@ -141,7 +143,7 @@ function buildSummaryRow(period: PeriodExport): Record const cost = period.projects.reduce((s, p) => s + p.totalCostUSD, 0) const calls = period.projects.reduce((s, p) => s + p.totalApiCalls, 0) const sessions = period.projects.reduce((s, p) => s + p.sessions.length, 0) - return { Period: period.label, 'Cost (USD)': Math.round(cost * 100) / 100, 'API Calls': calls, Sessions: sessions } + return { Period: period.label, [getCostColumnHeader()]: convertCost(cost), 'API Calls': calls, Sessions: sessions } } export async function exportCsv(periods: PeriodExport[], outputPath: string): Promise { diff --git a/src/format.ts b/src/format.ts index 201b7981..493d4e67 100644 --- a/src/format.ts +++ b/src/format.ts @@ -1,11 +1,11 @@ import chalk from 'chalk' import type { ProjectSummary } from './types.js' -export function formatCost(cost: number): string { - if (cost >= 1) return `$${cost.toFixed(2)}` - if (cost >= 0.01) return `$${cost.toFixed(3)}` - return `$${cost.toFixed(4)}` -} +// Re-exported from currency.ts so existing imports from './format.js' keep working. +// The currency-aware version applies exchange rate and symbol automatically. +// Imported locally too since renderStatusBar below uses it directly. +import { formatCost } from './currency.js' +export { formatCost } export function formatTokens(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`