mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
feat(cli): track local-model cost savings against a paid baseline (#421)
Add a new `localModelSavings` config and `codeburn model-savings` CLI that maps a local-model name (e.g. llama3.1:8b) to a paid baseline (e.g. gpt-4o). The local call still costs $0; the new `savingsUSD` field tracks the counterfactual spend avoided by running locally and is reported separately from `costUSD` everywhere a number is shown. * Parser normalization (`applyLocalModelSavings`) runs on Claude parse, direct provider calls, and the cached-call path. It forces `costUSD` to 0 and attaches `savingsUSD` + `savingsBaselineModel` + `isLocalSavings` on the `ParsedApiCall`. Local-savings wins for actual cost even when the same model is also in `modelAliases`. * Session, project, day, model, category, activity, skill, and subagent rollups all carry `savingsUSD` alongside `costUSD`. * `status --format json` adds `today.savings` and `month.savings`. * `status --format menubar-json` adds a `current.localModelSavings` block (totalUSD, calls, byModel, byProvider) plus savings on topModels, topProjects, topSessions, topActivities, and history daily entries. Schema fields default-decode for backward compat. * `report --format json` adds savings across overview/daily/ projects/models/activities/skills/subagents/topSessions, with the active paid baseline name on each model row. * `models` command gains a `Saved` column on table/markdown/CSV and a `savingsUSD`/`savingsBaselineModel` pair in JSON. Default `--min-cost 0.01` filter now ORs in `savingsUSD >= minCost` so local models with $0 actual cost but >0 savings still surface. * CSV/JSON exports add a `Saved (CODE)` column on summary/daily/ models/projects/sessions. * Dashboard TUI shows a green 'saved $X by local models' footer line in the overview when any savings are present. * macOS Swift payload gains a `LocalModelSavings` Codable block and savings fields on every model/activity/session/daily struct. Hero shows a green leaf 'Saved $X' caption, models section gets a green `Saved` column. `swift build` clean. * GNOME indicator adds 'saved $X' to the hero meta line and a `codeburn-model-saved` column to the model row. * Daily cache schema bumped to v8 (`savingsUSD` on day/model/ category/provider). `savingsConfigHash` invalidates the cache when the user changes their baseline mapping so historical saved-spend numbers never lie about a stale baseline. * Defensive `Object.hasOwn` lookup in `getLocalSavingsBaseline` blocks the prototype-pollution test that previously surfaced via the savings path with a hostile `__proto__` model name. * New tests (5 files, 25 tests, 549 lines) cover pricing helpers, end-to-end parser normalization, day aggregator savings, menubar payload savings, CLI set/list/remove, and daily-cache hash invalidation. Existing tests for daily-cache / day-aggregator / models-report updated for the new fields. Full vitest suite: 1028/1028 passing across 73 test files. `tsc --noEmit` clean. `npm run build` clean. (Note: `mac/Tests` has a pre-existing `no such module 'Testing'` environment error on the installed Swift toolchain, confirmed on `main` before this PR; not caused by these changes.)
This commit is contained in:
parent
69b1736365
commit
8ded6ad6fd
25 changed files with 1308 additions and 113 deletions
|
|
@ -27,6 +27,12 @@ export type CodeburnConfig = {
|
|||
plan?: Plan
|
||||
plans?: PlanConfigMap
|
||||
modelAliases?: Record<string, string>
|
||||
/// Map raw local-model names (e.g. "llama3.1:8b") to the paid model
|
||||
/// we'd price the call against (e.g. "gpt-4o"). The local call still
|
||||
/// costs $0; we track what the same tokens would have cost on the
|
||||
/// baseline so the dashboard can show "saved $X by running locally".
|
||||
/// Distinct from `modelAliases` which rewrites actual spend.
|
||||
localModelSavings?: Record<string, string>
|
||||
}
|
||||
|
||||
function getConfigDir(): string {
|
||||
|
|
|
|||
|
|
@ -5,16 +5,20 @@ import { homedir } from 'os'
|
|||
import { join } from 'path'
|
||||
import type { DateRange, ProjectSummary } from './types.js'
|
||||
|
||||
// Bumped to 7: new providers (Codebuff, Mistral Vibe, Kimi, Cline) and
|
||||
// the per-provider menubar path now reads historical cost from the cache.
|
||||
// Stale entries computed by older binaries may carry incorrect totals.
|
||||
export const DAILY_CACHE_VERSION = 7
|
||||
const MIN_SUPPORTED_VERSION = 7
|
||||
// Bumped to 8: local-model savings accounting is now part of the daily rollup
|
||||
// (savingsUSD per day / per model / per category / per provider). Stale entries
|
||||
// computed by older binaries lack those fields, so MIN_SUPPORTED_VERSION is
|
||||
// also raised to 8 to force a full re-hydration. The `savingsConfigHash` field
|
||||
// is invalidated separately when the user changes their `localModelSavings`
|
||||
// mapping so historical "saved" totals stay in sync with the active baseline.
|
||||
export const DAILY_CACHE_VERSION = 8
|
||||
const MIN_SUPPORTED_VERSION = 8
|
||||
const DAILY_CACHE_FILENAME = 'daily-cache.json'
|
||||
|
||||
export type DailyEntry = {
|
||||
date: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
sessions: number
|
||||
inputTokens: number
|
||||
|
|
@ -26,17 +30,23 @@ export type DailyEntry = {
|
|||
models: Record<string, {
|
||||
calls: number
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
}>
|
||||
categories: Record<string, { turns: number; cost: number; editTurns: number; oneShotTurns: number }>
|
||||
providers: Record<string, { calls: number; cost: number }>
|
||||
categories: Record<string, { turns: number; cost: number; savingsUSD: number; editTurns: number; oneShotTurns: number }>
|
||||
providers: Record<string, { calls: number; cost: number; savingsUSD: number }>
|
||||
}
|
||||
|
||||
export type DailyCache = {
|
||||
version: number
|
||||
/// Hash of the active `localModelSavings` config at the time the cache
|
||||
/// was last written. When the user changes their baseline mapping the
|
||||
/// hash mismatches and `ensureCacheHydrated` discards the cached days
|
||||
/// so historical savings are recomputed against the current mapping.
|
||||
savingsConfigHash: string
|
||||
lastComputedDate: string | null
|
||||
days: DailyEntry[]
|
||||
}
|
||||
|
|
@ -49,11 +59,11 @@ function getCachePath(): string {
|
|||
return join(getCacheDir(), DAILY_CACHE_FILENAME)
|
||||
}
|
||||
|
||||
export function emptyCache(): DailyCache {
|
||||
return { version: DAILY_CACHE_VERSION, lastComputedDate: null, days: [] }
|
||||
export function emptyCache(savingsConfigHash = ''): DailyCache {
|
||||
return { version: DAILY_CACHE_VERSION, savingsConfigHash, lastComputedDate: null, days: [] }
|
||||
}
|
||||
|
||||
function isMigratableCache(parsed: unknown): parsed is { version: number; lastComputedDate: string | null; days: Record<string, unknown>[] } {
|
||||
function isMigratableCache(parsed: unknown): parsed is { version: number; lastComputedDate: string | null; savingsConfigHash?: string; days: Record<string, unknown>[] } {
|
||||
if (!parsed || typeof parsed !== 'object') return false
|
||||
const c = parsed as Partial<DailyCache>
|
||||
if (typeof c.version !== 'number') return false
|
||||
|
|
@ -65,6 +75,7 @@ function migrateDays(days: Record<string, unknown>[]): DailyEntry[] {
|
|||
return days.map(d => ({
|
||||
date: d.date as string,
|
||||
cost: (d.cost as number) ?? 0,
|
||||
savingsUSD: (d.savingsUSD as number) ?? 0,
|
||||
calls: (d.calls as number) ?? 0,
|
||||
sessions: (d.sessions as number) ?? 0,
|
||||
inputTokens: (d.inputTokens as number) ?? 0,
|
||||
|
|
@ -93,6 +104,7 @@ export async function loadDailyCache(): Promise<DailyCache> {
|
|||
if (isMigratableCache(parsed)) {
|
||||
const migrated: DailyCache = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash: parsed.savingsConfigHash ?? '',
|
||||
lastComputedDate: parsed.lastComputedDate,
|
||||
days: migrateDays(parsed.days),
|
||||
}
|
||||
|
|
@ -153,7 +165,12 @@ export function addNewDays(cache: DailyCache, incoming: DailyEntry[], newestDate
|
|||
const nextLast = cache.lastComputedDate && cache.lastComputedDate > newestDate
|
||||
? cache.lastComputedDate
|
||||
: newestDate
|
||||
return { version: DAILY_CACHE_VERSION, lastComputedDate: nextLast, days: pruned }
|
||||
return {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash: cache.savingsConfigHash,
|
||||
lastComputedDate: nextLast,
|
||||
days: pruned,
|
||||
}
|
||||
}
|
||||
|
||||
export function getDaysInRange(cache: DailyCache, start: string, end: string): DailyEntry[] {
|
||||
|
|
@ -182,6 +199,11 @@ export function toDateString(date: Date): string {
|
|||
export async function ensureCacheHydrated(
|
||||
parseSessions: (range: DateRange) => Promise<ProjectSummary[]>,
|
||||
aggregateDays: (projects: ProjectSummary[]) => DailyEntry[],
|
||||
/// Hash of the active `localModelSavings` config. When this changes
|
||||
/// (user re-mapped a baseline) the cached `savingsUSD` totals are no
|
||||
/// longer accurate, so we treat the cache as stale and force a full
|
||||
/// re-hydration. Pass `''` for "no savings config" to disable.
|
||||
savingsConfigHash: string = '',
|
||||
): Promise<DailyCache> {
|
||||
const now = new Date()
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
|
|
@ -191,6 +213,19 @@ export async function ensureCacheHydrated(
|
|||
return withDailyCacheLock(async () => {
|
||||
let c = await loadDailyCache()
|
||||
|
||||
// Savings config changed: roll the cache forward into the active
|
||||
// mapping. We can't cheaply recompute savings for already-cached
|
||||
// historical days without re-parsing every session, so we drop the
|
||||
// cached days and re-hydrate from the daily cache retention window.
|
||||
if (c.savingsConfigHash !== savingsConfigHash) {
|
||||
c = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash,
|
||||
lastComputedDate: null,
|
||||
days: [],
|
||||
}
|
||||
}
|
||||
|
||||
const hadYesterday = c.days.some(d => d.date >= yesterdayStr)
|
||||
if (hadYesterday) {
|
||||
const freshDays = c.days.filter(d => d.date < yesterdayStr)
|
||||
|
|
|
|||
|
|
@ -192,6 +192,7 @@ function planStatusText(planUsage: PlanUsage): string {
|
|||
|
||||
function Overview({ projects, label, width, planUsages }: { projects: ProjectSummary[]; label: string; width: number; planUsages?: PlanUsage[] }) {
|
||||
const totalCost = projects.reduce((s, p) => s + p.totalCostUSD, 0)
|
||||
const totalSavings = projects.reduce((s, p) => s + p.totalSavingsUSD, 0)
|
||||
const totalCalls = projects.reduce((s, p) => s + p.totalApiCalls, 0)
|
||||
const totalSessions = projects.reduce((s, p) => s + p.sessions.length, 0)
|
||||
const allSessions = projects.flatMap(p => p.sessions)
|
||||
|
|
@ -223,6 +224,12 @@ function Overview({ projects, label, width, planUsages }: { projects: ProjectSum
|
|||
<Text dimColor wrap="truncate-end">
|
||||
{formatTokens(totalInput)} in {formatTokens(totalOutput)} out {formatTokens(totalCacheRead)} cached {formatTokens(totalCacheWrite)} written
|
||||
</Text>
|
||||
{totalSavings > 0 && (
|
||||
<Text wrap="truncate-end">
|
||||
<Text color="green">{formatCost(totalSavings)}</Text>
|
||||
<Text dimColor> saved by local models</Text>
|
||||
</Text>
|
||||
)}
|
||||
{activePlanUsages.length > 0 && (
|
||||
<>
|
||||
{activePlanUsages.map(planUsage => {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ function emptyEntry(date: string): DailyEntry {
|
|||
return {
|
||||
date,
|
||||
cost: 0,
|
||||
savingsUSD: 0,
|
||||
calls: 0,
|
||||
sessions: 0,
|
||||
inputTokens: 0,
|
||||
|
|
@ -46,13 +47,15 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[]): DailyEntr
|
|||
const editTurns = turn.hasEdits ? 1 : 0
|
||||
const oneShotTurns = turn.hasEdits && turn.retries === 0 ? 1 : 0
|
||||
const turnCost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0)
|
||||
const turnSavings = turn.assistantCalls.reduce((s, c) => s + (c.savingsUSD ?? 0), 0)
|
||||
|
||||
turnDay.editTurns += editTurns
|
||||
turnDay.oneShotTurns += oneShotTurns
|
||||
|
||||
const cat = turnDay.categories[turn.category] ?? { turns: 0, cost: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
const cat = turnDay.categories[turn.category] ?? { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
cat.turns += 1
|
||||
cat.cost += turnCost
|
||||
cat.savingsUSD += turnSavings
|
||||
cat.editTurns += editTurns
|
||||
cat.oneShotTurns += oneShotTurns
|
||||
turnDay.categories[turn.category] = cat
|
||||
|
|
@ -60,8 +63,10 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[]): DailyEntr
|
|||
for (const call of turn.assistantCalls) {
|
||||
const callDate = dateKey(call.timestamp)
|
||||
const callDay = ensure(callDate)
|
||||
const callSavings = call.savingsUSD ?? 0
|
||||
|
||||
callDay.cost += call.costUSD
|
||||
callDay.savingsUSD += callSavings
|
||||
callDay.calls += 1
|
||||
callDay.inputTokens += call.usage.inputTokens
|
||||
callDay.outputTokens += call.usage.outputTokens
|
||||
|
|
@ -69,21 +74,23 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[]): DailyEntr
|
|||
callDay.cacheWriteTokens += call.usage.cacheCreationInputTokens
|
||||
|
||||
const model = callDay.models[call.model] ?? {
|
||||
calls: 0, cost: 0,
|
||||
calls: 0, cost: 0, savingsUSD: 0,
|
||||
inputTokens: 0, outputTokens: 0,
|
||||
cacheReadTokens: 0, cacheWriteTokens: 0,
|
||||
}
|
||||
model.calls += 1
|
||||
model.cost += call.costUSD
|
||||
model.savingsUSD += callSavings
|
||||
model.inputTokens += call.usage.inputTokens
|
||||
model.outputTokens += call.usage.outputTokens
|
||||
model.cacheReadTokens += call.usage.cacheReadInputTokens
|
||||
model.cacheWriteTokens += call.usage.cacheCreationInputTokens
|
||||
callDay.models[call.model] = model
|
||||
|
||||
const provider = callDay.providers[call.provider] ?? { calls: 0, cost: 0 }
|
||||
const provider = callDay.providers[call.provider] ?? { calls: 0, cost: 0, savingsUSD: 0 }
|
||||
provider.calls += 1
|
||||
provider.cost += call.costUSD
|
||||
provider.savingsUSD += callSavings
|
||||
callDay.providers[call.provider] = provider
|
||||
}
|
||||
}
|
||||
|
|
@ -94,13 +101,14 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[]): DailyEntr
|
|||
}
|
||||
|
||||
export function buildPeriodDataFromDays(days: DailyEntry[], label: string): PeriodData {
|
||||
let cost = 0, calls = 0, sessions = 0
|
||||
let cost = 0, savingsUSD = 0, calls = 0, sessions = 0
|
||||
let inputTokens = 0, outputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0
|
||||
const catTotals: Record<string, { turns: number; cost: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const modelTotals: Record<string, { calls: number; cost: number }> = {}
|
||||
const catTotals: Record<string, { turns: number; cost: number; savingsUSD: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const modelTotals: Record<string, { calls: number; cost: number; savingsUSD: number }> = {}
|
||||
|
||||
for (const d of days) {
|
||||
cost += d.cost
|
||||
savingsUSD += d.savingsUSD
|
||||
calls += d.calls
|
||||
sessions += d.sessions
|
||||
inputTokens += d.inputTokens
|
||||
|
|
@ -109,15 +117,17 @@ export function buildPeriodDataFromDays(days: DailyEntry[], label: string): Peri
|
|||
cacheWriteTokens += d.cacheWriteTokens
|
||||
|
||||
for (const [name, m] of Object.entries(d.models)) {
|
||||
const acc = modelTotals[name] ?? { calls: 0, cost: 0 }
|
||||
const acc = modelTotals[name] ?? { calls: 0, cost: 0, savingsUSD: 0 }
|
||||
acc.calls += m.calls
|
||||
acc.cost += m.cost
|
||||
acc.savingsUSD += (m.savingsUSD ?? 0)
|
||||
modelTotals[name] = acc
|
||||
}
|
||||
for (const [cat, c] of Object.entries(d.categories)) {
|
||||
const acc = catTotals[cat] ?? { turns: 0, cost: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
const acc = catTotals[cat] ?? { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
acc.turns += c.turns
|
||||
acc.cost += c.cost
|
||||
acc.savingsUSD += (c.savingsUSD ?? 0)
|
||||
acc.editTurns += c.editTurns
|
||||
acc.oneShotTurns += c.oneShotTurns
|
||||
catTotals[cat] = acc
|
||||
|
|
@ -127,6 +137,7 @@ export function buildPeriodDataFromDays(days: DailyEntry[], label: string): Peri
|
|||
return {
|
||||
label,
|
||||
cost,
|
||||
savingsUSD,
|
||||
calls,
|
||||
sessions,
|
||||
inputTokens,
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ function pct(n: number, total: number): number {
|
|||
|
||||
type DailyAgg = {
|
||||
cost: number
|
||||
savings: number
|
||||
calls: number
|
||||
input: number
|
||||
output: number
|
||||
|
|
@ -52,11 +53,12 @@ function buildDailyRows(projects: ProjectSummary[], period: string): Row[] {
|
|||
if (!turn.timestamp) continue
|
||||
const day = dateKey(turn.timestamp)
|
||||
if (!daily[day]) {
|
||||
daily[day] = { cost: 0, calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, sessions: new Set() }
|
||||
daily[day] = { cost: 0, savings: 0, calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, sessions: new Set() }
|
||||
}
|
||||
daily[day].sessions.add(session.sessionId)
|
||||
for (const call of turn.assistantCalls) {
|
||||
daily[day].cost += call.costUSD
|
||||
daily[day].savings += call.savingsUSD ?? 0
|
||||
daily[day].calls++
|
||||
daily[day].input += call.usage.inputTokens
|
||||
daily[day].output += call.usage.outputTokens
|
||||
|
|
@ -71,6 +73,7 @@ function buildDailyRows(projects: ProjectSummary[], period: string): Row[] {
|
|||
Period: period,
|
||||
Date: date,
|
||||
[`Cost (${code})`]: roundForActiveCurrency(convertCost(d.cost)),
|
||||
[`Saved (${code})`]: roundForActiveCurrency(convertCost(d.savings)),
|
||||
'API Calls': d.calls,
|
||||
Sessions: d.sessions.size,
|
||||
'Input Tokens': d.input,
|
||||
|
|
@ -105,14 +108,15 @@ function buildActivityRows(projects: ProjectSummary[], period: string): Row[] {
|
|||
}
|
||||
|
||||
function buildModelRows(projects: ProjectSummary[], period: string): Row[] {
|
||||
const modelTotals: Record<string, { calls: number; cost: number; input: number; output: number; cacheRead: number; cacheWrite: number }> = {}
|
||||
const modelTotals: Record<string, { calls: number; cost: number; savings: number; input: number; output: number; cacheRead: number; cacheWrite: number }> = {}
|
||||
const modelEfficiency = aggregateModelEfficiency(projects)
|
||||
for (const project of projects) {
|
||||
for (const session of project.sessions) {
|
||||
for (const [model, d] of Object.entries(session.modelBreakdown)) {
|
||||
if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
|
||||
if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0, savings: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
|
||||
modelTotals[model].calls += d.calls
|
||||
modelTotals[model].cost += d.costUSD
|
||||
modelTotals[model].savings += d.savingsUSD
|
||||
modelTotals[model].input += d.tokens.inputTokens
|
||||
modelTotals[model].output += d.tokens.outputTokens
|
||||
modelTotals[model].cacheRead += d.tokens.cacheReadInputTokens ?? 0
|
||||
|
|
@ -124,13 +128,14 @@ function buildModelRows(projects: ProjectSummary[], period: string): Row[] {
|
|||
const { code } = getCurrency()
|
||||
return Object.entries(modelTotals)
|
||||
.filter(([name]) => name !== '<synthetic>')
|
||||
.sort(([, a], [, b]) => b.cost - a.cost)
|
||||
.sort(([, a], [, b]) => (b.cost + b.savings) - (a.cost + a.savings))
|
||||
.map(([model, d]) => {
|
||||
const efficiency = modelEfficiency.get(model)
|
||||
return {
|
||||
Period: period,
|
||||
Model: model,
|
||||
[`Cost (${code})`]: roundForActiveCurrency(convertCost(d.cost)),
|
||||
[`Saved (${code})`]: roundForActiveCurrency(convertCost(d.savings)),
|
||||
'Share (%)': pct(d.cost, totalCost),
|
||||
'API Calls': d.calls,
|
||||
'Edit Turns': efficiency?.editTurns ?? 0,
|
||||
|
|
@ -190,10 +195,11 @@ function buildProjectRows(projects: ProjectSummary[]): Row[] {
|
|||
const total = projects.reduce((s, p) => s + p.totalCostUSD, 0)
|
||||
return projects
|
||||
.slice()
|
||||
.sort((a, b) => b.totalCostUSD - a.totalCostUSD)
|
||||
.sort((a, b) => (b.totalCostUSD + b.totalSavingsUSD) - (a.totalCostUSD + a.totalSavingsUSD))
|
||||
.map(p => ({
|
||||
Project: p.projectPath,
|
||||
[`Cost (${code})`]: roundForActiveCurrency(convertCost(p.totalCostUSD)),
|
||||
[`Saved (${code})`]: roundForActiveCurrency(convertCost(p.totalSavingsUSD)),
|
||||
[`Avg/Session (${code})`]: p.sessions.length > 0 ? roundForActiveCurrency(convertCost(p.totalCostUSD / p.sessions.length)) : '',
|
||||
'Share (%)': pct(p.totalCostUSD, total),
|
||||
'API Calls': p.totalApiCalls,
|
||||
|
|
@ -211,12 +217,13 @@ function buildSessionRows(projects: ProjectSummary[]): Row[] {
|
|||
'Session ID': s.sessionId,
|
||||
'Started At': s.firstTimestamp ?? '',
|
||||
[`Cost (${code})`]: roundForActiveCurrency(convertCost(s.totalCostUSD)),
|
||||
[`Saved (${code})`]: roundForActiveCurrency(convertCost(s.totalSavingsUSD)),
|
||||
'API Calls': s.apiCalls,
|
||||
Turns: s.turns.length,
|
||||
})
|
||||
}
|
||||
}
|
||||
return rows.sort((a, b) => (b[`Cost (${code})`] as number) - (a[`Cost (${code})`] as number))
|
||||
return rows.sort((a, b) => ((b[`Cost (${code})`] as number) + (b[`Saved (${code})`] as number)) - ((a[`Cost (${code})`] as number) + (a[`Saved (${code})`] as number)))
|
||||
}
|
||||
|
||||
export type PeriodExport = {
|
||||
|
|
@ -228,12 +235,14 @@ function buildSummaryRows(periods: PeriodExport[]): Row[] {
|
|||
const { code } = getCurrency()
|
||||
return periods.map(p => {
|
||||
const cost = p.projects.reduce((s, proj) => s + proj.totalCostUSD, 0)
|
||||
const savings = p.projects.reduce((s, proj) => s + proj.totalSavingsUSD, 0)
|
||||
const calls = p.projects.reduce((s, proj) => s + proj.totalApiCalls, 0)
|
||||
const sessions = p.projects.reduce((s, proj) => s + proj.sessions.length, 0)
|
||||
const projectCount = p.projects.filter(proj => proj.totalCostUSD > 0).length
|
||||
const projectCount = p.projects.filter(proj => proj.totalCostUSD > 0 || proj.totalSavingsUSD > 0).length
|
||||
return {
|
||||
Period: p.label,
|
||||
[`Cost (${code})`]: roundForActiveCurrency(convertCost(cost)),
|
||||
[`Saved (${code})`]: roundForActiveCurrency(convertCost(savings)),
|
||||
'API Calls': calls,
|
||||
Sessions: sessions,
|
||||
Projects: projectCount,
|
||||
|
|
|
|||
225
src/main.ts
225
src/main.ts
|
|
@ -2,7 +2,7 @@ import { homedir } from 'node:os'
|
|||
import { Command } from 'commander'
|
||||
import { installMenubarApp } from './menubar-installer.js'
|
||||
import { exportCsv, exportJson, type PeriodExport } from './export.js'
|
||||
import { loadPricing, setModelAliases } from './models.js'
|
||||
import { loadPricing, setLocalModelSavings, setModelAliases, getLocalModelSavingsConfigHash, calculateCost, getShortModelName } from './models.js'
|
||||
import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, filterProjectsByDays, clearSessionCache } from './parser.js'
|
||||
import { convertCost } from './currency.js'
|
||||
import { renderStatusBar } from './format.js'
|
||||
|
|
@ -36,6 +36,7 @@ async function hydrateCache() {
|
|||
return await ensureCacheHydrated(
|
||||
(range) => parseAllSessions(range, 'all'),
|
||||
aggregateProjectsIntoDays,
|
||||
getLocalModelSavingsConfigHash(),
|
||||
)
|
||||
} catch {
|
||||
return emptyCache()
|
||||
|
|
@ -163,6 +164,7 @@ program.hook('preAction', async (thisCommand) => {
|
|||
}
|
||||
const config = await readConfig()
|
||||
setModelAliases(config.modelAliases ?? {})
|
||||
setLocalModelSavings(config.localModelSavings ?? {})
|
||||
if (thisCommand.opts<{ verbose?: boolean }>().verbose) {
|
||||
process.env['CODEBURN_VERBOSE'] = '1'
|
||||
}
|
||||
|
|
@ -174,6 +176,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
const { code } = getCurrency()
|
||||
|
||||
const totalCostUSD = projects.reduce((s, p) => s + p.totalCostUSD, 0)
|
||||
const totalSavingsUSD = projects.reduce((s, p) => s + p.totalSavingsUSD, 0)
|
||||
const totalCalls = projects.reduce((s, p) => s + p.totalApiCalls, 0)
|
||||
const totalSessions = projects.reduce((s, p) => s + p.sessions.length, 0)
|
||||
const totalInput = sessions.reduce((s, sess) => s + sess.totalInputTokens, 0)
|
||||
|
|
@ -191,7 +194,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
// `turns`, edit turns count for `editTurns`, edit turns with zero retries
|
||||
// count for `oneShotTurns`. Issue #279 — daily-resolution efficiency
|
||||
// dashboards need this without re-deriving from activity-level rollups.
|
||||
const dailyMap: Record<string, { cost: number; calls: number; turns: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const dailyMap: Record<string, { cost: number; savings: number; calls: number; turns: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
for (const sess of sessions) {
|
||||
for (const turn of sess.turns) {
|
||||
// Prefer the user-message timestamp on the turn; fall back to the first
|
||||
|
|
@ -202,7 +205,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
const ts = turn.timestamp || turn.assistantCalls[0]?.timestamp
|
||||
if (!ts) { continue }
|
||||
const day = dateKey(ts)
|
||||
if (!dailyMap[day]) { dailyMap[day] = { cost: 0, calls: 0, turns: 0, editTurns: 0, oneShotTurns: 0 } }
|
||||
if (!dailyMap[day]) { dailyMap[day] = { cost: 0, savings: 0, calls: 0, turns: 0, editTurns: 0, oneShotTurns: 0 } }
|
||||
dailyMap[day].turns += 1
|
||||
if (turn.hasEdits) {
|
||||
dailyMap[day].editTurns += 1
|
||||
|
|
@ -210,6 +213,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
}
|
||||
for (const call of turn.assistantCalls) {
|
||||
dailyMap[day].cost += call.costUSD
|
||||
dailyMap[day].savings += call.savingsUSD ?? 0
|
||||
dailyMap[day].calls += 1
|
||||
}
|
||||
}
|
||||
|
|
@ -217,6 +221,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
const daily = Object.entries(dailyMap).sort().map(([date, d]) => ({
|
||||
date,
|
||||
cost: convertCost(d.cost),
|
||||
savings: convertCost(d.savings),
|
||||
calls: d.calls,
|
||||
turns: d.turns,
|
||||
editTurns: d.editTurns,
|
||||
|
|
@ -233,6 +238,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
name: p.project,
|
||||
path: p.projectPath,
|
||||
cost: convertCost(p.totalCostUSD),
|
||||
savings: convertCost(p.totalSavingsUSD),
|
||||
avgCostPerSession: p.sessions.length > 0
|
||||
? convertCost(p.totalCostUSD / p.sessions.length)
|
||||
: null,
|
||||
|
|
@ -240,27 +246,51 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
sessions: p.sessions.length,
|
||||
}))
|
||||
|
||||
const modelMap: Record<string, { calls: number; cost: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }> = {}
|
||||
const modelMap: Record<string, { calls: number; cost: number; savings: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; baselineModel: string }> = {}
|
||||
const modelEfficiency = aggregateModelEfficiency(projects)
|
||||
for (const sess of sessions) {
|
||||
for (const [model, d] of Object.entries(sess.modelBreakdown)) {
|
||||
if (!modelMap[model]) { modelMap[model] = { calls: 0, cost: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 } }
|
||||
if (!modelMap[model]) { modelMap[model] = { calls: 0, cost: 0, savings: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, baselineModel: '' } }
|
||||
modelMap[model].calls += d.calls
|
||||
modelMap[model].cost += d.costUSD
|
||||
modelMap[model].savings += d.savingsUSD
|
||||
modelMap[model].inputTokens += d.tokens.inputTokens
|
||||
modelMap[model].outputTokens += d.tokens.outputTokens
|
||||
modelMap[model].cacheReadTokens += d.tokens.cacheReadInputTokens
|
||||
modelMap[model].cacheWriteTokens += d.tokens.cacheCreationInputTokens
|
||||
}
|
||||
}
|
||||
// Pull the active baseline model name out of the savings config so the
|
||||
// report can show what the local calls were mapped against without
|
||||
// forcing the consumer to cross-reference a separate file. Empty when
|
||||
// no savings are configured for this period.
|
||||
for (const [model, acc] of Object.entries(modelMap)) {
|
||||
if (acc.savings <= 0) continue
|
||||
for (const sess of sessions) {
|
||||
const bucket = sess.modelBreakdown[model]
|
||||
if (!bucket || bucket.savingsUSD <= 0) continue
|
||||
for (const turn of sess.turns) {
|
||||
for (const call of turn.assistantCalls) {
|
||||
if (call.model === model && call.savingsBaselineModel) {
|
||||
acc.baselineModel = call.savingsBaselineModel
|
||||
break
|
||||
}
|
||||
}
|
||||
if (acc.baselineModel) break
|
||||
}
|
||||
if (acc.baselineModel) break
|
||||
}
|
||||
}
|
||||
const models = Object.entries(modelMap)
|
||||
.sort(([, a], [, b]) => b.cost - a.cost)
|
||||
.map(([name, { cost, ...rest }]) => {
|
||||
.sort(([, a], [, b]) => (b.cost + b.savings) - (a.cost + a.savings))
|
||||
.map(([name, { cost, savings, baselineModel, ...rest }]) => {
|
||||
const efficiency = modelEfficiency.get(name)
|
||||
return {
|
||||
name,
|
||||
...rest,
|
||||
cost: convertCost(cost),
|
||||
savings: convertCost(savings),
|
||||
savingsBaselineModel: baselineModel,
|
||||
editTurns: efficiency?.editTurns ?? 0,
|
||||
oneShotTurns: efficiency?.oneShotTurns ?? 0,
|
||||
oneShotRate: efficiency?.oneShotRate ?? null,
|
||||
|
|
@ -271,21 +301,23 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
}
|
||||
})
|
||||
|
||||
const catMap: Record<string, { turns: number; cost: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const catMap: Record<string, { turns: number; cost: number; savings: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
for (const sess of sessions) {
|
||||
for (const [cat, d] of Object.entries(sess.categoryBreakdown)) {
|
||||
if (!catMap[cat]) { catMap[cat] = { turns: 0, cost: 0, editTurns: 0, oneShotTurns: 0 } }
|
||||
if (!catMap[cat]) { catMap[cat] = { turns: 0, cost: 0, savings: 0, editTurns: 0, oneShotTurns: 0 } }
|
||||
catMap[cat].turns += d.turns
|
||||
catMap[cat].cost += d.costUSD
|
||||
catMap[cat].savings += d.savingsUSD
|
||||
catMap[cat].editTurns += d.editTurns
|
||||
catMap[cat].oneShotTurns += d.oneShotTurns
|
||||
}
|
||||
}
|
||||
const activities = Object.entries(catMap)
|
||||
.sort(([, a], [, b]) => b.cost - a.cost)
|
||||
.sort(([, a], [, b]) => (b.cost + b.savings) - (a.cost + a.savings))
|
||||
.map(([cat, d]) => ({
|
||||
category: CATEGORY_LABELS[cat as TaskCategory] ?? cat,
|
||||
cost: convertCost(d.cost),
|
||||
savings: convertCost(d.savings),
|
||||
turns: d.turns,
|
||||
editTurns: d.editTurns,
|
||||
oneShotTurns: d.oneShotTurns,
|
||||
|
|
@ -295,8 +327,8 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
const toolMap: Record<string, number> = {}
|
||||
const mcpMap: Record<string, number> = {}
|
||||
const bashMap: Record<string, number> = {}
|
||||
const skillMap: Record<string, { turns: number; cost: number }> = {}
|
||||
const subagentMap: Record<string, { calls: number; cost: number }> = {}
|
||||
const skillMap: Record<string, { turns: number; cost: number; savings: number }> = {}
|
||||
const subagentMap: Record<string, { calls: number; cost: number; savings: number }> = {}
|
||||
for (const sess of sessions) {
|
||||
for (const [tool, d] of Object.entries(sess.toolBreakdown)) {
|
||||
toolMap[tool] = (toolMap[tool] ?? 0) + d.calls
|
||||
|
|
@ -308,14 +340,16 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
bashMap[cmd] = (bashMap[cmd] ?? 0) + d.calls
|
||||
}
|
||||
for (const [skill, d] of Object.entries(sess.skillBreakdown)) {
|
||||
if (!skillMap[skill]) skillMap[skill] = { turns: 0, cost: 0 }
|
||||
if (!skillMap[skill]) skillMap[skill] = { turns: 0, cost: 0, savings: 0 }
|
||||
skillMap[skill].turns += d.turns
|
||||
skillMap[skill].cost += d.costUSD
|
||||
skillMap[skill].savings += d.savingsUSD
|
||||
}
|
||||
for (const [sat, d] of Object.entries(sess.subagentBreakdown)) {
|
||||
if (!subagentMap[sat]) subagentMap[sat] = { calls: 0, cost: 0 }
|
||||
if (!subagentMap[sat]) subagentMap[sat] = { calls: 0, cost: 0, savings: 0 }
|
||||
subagentMap[sat].calls += d.calls
|
||||
subagentMap[sat].cost += d.costUSD
|
||||
subagentMap[sat].savings += d.savingsUSD
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -323,8 +357,15 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
Object.entries(m).sort(([, a], [, b]) => b - a).map(([name, calls]) => ({ name, calls }))
|
||||
|
||||
const topSessions = projects
|
||||
.flatMap(p => p.sessions.map(s => ({ project: p.project, sessionId: s.sessionId, date: s.firstTimestamp ? dateKey(s.firstTimestamp) : null, cost: convertCost(s.totalCostUSD), calls: s.apiCalls })))
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.flatMap(p => p.sessions.map(s => ({
|
||||
project: p.project,
|
||||
sessionId: s.sessionId,
|
||||
date: s.firstTimestamp ? dateKey(s.firstTimestamp) : null,
|
||||
cost: convertCost(s.totalCostUSD),
|
||||
savings: convertCost(s.totalSavingsUSD),
|
||||
calls: s.apiCalls,
|
||||
})))
|
||||
.sort((a, b) => (b.cost + b.savings) - (a.cost + a.savings))
|
||||
.slice(0, 5)
|
||||
|
||||
return {
|
||||
|
|
@ -334,6 +375,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
periodKey,
|
||||
overview: {
|
||||
cost: convertCost(totalCostUSD),
|
||||
savings: convertCost(totalSavingsUSD),
|
||||
calls: totalCalls,
|
||||
sessions: totalSessions,
|
||||
cacheHitPercent,
|
||||
|
|
@ -351,8 +393,8 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
tools: sortedMap(toolMap),
|
||||
mcpServers: sortedMap(mcpMap),
|
||||
shellCommands: sortedMap(bashMap),
|
||||
skills: Object.entries(skillMap).sort(([, a], [, b]) => b.cost - a.cost).map(([name, d]) => ({ name, turns: d.turns, cost: convertCost(d.cost) })),
|
||||
subagents: Object.entries(subagentMap).sort(([, a], [, b]) => b.cost - a.cost).map(([name, d]) => ({ name, calls: d.calls, cost: convertCost(d.cost) })),
|
||||
skills: Object.entries(skillMap).sort(([, a], [, b]) => (b.cost + b.savings) - (a.cost + a.savings)).map(([name, d]) => ({ name, turns: d.turns, cost: convertCost(d.cost), savings: convertCost(d.savings) })),
|
||||
subagents: Object.entries(subagentMap).sort(([, a], [, b]) => (b.cost + b.savings) - (a.cost + a.savings)).map(([name, d]) => ({ name, calls: d.calls, cost: convertCost(d.cost), savings: convertCost(d.savings) })),
|
||||
topSessions,
|
||||
}
|
||||
}
|
||||
|
|
@ -409,8 +451,8 @@ program
|
|||
|
||||
function buildPeriodData(label: string, projects: ProjectSummary[]): PeriodData {
|
||||
const sessions = projects.flatMap(p => p.sessions)
|
||||
const catTotals: Record<string, { turns: number; cost: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const modelTotals: Record<string, { calls: number; cost: number }> = {}
|
||||
const catTotals: Record<string, { turns: number; cost: number; savingsUSD: number; editTurns: number; oneShotTurns: number }> = {}
|
||||
const modelTotals: Record<string, { calls: number; cost: number; savingsUSD: number }> = {}
|
||||
let inputTokens = 0, outputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0
|
||||
|
||||
for (const sess of sessions) {
|
||||
|
|
@ -419,22 +461,25 @@ function buildPeriodData(label: string, projects: ProjectSummary[]): PeriodData
|
|||
cacheReadTokens += sess.totalCacheReadTokens
|
||||
cacheWriteTokens += sess.totalCacheWriteTokens
|
||||
for (const [cat, d] of Object.entries(sess.categoryBreakdown)) {
|
||||
if (!catTotals[cat]) catTotals[cat] = { turns: 0, cost: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
if (!catTotals[cat]) catTotals[cat] = { turns: 0, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
catTotals[cat].turns += d.turns
|
||||
catTotals[cat].cost += d.costUSD
|
||||
catTotals[cat].savingsUSD += d.savingsUSD
|
||||
catTotals[cat].editTurns += d.editTurns
|
||||
catTotals[cat].oneShotTurns += d.oneShotTurns
|
||||
}
|
||||
for (const [model, d] of Object.entries(sess.modelBreakdown)) {
|
||||
if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0 }
|
||||
if (!modelTotals[model]) modelTotals[model] = { calls: 0, cost: 0, savingsUSD: 0 }
|
||||
modelTotals[model].calls += d.calls
|
||||
modelTotals[model].cost += d.costUSD
|
||||
modelTotals[model].savingsUSD += d.savingsUSD
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
cost: projects.reduce((s, p) => s + p.totalCostUSD, 0),
|
||||
savingsUSD: projects.reduce((s, p) => s + p.totalSavingsUSD, 0),
|
||||
calls: projects.reduce((s, p) => s + p.totalApiCalls, 0),
|
||||
sessions: projects.reduce((s, p) => s + p.sessions.length, 0),
|
||||
inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens,
|
||||
|
|
@ -598,6 +643,7 @@ program
|
|||
.map(([name, m]) => ({
|
||||
name,
|
||||
cost: m.cost,
|
||||
savingsUSD: m.savingsUSD,
|
||||
calls: m.calls,
|
||||
inputTokens: m.inputTokens,
|
||||
outputTokens: m.outputTokens,
|
||||
|
|
@ -605,6 +651,7 @@ program
|
|||
return {
|
||||
date: d.date,
|
||||
cost: d.cost,
|
||||
savingsUSD: d.savingsUSD,
|
||||
calls: d.calls,
|
||||
inputTokens: d.inputTokens,
|
||||
outputTokens: d.outputTokens,
|
||||
|
|
@ -614,12 +661,13 @@ program
|
|||
}
|
||||
})
|
||||
} else {
|
||||
const emptyModels = [] as { name: string; cost: number; calls: number; inputTokens: number; outputTokens: number }[]
|
||||
const emptyModels = [] as { name: string; cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number }[]
|
||||
const historyFromCache = allCacheDays.map(d => {
|
||||
const prov = d.providers[pf] ?? { calls: 0, cost: 0 }
|
||||
const prov = d.providers[pf] ?? { calls: 0, cost: 0, savingsUSD: 0 }
|
||||
return {
|
||||
date: d.date,
|
||||
cost: prov.cost,
|
||||
savingsUSD: prov.savingsUSD,
|
||||
calls: prov.calls,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
|
|
@ -631,10 +679,11 @@ program
|
|||
const todayFromParse = aggregateProjectsIntoDays(scanProjects)
|
||||
.filter(d => d.date === todayStr)
|
||||
.map(d => {
|
||||
const prov = d.providers[pf] ?? { calls: 0, cost: 0 }
|
||||
const prov = d.providers[pf] ?? { calls: 0, cost: 0, savingsUSD: 0 }
|
||||
return {
|
||||
date: d.date,
|
||||
cost: prov.cost,
|
||||
savingsUSD: prov.savingsUSD,
|
||||
calls: prov.calls,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
|
|
@ -656,18 +705,20 @@ program
|
|||
currentData.projects = scanProjects.map(p => ({
|
||||
name: friendlyProject(p),
|
||||
cost: p.totalCostUSD,
|
||||
savingsUSD: p.totalSavingsUSD,
|
||||
sessions: p.sessions.length,
|
||||
sessionDetails: [...p.sessions]
|
||||
.sort((a, b) => b.totalCostUSD - a.totalCostUSD)
|
||||
.slice(0, 10)
|
||||
.map(s => ({
|
||||
cost: s.totalCostUSD,
|
||||
savingsUSD: s.totalSavingsUSD,
|
||||
calls: s.apiCalls,
|
||||
inputTokens: s.totalInputTokens,
|
||||
outputTokens: s.totalOutputTokens,
|
||||
date: s.firstTimestamp?.split('T')[0] ?? '',
|
||||
models: Object.entries(s.modelBreakdown)
|
||||
.map(([name, m]) => ({ name, cost: m.costUSD }))
|
||||
.map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD }))
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.slice(0, 3),
|
||||
})),
|
||||
|
|
@ -700,10 +751,11 @@ program
|
|||
p.sessions.map(s => ({
|
||||
project: friendlyProject(p),
|
||||
cost: s.totalCostUSD,
|
||||
savingsUSD: s.totalSavingsUSD,
|
||||
calls: s.apiCalls,
|
||||
date: s.firstTimestamp?.split('T')[0] ?? '',
|
||||
}))
|
||||
).sort((a, b) => b.cost - a.cost).slice(0, 5)
|
||||
).sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD)).slice(0, 5)
|
||||
|
||||
// Routing waste: find cheapest reliable model (≥90% 1-shot, ≥5 edits),
|
||||
// then compute how much each pricier model overpaid.
|
||||
|
|
@ -747,11 +799,52 @@ program
|
|||
for (const [sa, d] of Object.entries(s.subagentBreakdown)) { const e = subagentMap[sa] ?? { calls: 0, cost: 0 }; e.calls += d.calls; e.cost += d.costUSD; subagentMap[sa] = e }
|
||||
for (const [m, d] of Object.entries(s.mcpBreakdown)) { mcpMap[m] = (mcpMap[m] ?? 0) + d.calls }
|
||||
}
|
||||
|
||||
// Per-provider and per-model local-savings rollup. Walks the raw
|
||||
// ParsedApiCall so we can keep baseline model + token info that
|
||||
// doesn't survive the category rollup. ByModel and byProvider are
|
||||
// capped at 5 entries each so the payload stays small.
|
||||
const byModel = new Map<string, { calls: number; actualUSD: number; savingsUSD: number; baselineModel: string; inputTokens: number; outputTokens: number }>()
|
||||
const byProvider = new Map<string, { calls: number; savingsUSD: number }>()
|
||||
let totalSavings = 0
|
||||
let totalCalls = 0
|
||||
for (const p of scanProjects) for (const s of p.sessions) for (const turn of s.turns) for (const call of turn.assistantCalls) {
|
||||
if (!call.savingsUSD || call.savingsUSD <= 0) continue
|
||||
totalSavings += call.savingsUSD
|
||||
totalCalls += 1
|
||||
const modelKey = getShortModelName(call.model)
|
||||
const acc = byModel.get(modelKey) ?? { calls: 0, actualUSD: 0, savingsUSD: 0, baselineModel: call.savingsBaselineModel ?? '', inputTokens: 0, outputTokens: 0 }
|
||||
acc.calls += 1
|
||||
acc.actualUSD += call.costUSD
|
||||
acc.savingsUSD += call.savingsUSD
|
||||
acc.baselineModel = acc.baselineModel || (call.savingsBaselineModel ?? '')
|
||||
acc.inputTokens += call.usage.inputTokens
|
||||
acc.outputTokens += call.usage.outputTokens
|
||||
byModel.set(modelKey, acc)
|
||||
const provAcc = byProvider.get(call.provider) ?? { calls: 0, savingsUSD: 0 }
|
||||
provAcc.calls += 1
|
||||
provAcc.savingsUSD += call.savingsUSD
|
||||
byProvider.set(call.provider, provAcc)
|
||||
}
|
||||
const localModelSavings = {
|
||||
totalUSD: totalSavings,
|
||||
calls: totalCalls,
|
||||
byModel: Array.from(byModel.entries())
|
||||
.sort(([, a], [, b]) => b.savingsUSD - a.savingsUSD)
|
||||
.slice(0, 5)
|
||||
.map(([name, d]) => ({ name, ...d })),
|
||||
byProvider: Array.from(byProvider.entries())
|
||||
.sort(([, a], [, b]) => b.savingsUSD - a.savingsUSD)
|
||||
.slice(0, 5)
|
||||
.map(([name, d]) => ({ name, ...d })),
|
||||
}
|
||||
|
||||
return {
|
||||
tools: Object.entries(toolMap).sort(([, a], [, b]) => b - a).slice(0, 10).map(([name, calls]) => ({ name, calls })),
|
||||
skills: Object.entries(skillMap).sort(([, a], [, b]) => b.cost - a.cost).slice(0, 10).map(([name, d]) => ({ name, ...d })),
|
||||
subagents: Object.entries(subagentMap).sort(([, a], [, b]) => b.cost - a.cost).slice(0, 10).map(([name, d]) => ({ name, ...d })),
|
||||
mcpServers: Object.entries(mcpMap).sort(([, a], [, b]) => b - a).slice(0, 10).map(([name, calls]) => ({ name, calls })),
|
||||
localModelSavings,
|
||||
}
|
||||
})()
|
||||
|
||||
|
|
@ -770,14 +863,25 @@ program
|
|||
const { code, rate } = getCurrency()
|
||||
const payload: {
|
||||
currency: string
|
||||
today: { cost: number; calls: number }
|
||||
month: { cost: number; calls: number }
|
||||
today: { cost: number; savings: number; calls: number }
|
||||
month: { cost: number; savings: number; calls: number }
|
||||
localModelSavings?: { today: number; month: number; callsToday: number; callsMonth: number }
|
||||
plan?: JsonPlanSummary
|
||||
plans?: JsonPlanSummaryMap
|
||||
} = {
|
||||
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 },
|
||||
today: { cost: Math.round(todayData.cost * rate * 100) / 100, savings: Math.round(todayData.savingsUSD * rate * 100) / 100, calls: todayData.calls },
|
||||
month: { cost: Math.round(monthData.cost * rate * 100) / 100, savings: Math.round(monthData.savingsUSD * rate * 100) / 100, calls: monthData.calls },
|
||||
}
|
||||
const savingsCallsToday = todayProjects.reduce((s, p) => s + p.sessions.reduce((s2, sess) => s2 + sess.turns.reduce((s3, turn) => s3 + turn.assistantCalls.reduce((s4, c) => s4 + (c.savingsUSD && c.savingsUSD > 0 ? 1 : 0), 0), 0), 0), 0)
|
||||
const savingsCallsMonth = monthProjects.reduce((s, p) => s + p.sessions.reduce((s2, sess) => s2 + sess.turns.reduce((s3, turn) => s3 + turn.assistantCalls.reduce((s4, c) => s4 + (c.savingsUSD && c.savingsUSD > 0 ? 1 : 0), 0), 0), 0), 0)
|
||||
if (todayData.savingsUSD > 0 || monthData.savingsUSD > 0) {
|
||||
payload.localModelSavings = {
|
||||
today: payload.today.savings,
|
||||
month: payload.month.savings,
|
||||
callsToday: savingsCallsToday,
|
||||
callsMonth: savingsCallsMonth,
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify(await attachPlanSummaries(payload)))
|
||||
return
|
||||
|
|
@ -1004,6 +1108,65 @@ program
|
|||
console.log(` Config: ${getConfigFilePath()}\n`)
|
||||
})
|
||||
|
||||
program
|
||||
.command('model-savings [local] [baseline]')
|
||||
.description('Track a local model as "savings" rather than cost. Maps a local-model name to a paid baseline so the dashboard can show what the same tokens would have cost on the baseline (e.g. codeburn model-savings "llama3.1:8b" gpt-4o). The local call itself still costs $0 — actual cost is left untouched.')
|
||||
.option('--remove <local>', 'Remove a savings mapping for the given local model')
|
||||
.option('--list', 'List configured savings mappings')
|
||||
.action(async (local?: string, baseline?: string, opts?: { remove?: string; list?: boolean }) => {
|
||||
const config = await readConfig()
|
||||
const mappings = { ...(config.localModelSavings ?? {}) }
|
||||
|
||||
if (opts?.list || (!local && !opts?.remove)) {
|
||||
const entries = Object.entries(mappings)
|
||||
if (entries.length === 0) {
|
||||
console.log('\n No local-model savings mappings configured.')
|
||||
console.log(` Config: ${getConfigFilePath()}`)
|
||||
console.log(' Add one with: codeburn model-savings <local-model> <baseline-model>\n')
|
||||
} else {
|
||||
console.log('\n Local-model savings mappings:')
|
||||
for (const [src, dst] of entries) {
|
||||
console.log(` ${src} -> ${dst}`)
|
||||
}
|
||||
console.log(` Config: ${getConfigFilePath()}\n`)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (opts?.remove) {
|
||||
if (!(opts.remove in mappings)) {
|
||||
console.error(`\n No savings mapping found for: ${opts.remove}\n`)
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
delete mappings[opts.remove]
|
||||
config.localModelSavings = Object.keys(mappings).length > 0 ? mappings : undefined
|
||||
await saveConfig(config)
|
||||
console.log(`\n Removed savings mapping: ${opts.remove}\n`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!local || !baseline) {
|
||||
console.error('\n Usage: codeburn model-savings <local-model> <baseline-model>\n')
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
|
||||
mappings[local] = baseline
|
||||
config.localModelSavings = mappings
|
||||
await saveConfig(config)
|
||||
|
||||
// Warn when the same model is also in modelAliases so the user is
|
||||
// not surprised that `savings` wins for actual cost.
|
||||
if (config.modelAliases && Object.hasOwn(config.modelAliases, local)) {
|
||||
console.log(`\n Note: ${local} is also in modelAliases (-> ${config.modelAliases[local]}).`)
|
||||
console.log(' Local-model savings take precedence: the call is treated as $0 actual cost and the baseline is used for counterfactual savings.')
|
||||
}
|
||||
|
||||
console.log(`\n Savings mapping saved: ${local} -> ${baseline}`)
|
||||
console.log(` Config: ${getConfigFilePath()}\n`)
|
||||
})
|
||||
|
||||
program
|
||||
.command('plan [action] [id]')
|
||||
.description('Show or configure a subscription plan for overage tracking')
|
||||
|
|
|
|||
|
|
@ -4,17 +4,23 @@
|
|||
export type PeriodData = {
|
||||
label: string
|
||||
cost: number
|
||||
/// Counterfactual USD the same tokens would have cost on the paid
|
||||
/// baseline configured for each local model. Stays `0` when no
|
||||
/// `codeburn model-savings` mappings are active. Always shown
|
||||
/// separately from `cost` so the two never get summed into a "real
|
||||
/// spend" number by accident.
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
sessions: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
categories: Array<{ name: string; cost: number; turns: number; editTurns: number; oneShotTurns: number }>
|
||||
models: Array<{ name: string; cost: number; calls: number }>
|
||||
projects?: Array<{ name: string; cost: number; sessions: number; sessionDetails?: Array<{ cost: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number }> }> }>
|
||||
categories: Array<{ name: string; cost: number; savingsUSD: number; turns: number; editTurns: number; oneShotTurns: number }>
|
||||
models: Array<{ name: string; cost: number; savingsUSD: number; calls: number }>
|
||||
projects?: Array<{ name: string; cost: number; savingsUSD: number; sessions: number; sessionDetails?: Array<{ cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number; savingsUSD: number }> }> }>
|
||||
modelEfficiency?: Array<{ name: string; costPerEdit: number | null; oneShotRate: number | null }>
|
||||
topSessions?: Array<{ project: string; cost: number; calls: number; date: string }>
|
||||
topSessions?: Array<{ project: string; cost: number; savingsUSD: number; calls: number; date: string }>
|
||||
}
|
||||
|
||||
export type ProviderCost = {
|
||||
|
|
@ -35,6 +41,7 @@ const MODEL_EFFICIENCY_LIMIT = 5
|
|||
export type DailyModelBreakdown = {
|
||||
name: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
|
|
@ -43,6 +50,7 @@ export type DailyModelBreakdown = {
|
|||
export type DailyHistoryEntry = {
|
||||
date: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
|
|
@ -51,6 +59,21 @@ export type DailyHistoryEntry = {
|
|||
topModels: DailyModelBreakdown[]
|
||||
}
|
||||
|
||||
export type LocalModelSavings = {
|
||||
totalUSD: number
|
||||
calls: number
|
||||
byModel: Array<{
|
||||
name: string
|
||||
calls: number
|
||||
actualUSD: number
|
||||
savingsUSD: number
|
||||
baselineModel: string
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
}>
|
||||
byProvider: Array<{ name: string; calls: number; savingsUSD: number }>
|
||||
}
|
||||
|
||||
export type MenubarPayload = {
|
||||
generated: string
|
||||
current: {
|
||||
|
|
@ -65,27 +88,38 @@ export type MenubarPayload = {
|
|||
topActivities: Array<{
|
||||
name: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
turns: number
|
||||
oneShotRate: number | null
|
||||
}>
|
||||
topModels: Array<{
|
||||
name: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
savingsBaselineModel: string
|
||||
calls: number
|
||||
}>
|
||||
/// Local-model savings rollup, distinct from the routing-waste /
|
||||
/// optimize savings concepts which describe hypothetical optimization
|
||||
/// opportunities. This block tracks counterfactual spend that was
|
||||
/// already avoided because the user ran a local model mapped via
|
||||
/// `codeburn model-savings`.
|
||||
localModelSavings: LocalModelSavings
|
||||
providers: Record<string, number>
|
||||
topProjects: Array<{
|
||||
name: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
sessions: number
|
||||
avgCostPerSession: number
|
||||
sessionDetails: Array<{
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
date: string
|
||||
models: Array<{ name: string; cost: number }>
|
||||
models: Array<{ name: string; cost: number; savingsUSD: number }>
|
||||
}>
|
||||
}>
|
||||
modelEfficiency: Array<{
|
||||
|
|
@ -96,6 +130,7 @@ export type MenubarPayload = {
|
|||
topSessions: Array<{
|
||||
project: string
|
||||
cost: number
|
||||
savingsUSD: number
|
||||
calls: number
|
||||
date: string
|
||||
}>
|
||||
|
|
@ -168,6 +203,7 @@ function buildTopActivities(categories: PeriodData['categories']): MenubarPayloa
|
|||
return categories.slice(0, TOP_ACTIVITIES_LIMIT).map(cat => ({
|
||||
name: cat.name,
|
||||
cost: cat.cost,
|
||||
savingsUSD: cat.savingsUSD,
|
||||
turns: cat.turns,
|
||||
oneShotRate: oneShotRateFor(cat.editTurns, cat.oneShotTurns),
|
||||
}))
|
||||
|
|
@ -177,7 +213,7 @@ function buildTopModels(models: PeriodData['models']): MenubarPayload['current']
|
|||
return models
|
||||
.filter(m => m.name !== SYNTHETIC_MODEL_NAME)
|
||||
.slice(0, TOP_MODELS_LIMIT)
|
||||
.map(m => ({ name: m.name, cost: m.cost, calls: m.calls }))
|
||||
.map(m => ({ name: m.name, cost: m.cost, calls: m.calls, savingsUSD: m.savingsUSD, savingsBaselineModel: '' }))
|
||||
}
|
||||
|
||||
function buildOptimize(optimize: OptimizeResult | null): MenubarPayload['optimize'] {
|
||||
|
|
@ -216,16 +252,18 @@ function buildHistory(daily: DailyHistoryEntry[] | undefined): MenubarPayload['h
|
|||
|
||||
function buildTopProjects(projects: PeriodData['projects']): MenubarPayload['current']['topProjects'] {
|
||||
return (projects ?? [])
|
||||
.filter(p => p.cost > 0)
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.filter(p => p.cost > 0 || p.savingsUSD > 0)
|
||||
.sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD))
|
||||
.slice(0, TOP_PROJECTS_LIMIT)
|
||||
.map(p => ({
|
||||
name: p.name,
|
||||
cost: p.cost,
|
||||
savingsUSD: p.savingsUSD,
|
||||
sessions: p.sessions,
|
||||
avgCostPerSession: p.sessions > 0 ? p.cost / p.sessions : 0,
|
||||
sessionDetails: (p.sessionDetails ?? []).map(s => ({
|
||||
cost: s.cost,
|
||||
savingsUSD: s.savingsUSD,
|
||||
calls: s.calls,
|
||||
inputTokens: s.inputTokens,
|
||||
outputTokens: s.outputTokens,
|
||||
|
|
@ -245,9 +283,9 @@ function buildModelEfficiency(models: PeriodData['modelEfficiency']): MenubarPay
|
|||
|
||||
function buildTopSessions(sessions: PeriodData['topSessions']): MenubarPayload['current']['topSessions'] {
|
||||
return (sessions ?? [])
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD))
|
||||
.slice(0, TOP_SESSIONS_LIMIT)
|
||||
.map(s => ({ project: s.project, cost: s.cost, calls: s.calls, date: s.date }))
|
||||
.map(s => ({ project: s.project, cost: s.cost, savingsUSD: s.savingsUSD, calls: s.calls, date: s.date }))
|
||||
}
|
||||
|
||||
export type BreakdownArrays = {
|
||||
|
|
@ -255,6 +293,12 @@ export type BreakdownArrays = {
|
|||
skills?: MenubarPayload['current']['skills']
|
||||
subagents?: MenubarPayload['current']['subagents']
|
||||
mcpServers?: MenubarPayload['current']['mcpServers']
|
||||
/// Optional rollup of per-model and per-provider local-model savings.
|
||||
/// Computed by the CLI from the parsed projects (we have raw token
|
||||
/// + baseline info there, not in `PeriodData`). When omitted, the
|
||||
/// menubar payload defaults to an empty savings block — keeping the
|
||||
/// schema stable for consumers that don't care about local savings.
|
||||
localModelSavings?: LocalModelSavings
|
||||
}
|
||||
|
||||
export function buildMenubarPayload(
|
||||
|
|
@ -279,6 +323,7 @@ export function buildMenubarPayload(
|
|||
cacheHitPercent: cacheHitPercent(current.inputTokens, current.cacheReadTokens),
|
||||
topActivities: buildTopActivities(current.categories),
|
||||
topModels: buildTopModels(current.models),
|
||||
localModelSavings: breakdowns?.localModelSavings ?? { totalUSD: 0, calls: 0, byModel: [], byProvider: [] },
|
||||
providers: buildProviders(providers),
|
||||
topProjects: buildTopProjects(current.projects ?? []),
|
||||
modelEfficiency: buildModelEfficiency(current.modelEfficiency ?? []),
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ export type ModelReportRow = {
|
|||
cacheReadTokens: number
|
||||
totalTokens: number
|
||||
costUSD: number
|
||||
savingsUSD: number
|
||||
savingsBaselineModel: string
|
||||
calls: number
|
||||
topCategory?: TaskCategory
|
||||
topCategoryCost?: number
|
||||
|
|
@ -27,6 +29,10 @@ export type AggregateOptions = {
|
|||
byTask?: boolean
|
||||
taskFilter?: TaskCategory
|
||||
topN?: number
|
||||
/// Threshold for the `cost`-based filter. The default `0.01` would
|
||||
/// hide local-only models whose `costUSD` is 0 but `savingsUSD` is
|
||||
/// meaningful. The implementation ORs in `savingsUSD >= minCost`
|
||||
/// so saved-only rows still surface by default.
|
||||
minCost?: number
|
||||
}
|
||||
|
||||
|
|
@ -39,6 +45,8 @@ type Bucket = {
|
|||
cacheWriteTokens: number
|
||||
cacheReadTokens: number
|
||||
costUSD: number
|
||||
savingsUSD: number
|
||||
savingsBaselineModel: string
|
||||
calls: number
|
||||
}
|
||||
|
||||
|
|
@ -82,6 +90,8 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat
|
|||
cacheWriteTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
costUSD: 0,
|
||||
savingsUSD: 0,
|
||||
savingsBaselineModel: '',
|
||||
calls: 0,
|
||||
}
|
||||
buckets.set(key, bucket)
|
||||
|
|
@ -91,6 +101,10 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat
|
|||
bucket.cacheWriteTokens += call.usage.cacheCreationInputTokens
|
||||
bucket.cacheReadTokens += call.usage.cacheReadInputTokens + call.usage.cachedInputTokens
|
||||
bucket.costUSD += call.costUSD
|
||||
bucket.savingsUSD += call.savingsUSD ?? 0
|
||||
if (!bucket.savingsBaselineModel && call.savingsBaselineModel) {
|
||||
bucket.savingsBaselineModel = call.savingsBaselineModel
|
||||
}
|
||||
bucket.calls += 1
|
||||
|
||||
const modelKey = `${provider} ${model}`
|
||||
|
|
@ -135,6 +149,8 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat
|
|||
cacheReadTokens: bucket.cacheReadTokens,
|
||||
totalTokens: total,
|
||||
costUSD: bucket.costUSD,
|
||||
savingsUSD: bucket.savingsUSD,
|
||||
savingsBaselineModel: bucket.savingsBaselineModel,
|
||||
calls: bucket.calls,
|
||||
}
|
||||
|
||||
|
|
@ -167,15 +183,17 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat
|
|||
if (aTotal !== bTotal) return bTotal - aTotal
|
||||
if (a.provider !== b.provider) return a.provider.localeCompare(b.provider)
|
||||
if (a.model !== b.model) return a.model.localeCompare(b.model)
|
||||
return b.costUSD - a.costUSD
|
||||
return (b.costUSD + b.savingsUSD) - (a.costUSD + a.savingsUSD)
|
||||
})
|
||||
} else {
|
||||
rows.sort((a, b) => b.costUSD - a.costUSD)
|
||||
rows.sort((a, b) => (b.costUSD + b.savingsUSD) - (a.costUSD + a.savingsUSD))
|
||||
}
|
||||
|
||||
let filtered = rows
|
||||
if (opts.minCost !== undefined) {
|
||||
filtered = filtered.filter(r => r.costUSD >= opts.minCost!)
|
||||
// OR with savings so local models with $0 actual cost but > 0 saved
|
||||
// counterfactual still surface in the default `models` view.
|
||||
filtered = filtered.filter(r => r.costUSD >= opts.minCost! || r.savingsUSD >= opts.minCost!)
|
||||
}
|
||||
if (opts.topN !== undefined) {
|
||||
filtered = filtered.slice(0, opts.topN)
|
||||
|
|
@ -222,7 +240,7 @@ type Column = {
|
|||
/// Drop priority. 0 = always shown; higher numbers get dropped first when
|
||||
/// the terminal is narrow.
|
||||
priority: number
|
||||
key: 'provider' | 'model' | 'task' | 'input' | 'output' | 'cacheWrite' | 'cacheRead' | 'total' | 'cost'
|
||||
key: 'provider' | 'model' | 'task' | 'input' | 'output' | 'cacheWrite' | 'cacheRead' | 'total' | 'cost' | 'saved'
|
||||
}
|
||||
|
||||
type TableRenderOptions = {
|
||||
|
|
@ -236,12 +254,14 @@ const DROP_COLUMN_GROUPS: Array<Array<Column['key']>> = [
|
|||
['cacheWrite', 'cacheRead'],
|
||||
['input', 'output'],
|
||||
['task'],
|
||||
['saved'],
|
||||
]
|
||||
|
||||
function defaultColumns(byTask: boolean): Column[] {
|
||||
// Higher priority numbers drop FIRST when the terminal is narrow.
|
||||
// Cache columns are the cheapest to lose, then input/output, then top-task.
|
||||
// Provider/Model/Total/Cost stay regardless.
|
||||
// Provider/Model/Total/Cost/Saved stay regardless — Saved is the headline
|
||||
// of issue #421 and should survive almost every narrow-terminal cut.
|
||||
// Widths are MINIMUMS; sizeColumnsToContent() expands them to fit cell text.
|
||||
return [
|
||||
{ key: 'provider', header: 'Provider', align: 'left', width: 8, priority: 0 },
|
||||
|
|
@ -253,6 +273,7 @@ function defaultColumns(byTask: boolean): Column[] {
|
|||
{ key: 'cacheRead', header: 'Cache Read', align: 'right', width: 10, priority: 3 },
|
||||
{ key: 'total', header: 'Total', align: 'right', width: 6, priority: 0 },
|
||||
{ key: 'cost', header: 'Cost', align: 'right', width: 6, priority: 0 },
|
||||
{ key: 'saved', header: 'Saved', align: 'right', width: 6, priority: 0 },
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -395,6 +416,7 @@ export function renderTable(
|
|||
case 'cacheRead': return formatTokens(row.cacheReadTokens)
|
||||
case 'total': return formatTokens(row.totalTokens)
|
||||
case 'cost': return formatCost(row.costUSD)
|
||||
case 'saved': return row.savingsUSD > 0 ? formatCost(row.savingsUSD) : chalk.dim('-')
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -424,9 +446,10 @@ export function renderTable(
|
|||
acc.cacheRead += r.cacheReadTokens
|
||||
acc.total += r.totalTokens
|
||||
acc.cost += r.costUSD
|
||||
acc.savings += r.savingsUSD
|
||||
return acc
|
||||
},
|
||||
{ input: 0, output: 0, cacheWrite: 0, cacheRead: 0, total: 0, cost: 0 },
|
||||
{ input: 0, output: 0, cacheWrite: 0, cacheRead: 0, total: 0, cost: 0, savings: 0 },
|
||||
)
|
||||
const cells = defaultColumns(byTask).map(col => {
|
||||
switch (col.key) {
|
||||
|
|
@ -439,6 +462,7 @@ export function renderTable(
|
|||
case 'cacheRead': return chalk.yellow(formatTokens(totals.cacheRead))
|
||||
case 'total': return chalk.yellow.bold(formatTokens(totals.total))
|
||||
case 'cost': return chalk.yellow.bold(formatCost(totals.cost))
|
||||
case 'saved': return totals.savings > 0 ? chalk.yellow.bold(formatCost(totals.savings)) : chalk.dim('-')
|
||||
}
|
||||
})
|
||||
totalsEntry = { kind: 'totals', cells, isNewGroup: true }
|
||||
|
|
@ -519,13 +543,16 @@ export function renderJson(rows: ModelReportRow[]): string {
|
|||
totalTokens: r.totalTokens,
|
||||
calls: r.calls,
|
||||
costUSD: r.costUSD,
|
||||
savingsUSD: r.savingsUSD,
|
||||
savingsBaselineModel: r.savingsBaselineModel,
|
||||
})),
|
||||
null,
|
||||
2,
|
||||
)
|
||||
}
|
||||
|
||||
function csvEscape(value: string): string {
|
||||
function csvEscape(value: string | undefined | null): string {
|
||||
if (value === undefined || value === null) return ''
|
||||
if (value.includes(',') || value.includes('"') || value.includes('\n')) {
|
||||
return `"${value.replace(/"/g, '""')}"`
|
||||
}
|
||||
|
|
@ -546,9 +573,9 @@ export function renderMarkdown(rows: ModelReportRow[], opts: { byTask?: boolean;
|
|||
const showTotals = opts.showTotals ?? true
|
||||
|
||||
const header = byTask
|
||||
? ['Provider', 'Model', 'Task', 'Input', 'Output', 'Cache Write', 'Cache Read', 'Total', 'Cost']
|
||||
: ['Provider', 'Model', 'Top Task', 'Input', 'Output', 'Cache Write', 'Cache Read', 'Total', 'Cost']
|
||||
const align = ['---', '---', '---', '---:', '---:', '---:', '---:', '---:', '---:']
|
||||
? ['Provider', 'Model', 'Task', 'Input', 'Output', 'Cache Write', 'Cache Read', 'Total', 'Cost', 'Saved']
|
||||
: ['Provider', 'Model', 'Top Task', 'Input', 'Output', 'Cache Write', 'Cache Read', 'Total', 'Cost', 'Saved']
|
||||
const align = ['---', '---', '---', '---:', '---:', '---:', '---:', '---:', '---:', '---:']
|
||||
|
||||
const lines: string[] = []
|
||||
lines.push(`| ${header.join(' | ')} |`)
|
||||
|
|
@ -570,6 +597,7 @@ export function renderMarkdown(rows: ModelReportRow[], opts: { byTask?: boolean;
|
|||
formatTokens(row.cacheReadTokens),
|
||||
formatTokens(row.totalTokens),
|
||||
formatCost(row.costUSD),
|
||||
row.savingsUSD > 0 ? formatCost(row.savingsUSD) : '-',
|
||||
]
|
||||
lines.push(`| ${cells.join(' | ')} |`)
|
||||
}
|
||||
|
|
@ -583,9 +611,10 @@ export function renderMarkdown(rows: ModelReportRow[], opts: { byTask?: boolean;
|
|||
acc.cacheRead += r.cacheReadTokens
|
||||
acc.total += r.totalTokens
|
||||
acc.cost += r.costUSD
|
||||
acc.savings += r.savingsUSD
|
||||
return acc
|
||||
},
|
||||
{ input: 0, output: 0, cacheWrite: 0, cacheRead: 0, total: 0, cost: 0 },
|
||||
{ input: 0, output: 0, cacheWrite: 0, cacheRead: 0, total: 0, cost: 0, savings: 0 },
|
||||
)
|
||||
const totalCells = [
|
||||
'',
|
||||
|
|
@ -597,6 +626,7 @@ export function renderMarkdown(rows: ModelReportRow[], opts: { byTask?: boolean;
|
|||
`**${formatTokens(totals.cacheRead)}**`,
|
||||
`**${formatTokens(totals.total)}**`,
|
||||
`**${formatCost(totals.cost)}**`,
|
||||
totals.savings > 0 ? `**${formatCost(totals.savings)}**` : '-',
|
||||
]
|
||||
lines.push(`| ${totalCells.join(' | ')} |`)
|
||||
}
|
||||
|
|
@ -609,8 +639,8 @@ export function renderCsv(rows: ModelReportRow[], opts: { byTask?: boolean } = {
|
|||
// CSV intentionally repeats provider/model on every row so downstream
|
||||
// consumers can sort/filter without first reconstructing the grouping.
|
||||
const header = byTask
|
||||
? ['provider', 'model', 'task', 'input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens', 'total_tokens', 'calls', 'cost_usd']
|
||||
: ['provider', 'model', 'top_task', 'top_task_share', 'input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens', 'total_tokens', 'calls', 'cost_usd']
|
||||
? ['provider', 'model', 'task', 'input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens', 'total_tokens', 'calls', 'cost_usd', 'savings_usd', 'savings_baseline_model']
|
||||
: ['provider', 'model', 'top_task', 'top_task_share', 'input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens', 'total_tokens', 'calls', 'cost_usd', 'savings_usd', 'savings_baseline_model']
|
||||
const lines: string[] = [header.join(',')]
|
||||
for (const r of rows) {
|
||||
const cells = byTask
|
||||
|
|
@ -625,6 +655,8 @@ export function renderCsv(rows: ModelReportRow[], opts: { byTask?: boolean } = {
|
|||
String(r.totalTokens),
|
||||
String(r.calls),
|
||||
r.costUSD.toFixed(6),
|
||||
(r.savingsUSD ?? 0).toFixed(6),
|
||||
csvEscape(r.savingsBaselineModel),
|
||||
]
|
||||
: [
|
||||
csvEscape(r.providerDisplayName),
|
||||
|
|
@ -638,6 +670,8 @@ export function renderCsv(rows: ModelReportRow[], opts: { byTask?: boolean } = {
|
|||
String(r.totalTokens),
|
||||
String(r.calls),
|
||||
r.costUSD.toFixed(6),
|
||||
(r.savingsUSD ?? 0).toFixed(6),
|
||||
csvEscape(r.savingsBaselineModel),
|
||||
]
|
||||
lines.push(cells.join(','))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -268,6 +268,69 @@ export function setModelAliases(aliases: Record<string, string>): void {
|
|||
userAliases = aliases
|
||||
}
|
||||
|
||||
// Local-model savings config. Kept separate from userAliases: a `modelAliases`
|
||||
// entry rewrites a model's identity for actual cost; a `localModelSavings`
|
||||
// entry keeps the model cost at $0 and reports the *avoided* spend against a
|
||||
// paid baseline. Set during preAction from `config.localModelSavings`.
|
||||
let userLocalModelSavings: Record<string, string> = {}
|
||||
|
||||
export function setLocalModelSavings(mappings: Record<string, string>): void {
|
||||
userLocalModelSavings = { ...mappings }
|
||||
}
|
||||
|
||||
export function getLocalSavingsBaseline(rawModel: string): string | undefined {
|
||||
if (!rawModel || typeof rawModel !== 'string') return undefined
|
||||
// Defensive: bracket-accessing user-controlled keys on a plain object
|
||||
// exposes the prototype chain (`__proto__` would resolve to Object.prototype).
|
||||
// Use Object.hasOwn so a hostile JSONL model name cannot piggyback into
|
||||
// Object.prototype either through the alias map or here.
|
||||
if (!Object.hasOwn(userLocalModelSavings, rawModel)) return undefined
|
||||
return userLocalModelSavings[rawModel]
|
||||
}
|
||||
|
||||
/// Compute the hypothetical baseline cost for a local call. The baseline
|
||||
/// model is priced through the normal `calculateCost` pipeline (so it can
|
||||
/// be aliased / canonicalized). Returns `null` when the source model has
|
||||
/// no savings mapping, the baseline is unknown to the pricing snapshot, or
|
||||
/// any input is unusable — callers should treat null as "no savings
|
||||
/// recorded for this call" rather than a hard error.
|
||||
export function calculateLocalModelSavings(
|
||||
rawModel: string,
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
cacheCreationTokens: number,
|
||||
cacheReadTokens: number,
|
||||
webSearchRequests: number,
|
||||
speed: 'standard' | 'fast' = 'standard',
|
||||
oneHourCacheCreationTokens = 0,
|
||||
): { savingsUSD: number; baselineModel: string } | null {
|
||||
const baseline = getLocalSavingsBaseline(rawModel)
|
||||
if (!baseline) return null
|
||||
if (!getModelCosts(baseline)) return null
|
||||
const savingsUSD = calculateCost(
|
||||
baseline,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheCreationTokens,
|
||||
cacheReadTokens,
|
||||
webSearchRequests,
|
||||
speed,
|
||||
oneHourCacheCreationTokens,
|
||||
)
|
||||
return { savingsUSD, baselineModel: baseline }
|
||||
}
|
||||
|
||||
/// Stable hash of the current savings config so the daily cache can detect
|
||||
/// "user changed their baseline mapping" and rebuild instead of presenting
|
||||
/// stale saved-spend numbers. Two configs with the same key→baseline pairs
|
||||
/// in any order collapse to the same hash.
|
||||
export function getLocalModelSavingsConfigHash(): string {
|
||||
const keys = Object.keys(userLocalModelSavings).sort()
|
||||
if (keys.length === 0) return ''
|
||||
const parts = keys.map(k => `${k}\u0001${userLocalModelSavings[k]}`)
|
||||
return parts.join('\u0002')
|
||||
}
|
||||
|
||||
function resolveAlias(model: string): string {
|
||||
if (Object.hasOwn(userAliases, model)) return userAliases[model]!
|
||||
if (Object.hasOwn(BUILTIN_ALIASES, model)) return BUILTIN_ALIASES[model]!
|
||||
|
|
@ -353,7 +416,7 @@ export function calculateCost(
|
|||
// payloads written by external tools, so a hostile or corrupt file
|
||||
// could embed terminal escape sequences here.
|
||||
const safeName = model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200)
|
||||
const aliasHint = `Map it with: codeburn model-alias "${safeName}" <known-model>`
|
||||
const aliasHint = `Map it with: codeburn model-alias "${safeName}" <known-model>, or track local-model savings with: codeburn model-savings "${safeName}" <baseline-model>`
|
||||
process.stderr.write(
|
||||
`codeburn: no pricing data for model "${safeName}" — costs for this model will show $0. ` +
|
||||
`${aliasHint}, or update with: npx codeburn@latest.\n`
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { lstat, readFile, readdir, stat } from 'fs/promises'
|
||||
import { basename, dirname, join, resolve, sep } from 'path'
|
||||
import { readSessionLines } from './fs-utils.js'
|
||||
import { calculateCost, getShortModelName } from './models.js'
|
||||
import { calculateCost, calculateLocalModelSavings, getShortModelName } from './models.js'
|
||||
import { discoverAllSessions, getProvider } from './providers/index.js'
|
||||
import { flushCodexCache } from './codex-cache.js'
|
||||
import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js'
|
||||
|
|
@ -1040,6 +1040,33 @@ function extractClaudeCacheCreation(usage: AssistantMessageContent['usage']): {
|
|||
}
|
||||
}
|
||||
|
||||
/// Apply local-model savings accounting to a call. If the raw model name is
|
||||
/// mapped via `codeburn model-savings`, the call's actual cost is forced
|
||||
/// to $0 and the hypothetical baseline cost is recorded as `savingsUSD`.
|
||||
/// Returns the input unchanged when no mapping is configured for the
|
||||
/// model — keeps the hot path branch-free for the common paid-only case.
|
||||
function applyLocalModelSavings(call: ParsedApiCall): ParsedApiCall {
|
||||
const u = call.usage
|
||||
const savings = calculateLocalModelSavings(
|
||||
call.model,
|
||||
u.inputTokens,
|
||||
u.outputTokens,
|
||||
u.cacheCreationInputTokens,
|
||||
u.cacheReadInputTokens,
|
||||
u.webSearchRequests,
|
||||
call.speed,
|
||||
call.cacheCreationOneHourTokens ?? 0,
|
||||
)
|
||||
if (!savings) return call
|
||||
return {
|
||||
...call,
|
||||
costUSD: 0,
|
||||
savingsUSD: savings.savingsUSD,
|
||||
savingsBaselineModel: savings.baselineModel,
|
||||
isLocalSavings: true,
|
||||
}
|
||||
}
|
||||
|
||||
function parseApiCall(entry: JournalEntry): ParsedApiCall | null {
|
||||
if (entry.type !== 'assistant') return null
|
||||
const msg = entry.message as AssistantMessageContent | undefined
|
||||
|
|
@ -1083,7 +1110,7 @@ function parseApiCall(entry: JournalEntry): ParsedApiCall | null {
|
|||
return [call]
|
||||
})
|
||||
|
||||
return {
|
||||
return applyLocalModelSavings({
|
||||
provider: 'claude',
|
||||
model: msg.model,
|
||||
usage: tokens,
|
||||
|
|
@ -1100,7 +1127,7 @@ function parseApiCall(entry: JournalEntry): ParsedApiCall | null {
|
|||
deduplicationKey: msg.id ?? `claude:${entry.timestamp}`,
|
||||
cacheCreationOneHourTokens: cacheCreation.oneHourTokens || undefined,
|
||||
toolSequence: toolSeq.length > 0 ? toolSeq : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function dedupeStreamingMessageIds(entries: JournalEntry[]): JournalEntry[] {
|
||||
|
|
@ -1239,6 +1266,7 @@ function buildSessionSummary(
|
|||
const subagentBreakdown: SessionSummary['subagentBreakdown'] = Object.create(null)
|
||||
|
||||
let totalCost = 0
|
||||
let totalSavings = 0
|
||||
let totalInput = 0
|
||||
let totalOutput = 0
|
||||
let totalCacheRead = 0
|
||||
|
|
@ -1249,12 +1277,14 @@ function buildSessionSummary(
|
|||
|
||||
for (const turn of turns) {
|
||||
const turnCost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0)
|
||||
const turnSavings = turn.assistantCalls.reduce((s, c) => s + (c.savingsUSD ?? 0), 0)
|
||||
|
||||
if (!categoryBreakdown[turn.category]) {
|
||||
categoryBreakdown[turn.category] = { turns: 0, costUSD: 0, retries: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
categoryBreakdown[turn.category] = { turns: 0, costUSD: 0, savingsUSD: 0, retries: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
}
|
||||
categoryBreakdown[turn.category].turns++
|
||||
categoryBreakdown[turn.category].costUSD += turnCost
|
||||
categoryBreakdown[turn.category].savingsUSD += turnSavings
|
||||
if (turn.hasEdits) {
|
||||
categoryBreakdown[turn.category].editTurns++
|
||||
categoryBreakdown[turn.category].retries += turn.retries
|
||||
|
|
@ -1264,10 +1294,11 @@ function buildSessionSummary(
|
|||
if (turn.subCategory) {
|
||||
const skillKey = turn.subCategory
|
||||
if (!skillBreakdown[skillKey]) {
|
||||
skillBreakdown[skillKey] = { turns: 0, costUSD: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
skillBreakdown[skillKey] = { turns: 0, costUSD: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 }
|
||||
}
|
||||
skillBreakdown[skillKey].turns++
|
||||
skillBreakdown[skillKey].costUSD += turnCost
|
||||
skillBreakdown[skillKey].savingsUSD += turnSavings
|
||||
if (turn.hasEdits) {
|
||||
skillBreakdown[skillKey].editTurns++
|
||||
if (turn.retries === 0) skillBreakdown[skillKey].oneShotTurns++
|
||||
|
|
@ -1275,7 +1306,9 @@ function buildSessionSummary(
|
|||
}
|
||||
|
||||
for (const call of turn.assistantCalls) {
|
||||
const callSavings = call.savingsUSD ?? 0
|
||||
totalCost += call.costUSD
|
||||
totalSavings += callSavings
|
||||
totalInput += call.usage.inputTokens
|
||||
totalOutput += call.usage.outputTokens
|
||||
totalCacheRead += call.usage.cacheReadInputTokens
|
||||
|
|
@ -1287,11 +1320,13 @@ function buildSessionSummary(
|
|||
modelBreakdown[modelKey] = {
|
||||
calls: 0,
|
||||
costUSD: 0,
|
||||
savingsUSD: 0,
|
||||
tokens: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0 },
|
||||
}
|
||||
}
|
||||
modelBreakdown[modelKey].calls++
|
||||
modelBreakdown[modelKey].costUSD += call.costUSD
|
||||
modelBreakdown[modelKey].savingsUSD += callSavings
|
||||
modelBreakdown[modelKey].tokens.inputTokens += call.usage.inputTokens
|
||||
modelBreakdown[modelKey].tokens.outputTokens += call.usage.outputTokens
|
||||
modelBreakdown[modelKey].tokens.cacheReadInputTokens += call.usage.cacheReadInputTokens
|
||||
|
|
@ -1311,9 +1346,10 @@ function buildSessionSummary(
|
|||
bashBreakdown[cmd].calls++
|
||||
}
|
||||
for (const sat of call.subagentTypes) {
|
||||
subagentBreakdown[sat] = subagentBreakdown[sat] ?? { calls: 0, costUSD: 0 }
|
||||
subagentBreakdown[sat] = subagentBreakdown[sat] ?? { calls: 0, costUSD: 0, savingsUSD: 0 }
|
||||
subagentBreakdown[sat].calls++
|
||||
subagentBreakdown[sat].costUSD += call.costUSD
|
||||
subagentBreakdown[sat].savingsUSD += callSavings
|
||||
}
|
||||
|
||||
if (!firstTs || call.timestamp < firstTs) firstTs = call.timestamp
|
||||
|
|
@ -1327,6 +1363,7 @@ function buildSessionSummary(
|
|||
firstTimestamp: firstTs || turns[0]?.timestamp || '',
|
||||
lastTimestamp: lastTs || turns[turns.length - 1]?.timestamp || '',
|
||||
totalCostUSD: totalCost,
|
||||
totalSavingsUSD: totalSavings,
|
||||
totalInputTokens: totalInput,
|
||||
totalOutputTokens: totalOutput,
|
||||
totalCacheReadTokens: totalCacheRead,
|
||||
|
|
@ -1576,6 +1613,7 @@ async function scanProjectDirs(
|
|||
projectPath,
|
||||
sessions,
|
||||
totalCostUSD: sessions.reduce((s, sess) => s + sess.totalCostUSD, 0),
|
||||
totalSavingsUSD: sessions.reduce((s, sess) => s + sess.totalSavingsUSD, 0),
|
||||
totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0),
|
||||
})
|
||||
}
|
||||
|
|
@ -1595,7 +1633,7 @@ function providerCallToTurn(call: ParsedProviderCall): ParsedTurn {
|
|||
webSearchRequests: call.webSearchRequests,
|
||||
}
|
||||
|
||||
const apiCall: ParsedApiCall = {
|
||||
const apiCall: ParsedApiCall = applyLocalModelSavings({
|
||||
provider: call.provider,
|
||||
model: call.model,
|
||||
usage,
|
||||
|
|
@ -1610,7 +1648,7 @@ function providerCallToTurn(call: ParsedProviderCall): ParsedTurn {
|
|||
timestamp: call.timestamp,
|
||||
bashCommands: call.bashCommands,
|
||||
deduplicationKey: call.deduplicationKey,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
userMessage: call.userMessage,
|
||||
|
|
@ -1735,7 +1773,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall {
|
|||
u.cacheCreationInputTokens, u.cacheReadInputTokens,
|
||||
u.webSearchRequests, call.speed, u.cacheCreationOneHourTokens,
|
||||
)
|
||||
return {
|
||||
return applyLocalModelSavings({
|
||||
provider: call.provider,
|
||||
model: call.model,
|
||||
usage: {
|
||||
|
|
@ -1760,7 +1798,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall {
|
|||
deduplicationKey: call.deduplicationKey,
|
||||
cacheCreationOneHourTokens: u.cacheCreationOneHourTokens || undefined,
|
||||
toolSequence: call.toolSequence,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function cachedTurnToClassified(turn: CachedTurn): ClassifiedTurn {
|
||||
|
|
@ -1979,6 +2017,7 @@ async function parseProviderSources(
|
|||
projectPath: projectPath ?? unsanitizePath(dirName),
|
||||
sessions,
|
||||
totalCostUSD: sessions.reduce((s, sess) => s + sess.totalCostUSD, 0),
|
||||
totalSavingsUSD: sessions.reduce((s, sess) => s + sess.totalSavingsUSD, 0),
|
||||
totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0),
|
||||
})
|
||||
}
|
||||
|
|
@ -2077,6 +2116,7 @@ export function filterProjectsByDays(projects: ProjectSummary[], days: Set<strin
|
|||
projectPath: project.projectPath,
|
||||
sessions,
|
||||
totalCostUSD: sessions.reduce((s, sess) => s + sess.totalCostUSD, 0),
|
||||
totalSavingsUSD: sessions.reduce((s, sess) => s + sess.totalSavingsUSD, 0),
|
||||
totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0),
|
||||
})
|
||||
}
|
||||
|
|
@ -2098,6 +2138,7 @@ export function filterProjectsByDateRange(projects: ProjectSummary[], dateRange:
|
|||
projectPath: project.projectPath,
|
||||
sessions,
|
||||
totalCostUSD: sessions.reduce((s, sess) => s + sess.totalCostUSD, 0),
|
||||
totalSavingsUSD: sessions.reduce((s, sess) => s + sess.totalSavingsUSD, 0),
|
||||
totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
17
src/types.ts
17
src/types.ts
|
|
@ -86,6 +86,13 @@ export type ParsedApiCall = {
|
|||
deduplicationKey: string
|
||||
cacheCreationOneHourTokens?: number
|
||||
toolSequence?: ToolCall[][]
|
||||
/// When set, `costUSD` is the actual local call (forced to 0) and
|
||||
/// `savingsUSD` is the counterfactual cost the same tokens would have
|
||||
/// incurred against `savingsBaselineModel`. Set by the savings
|
||||
/// normalization step in `src/parser.ts`.
|
||||
savingsUSD?: number
|
||||
savingsBaselineModel?: string
|
||||
isLocalSavings?: boolean
|
||||
}
|
||||
|
||||
export type ToolCall = {
|
||||
|
|
@ -122,19 +129,20 @@ export type SessionSummary = {
|
|||
firstTimestamp: string
|
||||
lastTimestamp: string
|
||||
totalCostUSD: number
|
||||
totalSavingsUSD: number
|
||||
totalInputTokens: number
|
||||
totalOutputTokens: number
|
||||
totalCacheReadTokens: number
|
||||
totalCacheWriteTokens: number
|
||||
apiCalls: number
|
||||
turns: ClassifiedTurn[]
|
||||
modelBreakdown: Record<string, { calls: number; costUSD: number; tokens: TokenUsage }>
|
||||
modelBreakdown: Record<string, { calls: number; costUSD: number; tokens: TokenUsage; savingsUSD: number }>
|
||||
toolBreakdown: Record<string, { calls: number }>
|
||||
mcpBreakdown: Record<string, { calls: number }>
|
||||
bashBreakdown: Record<string, { calls: number }>
|
||||
categoryBreakdown: Record<TaskCategory, { turns: number; costUSD: number; retries: number; editTurns: number; oneShotTurns: number }>
|
||||
skillBreakdown: Record<string, { turns: number; costUSD: number; editTurns: number; oneShotTurns: number }>
|
||||
subagentBreakdown: Record<string, { calls: number; costUSD: number }>
|
||||
categoryBreakdown: Record<TaskCategory, { turns: number; costUSD: number; savingsUSD: number; retries: number; editTurns: number; oneShotTurns: number }>
|
||||
skillBreakdown: Record<string, { turns: number; costUSD: number; savingsUSD: number; editTurns: number; oneShotTurns: number }>
|
||||
subagentBreakdown: Record<string, { calls: number; costUSD: number; savingsUSD: number }>
|
||||
// Observed MCP tools available in this session, captured from
|
||||
// `attachment.deferred_tools_delta.addedNames` entries. Union across all
|
||||
// turns. Each name is a fully-qualified `mcp__<server>__<tool>` identifier.
|
||||
|
|
@ -148,6 +156,7 @@ export type ProjectSummary = {
|
|||
projectPath: string
|
||||
sessions: SessionSummary[]
|
||||
totalCostUSD: number
|
||||
totalSavingsUSD: number
|
||||
totalApiCalls: number
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue