mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
0.9.25: correctness, energy, menu bar and installer fixes (#1511)
* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed; codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate; openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp; sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty); codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+ grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export subfolder; providers pane fixed window; Warp credit-based cost. Desktop/menubar: unified flame logo; default DMG; docs signed+notarized. * menubar: one running instance, self-relaunch on language change The single-instance guard only retired strictly older copies, so two login items starting in the same instant both survived, and a copy whose bundle identity did not survive install was never seen at all. The decision is now total (newest launch wins, ties break on pid) and peers are matched on bundle id or executable name. --keep-both opts one launch out. Language changes no longer have the desktop app quit and reopen the menu bar, which made macOS attribute the new process to the desktop app and re-ask for the data-access grant. The menu bar relaunches itself via the existing remote command key; older menu bars that do not watch the key fall back to the old path after 5s. * desktop: export toast shows the saved path; resource buckets on app_close The export toast showed the folder that was picked, not the dated subfolder the files land in. The handler already parsed the CLI's saved line; it now returns that path and the toast uses it. app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb to its answer frames. Unmeasured figures are omitted, never sent as zero. * menubar guard never leaves zero instances; installer replaces in place; JSON export into folder Guard: an unreadable launch date on either side could make two copies retire each other. Unreadable peers now count only when their pid is lower, and a copy that cannot read its own date retires lower pids only, so a disagreement keeps at least one instance. Installer: an existing bundle in /Applications or ~/Applications is replaced where it lives instead of a second copy being added. The old bundle is moved aside and restored on any failure; a cross-volume move falls back to a copy that is re-verified with codesign. An unwritable location is never escalated: the install goes to ~/Applications and the leftover is named. Export: -o pointing at an existing folder writes the JSON inside it. Short sessions omit the cpu buckets. setLanguage reopens the menu bar if its own relaunch never comes back. AppRelaunch passes the bundle path as an argument. * menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install Guard: launch dates could be unreadable and pid order can disagree with start order after pid reuse, so two copies could still retire each other. Ordering now uses the kernel-reported process start time, which both sides read identically. A copy whose start time cannot be read is left out, so the worst case is two menu bars, never none. Installer: with the only copy in an unwritable /Applications, a plain run tried to open a path that did not exist. It now opens the installed copy. A placement killed mid-way is recovered on the next run, a concurrent install is refused, and a failed restore names where the previous bundle is. Process matching uses the exact executable name. Export: a trailing separator names a folder. Telemetry cpu is measured from telemetry start. * installer: a recycled pid can no longer block installs; language change waits for the replacement process An aside left by an earlier install counted as an active install whenever its pid was live, so once that pid was reused every install was refused for good. It now also has to be recent (ctime within 10 minutes), a pid we may not signal is not ours, the refusal names the file, and an orphan that cannot be cleared is reported instead of aborting the install. setLanguage confirmed the relaunch with a matcher the dying process still satisfied, so the reopen fallback never fired. It now waits for a pid that was not running before. * desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers An open window ran act report (a fresh CLI process each time), yield and an optimize scan on every refresh. The headline poll now passes --no-optimize and takes the snapshot path; act report refreshes on mount, on manual refresh and every 10 minutes, yield every 5. The optimize scan runs at most once a day per query scope, is stored in userData with its time, and is forced fresh by the Optimize page or a manual refresh. Figures that are not live show their age, and no stored scan means no savings clause rather than a zero. On battery the live interval doubles; the chosen cadence stays the base. * desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch The scan cache is keyed on the argv, which says 'today' or '30days', not a date, so yesterday's scan was served as today's. It is now reused only on the same local day. Stored findings in Signals carry their age, a failed scan shows the error instead of scanning forever, and the cold-boot label uses the time the app received the payload. usePolled fetched immediately whenever its interval changed, so every power transition (and launching on battery) refetched every live hook and could spawn an extra act report. Fetching and timer arming are now separate effects. Optimize's yield is on the same 5 minute tier as Overview. * desktop: re-ask for the optimize scan on the first render of a new local day An app left open across midnight kept yesterday's stored savings under Today, because the scan was only requested on mount, scope change or manual refresh. The local day is now one of the hook's triggers; the previous day's figure is dropped while the new scan runs. * serve: a menubar poll is never answered from the status snapshot Inside its settle window the status snapshot returns the pre-change payload on purpose. The resident serve process then memoized that answer as clean, so after a single write followed by quiet the headline stayed on the old figure until the next write or the five minute memo cap. The snapshot is for one-shot runs; the resident process already holds the parsed state, so it now skips it. * tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card ServeConnection takes its pid file as a parameter, so the Swift tests no longer share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the reaper only signals a record that is a serve --stdio command. Superseded session-cache, codex-results and cursor-results files (100MB+ each) are removed once untouched for 14 days, at most once a day. daily-cache and the hermes ledger are never swept: they carry sealed days a version bump adopts. The menu bar installer's leftover-copy advice is emitted as a marked line under CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is debug only. The app's vitest workers turn off Node's built-in web storage. * menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows tray. It now follows the desktop's telemetry.v1.json when that exists (read only: same install id, same on/off, onboarded required) and otherwise keeps its own state with the same region default (off in EU/EEA/UK/CH and when the region is unknown). Settings gains one Privacy toggle, disabled when the desktop owns the choice. Events use the tray's names; the daily usage snapshot is the CLI's block passed through a sanitizer and is left to the desktop when it is the consent source. Debug builds never send. A resident CLI that gets disabled for the run now says so in the log. * menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away The sender used URLSession.shared, so a server or CDN cookie and the default User-Agent rode along and would have outlived an opt-out. It now owns an ephemeral session with no cookies, no cache, a fixed agent string and no redirects. A batch that is out when the toggle goes off is dropped rather than re-queued under the fresh id. The desktop's answer is recorded locally, so a missing or damaged state file never falls back to the region default, and the standalone id is persisted when minted. The toggle stays usable as a local off switch under desktop consent. Copy states what this app actually sends. * vercel gateway spend is shown on its own row and kept out of totals by default The gateway reports daily aggregates per model, with nothing to match against the local tools that were pointed at it, so every headline counted that traffic twice. Totals now leave the gateway slice out when all providers are shown; the row keeps its full amount and is marked not in total, --provider vercel-gateway is unchanged, and codeburn gateway-totals include folds it back in. The daily cache still stores the slice, so the choice applies retroactively. Reports with no gateway credential are byte-identical. The gateway's request_count now feeds the call count instead of each daily row counting as one call. Hermes: a mid-session price change lands on the day it is observed and sealed days are never rewritten; stated in the code and changelog. * gateway exclusion applies to every report through the parse, and the detail panels follow the headline The first pass narrowed only the day totals, so By tool, top models, top projects, activities, status json projects and any project-filtered table still carried gateway spend next to a headline that did not, and By tool shares could pass 100%. The rule now lives in parseAllSessions: with all providers in scope and the opt-in off, aggregate-only sessions are dropped after the memo, and the callers that derive cached days opt out so stored slices are unchanged. day.projects is reduced like models. The gateway stays visible once, as a labelled not-in-total row with no share, and standalone reports note the excluded amount on stderr so machine output is unchanged. * dashboard: the background history index follows the gateway exclusion too The index keeps the whole corpus so it can fill the daily cache, but its per-period projection handed that unfiltered list to the project, model and activity panels, so they regained gateway spend once the index landed. * ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits The cache-lock step failed 6 of the last 60 runs with no output for five minutes after the vitest banner; passing runs take 12-18s on every Node version. Each attempt is now capped at 90s and retried once, with a warning whenever that happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn status snapshot test and the c6 parser suite get limits taken from those runs, each with its reason. Both test jobs print their ten slowest cases. * desktop: Privacy & data uses the same rows as the rest of Settings The pane mixed two static claims with two controls in its own layout. It now uses the about-row pattern every other pane uses: title and hint on the left, one control on the right. The claims became the subtitle. Rows: anonymous usage statistics (toggle, link to what is sent), device sharing state with Manage, local report snapshots with Clear, export with Open export. * desktop: Privacy & data keeps one bounded column and rows that never squeeze The card stretched with the window, stranding each control hundreds of pixels from its text. This pane's heading, subtitle and card now share a 760px column and one text measure. Rows stack on their own width, because the window can never be narrow enough for the old viewport rule to fire; row buttons do not wrap. The what-is-sent link sits on its own line, and the snapshot and export descriptions fit their measure and say this machine. * menubar tests clean up their scratch defaults and leave the real Keychain alone Four test files never removed their UserDefaults suites and the rest removed the domain but left the plist, so thousands of files piled up in ~/Library/Preferences. A shared helper forgets a suite and deletes its file, and every test that makes a suite now uses it. cfprefsd still rewrites an empty plist when the test process exits, so a run leaves about a hundred 42-byte files with no test data in them. The real-Keychain round trip only runs with CODEBURN_TEST_REAL_KEYCHAIN=1. * desktop: the resident parser retires after 15 idle minutes and restarts on demand The renderer stops polling while the window is hidden, but the serve child stayed resident with its parsed cache, one to two GB on a large corpus. After 15 minutes without a request it is stopped the way a settings restart stops it, without spending the unexpected-death budget, and the next request starts a new resident through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or disables it. * desktop: every settings pane keeps a bounded column, and dark buttons have an edge Cards stretched with the window, so on a wide display controls sat up to 1300px from their labels and intro lines ran past 140 characters. All panes now share one left-aligned column (760px, 980px for projects, aliases and pricing, which hold wide rows) and one text measure. Rows stack on their own width instead of a viewport rule the 900px minimum window could never reach, and a long path in Projects no longer overflows the pane. In dark mode the secondary button matched or sat below its surface, and was invisible on the plugin install dialog. It gets a face and a border from two new tokens; light is unchanged. The onboarding consent label matches Settings. * desktop: this device shows its fingerprint on its own line The local name and the fingerprint are two adjacent inline spans, so they read as one run of text. * menubar: the resident parser retires after 15 idle minutes and restarts on demand The menu bar kept its serve child, and the parsed cache with it, for the whole run, even with the popover closed and nothing changing. After 15 minutes without a request the child is retired without counting as a death, and the next request starts a new resident through ensureStarted, never the one-shot fallback, whose snapshot settle window would make the figure lag a whole tick. The window sits above the longest gap between real requests, so a child stays warm while work is happening. CodeBurnServeIdleSeconds tunes or disables it. * serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced With a session being written, every poll re-listed about 2,400 directories and re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month shard (49MB on a large corpus) and read it back on the next poll. The resident process now reuses the previous listing and fingerprints for paths its root watcher proves untouched, and falls back to the full sweep whenever the watcher is missing, unhealthy, overflowed, armed after the sweep, does not cover the path, the memo is older than 4.5 minutes, or the process was suspended. Shard publication is held for up to 90s and flushed when stdin closes; a held write is dropped rather than written over something another process published. One-shot runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence; time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete, rename-over, in-flight, watcher overflow and unhealthy watcher. Changelog: state the telemetry default as it is in this version. * a retired parser gets to publish its held shards, and durable providers are never held Both apps retired the serve child with SIGTERM before its stdin-close flush could run, so every retire discarded the coalesced window. They now close stdin, give the child a bounded grace to publish and exit, and signal it only if it is still running; a settings restart does the same. Measured: flushed 0/5 before, 5/5 after, for both clients. copilot's cache entries are the only record once Copilot prunes its own files, so a held window that was dropped (retire, crash, kill -9) before the source was pruned lost that spend for good. A window that a durable provider dirtied is published on the poll that parsed it, as before coalescing existed. The RSS guard publishes a held window before it clears the caches instead of discarding it. * serve: release the lifetime parse after the fill, and make the collection real The RSS guard dropped its memos and then called globalThis.gc, which exists only under --expose-gc; no launcher passes it, so the collection had never run and the freed pages never went back. On a cold start the resident idled at 2.2GB with 364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by 700MB. After the background fill has sealed its summaries the process now publishes any held shard window, drops the memos it can re-read from disk (the cold start had loaded the cache with scope 'all', which then served every later poll), and collects; it collects again a minute later for as long as a pass returns 64MB, at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are leaf-identical cold and warm, time-to-reflect unchanged, a released month scope reloads in 0.3-0.5s. * warp: the billed cost reaches reports and survives the cache The provider derived a dollar cost from Warp's own billing record (provider cents, charged usage, or credits), but warp was missing from the reported-cost pass-through, so the cached call kept no cost and every report, cold or warm, priced the conversation from its tokens. A fixture billed at $1.22 reported $0.15. A call whose cost came from a billing record now keeps it; a call that only has the token floor stores none and is still re-priced when prices change. Warp entries re-parse once (provider parse version), and the daily cache moves to v34 so days whose Warp source still exists re-derive; call counts do not move, so nothing is double counted or dropped. * openclaw and pi: a reported cost survives the cache like every other reported cost Both providers read the cost their tool recorded for a message, and both were missing from the reported-cost pass-through, so reports priced every call from tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013 against $0.410 (pi). A call with a reported cost now keeps it; a call with none, or an explicit zero, stores none and is still re-priced when prices change. omp had been added to the list in #1150 and pi, the same parser, was never revisited. The provider list is one named set, the unreachable providerCallToTurn is gone, and both providers re-parse once; the v34 daily cache re-derives their days with call counts unchanged. * test: pin parse count per report and per resident poll
This commit is contained in:
parent
ea78d36ccf
commit
2fc62f7876
155 changed files with 9251 additions and 783 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { billableOutputTokens, fallbackRawModelDisplayName, getModelCosts, getShortModelName, sanitizeModelForDisplay, type ModelCosts } from './models.js'
|
||||
import { getProvider } from './providers/index.js'
|
||||
import { formatCost, formatTokens } from './format.js'
|
||||
|
|
@ -101,7 +101,7 @@ export async function aggregateAudit(projects: ProjectSummary[]): Promise<AuditR
|
|||
bucket.attributedCostUSD += call.costUSD
|
||||
// Supplementary accounting calls keep their tokens and cost above but are not
|
||||
// distinct requests, so they add no call weight (see behavioral-weight.ts).
|
||||
if (isBehavioralCall(call)) bucket.calls += 1
|
||||
bucket.calls += behavioralCallWeight(call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,18 +8,30 @@
|
|||
// history. Token and cost sums intentionally keep every call —
|
||||
// supplementary accounting must never be filtered out, only weightless.
|
||||
|
||||
type WeightedCall = { supplementaryAccounting?: boolean }
|
||||
type WeightedCall = { supplementaryAccounting?: boolean; requestCount?: number }
|
||||
type WeightedTurn = { assistantCalls: readonly WeightedCall[] }
|
||||
|
||||
/** True when the call is a real request (weight 1); false for supplementary accounting (weight 0). */
|
||||
/** True when the call is a real request; false for supplementary accounting (weight 0). */
|
||||
export function isBehavioralCall(call: WeightedCall): boolean {
|
||||
return !call.supplementaryAccounting
|
||||
}
|
||||
|
||||
/// How many requests one served call stands for. Normally 1. A provider that
|
||||
/// only publishes DAILY AGGREGATES (Vercel AI Gateway's /v1/report, one row per
|
||||
/// day+model carrying `request_count`) has no per-request record to yield, so
|
||||
/// its single call carries the count instead — synthesizing N empty calls would
|
||||
/// fabricate rows in every session drill-down and scale with the user's traffic.
|
||||
/// Cost and tokens stay on the one call, so only request counters move.
|
||||
export function behavioralCallWeight(call: WeightedCall): number {
|
||||
if (call.supplementaryAccounting) return 0
|
||||
const count = call.requestCount
|
||||
return count != null && Number.isFinite(count) && count > 0 ? Math.floor(count) : 1
|
||||
}
|
||||
|
||||
/** Number of real requests among a turn's calls. */
|
||||
export function behavioralCallCount(calls: readonly WeightedCall[]): number {
|
||||
let n = 0
|
||||
for (const call of calls) if (!call.supplementaryAccounting) n++
|
||||
for (const call of calls) n += behavioralCallWeight(call)
|
||||
return n
|
||||
}
|
||||
|
||||
|
|
|
|||
66
src/cache-sweep.ts
Normal file
66
src/cache-sweep.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { lstat, readdir, stat, unlink, writeFile } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
|
||||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||||
import { CODEX_CACHE_VERSION } from './codex-cache.js'
|
||||
import { CURSOR_CACHE_VERSION } from './cursor-cache.js'
|
||||
import { CACHE_VERSION } from './session-cache.js'
|
||||
|
||||
const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000
|
||||
const STALE_AFTER_MS = 14 * 24 * 60 * 60 * 1000
|
||||
const STAMP_FILE = 'cache-sweep.stamp'
|
||||
|
||||
/// `<family>.v<n>.json`, plus the two shapes a family's own history takes: the
|
||||
/// pre-versioning `<family>.json` and the `<family>.json.v<n>.bak` copies.
|
||||
/// The family part admits no digits or dots, so `status-snapshot.<hash>.json`
|
||||
/// and every credential file fall outside it.
|
||||
const CACHE_FILENAME = /^([a-z-]+)(?:\.v(\d+))?\.json(?:\.v(\d+)\.bak)?$/
|
||||
|
||||
/// Only caches that re-derive in full from the session files. daily-cache and
|
||||
/// hermes-session-ledger are left out on purpose: they hold sealed days whose
|
||||
/// sources may be gone, and a version bump reads every older copy to carry them.
|
||||
function currentVersions(): Record<string, number> {
|
||||
return {
|
||||
'session-cache': CACHE_VERSION,
|
||||
'codex-results': CODEX_CACHE_VERSION,
|
||||
'cursor-results': CURSOR_CACHE_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
/// True only for a KNOWN cache family at a version this binary has moved past
|
||||
/// (the unversioned legacy name counts as the oldest version there is).
|
||||
export function isSupersededCacheFile(name: string): boolean {
|
||||
const match = CACHE_FILENAME.exec(name)
|
||||
if (!match) return false
|
||||
const current = currentVersions()[match[1]!]
|
||||
if (current === undefined) return false
|
||||
const version = match[2] ?? match[3]
|
||||
return version === undefined || Number(version) < current
|
||||
}
|
||||
|
||||
/// Delete cache files a version bump left behind — a single superseded
|
||||
/// session-cache runs to 100MB+ and nothing ever reclaimed them. Deliberately
|
||||
/// timid: known filenames only, strictly older versions only, plain files
|
||||
/// only (never a directory or a symlink), inside the resolved cache dir only,
|
||||
/// and only once a file has gone untouched for a fortnight — an older CLI or
|
||||
/// menubar still in use keeps writing its own files, so they survive.
|
||||
export async function sweepSupersededCacheFiles(now = Date.now()): Promise<void> {
|
||||
try {
|
||||
const dir = getCodeburnCacheDir()
|
||||
const stamp = join(dir, STAMP_FILE)
|
||||
const lastSweep = await stat(stamp).then(s => s.mtimeMs, () => 0)
|
||||
if (now - lastSweep < SWEEP_INTERVAL_MS) return
|
||||
// Stamped before the pass, so a failure mid-sweep waits for tomorrow
|
||||
// rather than retrying on every save.
|
||||
await writeFile(stamp, '')
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
if (!entry.isFile() || !isSupersededCacheFile(entry.name)) continue
|
||||
const path = join(dir, entry.name)
|
||||
const stats = await lstat(path).catch(() => null)
|
||||
if (!stats?.isFile() || now - stats.mtimeMs < STALE_AFTER_MS) continue
|
||||
await unlink(path).catch(() => {})
|
||||
}
|
||||
} catch {
|
||||
// Housekeeping never fails a save.
|
||||
}
|
||||
}
|
||||
|
|
@ -171,7 +171,13 @@ async function loadCacheFromDisk(cacheDir: string): Promise<ResultCache> {
|
|||
function getEntry(cache: ResultCache, filePath: string, fp: FileFingerprint): FileEntry | null {
|
||||
if (!Object.hasOwn(cache.files, filePath)) return null
|
||||
const entry = cache.files[filePath]
|
||||
if (entry && entry.mtimeMs === fp.mtimeMs && entry.sizeBytes === fp.sizeBytes) {
|
||||
if (
|
||||
entry
|
||||
&& entry.dev === fp.dev
|
||||
&& entry.ino === fp.ino
|
||||
&& entry.mtimeMs === fp.mtimeMs
|
||||
&& entry.sizeBytes === fp.sizeBytes
|
||||
) {
|
||||
return entry
|
||||
}
|
||||
return null
|
||||
|
|
|
|||
|
|
@ -33,10 +33,19 @@ const ACTIVITY_CREDIT_MODELS: Record<string, string> = {
|
|||
export function codexCreditRate(model: string): CodexCreditRate | null {
|
||||
const mapped = ACTIVITY_CREDIT_MODELS[model] ?? ACTIVITY_CREDIT_MODELS[model.toLowerCase()]
|
||||
const m = (mapped ?? model).toLowerCase()
|
||||
if (m.includes('5.4') && m.includes('mini')) return CREDITS_PER_MILLION['gpt-5.4-mini']!
|
||||
if (m.includes('5.4')) return CREDITS_PER_MILLION['gpt-5.4']!
|
||||
if (m.includes('5.5')) return CREDITS_PER_MILLION['gpt-5.5']!
|
||||
return null
|
||||
// Match the version only at a token boundary (start/'-' before, '-'/end
|
||||
// after) so a bare `includes('5.4')` can't catch a substring. The tokens
|
||||
// AFTER the version give the SKU tier: only the base and `-mini` SKUs have
|
||||
// credit rates, so a distinct sibling tier (gpt-5.4-pro, gpt-5.4-nano) must
|
||||
// fall through to the unknown fallback instead of billing at the base rate.
|
||||
const match = m.match(/(?:^|-)(5\.[45])(?:-|$)/)
|
||||
if (!match) return null
|
||||
const version = match[1]!
|
||||
const tierTokens = m.slice(match.index! + match[0].length).split('-')
|
||||
if (tierTokens.includes('pro') || tierTokens.includes('nano')) return null
|
||||
if (version === '5.4' && tierTokens.includes('mini')) return CREDITS_PER_MILLION['gpt-5.4-mini']!
|
||||
if (version === '5.4') return CREDITS_PER_MILLION['gpt-5.4']!
|
||||
return CREDITS_PER_MILLION['gpt-5.5']!
|
||||
}
|
||||
|
||||
export type CodexCreditTokens = {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { readdir, readFile } from 'fs/promises'
|
|||
import { basename, join } from 'path'
|
||||
|
||||
import type { ClassifiedTurn, ProjectSummary } from './types.js'
|
||||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight, isBehavioralCall } from './behavioral-weight.js'
|
||||
import { modelRowKey } from './models.js'
|
||||
import { callBillableOutputTokens } from './session-output.js'
|
||||
|
||||
|
|
@ -66,7 +66,7 @@ export function aggregateModelStats(projects: ProjectSummary[]): ModelStats[] {
|
|||
for (const call of turn.assistantCalls) {
|
||||
if (call.model === '<synthetic>') continue
|
||||
const cs = call.model === primaryModel ? ms : ensure(call.model)
|
||||
if (isBehavioralCall(call)) cs.calls++
|
||||
cs.calls += behavioralCallWeight(call)
|
||||
cs.cost += call.costUSD
|
||||
cs.outputTokens += callBillableOutputTokens(call)
|
||||
cs.inputTokens += call.usage.inputTokens
|
||||
|
|
|
|||
|
|
@ -70,6 +70,29 @@ export type CodeburnConfig = {
|
|||
// Matched against the canonical project path: prefix on a path-segment
|
||||
// boundary, case-insensitive, trailing-slash and backslash tolerant.
|
||||
proxyPaths?: string[]
|
||||
// Vercel AI Gateway rows are DAILY AGGREGATES per model with no request id,
|
||||
// timestamp or attribution (see src/providers/vercel-gateway.ts), so they
|
||||
// cannot be matched against the local tools that were pointed at the gateway
|
||||
// (Claude Code via ANTHROPIC_BASE_URL, Codex, OpenCode, Cline/Roo/Kilo,
|
||||
// Cursor) — counting both double counts the same spend. Gateway rows are
|
||||
// therefore always shown as their own labelled row but kept OUT of every
|
||||
// headline total unless this is true. Read-side only: the daily cache always
|
||||
// seals the gateway slice, so flipping this re-includes sealed days without
|
||||
// re-fetching anything.
|
||||
includeGatewayInTotals?: boolean
|
||||
}
|
||||
|
||||
// Read synchronously by the aggregator on every period build, so it is set
|
||||
// once per process from config.json (the `preAction` hook), the same way
|
||||
// models.ts holds the pricing config.
|
||||
let includeGatewayInTotals = false
|
||||
|
||||
export function setIncludeGatewayInTotals(value: boolean): void {
|
||||
includeGatewayInTotals = value
|
||||
}
|
||||
|
||||
export function gatewayIncludedInTotals(): boolean {
|
||||
return includeGatewayInTotals
|
||||
}
|
||||
|
||||
function getConfigDir(): string {
|
||||
|
|
|
|||
|
|
@ -62,7 +62,20 @@ async function readCacheFile(path: string): Promise<ResultCache | null> {
|
|||
async function getDbFingerprint(dbPath: string): Promise<{ mtimeMs: number; size: number } | null> {
|
||||
try {
|
||||
const s = await stat(dbPath)
|
||||
return { mtimeMs: s.mtimeMs, size: s.size }
|
||||
// Cursor writes chat usage through the WAL, so new activity lands in
|
||||
// state.vscdb-wal while the main file's mtime/size stay put. Fold the WAL
|
||||
// into the fingerprint (mirrors fingerprintDatabase in sqlite.ts).
|
||||
let wal: Awaited<ReturnType<typeof stat>> | null = null
|
||||
try {
|
||||
wal = await stat(dbPath + '-wal')
|
||||
} catch (err) {
|
||||
// -wal absent (checkpointed) is expected; anything else fails the read.
|
||||
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err
|
||||
}
|
||||
return {
|
||||
mtimeMs: wal ? Math.max(s.mtimeMs, wal.mtimeMs) : s.mtimeMs,
|
||||
size: s.size + (wal?.size ?? 0),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'fs/promise
|
|||
import { join } from 'path'
|
||||
|
||||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||||
import { sweepSupersededCacheFiles } from './cache-sweep.js'
|
||||
import type { ProjectFilterTarget } from './parser.js'
|
||||
import type { DateRange, ProjectSummary } from './types.js'
|
||||
|
||||
|
|
@ -189,7 +190,15 @@ import type { DateRange, ProjectSummary } from './types.js'
|
|||
// which re-derive to the same rows for direct calls and to "(Bedrock)" rows
|
||||
// for Bedrock-shaped ids, but its Hermes column routes are unrecoverable
|
||||
// without a re-parse, so hermes joins PENDING_REDERIVE_PROVIDER_VERSIONS.
|
||||
export const DAILY_CACHE_VERSION = 33
|
||||
// v34: Warp cost accounting changed the same way kiro's did at v11 - Warp's
|
||||
// own billing record (provider cost / charged usage / metered credits) now
|
||||
// passes through the session cache instead of being re-priced from the token
|
||||
// floor, which understated or overstated every Warp day. Days finalized at v33
|
||||
// carry the floor figure; the bump re-derives those whose Warp conversations
|
||||
// still exist (Warp's sqlite is durable, so effectively all of them) and
|
||||
// carries the rest forward untouched. Call counts are unchanged, so no
|
||||
// PENDING_REDERIVE entry is needed and the partial-survival guard is unaffected.
|
||||
export const DAILY_CACHE_VERSION = 34
|
||||
const MIN_SUPPORTED_VERSION = 28
|
||||
|
||||
/// Providers whose per-day CALL COUNT means something different at
|
||||
|
|
@ -698,6 +707,8 @@ export async function saveDailyCache(cache: DailyCache): Promise<void> {
|
|||
try { await unlink(tempPath) } catch { /* ignore */ }
|
||||
throw err
|
||||
}
|
||||
// Off the hot path and at most once a day: the save is already done.
|
||||
await sweepSupersededCacheFiles()
|
||||
}
|
||||
|
||||
export function addNewDays(cache: DailyCache, incoming: DailyEntry[], newestDate: string): DailyCache {
|
||||
|
|
@ -1270,6 +1281,36 @@ export function getDaysInRange(cache: DailyCache, start: string, end: string): D
|
|||
return cache.days.filter(d => d.date >= start && d.date <= end)
|
||||
}
|
||||
|
||||
function phantomAmountBucket(cost: number): string {
|
||||
if (cost < 1) return '<$1'
|
||||
if (cost < 10) return '$1-10'
|
||||
if (cost < 100) return '$10-100'
|
||||
if (cost < 1000) return '$100-1000'
|
||||
return '>$1000'
|
||||
}
|
||||
|
||||
/// DETECTION-ONLY tripwire for the "phantom spend" anomaly: a rare, non-repro
|
||||
/// over-count that attributed cost/calls to days with ZERO underlying source
|
||||
/// records. Pure observer — never changes a day, a total, or any output; it only
|
||||
/// warns (at most once per run). A non-carried day is expected to be backed by a
|
||||
/// fresh source record for its date; a carried/preserved day legitimately has
|
||||
/// spend with no live records (its session files expired), so it is never
|
||||
/// suspect. `datesWithSourceRecords` is the set of dates the fresh parse
|
||||
/// actually produced records for (a date is in it iff it had >=1 record).
|
||||
export function detectPhantomSpend(
|
||||
days: DailyEntry[],
|
||||
datesWithSourceRecords: ReadonlySet<string>,
|
||||
warn: (message: string) => void = message => console.warn(message),
|
||||
): void {
|
||||
for (const day of days) {
|
||||
if (day.carried === true) continue
|
||||
if (day.cost <= 0 && day.calls <= 0) continue
|
||||
if (datesWithSourceRecords.has(day.date)) continue
|
||||
warn(`codeburn: phantom-spend guard tripped — ${day.date} has spend without source records (${phantomAmountBucket(day.cost)}); totals unchanged, please report`)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let lockChain: Promise<unknown> = Promise.resolve()
|
||||
|
||||
export function withDailyCacheLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
|
|
@ -1472,6 +1513,14 @@ export async function ensureCacheHydrated(
|
|||
const merged = parseWasComplete
|
||||
? mergeDayEntries(freshDays, baseline, true, tzSubtraction, true, pendingRederive)
|
||||
: mergeDayEntries(baseline, freshDays, false)
|
||||
// Only the complete re-derive re-parses the whole window, so freshDays is
|
||||
// the authoritative record set and every non-carried merged day should be
|
||||
// one of them; the partial path only fills gaps and cannot vouch for
|
||||
// record presence, so it is not checked. Observer only — wrapped so it can
|
||||
// never affect hydration.
|
||||
if (parseWasComplete) {
|
||||
try { detectPhantomSpend(merged, new Set(freshDays.map(d => d.date))) } catch { /* detection must never break hydration */ }
|
||||
}
|
||||
c = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash,
|
||||
|
|
|
|||
|
|
@ -4,14 +4,14 @@ import { EventEmitter } from 'node:events'
|
|||
import React, { Fragment, useState, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react'
|
||||
import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement, type Instance, type RenderOptions } from 'ink'
|
||||
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import { formatCost, formatTokens, markEstimated, carriedCostNote } from './format.js'
|
||||
import { formatCost, formatTokens, markEstimated, carriedCostNote, excludedGatewayNote } from './format.js'
|
||||
import { maxOf } from './math-utils.js'
|
||||
import { formatSessionCount } from './session-count-label.js'
|
||||
import { aggregateModelEfficiency } from './model-efficiency.js'
|
||||
import { parseAllSessions, filterProjectsByDateRange, filterProjectsByName, setInteractiveScanUI, withSinglePassParse, withColdFirstPaintFloor, filesParsedFromSourceCount, isCompleteSessionSnapshotAvailable } from './parser.js'
|
||||
import { parseAllSessions, excludeAggregateOnlyProjects, filterProjectsByDateRange, filterProjectsByName, setInteractiveScanUI, withSinglePassParse, withColdFirstPaintFloor, filesParsedFromSourceCount, isCompleteSessionSnapshotAvailable } from './parser.js'
|
||||
import { findUnpricedModels, isExpectedFreeModel, loadPricing } from './models.js'
|
||||
import { aggregateModelTotals } from './model-breakdown.js'
|
||||
import { buildDurableOverviewFromNormalizedIndex, buildDurablePeriod, hydrateDailyCacheFromNormalizedProjects } from './usage-aggregator.js'
|
||||
import { buildDurableOverviewFromNormalizedIndex, buildDurablePeriod, hydrateDailyCacheFromNormalizedProjects, type ExcludedGatewayTotals } from './usage-aggregator.js'
|
||||
import { loadDailyCache, type DailyCache } from './daily-cache.js'
|
||||
import { exitAfterCacheCleanup } from './session-cache.js'
|
||||
import { getAllProviders } from './providers/index.js'
|
||||
|
|
@ -373,6 +373,10 @@ export type DurableOverview = {
|
|||
// its total may exceed what the (live-scan-bounded) Daily Activity panel
|
||||
// below can show. See carriedCostNote in format.ts.
|
||||
carriedCostUSD: number
|
||||
// Gateway spend shown on its own labelled row but held out of `cost`.
|
||||
// Optional like OverviewDurable's: a fixture or an older persisted shape
|
||||
// simply has nothing to footnote. See excludedGatewayNote in format.ts.
|
||||
excludedGateway?: ExcludedGatewayTotals
|
||||
}
|
||||
|
||||
function getDurableRange(period: Period, customRange: DateRange | null | undefined, day: string | null): DateRange {
|
||||
|
|
@ -388,7 +392,7 @@ async function computeDurableOverview(
|
|||
day: string | null,
|
||||
): Promise<DurableOverview> {
|
||||
const range = getDurableRange(period, customRange, day)
|
||||
const { data, carriedCostUSD } = await buildDurablePeriod(
|
||||
const { data, carriedCostUSD, excludedGateway } = await buildDurablePeriod(
|
||||
{ range, label: PERIOD_LABELS[period] },
|
||||
{ provider, project: projectFilter ?? [], exclude: excludeFilter ?? [] },
|
||||
)
|
||||
|
|
@ -403,6 +407,7 @@ async function computeDurableOverview(
|
|||
cacheReadTokens: data.cacheReadTokens,
|
||||
cacheWriteTokens: data.cacheWriteTokens,
|
||||
carriedCostUSD,
|
||||
excludedGateway,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -638,6 +643,9 @@ function Overview({ projects, label, width, planUsages, durable }: { projects: P
|
|||
{durable && carriedCostNote(durable.carriedCostUSD) && (
|
||||
<Text dimColor wrap="truncate-end"> {carriedCostNote(durable.carriedCostUSD)}</Text>
|
||||
)}
|
||||
{durable && excludedGatewayNote(durable.excludedGateway?.costUSD ?? 0) && (
|
||||
<Text dimColor wrap="truncate-end"> {excludedGatewayNote(durable.excludedGateway?.costUSD ?? 0)}</Text>
|
||||
)}
|
||||
{activePlanUsages.length > 0 && (
|
||||
<>
|
||||
{activePlanUsages.map(planUsage => {
|
||||
|
|
@ -2339,7 +2347,10 @@ export async function buildDashboardHistoryIndex(
|
|||
): Promise<DashboardHistoryIndex> {
|
||||
const readyThrough = options.readyThrough ?? 'lifetime'
|
||||
const range = dashboardIndexScanRange(readyThrough)
|
||||
const parse = () => parseAllSessions(range, provider)
|
||||
// Feeds hydrateDailyCacheFromNormalizedProjects below, so it takes the whole
|
||||
// corpus; the period projection holds the aggregate-only provider out of its
|
||||
// totals instead (buildDurableOverviewFromNormalizedIndex).
|
||||
const parse = () => parseAllSessions(range, provider, { includeAggregateOnly: true })
|
||||
const normalizedProjects = options.preferCompleteSnapshot || options.progressiveSource
|
||||
? (await withColdFirstPaintFloor(
|
||||
range.start,
|
||||
|
|
@ -2364,7 +2375,8 @@ export function selectDashboardHistoryIndex(
|
|||
period: Period,
|
||||
): { projects: ProjectSummary[]; durable: DurableOverview } {
|
||||
const filtered = filterProjectsByName(index.normalizedProjects, index.projectFilter, index.excludeFilter)
|
||||
const projects = filterProjectsByDateRange(filtered, getPeriodRange(period))
|
||||
// The index holds the whole corpus for the cache fill; the panels follow the headline.
|
||||
const projects = excludeAggregateOnlyProjects(filterProjectsByDateRange(filtered, getPeriodRange(period)), index.provider)
|
||||
const durable = buildDurableOverviewFromNormalizedIndex(
|
||||
{ range: getPeriodRange(period), label: PERIOD_LABELS[period] },
|
||||
index.normalizedProjects,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { DailyEntry, ProjectDayStats, ProviderDaySlice } from './daily-cache.js'
|
||||
import type { PeriodData } from './menubar-json.js'
|
||||
import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight, isBehavioralTurn } from './behavioral-weight.js'
|
||||
import { billableOutputTokens, modelRowKey } from './models.js'
|
||||
|
||||
function emptyEntry(date: string): DailyEntry {
|
||||
|
|
@ -180,7 +180,7 @@ export function aggregateProjectsIntoDays(projects: ProjectSummary[], dateKeyFn:
|
|||
// accounting call contributes cost/tokens but is not a distinct
|
||||
// request, so it must not increment any `calls` counter the daily
|
||||
// cache seals (day, project, model, provider slice).
|
||||
const callWeight = isBehavioralCall(call) ? 1 : 0
|
||||
const callWeight = behavioralCallWeight(call)
|
||||
// Call-derived values bucket under the call's OWN day (see the
|
||||
// two-rule comment above). An unparseable call timestamp falls back
|
||||
// to the turn's anchor day rather than producing a garbage date key.
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { dirname, join, resolve } from 'path'
|
|||
import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import { getCurrency, convertCost, roundForActiveCurrency } from './currency.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { behavioralTurnCount, isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight, behavioralTurnCount } from './behavioral-weight.js'
|
||||
import { aggregateModelEfficiency } from './model-efficiency.js'
|
||||
import { callBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js'
|
||||
|
||||
|
|
@ -64,7 +64,7 @@ function buildDailyRows(projects: ProjectSummary[], period: string): Row[] {
|
|||
// Same weight rule as aggregateProjectsIntoDays: a supplementary
|
||||
// accounting call carries cost/tokens but is not a distinct request,
|
||||
// so daily.csv call counts must reconcile with summary.csv.
|
||||
if (isBehavioralCall(call)) daily[day].calls++
|
||||
daily[day].calls += behavioralCallWeight(call)
|
||||
daily[day].input += call.usage.inputTokens
|
||||
daily[day].output += callBillableOutputTokens(call)
|
||||
daily[day].cacheRead += call.usage.cacheReadInputTokens
|
||||
|
|
@ -386,6 +386,15 @@ export async function exportCsv(periods: PeriodExport[], outputPath: string): Pr
|
|||
folder = folder.slice(0, -4)
|
||||
}
|
||||
|
||||
// The desktop app (and any `-o <existing dir>`) hands us a real folder like the
|
||||
// Desktop, not a slot to fill: writing our ~11 files straight in would trip the
|
||||
// reuse guard below. Nest the export in a dated subfolder of our own and let the
|
||||
// guard apply to that. A folder we made earlier (marker present) is reused as-is.
|
||||
const targetStat = await stat(folder).catch(() => null)
|
||||
if (targetStat?.isDirectory() && !(await isCodeburnExportFolder(folder))) {
|
||||
folder = join(folder, `codeburn-export-${new Date().toISOString().slice(0, 10)}`)
|
||||
}
|
||||
|
||||
const existingStat = await stat(folder).catch(() => null)
|
||||
if (existingStat?.isFile()) {
|
||||
throw new Error(`Refusing to overwrite existing file at ${folder}. Pass a directory path instead.`)
|
||||
|
|
@ -445,7 +454,17 @@ export async function exportJson(periods: PeriodExport[], outputPath: string): P
|
|||
shellCommands: buildBashRows(thirtyDayProjects),
|
||||
}
|
||||
|
||||
const target = resolve(outputPath.toLowerCase().endsWith('.json') ? outputPath : `${outputPath}.json`)
|
||||
// The desktop app (and any `-o <existing dir>`) hands us a real folder, not a slot to
|
||||
// fill: appending `.json` to it wrote a sibling *of* the folder. Name a dated file
|
||||
// inside it instead, the same name exportCsv gives its dated subfolder. A path written
|
||||
// with a trailing separator says folder just as plainly, whether or not it exists yet.
|
||||
const namedAsFolder = /[\\/]$/.test(outputPath)
|
||||
let target = resolve(outputPath)
|
||||
if (namedAsFolder || (await stat(target).catch(() => null))?.isDirectory()) {
|
||||
target = join(target, `codeburn-export-${new Date().toISOString().slice(0, 10)}.json`)
|
||||
} else if (!target.toLowerCase().endsWith('.json')) {
|
||||
target = `${target}.json`
|
||||
}
|
||||
// Refuse to overwrite an existing file that wasn't produced by codeburn
|
||||
// export. CSV path has the same guard via the .codeburn-export marker; JSON
|
||||
// was missing it, so a stray `-o ~/important.json` would silently clobber.
|
||||
|
|
|
|||
|
|
@ -26,6 +26,17 @@ export function carriedCostNote(carriedCostUSD: number): string | null {
|
|||
return carriedCostUSD > 0 ? `includes ${formatCost(carriedCostUSD)} preserved from expired session logs` : null
|
||||
}
|
||||
|
||||
/// Shared wording for the gateway-exclusion footnote. A Vercel AI Gateway row
|
||||
/// is a daily aggregate the local tools routed through the gateway already
|
||||
/// report, so it is shown but never added to a total. overview.ts and
|
||||
/// dashboard.tsx both print this so a headline that is short of the provider
|
||||
/// list explains itself.
|
||||
export function excludedGatewayNote(excludedGatewayCostUSD: number): string | null {
|
||||
return excludedGatewayCostUSD > 0
|
||||
? `excludes ${formatCost(excludedGatewayCostUSD)} of Vercel AI Gateway daily totals (your local tools may already count it) — include with: codeburn gateway-totals include`
|
||||
: null
|
||||
}
|
||||
|
||||
export function formatTokens(n: number): string {
|
||||
// Guard against Infinity / NaN / negatives that would otherwise leak into
|
||||
// the UI as "Infinity" or "NaN" strings when an upstream calculation glitches.
|
||||
|
|
|
|||
108
src/main.ts
108
src/main.ts
|
|
@ -5,22 +5,23 @@ import { exportCsv, exportJson, type PeriodExport } from './export.js'
|
|||
import { findUnpricedModels, modelRowKey, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setFlatRateModels, setFlatRateRemoved, setProxyPaths, normalizeProxyPath, unpricedModelHint, isBuiltInFlatRateModel, isSameFlatRateModel, getProxyPathsConfigHash, getModelAliasesConfigHash, getPriceOverridesConfigHash, getLocalModelSavingsConfigHash, getFlatRateModelsConfigHash, getPricingGenerationKey } from './models.js'
|
||||
import { cachedProjectIdentitiesForRange } from './daily-cache.js'
|
||||
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
|
||||
import { getVercelGatewayApiKey } from './providers/vercel-gateway.js'
|
||||
import { BILLING_FILTER_VALUES, ROUTE_FILTER_VALUES, filterProjectsByBillingRoute } from './billing-filter.js'
|
||||
import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI, computeCorpusFingerprint, isSessionHydrationComplete } from './parser.js'
|
||||
import { AGGREGATE_ONLY_PROVIDER, aggregateOnlyCostUSD, excludesAggregateOnlyProviders, parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI, computeCorpusFingerprint, isSessionHydrationComplete } from './parser.js'
|
||||
import { allProviderNames, getAllProviders } from './providers/index.js'
|
||||
import { getProvider } from './providers/index.js'
|
||||
import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js'
|
||||
import { convertCost, formatCost } from './currency.js'
|
||||
import { formatTokens, renderStatusBar } from './format.js'
|
||||
import { excludedGatewayNote, formatTokens, renderStatusBar } from './format.js'
|
||||
import { toDateString } from './daily-cache.js'
|
||||
import { statusSnapshotSemanticKey } from './status-snapshot-semantic.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { inferSessionProvider } from './session-output.js'
|
||||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import type { AppliedFix } from './act/types.js'
|
||||
import { aggregateModelEfficiency } from './model-efficiency.js'
|
||||
import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, getDailyCacheConfigHash, type DurablePeriod } from './usage-aggregator.js'
|
||||
import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, getDailyCacheConfigHash, SERVE_HYDRATION_ENV, type DurablePeriod } from './usage-aggregator.js'
|
||||
import { aggregateProjectsIntoDays } from './day-aggregator.js'
|
||||
import { buildPeriodDiffReport, defaultSevenDayRanges, diffSessions, dayKeyToRange, historyBasis, localRangeInfo } from './period-diff.js'
|
||||
import { loadStatusSnapshot, saveStatusSnapshot } from './session-cache.js'
|
||||
|
|
@ -51,7 +52,7 @@ import {
|
|||
runAgyStatusLineHook,
|
||||
uninstallAntigravityStatusLineHook,
|
||||
} from './antigravity-statusline.js'
|
||||
import { clearPlan, readConfig, readPlan, readPlans, saveConfig, savePlan, getConfigFilePath, type CodeburnConfig, type Plan, type PlanId, type PlanProvider } from './config.js'
|
||||
import { clearPlan, readConfig, readPlan, readPlans, saveConfig, savePlan, getConfigFilePath, setIncludeGatewayInTotals, gatewayIncludedInTotals, type CodeburnConfig, type Plan, type PlanId, type PlanProvider } from './config.js'
|
||||
import { clampResetDay, copilotCreditsNote, getPlanUsageOrNull, getPlanUsages, type PlanUsage } from './plan-usage.js'
|
||||
import { getPresetPlan, isPlanId, isPlanProvider, PLAN_IDS, PLAN_PROVIDERS, planDisplayName } from './plans.js'
|
||||
import { createRequire } from 'node:module'
|
||||
|
|
@ -545,12 +546,27 @@ program.hook('preAction', async (thisCommand) => {
|
|||
setFlatRateModels(config.flatRateModels ?? [])
|
||||
setFlatRateRemoved(config.flatRateModelsRemoved ?? [])
|
||||
setProxyPaths(config.proxyPaths ?? [])
|
||||
setIncludeGatewayInTotals(config.includeGatewayInTotals === true)
|
||||
if (thisCommand.opts<{ verbose?: boolean }>().verbose) {
|
||||
process.env['CODEBURN_VERBOSE'] = '1'
|
||||
}
|
||||
await loadCurrency()
|
||||
})
|
||||
|
||||
/// Every standalone report (`models`, `sessions`, `export`, `compare`,
|
||||
/// `compare-periods`, `spend`, `yield`, `audit`, `web`, `optimize`) leaves the
|
||||
/// aggregate-only gateway corpus out of its totals, the same rule the headline
|
||||
/// uses. Say so once, on stderr — beside the unmatched-`--project` warning that
|
||||
/// already lives at these call sites — so every stdout body (text, JSON, CSV)
|
||||
/// stays byte-identical to a run with no gateway credential. Gated on the
|
||||
/// credential: without one there is no gateway corpus and this costs nothing.
|
||||
async function reportExcludedGatewayCost(range: DateRange, provider?: string): Promise<void> {
|
||||
if (!excludesAggregateOnlyProviders(provider) || !getVercelGatewayApiKey()) return
|
||||
// Same memo entry the caller just filled, so this is a sum, not a re-parse.
|
||||
const note = excludedGatewayNote(aggregateOnlyCostUSD(await parseAllSessions(range, provider, { includeAggregateOnly: true })))
|
||||
if (note) process.stderr.write(`codeburn: ${note}\n`)
|
||||
}
|
||||
|
||||
function buildJsonReport(projects: ProjectSummary[], period: string, periodKey: string, durable: DurablePeriod) {
|
||||
const sessions = projects.flatMap(p => p.sessions)
|
||||
const { code } = getCurrency()
|
||||
|
|
@ -566,6 +582,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
// out-of-pocket figure. `cost` stays the full billable/would-be amount.
|
||||
const totalProxiedUSD = projects.reduce((s, p) => s + p.totalProxiedCostUSD, 0)
|
||||
const netCostUSD = totalCostUSD - totalProxiedUSD
|
||||
const excludedGateway = durable.excludedGateway
|
||||
const totalCalls = durable.data.calls
|
||||
const totalSessions = durable.data.sessions
|
||||
const totalInput = durable.data.inputTokens
|
||||
|
|
@ -766,6 +783,23 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
// paths configured, so existing consumers are unaffected.
|
||||
proxiedCost: convertCost(totalProxiedUSD),
|
||||
netCost: convertCost(netCostUSD),
|
||||
// Vercel AI Gateway spend deliberately NOT in `cost`: its rows are daily
|
||||
// aggregates the local tools routed through the gateway already report,
|
||||
// so adding both double counts. Emitted only when something is actually
|
||||
// excluded, so a report with no gateway credential is unchanged.
|
||||
...(excludedGateway.costUSD > 0 ? {
|
||||
excludedGatewayCost: convertCost(excludedGateway.costUSD),
|
||||
// The same amount as one labelled provider row, so a consumer can show
|
||||
// it beside the counted providers without adding it to `cost` or
|
||||
// looking for it in `projects[]` / `models[]` (which no longer hold it).
|
||||
excludedProviders: [{
|
||||
id: AGGREGATE_ONLY_PROVIDER,
|
||||
cost: convertCost(excludedGateway.costUSD),
|
||||
calls: excludedGateway.calls,
|
||||
tokens: excludedGateway.tokens,
|
||||
excludedFromTotal: true,
|
||||
}],
|
||||
} : {}),
|
||||
savings: convertCost(totalSavingsUSD),
|
||||
// Portion of `cost` priced from estimated tokens (issue #639). Display/
|
||||
// metadata only; never subtracted from `cost`. 0 when nothing is estimated.
|
||||
|
|
@ -1045,6 +1079,7 @@ program
|
|||
days: durable.days,
|
||||
carriedCostUSD: durable.carriedCostUSD,
|
||||
unattributedCostUSD: durable.unattributedCostUSD,
|
||||
excludedGateway: durable.excludedGateway,
|
||||
},
|
||||
}))
|
||||
})
|
||||
|
|
@ -1104,6 +1139,7 @@ program
|
|||
const { range } = periodInfoFromQuery({ period: opts.period, from: opts.from, to: opts.to }, 'today')
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
}
|
||||
await runWebDashboard({
|
||||
period: opts.period,
|
||||
|
|
@ -1238,6 +1274,11 @@ program
|
|||
// fetch or a pricing-logic fix can keep serving old rendered costs
|
||||
// indefinitely against an unchanged session corpus.
|
||||
pricingGenerationKey: getPricingGenerationKey(),
|
||||
// Not a pricing input, but it moves the headline: with it off the
|
||||
// gateway's daily aggregates are held out of every total. A warm
|
||||
// snapshot taken under the other setting would keep serving the wrong
|
||||
// headline until something unrelated moved the corpus.
|
||||
includeGatewayInTotals: gatewayIncludedInTotals(),
|
||||
})
|
||||
// Optimize findings (the default; see --no-optimize) depend on mutable
|
||||
// project/config/prompt/hook state: ~/.claude and project-level
|
||||
|
|
@ -1255,7 +1296,17 @@ program
|
|||
// optimize path never reads or writes the disk snapshot at all, it
|
||||
// always recomputes fresh. One-shot and serve-child behavior are
|
||||
// identical for both optimize values.
|
||||
const useSnapshot = !queryScope.optimize
|
||||
// Inside the resident `serve` child (SERVE_HYDRATION_ENV is set for the
|
||||
// life of that process) the snapshot is pure downside: the process
|
||||
// already holds the incremental parse state and an output memo, so the
|
||||
// snapshot buys no work back — it only adds `loadStatusSnapshot`'s
|
||||
// settle window, which hands back the deliberately deferred PRE-change
|
||||
// payload. serve then memoizes that answer, and with the roots quiet
|
||||
// again the memo stays "clean", replaying the stale payload until the
|
||||
// next filesystem event or the 5-minute memo cap. One-shot invocations
|
||||
// (a terminal run, the menubar's spawn fallback) keep the snapshot and
|
||||
// its debounce exactly as before.
|
||||
const useSnapshot = !queryScope.optimize && process.env[SERVE_HYDRATION_ENV] !== '1'
|
||||
const corpus = useSnapshot ? await computeCorpusFingerprint(pf) : null
|
||||
const snapshot = corpus ? await loadStatusSnapshot(corpus.hash, queryKey, STATUS_SNAPSHOT_SEMANTIC_KEY) : null
|
||||
const payload = (snapshot ?? await buildMenubarPayloadForRange(periodInfo, {
|
||||
|
|
@ -1326,8 +1377,8 @@ program
|
|||
// Savings DOLLARS keep every call, but these are request COUNTS: a
|
||||
// supplementary accounting call (copilot rollup / paired store row) can
|
||||
// carry configured model-savings too and must not count as a request.
|
||||
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 && isBehavioralCall(c) ? 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 && isBehavioralCall(c) ? 1 : 0), 0), 0), 0), 0)
|
||||
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 ? behavioralCallWeight(c) : 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 ? behavioralCallWeight(c) : 0), 0), 0), 0), 0)
|
||||
if (todayData.savingsUSD > 0 || monthData.savingsUSD > 0) {
|
||||
payload.localModelSavings = {
|
||||
today: payload.today.savings,
|
||||
|
|
@ -1428,10 +1479,12 @@ program
|
|||
if (customRange) {
|
||||
periods = [{ label: formatDateRangeLabel(opts.from, opts.to), projects: fp(await parseAllSessions(customRange, pf)) }]
|
||||
await reportUnmatchedProjectPatterns(widestParse ?? [], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(customRange!))
|
||||
await reportExcludedGatewayCost(customRange!, opts.provider)
|
||||
clearSessionCache()
|
||||
} else {
|
||||
const thirtyDayProjects = fp(await parseAllSessions(getDateRange('30days').range, pf))
|
||||
await reportUnmatchedProjectPatterns(widestParse ?? [], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(getDateRange('30days').range))
|
||||
await reportExcludedGatewayCost(getDateRange('30days').range, opts.provider)
|
||||
clearSessionCache()
|
||||
periods = [
|
||||
{ label: 'Today', projects: filterProjectsByDateRange(thirtyDayProjects, getDateRange('today').range) },
|
||||
|
|
@ -1901,6 +1954,34 @@ program
|
|||
console.log(` Config: ${getConfigFilePath()}\n`)
|
||||
})
|
||||
|
||||
program
|
||||
.command('gateway-totals [mode]')
|
||||
.description('Include or exclude Vercel AI Gateway spend in headline totals. Gateway reports are daily per-model aggregates with no request identity, so the same spend is usually already counted by the local tools you pointed at the gateway (Claude Code, Codex, OpenCode, Cline/Roo/Kilo, Cursor). Excluded by default; the gateway is always shown as its own row either way. Modes: include, exclude.')
|
||||
.option('--format <format>', 'Output format: text, json', 'text')
|
||||
.action(async (mode?: string, opts?: { format?: string }) => {
|
||||
const format = opts?.format ?? 'text'
|
||||
assertFormat(format, ['text', 'json'], 'gateway-totals')
|
||||
const config = await readConfig()
|
||||
if (mode !== undefined) {
|
||||
if (mode !== 'include' && mode !== 'exclude') {
|
||||
console.error(`\n Usage: codeburn gateway-totals [include|exclude] (got: ${mode})\n`)
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
config.includeGatewayInTotals = mode === 'include' ? true : undefined
|
||||
await saveConfig(config)
|
||||
}
|
||||
const included = config.includeGatewayInTotals === true
|
||||
if (format === 'json') {
|
||||
console.log(JSON.stringify({ includeGatewayInTotals: included }, null, 2))
|
||||
return
|
||||
}
|
||||
console.log(included
|
||||
? '\n Vercel AI Gateway spend is INCLUDED in headline totals.\n Its daily aggregates may duplicate spend your local tools already report.\n Exclude it with: codeburn gateway-totals exclude'
|
||||
: '\n Vercel AI Gateway spend is EXCLUDED from headline totals (default).\n It is still shown as its own provider row.\n Include it with: codeburn gateway-totals include')
|
||||
console.log(` Config: ${getConfigFilePath()}\n`)
|
||||
})
|
||||
|
||||
program
|
||||
.command('plan [action] [id]')
|
||||
.description('Show or configure a subscription plan for overage tracking')
|
||||
|
|
@ -2123,6 +2204,7 @@ program
|
|||
}
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
|
||||
if (opts.apply) {
|
||||
const { runOptimizeApply } = await import('./act/optimize-apply.js')
|
||||
|
|
@ -2303,6 +2385,7 @@ program
|
|||
const { aggregateModelStats, buildCohortComparison, buildCohortFacets, findModelStat, renderCohortJson, selectCohortProjects } = await import('./compare-cohorts.js')
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = selectCohortProjects(filterProjectsByName(parsed, opts.project, opts.exclude), opts.projectId)
|
||||
|
||||
// Without --model-a/--model-b the cohort format answers the FACET query:
|
||||
|
|
@ -2339,6 +2422,7 @@ program
|
|||
const { aggregateModelStats, buildCompareJson, findModelStat, projectSessionIds, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js')
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = filterProjectsByName(parsed, opts.project, opts.exclude)
|
||||
const models = aggregateModelStats(projects)
|
||||
|
||||
|
|
@ -2465,6 +2549,7 @@ program
|
|||
parseAllSessions(keyRangeB, opts.provider),
|
||||
])
|
||||
await reportUnmatchedProjectPatterns([...parsedA, ...parsedB], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(keyRangeB))
|
||||
await reportExcludedGatewayCost(keyRangeB, opts.provider)
|
||||
const projectsA = filterProjectsByName(parsedA, opts.project, opts.exclude)
|
||||
const projectsB = filterProjectsByName(parsedB, opts.project, opts.exclude)
|
||||
|
||||
|
|
@ -2477,7 +2562,9 @@ program
|
|||
try {
|
||||
const { ensureCacheHydrated } = await import('./daily-cache.js')
|
||||
const cache = await ensureCacheHydrated(
|
||||
range => parseAllSessions(range, 'all'),
|
||||
// Cache writer: seals whole days, gateway slice included (see
|
||||
// parseAllSessions' includeAggregateOnly).
|
||||
range => parseAllSessions(range, 'all', { includeAggregateOnly: true }),
|
||||
aggregateProjectsIntoDays,
|
||||
getDailyCacheConfigHash(),
|
||||
isSessionHydrationComplete,
|
||||
|
|
@ -2539,6 +2626,7 @@ program
|
|||
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = filterProjectsByBillingRoute(
|
||||
filterProjectsByName(parsed, opts.project, opts.exclude),
|
||||
{ route: opts.route, billing: opts.billing },
|
||||
|
|
@ -2601,6 +2689,7 @@ program
|
|||
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = filterProjectsByBillingRoute(
|
||||
filterProjectsByName(parsed, opts.project, opts.exclude),
|
||||
{ route: opts.route, billing: opts.billing },
|
||||
|
|
@ -2750,6 +2839,7 @@ program
|
|||
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
await reportExcludedGatewayCost(range, opts.provider)
|
||||
const projects = filterProjectsByBillingRoute(
|
||||
filterProjectsByName(parsed, opts.project, opts.exclude),
|
||||
{ route: opts.route, billing: opts.billing },
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { spawn } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createWriteStream, constants as fsConstants } from 'node:fs'
|
||||
import { access, chmod, lstat, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { access, chmod, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { homedir, platform, tmpdir } from 'node:os'
|
||||
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
|
|
@ -226,6 +226,206 @@ function userApplicationsDir(): string {
|
|||
return join(homedir(), 'Applications')
|
||||
}
|
||||
|
||||
/// Where a bundle may already live, in the order the desktop app's Menu bar card looks
|
||||
/// (app/electron/mac-menubar.ts, locate()). Its Spotlight fallback is deliberately not
|
||||
/// mirrored: replacing a bundle is destructive, and a Spotlight hit can name anything.
|
||||
function macApplicationsDirs(): string[] {
|
||||
return [userApplicationsDir(), '/Applications']
|
||||
}
|
||||
|
||||
export type MacInstallTarget = {
|
||||
/// The bundle path the install writes.
|
||||
targetPath: string
|
||||
/// The copy that is already installed, or null. Not the same as targetPath when the
|
||||
/// folder it sits in cannot be written: then it is opened and left alone, not replaced.
|
||||
installedPath: string | null
|
||||
/// Every copy found, in precedence order. Whichever one is not kept gets the notice.
|
||||
found: string[]
|
||||
}
|
||||
|
||||
/// Replace a copy where it already lives, so a user with CodeBurnMenubar.app in
|
||||
/// /Applications does not end up with a second bundle, and a second login item, under
|
||||
/// ~/Applications. A directory we cannot write to is never escalated into: the install
|
||||
/// falls back to ~/Applications and the copy left behind is reported instead.
|
||||
export async function resolveMacInstallTarget(dirs: string[] = macApplicationsDirs()): Promise<MacInstallTarget> {
|
||||
const present: string[] = []
|
||||
for (const dir of dirs) {
|
||||
const candidate = join(dir, APP_BUNDLE_NAME)
|
||||
if (await exists(candidate)) present.push(candidate)
|
||||
}
|
||||
const chosen = present[0]
|
||||
const writable = chosen ? await access(dirname(chosen), fsConstants.W_OK).then(() => true, () => false) : false
|
||||
const targetPath = chosen && writable ? chosen : join(dirs[0]!, APP_BUNDLE_NAME)
|
||||
return { targetPath, installedPath: chosen ?? null, found: present }
|
||||
}
|
||||
|
||||
/// The copies the user is told about: everything except the one being kept.
|
||||
function otherCopies(found: string[], kept: string): string[] {
|
||||
return found.filter(path => path !== kept)
|
||||
}
|
||||
|
||||
/// Injected by the tests: the placement below has to be driven through failures a real
|
||||
/// filesystem will not produce on demand.
|
||||
export type BundlePlacementHooks = {
|
||||
rename?: (from: string, to: string) => Promise<void>
|
||||
copy?: (from: string, to: string) => Promise<void>
|
||||
verify?: (appPath: string) => Promise<void>
|
||||
isLivePid?: (pid: number) => boolean
|
||||
now?: () => number
|
||||
log?: (line: string) => void
|
||||
}
|
||||
|
||||
/// The two names a placement can leave in the target directory, each carrying the pid of the
|
||||
/// install that made it. Dot-prefixed, so neither is a second launchable .app.
|
||||
const ASIDE_PREFIX = `.${APP_BUNDLE_NAME}.old-`
|
||||
const STAGED_PREFIX = `.${APP_BUNDLE_NAME}.new-`
|
||||
|
||||
function placementPid(name: string): number | null {
|
||||
const prefix = [ASIDE_PREFIX, STAGED_PREFIX].find(p => name.startsWith(p))
|
||||
if (!prefix) return null
|
||||
const pid = Number(name.slice(prefix.length))
|
||||
return Number.isInteger(pid) && pid > 0 ? pid : null
|
||||
}
|
||||
|
||||
/// How long a placement whose pid is still live is taken at face value. A placement outlives
|
||||
/// its install whenever the last cleanup fails or the process is killed, and pids are reused,
|
||||
/// so without a window one recycled pid would refuse every install on that machine from then
|
||||
/// on. Ten minutes is far longer than a placement takes and far shorter than a pid cycle.
|
||||
const ACTIVE_PLACEMENT_WINDOW_MS = 10 * 60_000
|
||||
|
||||
/// Only a pid we can signal is an install of ours: a second `codeburn menubar` runs as the
|
||||
/// same user, so EPERM means the pid has been recycled by somebody else's process.
|
||||
export function pidIsLive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// What an install finds of the installs before it. One question answers all of it: is the
|
||||
/// pid in the name still alive. A live one means a second install is running right now, and
|
||||
/// this one stops before touching anything; a dead one left its files behind, and if the
|
||||
/// real name is free its aside copy *is* the user's app, waiting to be put back. Run before
|
||||
/// the target is resolved, or a killed install into /Applications would look like no install
|
||||
/// at all and the app would quietly move to ~/Applications.
|
||||
export async function recoverPlacements(dirs: string[], hooks: BundlePlacementHooks = {}): Promise<void> {
|
||||
const move = hooks.rename ?? rename
|
||||
const isLive = hooks.isLivePid ?? pidIsLive
|
||||
const now = hooks.now ?? Date.now
|
||||
const log = hooks.log ?? console.log
|
||||
const orphans: Array<{ path: string; dir: string; name: string; pid: number }> = []
|
||||
for (const dir of dirs) {
|
||||
for (const name of await readdir(dir).catch(() => [] as string[])) {
|
||||
const pid = placementPid(name)
|
||||
if (pid !== null && pid !== process.pid) orphans.push({ path: join(dir, name), dir, name, pid })
|
||||
}
|
||||
}
|
||||
for (const orphan of orphans) {
|
||||
if (!isLive(orphan.pid)) continue
|
||||
// ctime, not mtime: renaming a bundle aside leaves its own mtime at whenever the app was
|
||||
// last written, which can be months back, while ctime is the moment of the rename.
|
||||
const placed = (await stat(orphan.path).catch(() => null))?.ctimeMs
|
||||
if (placed === undefined || now() - placed > ACTIVE_PLACEMENT_WINDOW_MS) continue
|
||||
throw new Error(
|
||||
`Another CodeBurn Menubar install (pid ${orphan.pid}) is working on ${orphan.path}. ` +
|
||||
`Nothing was changed; try again once it has finished, or delete that file if no install is running.`
|
||||
)
|
||||
}
|
||||
for (const { path, dir, name } of orphans) {
|
||||
const target = join(dir, APP_BUNDLE_NAME)
|
||||
try {
|
||||
if (name.startsWith(ASIDE_PREFIX) && !(await exists(target))) await move(path, target)
|
||||
else await rm(path, { recursive: true, force: true })
|
||||
} catch {
|
||||
// A folder we cannot write to is not a reason to stop: the install either lands
|
||||
// somewhere else or fails on its own terms, with its own message.
|
||||
log(`Could not clear ${path}, left by an earlier install. Delete it by hand when you can.`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the staged bundle at targetPath, leaving the user with a working app whatever fails.
|
||||
/// The copy that is there is renamed aside first, never deleted, so a failed placement can
|
||||
/// put it back; only a placement that worked removes it. The aside name is dot-prefixed:
|
||||
/// one we cannot remove is still not a second launchable .app sitting in Applications.
|
||||
export async function placeMenubarBundle(
|
||||
stagedApp: string,
|
||||
targetPath: string,
|
||||
hooks: BundlePlacementHooks = {},
|
||||
): Promise<void> {
|
||||
const move = hooks.rename ?? rename
|
||||
// verbatimSymlinks keeps the framework symlinks inside the bundle as links rather than
|
||||
// resolving them into copies, which is one of the ways a copied bundle stops verifying.
|
||||
const copy = hooks.copy ?? ((from: string, to: string) => cp(from, to, {
|
||||
recursive: true, verbatimSymlinks: true, preserveTimestamps: true,
|
||||
}))
|
||||
const verify = hooks.verify ?? verifyBundleSignature
|
||||
const log = hooks.log ?? console.log
|
||||
|
||||
const dir = dirname(targetPath)
|
||||
const aside = join(dir, `${ASIDE_PREFIX}${process.pid}`)
|
||||
const replacing = await exists(targetPath)
|
||||
if (replacing) await move(targetPath, aside)
|
||||
|
||||
try {
|
||||
try {
|
||||
await move(stagedApp, targetPath)
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'EXDEV') throw err
|
||||
// Staging is on another volume, so the move has to be a copy. Copy into a sibling of
|
||||
// the target and rename that into place: a rename within one directory is atomic, and
|
||||
// nothing half-copied is ever visible under the real name.
|
||||
const sibling = join(dir, `${STAGED_PREFIX}${process.pid}`)
|
||||
try {
|
||||
await rm(sibling, { recursive: true, force: true })
|
||||
await copy(stagedApp, sibling)
|
||||
await move(sibling, targetPath)
|
||||
// A copy is where a signature breaks, and what the stager verified was the staged
|
||||
// bundle, not this one.
|
||||
await verify(targetPath)
|
||||
await rm(stagedApp, { recursive: true, force: true })
|
||||
} finally {
|
||||
await rm(sibling, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
await rm(targetPath, { recursive: true, force: true }).catch(() => {})
|
||||
if (replacing) {
|
||||
await move(aside, targetPath).catch(() => {
|
||||
log(`The menu bar app could not be put back. It is at ${aside}; rename it to ${targetPath} to restore it.`)
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
if (replacing) {
|
||||
await rm(aside, { recursive: true, force: true }).catch(() => {
|
||||
log(`The previous bundle is still at ${aside}; it is hidden and not running, delete it when you can.`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Machine-readable twin of the sentence below, for the desktop app's install
|
||||
/// reader (app/electron/mac-menubar.ts), which would otherwise have to match
|
||||
/// English prose. Gated the same way scan progress is, so a terminal sees only
|
||||
/// the sentence.
|
||||
export const LEFTOVER_LINE_PREFIX = 'CODEBURN_LEFTOVER '
|
||||
|
||||
export function leftoverBundleLines(leftovers: string[], env: NodeJS.ProcessEnv = process.env): string[] {
|
||||
const lines: string[] = []
|
||||
for (const path of leftovers) {
|
||||
lines.push(`An older copy is still at ${path}. Move it to the Trash; CodeBurn will not delete it for you.`)
|
||||
if (env['CODEBURN_PROGRESS'] === '1') lines.push(`${LEFTOVER_LINE_PREFIX}${path}`)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
function reportLeftoverBundles(leftovers: string[]): void {
|
||||
for (const line of leftoverBundleLines(leftovers)) console.log(line)
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await stat(path)
|
||||
|
|
@ -498,6 +698,10 @@ async function verifyBundleIdentity(appPath: string): Promise<void> {
|
|||
if (bundleID !== EXPECTED_BUNDLE_ID) {
|
||||
throw new Error(`Unexpected menubar bundle id ${bundleID}; expected ${EXPECTED_BUNDLE_ID}.`)
|
||||
}
|
||||
await verifyBundleSignature(appPath)
|
||||
}
|
||||
|
||||
async function verifyBundleSignature(appPath: string): Promise<void> {
|
||||
await runCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath])
|
||||
}
|
||||
|
||||
|
|
@ -547,9 +751,14 @@ export async function hasRunnableRecordedCli(recordPath: string = PERSISTED_CLI_
|
|||
}
|
||||
}
|
||||
|
||||
/// `-x`, not `-f`: the executable inside the bundle is named exactly CodeBurnMenubar, and
|
||||
/// matching the whole command line instead would also hit an editor with the bundle's
|
||||
/// Info.plist open, or a tail on a log path. The name is the same from either Applications
|
||||
/// folder, so a copy running from the other one is still matched. killRunningApp must use
|
||||
/// the same matcher, or this reports a process that was never signalled.
|
||||
async function isAppRunning(): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn('/usr/bin/pgrep', ['-f', APP_PROCESS_NAME])
|
||||
const proc = spawn('/usr/bin/pgrep', ['-x', APP_PROCESS_NAME])
|
||||
proc.on('close', (code) => resolve(code === 0))
|
||||
proc.on('error', () => resolve(false))
|
||||
})
|
||||
|
|
@ -557,7 +766,7 @@ async function isAppRunning(): Promise<boolean> {
|
|||
|
||||
async function killRunningApp(): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
const proc = spawn('/usr/bin/pkill', ['-f', APP_PROCESS_NAME])
|
||||
const proc = spawn('/usr/bin/pkill', ['-x', APP_PROCESS_NAME])
|
||||
proc.on('close', () => resolve())
|
||||
proc.on('error', () => resolve())
|
||||
})
|
||||
|
|
@ -1315,15 +1524,17 @@ export async function installMenubarApp(options: InstallOptions = {}): Promise<I
|
|||
await ensureSupportedPlatform()
|
||||
await persistCodeburnPath()
|
||||
|
||||
const appsDir = userApplicationsDir()
|
||||
const targetPath = join(appsDir, APP_BUNDLE_NAME)
|
||||
const alreadyInstalled = await exists(targetPath)
|
||||
await recoverPlacements(macApplicationsDirs())
|
||||
const { targetPath, installedPath, found } = await resolveMacInstallTarget()
|
||||
|
||||
if (alreadyInstalled && !options.force) {
|
||||
if (installedPath && !options.force) {
|
||||
// The copy that is actually there, which is not targetPath when its folder cannot be
|
||||
// written: `open` on a path with nothing at it fails the command for no reason.
|
||||
if (!(await isAppRunning())) {
|
||||
await runCommand('/usr/bin/open', [targetPath])
|
||||
await runCommand('/usr/bin/open', [installedPath])
|
||||
}
|
||||
return { installedPath: targetPath, launched: true }
|
||||
reportLeftoverBundles(otherCopies(found, installedPath))
|
||||
return { installedPath, launched: true }
|
||||
}
|
||||
|
||||
const cliVersion = options.cliVersion ? normalizeCliVersion(options.cliVersion) : ''
|
||||
|
|
@ -1348,17 +1559,21 @@ export async function installMenubarApp(options: InstallOptions = {}): Promise<I
|
|||
unpackedApp = await stageMenubarApp(assets, stagingDir)
|
||||
}
|
||||
|
||||
await mkdir(appsDir, { recursive: true })
|
||||
if (alreadyInstalled) {
|
||||
await mkdir(dirname(targetPath), { recursive: true })
|
||||
if (installedPath) {
|
||||
// Kill the running copy before replacing its bundle so `mv` can proceed cleanly and the
|
||||
// user ends up on the new version.
|
||||
// user ends up on the new version. The match is on the process name, so a copy running
|
||||
// from the other Applications folder is asked to go too.
|
||||
await killRunningApp()
|
||||
await rm(targetPath, { recursive: true, force: true })
|
||||
}
|
||||
await rename(unpackedApp, targetPath)
|
||||
// Only now, with the new bundle downloaded, checksummed and its identity verified, is
|
||||
// the installed copy touched at all — and it is moved aside, not deleted, until this
|
||||
// returns.
|
||||
await placeMenubarBundle(unpackedApp, targetPath)
|
||||
|
||||
console.log('Launching CodeBurn Menubar...')
|
||||
await runCommand('/usr/bin/open', [targetPath])
|
||||
reportLeftoverBundles(otherCopies(found, targetPath))
|
||||
return { installedPath: targetPath, launched: true }
|
||||
} finally {
|
||||
await rm(stagingDir, { recursive: true, force: true })
|
||||
|
|
|
|||
|
|
@ -108,6 +108,10 @@ export type ProviderCost = {
|
|||
calls?: number
|
||||
/** True when the selected period contains cost, calls, sessions, savings, or tokens. */
|
||||
hasUsage?: boolean
|
||||
/** Set only on a provider whose spend the headline deliberately leaves out
|
||||
* (daily aggregates that local tools already report — see
|
||||
* `excludeProviderFromDay`). Add-only: absent means "counted". */
|
||||
excludedFromTotal?: boolean
|
||||
/** Provider-scoped tokens for the period. Absent (not zero) when no day in the
|
||||
* period carried a per-provider token breakdown, so a consumer can tell
|
||||
* "no token data" from "no tokens". */
|
||||
|
|
@ -353,6 +357,12 @@ export type MenubarPayload = {
|
|||
cost: number
|
||||
calls: number
|
||||
hasUsage: boolean
|
||||
/// Present (and always `true`) only on a provider this payload's totals
|
||||
/// deliberately exclude: its rows are daily aggregates the local tools
|
||||
/// pointed at it already report, so counting both double counts. The
|
||||
/// row still carries the real `cost` — a consumer must label it, never
|
||||
/// add it to `cost`.
|
||||
excludedFromTotal?: boolean
|
||||
inputTokens?: number
|
||||
outputTokens?: number
|
||||
sessions?: number
|
||||
|
|
@ -650,6 +660,7 @@ function buildProviderDetails(providers: ProviderCost[]): MenubarPayload['curren
|
|||
cost: p.cost,
|
||||
calls: p.calls ?? 0,
|
||||
hasUsage: p.hasUsage ?? (p.cost > 0 || (p.calls ?? 0) > 0),
|
||||
...(p.excludedFromTotal ? { excludedFromTotal: true as const } : {}),
|
||||
...(p.inputTokens === undefined ? {} : { inputTokens: p.inputTokens }),
|
||||
...(p.outputTokens === undefined ? {} : { outputTokens: p.outputTokens }),
|
||||
...(p.sessions === undefined ? {} : { sessions: p.sessions }),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import chalk from 'chalk'
|
||||
import stripAnsi from 'strip-ansi'
|
||||
|
||||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { codexCredits } from './codex-credits.js'
|
||||
import { formatCost, formatTokens } from './format.js'
|
||||
import { billableOutputTokens, fallbackRawModelDisplayName, getModelRoute, getRouteById, getShortModelName, modelRowKey, resolveCanonicalModelId, routeSuffix, sanitizeModelForDisplay } from './models.js'
|
||||
|
|
@ -186,7 +186,7 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat
|
|||
}
|
||||
// Supplementary accounting calls keep their tokens and cost above but are not
|
||||
// distinct requests, so they add no call weight (see behavioral-weight.ts).
|
||||
if (isBehavioralCall(call)) bucket.calls += 1
|
||||
bucket.calls += behavioralCallWeight(call)
|
||||
|
||||
const modelKey = `${provider} ${model} ${route ?? ''}`
|
||||
let perCat = perModelCategoryCost.get(modelKey)
|
||||
|
|
|
|||
|
|
@ -502,17 +502,14 @@ const BUILTIN_ALIASES: Record<string, string> = {
|
|||
'gemini-3-pro': 'gemini-3-pro-preview',
|
||||
'gemini-3.1-flash-image': 'gemini-3.1-flash-image-preview',
|
||||
'gemini-3.1-flash-lite': 'gemini-3.1-flash-lite-preview',
|
||||
// ZCode runs GLM-5.2 through z.ai's start-plan subscription; it isn't in
|
||||
// LiteLLM yet. Price as the nearest released sibling (GLM-5.1) until it is.
|
||||
'GLM-5.2': 'glm-5p1',
|
||||
// Hermes Agent stores the same model id lowercased (`glm-5.2`) in its
|
||||
// sessions table, so it misses the capitalized alias above and goes
|
||||
// unpriced. Map the lowercase spelling to the same sibling.
|
||||
'glm-5.2': 'glm-5p1',
|
||||
// GLM-5.3 is not in the LiteLLM snapshot yet. Price as the nearest
|
||||
// released sibling (GLM-5.2 / glm-5p2). Hermes stores the id lowercased.
|
||||
'GLM-5.3': 'glm-5p2',
|
||||
'glm-5.3': 'glm-5p2',
|
||||
// ZCode reports GLM-5.2/5.3 capitalized; Hermes/Cline use lowercase. The
|
||||
// snapshot's bare `glm-5.2`/`glm-5.3` rows carry the LIST rate ($1.4/$4.4);
|
||||
// z.ai's own `z-ai/glm-5.2`/`z-ai/glm-5.3` rows are the discounted rate we
|
||||
// actually pay. Point every spelling at the z-ai rows.
|
||||
'glm-5.2': 'z-ai/glm-5.2',
|
||||
'GLM-5.2': 'z-ai/glm-5.2',
|
||||
'glm-5.3': 'z-ai/glm-5.3',
|
||||
'GLM-5.3': 'z-ai/glm-5.3',
|
||||
}
|
||||
|
||||
let userAliases: Record<string, string> = {}
|
||||
|
|
@ -1257,6 +1254,8 @@ export function calculateCost(
|
|||
}
|
||||
|
||||
const autoModelNames: Record<string, string> = {
|
||||
'glm-5.2': 'GLM-5.2',
|
||||
'GLM-5.2': 'GLM-5.2',
|
||||
'glm-5.3': 'GLM-5.3',
|
||||
'GLM-5.3': 'GLM-5.3',
|
||||
'cursor-auto': 'Cursor (auto)',
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types
|
|||
import { formatCost as baseCost, getCurrency } from './currency.js'
|
||||
import { findUnpricedModels, modelRowKey, unpricedModelHint } from './models.js'
|
||||
import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js'
|
||||
import { markEstimated } from './format.js'
|
||||
import { markEstimated, excludedGatewayNote } from './format.js'
|
||||
import { AGGREGATE_ONLY_PROVIDER } from './parser.js'
|
||||
import { maxOf } from './math-utils.js'
|
||||
import { formatSessionCount, SESSION_COUNT_HELP, type SessionCountBasis } from './session-count-label.js'
|
||||
import { normalizeAbsProjectPathKey } from './parser.js'
|
||||
|
|
@ -122,6 +123,9 @@ export type OverviewDurable = {
|
|||
/// Cost a --project/--exclude filter could not attribute (cached days with no
|
||||
/// per-project split). Optional so callers that never filter can omit it.
|
||||
unattributedCostUSD?: number
|
||||
/// Gateway spend shown as its own labelled `By tool` row but deliberately
|
||||
/// not in `cost`. Optional so callers that never build it can omit it.
|
||||
excludedGateway?: { costUSD: number; calls: number; tokens: number }
|
||||
}
|
||||
|
||||
export function renderOverview(
|
||||
|
|
@ -293,15 +297,25 @@ export function renderOverview(
|
|||
out.push('')
|
||||
}
|
||||
|
||||
// By tool (provider)
|
||||
// By tool (provider). The aggregate-only gateway is never in `byProvider`
|
||||
// (the corpus filter dropped it) and never in `cost`, so the shares below
|
||||
// still sum over the counted tools only; it gets one labelled row of its own
|
||||
// with no share, because a share of a total it is not in is meaningless.
|
||||
const excludedGateway = durable?.excludedGateway
|
||||
const gatewayRow = excludedGateway && excludedGateway.costUSD > 0
|
||||
? [[`${AGGREGATE_ONLY_PROVIDER} (not in total)`, formatCost(excludedGateway.costUSD), formatTokens(excludedGateway.tokens), '-']]
|
||||
: []
|
||||
const providerRows = [...byProvider.entries()]
|
||||
.filter(([, v]) => v.cost > 0 || v.tokens > 0)
|
||||
.sort((a, b) => b[1].cost - a[1].cost)
|
||||
if (providerRows.length) {
|
||||
if (providerRows.length || gatewayRow.length) {
|
||||
out.push(heading('By tool'))
|
||||
out.push(renderTable(c,
|
||||
[{ header: 'Tool' }, { header: 'Cost', right: true }, { header: 'Tokens', right: true }, { header: 'Share', right: true }],
|
||||
providerRows.map(([name, v]) => [name, formatCost(v.cost), formatTokens(v.tokens), cost > 0 ? `${Math.round((v.cost / cost) * 100)}%` : '0%']),
|
||||
[
|
||||
...providerRows.map(([name, v]) => [name, formatCost(v.cost), formatTokens(v.tokens), cost > 0 ? `${Math.round((v.cost / cost) * 100)}%` : '0%']),
|
||||
...gatewayRow,
|
||||
],
|
||||
))
|
||||
out.push('')
|
||||
}
|
||||
|
|
@ -399,5 +413,8 @@ export function renderOverview(
|
|||
out.push(c.dim(` excludes ${formatCost(durable.unattributedCostUSD!)} from days with no per-project history`))
|
||||
}
|
||||
|
||||
const gatewayNote = excludedGatewayNote(durable?.excludedGateway?.costUSD ?? 0)
|
||||
if (gatewayNote) out.push(c.dim(` ${gatewayNote}`))
|
||||
|
||||
return out.join('\n') + '\n'
|
||||
}
|
||||
|
|
|
|||
359
src/parser.ts
359
src/parser.ts
|
|
@ -24,6 +24,7 @@ import {
|
|||
type CachedCall,
|
||||
type CachedFile,
|
||||
type CachedTurn,
|
||||
type FileFingerprint,
|
||||
type ProviderSection,
|
||||
type SessionCache,
|
||||
beginColdHydration,
|
||||
|
|
@ -31,7 +32,9 @@ import {
|
|||
computeEnvFingerprint,
|
||||
DURABLE_PROVIDER_NAMES,
|
||||
fingerprintFile,
|
||||
hasDirtyDurableProvider,
|
||||
isCacheComplete,
|
||||
isCacheCurrent,
|
||||
isCacheDirty,
|
||||
loadCache,
|
||||
markCacheDirty,
|
||||
|
|
@ -46,7 +49,8 @@ import { classifyWslCachePath, isWslUncPath, refreshWslHomes, wslMode } from './
|
|||
import { decideParseWorkers, parseFilesInOrder, ParseWorkerPool, type ClaudeWorkerParse, type ParseJob } from './parse-workers.js'
|
||||
import type { CodexFullParse } from './providers/codex.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight, isBehavioralTurn } from './behavioral-weight.js'
|
||||
import { gatewayIncludedInTotals } from './config.js'
|
||||
import type { ParsedProviderCall, Provider, SessionSource } from './providers/types.js'
|
||||
import type {
|
||||
ApiUsageIteration,
|
||||
|
|
@ -1226,7 +1230,7 @@ function applyLocalModelSavings(call: ParsedApiCall): ParsedApiCall {
|
|||
const savings = calculateLocalModelSavings(
|
||||
call.model,
|
||||
u.inputTokens,
|
||||
u.outputTokens,
|
||||
billableOutputTokens(call.provider, u.outputTokens, u.reasoningTokens),
|
||||
u.cacheCreationInputTokens,
|
||||
u.cacheReadInputTokens,
|
||||
u.webSearchRequests,
|
||||
|
|
@ -1798,7 +1802,7 @@ function buildSessionSummary(
|
|||
totalCacheWrite += call.usage.cacheCreationInputTokens
|
||||
// Supplementary accounting calls contribute tokens/cost above but are
|
||||
// not distinct requests: no api-call or per-model call weight.
|
||||
if (isBehavioralCall(call)) apiCalls++
|
||||
apiCalls += behavioralCallWeight(call)
|
||||
|
||||
const modelKey = call.provider === 'devin' ? call.model : modelRowKey(call.model, call.route)
|
||||
if (!modelBreakdown[modelKey]) {
|
||||
|
|
@ -1810,7 +1814,7 @@ function buildSessionSummary(
|
|||
tokens: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0 },
|
||||
}
|
||||
}
|
||||
if (isBehavioralCall(call)) modelBreakdown[modelKey].calls++
|
||||
modelBreakdown[modelKey].calls += behavioralCallWeight(call)
|
||||
modelBreakdown[modelKey].costUSD += call.costUSD
|
||||
modelBreakdown[modelKey].savingsUSD += callSavings
|
||||
modelBreakdown[modelKey].estimatedCostUSD = (modelBreakdown[modelKey].estimatedCostUSD ?? 0) + callEstimated
|
||||
|
|
@ -2019,8 +2023,12 @@ async function scanProjectDirs(
|
|||
// order: the reconcile loop feeds order-sensitive state (changedFiles order
|
||||
// drives the worker-result pairing, seenMsgIds pre-seeding), so only the
|
||||
// syscalls are allowed to overlap.
|
||||
const gate = openSweepGate()
|
||||
const sweptAt = Date.now()
|
||||
const walked = await mapWithConcurrency(dirs, FS_SCAN_CONCURRENCY, async ({ path: dirPath }) => {
|
||||
const jsonlFiles = await collectJsonlFiles(dirPath)
|
||||
const remembered = sweepDirFiles(gate, dirPath)
|
||||
const jsonlFiles = remembered ?? await collectJsonlFiles(dirPath)
|
||||
if (!remembered) rememberSweepDir(dirPath, jsonlFiles, sweptAt)
|
||||
dirsDone++
|
||||
await discoverProgress.tick(dirsDone)
|
||||
return jsonlFiles
|
||||
|
|
@ -2030,7 +2038,13 @@ async function scanProjectDirs(
|
|||
const { name: dirName, source } = dirs[i]!
|
||||
for (const filePath of walked[i]!) discovered.push({ filePath, dirName, source })
|
||||
}
|
||||
const fingerprints = await mapWithConcurrency(discovered, FS_SCAN_CONCURRENCY, e => fingerprintFile(e.filePath))
|
||||
const fingerprints = await mapWithConcurrency(discovered, FS_SCAN_CONCURRENCY, async (e) => {
|
||||
const remembered = sweepFingerprint(gate, e.filePath)
|
||||
if (remembered) return remembered
|
||||
const fp = await fingerprintFile(e.filePath)
|
||||
rememberSweepFingerprint(e.filePath, fp, sweptAt)
|
||||
return fp
|
||||
})
|
||||
for (const [i, { filePath, dirName, source }] of discovered.entries()) {
|
||||
allDiscoveredFiles.add(filePath)
|
||||
const fp = fingerprints[i]
|
||||
|
|
@ -2541,51 +2555,35 @@ export function extractPrUrlsFromText(text: string): string[] {
|
|||
return [...new Set(text.match(PR_URL_IN_TEXT_RE) ?? [])].sort()
|
||||
}
|
||||
|
||||
function providerCallToTurn(call: ParsedProviderCall): ParsedTurn {
|
||||
const tools = call.tools
|
||||
const usage: TokenUsage = {
|
||||
inputTokens: call.inputTokens,
|
||||
outputTokens: call.outputTokens,
|
||||
cacheCreationInputTokens: call.cacheCreationInputTokens,
|
||||
cacheReadInputTokens: call.cacheReadInputTokens,
|
||||
cachedInputTokens: call.cachedInputTokens,
|
||||
reasoningTokens: call.reasoningTokens,
|
||||
webSearchRequests: call.webSearchRequests,
|
||||
}
|
||||
|
||||
const apiCall: ParsedApiCall = applyLocalModelSavings({
|
||||
provider: call.provider,
|
||||
model: call.model,
|
||||
usage,
|
||||
costUSD: call.costUSD,
|
||||
tools,
|
||||
mcpTools: extractMcpTools(tools),
|
||||
skills: call.skills ?? [],
|
||||
subagentTypes: call.subagentTypes ?? [],
|
||||
hasAgentSpawn: tools.includes('Agent'),
|
||||
hasPlanMode: tools.includes('EnterPlanMode'),
|
||||
speed: call.speed,
|
||||
timestamp: call.timestamp,
|
||||
bashCommands: call.bashCommands,
|
||||
deduplicationKey: call.deduplicationKey,
|
||||
isEstimated: call.costIsEstimated,
|
||||
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
|
||||
...(call.route ? { route: call.route } : {}),
|
||||
...(call.billing ? { billing: call.billing } : {}),
|
||||
})
|
||||
|
||||
const prRefs = extractPrUrlsFromText(call.userMessage)
|
||||
return {
|
||||
userMessage: call.userMessage,
|
||||
assistantCalls: [apiCall],
|
||||
timestamp: call.timestamp,
|
||||
sessionId: call.sessionId,
|
||||
...(prRefs.length ? { prRefs } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cache Conversion ───────────────────────────────────────────────────
|
||||
|
||||
// Providers whose every parsed call carries a cost the tool itself computed or
|
||||
// was billed, not one derived from that call's tokens. Their cost is stored on
|
||||
// the cached call and served verbatim; every other provider's is recomputed
|
||||
// from the cached tokens on read (cachedCallToApiCall), so a pricing update
|
||||
// still reaches it.
|
||||
//
|
||||
// A new provider should set `ParsedProviderCall.costFromBilling` instead of
|
||||
// joining this set. The flag decides per call, so a provider that reports a
|
||||
// cost for some calls and falls back to token pricing for the rest keeps that
|
||||
// fallback re-priceable; membership here is the whole-provider form of the
|
||||
// same rule, kept for the providers that adopted it before the flag existed.
|
||||
// Either way, adding a provider needs a `PROVIDER_PARSE_VERSIONS` bump: calls
|
||||
// cached before the change hold `costUSD: undefined` and would otherwise be
|
||||
// re-priced from tokens forever.
|
||||
export const REPORTED_COST_PROVIDERS: ReadonlySet<string> = new Set([
|
||||
'mistral-vibe',
|
||||
'antigravity',
|
||||
'devin',
|
||||
'vercel-gateway',
|
||||
'hermes',
|
||||
'kiro',
|
||||
'codewhale',
|
||||
'quickdesk',
|
||||
'cline-cli',
|
||||
'omp',
|
||||
])
|
||||
|
||||
function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
|
||||
return {
|
||||
provider: call.provider,
|
||||
|
|
@ -2600,7 +2598,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
|
|||
webSearchRequests: call.webSearchRequests,
|
||||
cacheCreationOneHourTokens: 0,
|
||||
},
|
||||
costUSD: (call.provider === 'mistral-vibe' || call.provider === 'antigravity' || call.provider === 'devin' || call.provider === 'vercel-gateway' || call.provider === 'hermes' || call.provider === 'kiro' || call.provider === 'codewhale' || call.provider === 'quickdesk' || call.provider === 'cline-cli' || call.provider === 'omp') ? call.costUSD : undefined,
|
||||
costUSD: (REPORTED_COST_PROVIDERS.has(call.provider) || call.costFromBilling === true) ? call.costUSD : undefined,
|
||||
isEstimated: call.costIsEstimated || undefined,
|
||||
speed: call.speed,
|
||||
timestamp: call.timestamp,
|
||||
|
|
@ -2619,6 +2617,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
|
|||
...(call.locRemoved ? { locRemoved: call.locRemoved } : {}),
|
||||
...(call.editFailed ? { editFailed: call.editFailed } : {}),
|
||||
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
|
||||
...(call.requestCount != null ? { requestCount: call.requestCount } : {}),
|
||||
...(call.route ? { route: call.route } : {}),
|
||||
...(call.billing ? { billing: call.billing } : {}),
|
||||
...(call.requestMultiplier != null ? { requestMultiplier: call.requestMultiplier } : {}),
|
||||
|
|
@ -2790,6 +2789,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall {
|
|||
activeGeneratedTokens: call.activeGeneratedTokens,
|
||||
toolWaitMs: call.toolWaitMs,
|
||||
...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}),
|
||||
...(call.requestCount != null ? { requestCount: call.requestCount } : {}),
|
||||
...(call.route ? { route: call.route } : {}),
|
||||
...(call.billing ? { billing: call.billing } : {}),
|
||||
...(call.supplementaryAccounting || isHermesObservationKey(call.deduplicationKey)
|
||||
|
|
@ -3185,7 +3185,7 @@ function warnProviderParseFailure(providerName: string, sourcePath: string, err:
|
|||
// discovery errors are already isolated; this catches a provider-level throw so
|
||||
// one locked provider skips-and-continues instead of aborting the whole
|
||||
// hydration (which would empty the cache/daily backfill for every provider).
|
||||
function isPermissionError(err: unknown): boolean {
|
||||
export function isPermissionError(err: unknown): boolean {
|
||||
const code = (err as NodeJS.ErrnoException | undefined)?.code
|
||||
return code === 'EPERM' || code === 'EACCES'
|
||||
}
|
||||
|
|
@ -3414,9 +3414,17 @@ export async function parseProviderSources(
|
|||
// discovery order. Network sources on a write run never reach fingerprintFile
|
||||
// (they take the synthetic-fingerprint branch below), so they are skipped here.
|
||||
const skipFingerprint = provider.network && !readOnly
|
||||
const gate = openSweepGate()
|
||||
const sweptAt = Date.now()
|
||||
const sourceFingerprints = skipFingerprint
|
||||
? []
|
||||
: await mapWithConcurrency(sources, FS_SCAN_CONCURRENCY, s => fingerprintFile(s.path))
|
||||
: await mapWithConcurrency(sources, FS_SCAN_CONCURRENCY, async (s) => {
|
||||
const remembered = sweepFingerprint(gate, s.path)
|
||||
if (remembered) return remembered
|
||||
const fp = await fingerprintFile(s.path)
|
||||
rememberSweepFingerprint(s.path, fp, sweptAt)
|
||||
return fp
|
||||
})
|
||||
|
||||
for (const [sourceIndex, source] of sources.entries()) {
|
||||
allDiscoveredFiles.add(source.path)
|
||||
|
|
@ -4438,6 +4446,152 @@ export function setParseReuseValidator(validator: ParseReuseValidator | null): v
|
|||
parseReuseValidator = validator
|
||||
}
|
||||
|
||||
// ── Incremental discovery sweep (resident process only) ──────────────────────
|
||||
// Discovery re-readdirs every project directory and re-stats every transcript
|
||||
// on every parse. In a resident process the root watchers already know which
|
||||
// paths moved, so a directory listing / file fingerprint the watcher proved
|
||||
// untouched is reused instead of re-read. Nothing DERIVED is reused: only
|
||||
// dev/ino/mtime/size, and `reconcileFile` still runs for every file.
|
||||
export type SweepWatchSource = {
|
||||
/** When watcher coverage began; anything remembered before it is unproven. */
|
||||
startedAt: number
|
||||
/** The roots actually armed. A path outside them is never event-covered. */
|
||||
roots: readonly string[]
|
||||
healthy: () => boolean
|
||||
/** Paths changed since `sinceTs`, or null when coverage was unscoped. */
|
||||
changedSince: (sinceTs: number) => string[] | null
|
||||
}
|
||||
// Held a little shorter than the watcher's own path retention so a remembered
|
||||
// entry can never outlive the event record that would have invalidated it.
|
||||
const SWEEP_MEMO_MAX_AGE_MS = VALIDATED_REUSE_CAP_MS - 30_000
|
||||
// A wall-clock jump this much larger than elapsed monotonic time means the
|
||||
// process was suspended (sleep/wake) and events could have been missed.
|
||||
const SWEEP_SUSPEND_SLACK_MS = 2_000
|
||||
let sweepWatchSource: SweepWatchSource | null = null
|
||||
let sweepDirMemo = new Map<string, { files: string[]; at: number }>()
|
||||
let sweepFpMemo = new Map<string, { fp: FileFingerprint; at: number }>()
|
||||
let sweepClockMark: { wall: number; mono: number } | null = null
|
||||
|
||||
export function setSweepWatchSource(source: SweepWatchSource | null): void {
|
||||
sweepWatchSource = source
|
||||
sweepDirMemo = new Map()
|
||||
sweepFpMemo = new Map()
|
||||
sweepClockMark = null
|
||||
}
|
||||
|
||||
type SweepGate = { minAt: number; changed: Set<string>; touched: Set<string>; roots: readonly string[] }
|
||||
|
||||
/// The per-parse decision. Null means "sweep exactly as before": no watcher,
|
||||
/// degraded coverage, an unscoped event, a suspend, or a first parse.
|
||||
function openSweepGate(): SweepGate | null {
|
||||
const src = sweepWatchSource
|
||||
const now = Date.now()
|
||||
for (const [key, entry] of sweepDirMemo) if (entry.at < now - SWEEP_MEMO_MAX_AGE_MS) sweepDirMemo.delete(key)
|
||||
for (const [key, entry] of sweepFpMemo) if (entry.at < now - SWEEP_MEMO_MAX_AGE_MS) sweepFpMemo.delete(key)
|
||||
const mark = sweepClockMark
|
||||
const mono = Math.trunc(performance.now())
|
||||
sweepClockMark = { wall: now, mono }
|
||||
// A wall clock that moved backwards would keep extending `minAt` backwards
|
||||
// too, so treat it the same way a forward jump is treated.
|
||||
if (mark && Math.abs((now - mark.wall) - (mono - mark.mono)) > SWEEP_SUSPEND_SLACK_MS) {
|
||||
// Nothing remembered before the gap is trustworthy, and the gap is only
|
||||
// visible once — so drop it all rather than let the next gate bless it.
|
||||
sweepDirMemo.clear()
|
||||
sweepFpMemo.clear()
|
||||
return null
|
||||
}
|
||||
if (!src || !src.healthy()) return null
|
||||
const minAt = Math.max(now - SWEEP_MEMO_MAX_AGE_MS, src.startedAt)
|
||||
const changed = src.changedSince(minAt)
|
||||
if (!changed) return null
|
||||
// A changed path invalidates its own fingerprint and every directory listing
|
||||
// that could contain it — the path itself (a renamed directory) and every
|
||||
// ancestor, so a created or deleted file is seen by the next readdir.
|
||||
const touched = new Set<string>()
|
||||
for (const path of changed) {
|
||||
for (let dir = path; ;) {
|
||||
touched.add(dir)
|
||||
const parent = dirname(dir)
|
||||
if (parent === dir) break
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
return { minAt, changed: new Set(changed), touched, roots: src.roots }
|
||||
}
|
||||
|
||||
function sweepCovers(gate: SweepGate, path: string): boolean {
|
||||
// WSL/UNC roots are reached over a network redirector fs.watch does not cover,
|
||||
// and a path outside every armed root has no event source at all.
|
||||
if (isWslUncPath(path)) return false
|
||||
return gate.roots.some(root => path === root || path.startsWith(root.endsWith(sep) ? root : root + sep))
|
||||
}
|
||||
|
||||
function sweepDirFiles(gate: SweepGate | null, dirPath: string): string[] | null {
|
||||
if (!gate || gate.touched.has(dirPath) || !sweepCovers(gate, dirPath)) return null
|
||||
const hit = sweepDirMemo.get(dirPath)
|
||||
return hit && hit.at >= gate.minAt ? hit.files : null
|
||||
}
|
||||
|
||||
function sweepFingerprint(gate: SweepGate | null, path: string): FileFingerprint | null {
|
||||
// Only plain transcripts. A SQLite source folds its `-wal` sibling in, and a
|
||||
// virtual-suffix source (`<db>#cursor-ws=…`, `<db>:<session>`) fingerprints
|
||||
// the underlying database — in both cases the watcher would name a path that
|
||||
// is not this key, so no event could ever invalidate the entry.
|
||||
if (!path.endsWith('.jsonl')) return null
|
||||
if (!gate || gate.changed.has(path) || !sweepCovers(gate, path)) return null
|
||||
const hit = sweepFpMemo.get(path)
|
||||
return hit && hit.at >= gate.minAt ? hit.fp : null
|
||||
}
|
||||
|
||||
/// Remember what this sweep read. `at` is captured BEFORE the syscall, so an
|
||||
/// event that lands while the sweep runs still invalidates the entry.
|
||||
function rememberSweepDir(dirPath: string, files: string[], at: number): void {
|
||||
if (sweepWatchSource) sweepDirMemo.set(dirPath, { files, at })
|
||||
}
|
||||
|
||||
function rememberSweepFingerprint(path: string, fp: FileFingerprint | null, at: number): void {
|
||||
// A null fingerprint means the file was missing or unreadable; remembering
|
||||
// that would hide its later appearance behind a quiet watcher.
|
||||
if (sweepWatchSource && fp && path.endsWith('.jsonl')) sweepFpMemo.set(path, { fp, at })
|
||||
}
|
||||
|
||||
// ── Coalesced shard publication (resident process only) ─────────────────────
|
||||
// One appended transcript dirties one month bucket, and publishing that bucket
|
||||
// rewrites the whole month — the single most expensive thing on the live poll
|
||||
// path. A resident process publishes at most once per window and always on
|
||||
// clean shutdown. A skipped publish writes NOTHING, so the on-disk cache stays
|
||||
// exactly as consistent as it already was; the cost of losing a window is that
|
||||
// the next start re-parses those appends, never a wrong number.
|
||||
// Longer than the desktop's slowest poll (60s), or a window exactly as long as
|
||||
// the cadence would expire before every poll and coalesce nothing.
|
||||
const SHARD_PUBLISH_COALESCE_MS = 90_000
|
||||
let shardPublishCoalescing = false
|
||||
let lastShardPublishAt = 0
|
||||
let pendingShardPublish: SessionCache | null = null
|
||||
|
||||
export function setShardPublishCoalescing(on: boolean): void {
|
||||
shardPublishCoalescing = on
|
||||
pendingShardPublish = null
|
||||
lastShardPublishAt = 0
|
||||
}
|
||||
|
||||
export function hasPendingShardPublish(): boolean {
|
||||
return pendingShardPublish !== null
|
||||
}
|
||||
|
||||
export async function flushPendingShardPublish(): Promise<void> {
|
||||
const cache = pendingShardPublish
|
||||
pendingShardPublish = null
|
||||
if (!cache) return
|
||||
lastShardPublishAt = Date.now()
|
||||
// Unlike the deferral itself — which is published by a later refresh under
|
||||
// that refresh's own fence — this one runs outside the lock, so it checks
|
||||
// that nothing has been published since instead.
|
||||
try {
|
||||
if (await isCacheCurrent(cache)) await saveCache(cache)
|
||||
} catch { /* a lost publish only costs a re-parse */ }
|
||||
}
|
||||
|
||||
function burstReuse(dateRange: DateRange, sig: string): ProjectSummary[] | null {
|
||||
const windowMs = parseBurstWindowMs()
|
||||
if (windowMs <= 0) return null
|
||||
|
|
@ -5544,7 +5698,74 @@ function deferToBackgroundFill(path: string, fp: { mtimeMs: number }, cached: un
|
|||
return true
|
||||
}
|
||||
|
||||
export function parseAllSessions(dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
|
||||
/// Providers whose records are DAILY AGGREGATES instead of per-request rows:
|
||||
/// Vercel AI Gateway's `/v1/report` returns one cost/token/request_count per
|
||||
/// day per model, with no request id, timestamp or attribution. The local
|
||||
/// tools that were pointed at the gateway (Claude Code via
|
||||
/// ANTHROPIC_BASE_URL, Codex, OpenCode, Cline/Roo/Kilo, Cursor) record those
|
||||
/// same requests in their own session files, and nothing in an aggregate row
|
||||
/// can be matched against them — so a corpus holding both counts the same
|
||||
/// spend twice.
|
||||
export const AGGREGATE_ONLY_PROVIDER = 'vercel-gateway'
|
||||
export const AGGREGATE_ONLY_PROVIDERS: ReadonlySet<string> = new Set([AGGREGATE_ONLY_PROVIDER])
|
||||
|
||||
/// True when an all-provider read must drop the aggregate-only corpus. A
|
||||
/// provider-scoped read never does: `--provider vercel-gateway` exists to
|
||||
/// inspect the full amount.
|
||||
export function excludesAggregateOnlyProviders(providerFilter?: string): boolean {
|
||||
return (providerFilter ?? 'all') === 'all' && !gatewayIncludedInTotals()
|
||||
}
|
||||
|
||||
function hasAggregateOnlyCall(projects: ProjectSummary[]): boolean {
|
||||
return projects.some(project => project.sessions.some(session =>
|
||||
session.turns.some(turn => turn.assistantCalls.some(call => AGGREGATE_ONLY_PROVIDERS.has(call.provider)))))
|
||||
}
|
||||
|
||||
/// Drop the aggregate-only providers from a parsed corpus, rebuilding every
|
||||
/// nested total from the retained calls. Returns the SAME array when nothing
|
||||
/// matches, so a machine with no gateway credential pays nothing and its
|
||||
/// output is byte-identical to a build without this rule.
|
||||
export function excludeAggregateOnlyProjects(projects: ProjectSummary[], providerFilter?: string): ProjectSummary[] {
|
||||
if (!excludesAggregateOnlyProviders(providerFilter)) return projects
|
||||
if (!hasAggregateOnlyCall(projects)) return projects
|
||||
return filterProjectsByCall(projects, call => !AGGREGATE_ONLY_PROVIDERS.has(call.provider))
|
||||
}
|
||||
|
||||
/// Cost the aggregate-only providers contribute to a corpus, for the "what was
|
||||
/// left out" footnote. Read from the UNFILTERED parse.
|
||||
export function aggregateOnlyCostUSD(projects: ProjectSummary[]): number {
|
||||
let total = 0
|
||||
for (const project of projects) {
|
||||
for (const session of project.sessions) {
|
||||
for (const turn of session.turns) {
|
||||
for (const call of turn.assistantCalls) {
|
||||
if (AGGREGATE_ONLY_PROVIDERS.has(call.provider)) total += call.costUSD
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/// `includeAggregateOnly` is the WRITE-side opt-out. The session cache and the
|
||||
/// durable daily cache must keep sealing the gateway slice — it can never be
|
||||
/// re-fetched for a past day — so the cache writer, and the aggregator paths
|
||||
/// that derive day entries, ask for the full corpus and hold the provider out
|
||||
/// of the totals at read time instead (`excludeProviderFromDay`). Every other
|
||||
/// caller gets the shared default, which is what makes `models`, `sessions`,
|
||||
/// `export`, `compare`, `spend`, `yield`, `audit`, `budget` and the sync push
|
||||
/// agree with the headline without each one knowing the rule.
|
||||
export function parseAllSessions(
|
||||
dateRange?: DateRange,
|
||||
providerFilter?: string,
|
||||
opts?: { includeAggregateOnly?: boolean },
|
||||
): Promise<ProjectSummary[]> {
|
||||
const parsed = parseAllSessionsUnfiltered(dateRange, providerFilter)
|
||||
if (opts?.includeAggregateOnly === true) return parsed
|
||||
return parsed.then(projects => excludeAggregateOnlyProjects(projects, providerFilter))
|
||||
}
|
||||
|
||||
function parseAllSessionsUnfiltered(dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
|
||||
const scoped = singlePassParse(dateRange, providerFilter)
|
||||
if (scoped) return scoped
|
||||
// Capture synchronously, before the first await. AsyncLocalStorage keeps all
|
||||
|
|
@ -5741,6 +5962,12 @@ async function runParseInner(
|
|||
deferredRetryableSource = false
|
||||
firstPaintDeferredThisRun = 0
|
||||
dateFloorSkippedProviders.clear()
|
||||
// Providers whose mid-scan read threw EPERM/EACCES: a recoverable permission
|
||||
// error is "unknown", not "empty", so they are excluded from completeness
|
||||
// marking (like a failed discovery) and block hydration-complete, so that
|
||||
// restoring access later reopens the affected days instead of them staying
|
||||
// sealed as fully scanned.
|
||||
const permissionSkippedProviders = new Set<string>()
|
||||
const seenMsgIds = new Set<string>()
|
||||
const seenKeys = new Set<string>()
|
||||
const discovery = snapshotOnly
|
||||
|
|
@ -5808,6 +6035,7 @@ async function runParseInner(
|
|||
if (claudeSources.length > 0) emitScanProgress({ kind: 'provider', provider: 'claude', state: 'done', files: claudeSources.length })
|
||||
} catch (err) {
|
||||
if (!isPermissionError(err)) throw err
|
||||
permissionSkippedProviders.add('claude')
|
||||
process.stderr.write(`codeburn: skipped claude data (permission denied; grant Full Disk Access to include it)\n`)
|
||||
emitScanProgress({ kind: 'provider', provider: 'claude', state: 'skipped' })
|
||||
}
|
||||
|
|
@ -5825,6 +6053,7 @@ async function runParseInner(
|
|||
// A permission-locked provider skips-and-continues; any other error is a
|
||||
// real bug and still aborts (per-file/DB-lock cases are handled deeper).
|
||||
if (!isPermissionError(err)) throw err
|
||||
permissionSkippedProviders.add(providerName)
|
||||
process.stderr.write(`codeburn: skipped ${providerName} data (permission denied; grant Full Disk Access to include it)\n`)
|
||||
emitScanProgress({ kind: 'provider', provider: providerName, state: 'skipped' })
|
||||
}
|
||||
|
|
@ -5886,7 +6115,7 @@ async function runParseInner(
|
|||
const deferredForFirstPaint = firstPaintDeferredThisRun > 0
|
||||
const rangeStartMs = dateRange?.start.getTime()
|
||||
const scopedRun = !!providerFilter && providerFilter !== 'all'
|
||||
const discoveryFailed = new Set(discovery.failedProviders)
|
||||
const discoveryFailed = new Set([...discovery.failedProviders, ...permissionSkippedProviders])
|
||||
let completenessChanged = false
|
||||
if (!readOnly && !deferredForFirstPaint) {
|
||||
const walked = scopedRun ? [providerFilter!] : Object.keys(diskCache.providers)
|
||||
|
|
@ -5901,7 +6130,25 @@ async function runParseInner(
|
|||
}
|
||||
}
|
||||
if (!readOnly && (isCacheDirty(diskCache) || completenessChanged)) {
|
||||
try {
|
||||
// A superseded pre-image is dropped rather than carried: another process
|
||||
// published, so this object's months were reloaded into a different one,
|
||||
// and what the old one held is simply re-parsed.
|
||||
if (pendingShardPublish && pendingShardPublish !== diskCache) pendingShardPublish = null
|
||||
// A durable provider's cache entry is the only record of that spend once
|
||||
// the provider prunes its own files, so its window is published on the poll
|
||||
// that parsed it — exactly as it was before coalescing existed. Holding it
|
||||
// would put the spend one `kill -9` away from being gone for good.
|
||||
if (shardPublishCoalescing && !completenessChanged && !isCold
|
||||
&& !hasDirtyDurableProvider(diskCache)
|
||||
&& Date.now() - lastShardPublishAt < SHARD_PUBLISH_COALESCE_MS) {
|
||||
// Held, not lost: the entries stay in this cache object — the one the
|
||||
// next load memo hands back, dirty flags and all — until a later refresh
|
||||
// publishes them under its own fence, or the shutdown flush does.
|
||||
pendingShardPublish = diskCache
|
||||
traceTiming('save', ' coalesced')
|
||||
} else try {
|
||||
pendingShardPublish = null
|
||||
lastShardPublishAt = Date.now()
|
||||
const published = await saveCache(diskCache, refreshLock?.verifyStillOwner)
|
||||
if (!published) throw new RefreshFenceLostError()
|
||||
} catch (err) {
|
||||
|
|
@ -5913,7 +6160,7 @@ async function runParseInner(
|
|||
// files, or a write run that deferred a changed source on a retryable
|
||||
// failure, reached the end of the scan without hydrating everything, and
|
||||
// the daily backfill must not finalize history off it.
|
||||
sessionHydrationComplete = (!readOnly || !readOnlyServedStale) && !deferredRetryableSource && !deferredForFirstPaint
|
||||
sessionHydrationComplete = (!readOnly || !readOnlyServedStale) && !deferredRetryableSource && !deferredForFirstPaint && permissionSkippedProviders.size === 0
|
||||
sessionFirstPaintDeferred = deferredForFirstPaint
|
||||
|
||||
// Merge across providers by normalised project path so the same repository
|
||||
|
|
|
|||
|
|
@ -178,14 +178,26 @@ type TurnTools = {
|
|||
subagentTypes?: string[]
|
||||
}
|
||||
|
||||
const cachedServers = new Map<string, ServerInfo | null>()
|
||||
const cachedModelMaps = new Map<string, ModelMap>()
|
||||
// Server discovery and model maps are memoized for the process lifetime, which
|
||||
// in the resident `serve` daemon means a single transient miss (or an
|
||||
// Antigravity restart onto a new port/CSRF) would otherwise disable RPC
|
||||
// enrichment forever. Re-probe on a TTL: a good result is trusted for a while,
|
||||
// a null/empty (failed) one is retried soon.
|
||||
const DETECT_SUCCESS_TTL_MS = 60_000
|
||||
const DETECT_FAILURE_TTL_MS = 5_000
|
||||
type Cached<T> = { value: T; at: number }
|
||||
const cachedServers = new Map<string, Cached<ServerInfo | null>>()
|
||||
const cachedModelMaps = new Map<string, Cached<ModelMap>>()
|
||||
type AntigravityCacheState = { cache: AntigravityCache; dirty: boolean }
|
||||
const cacheStates = new Map<string, AntigravityCacheState>()
|
||||
|
||||
// Dropped by the resident RSS guard. A dirty state holds cascades not yet on
|
||||
// disk, so it stays resident until its own flush publishes it.
|
||||
// disk, so it stays resident until its own flush publishes it. The server and
|
||||
// model-map memos carry no unflushed data, so drop them wholesale — the next
|
||||
// call re-probes.
|
||||
export function clearAntigravityCacheStates(): void {
|
||||
cachedServers.clear()
|
||||
cachedModelMaps.clear()
|
||||
for (const [dir, state] of cacheStates) {
|
||||
if (!state.dirty) cacheStates.delete(dir)
|
||||
}
|
||||
|
|
@ -557,24 +569,29 @@ export function antigravityAppDataDirFromSourcePath(path: string): 'antigravity'
|
|||
return 'antigravity'
|
||||
}
|
||||
|
||||
function cachedValueIsFresh<T>(cached: Cached<T> | undefined, failed: (value: T) => boolean): boolean {
|
||||
if (!cached) return false
|
||||
const ttl = failed(cached.value) ? DETECT_FAILURE_TTL_MS : DETECT_SUCCESS_TTL_MS
|
||||
return Date.now() - cached.at < ttl
|
||||
}
|
||||
|
||||
async function detectServer(appDataDir: 'antigravity' | 'antigravity-cli' | 'antigravity-ide' = 'antigravity'): Promise<ServerInfo | null> {
|
||||
if (cachedServers.has(appDataDir)) return cachedServers.get(appDataDir)!
|
||||
const cached = cachedServers.get(appDataDir)
|
||||
if (cachedValueIsFresh(cached, value => value === null)) return cached!.value
|
||||
let resolved: ServerInfo | null = null
|
||||
try {
|
||||
const candidates = parseAntigravityServerCandidates(await readProcessCommandLines())
|
||||
const info = candidates.find(candidate => candidate.appDataDir === appDataDir)
|
||||
?? (appDataDir === 'antigravity' ? candidates.find(candidate => candidate.appDataDir === undefined) : undefined)
|
||||
?? null
|
||||
if (info && info.port > 0 && appDataDir !== 'antigravity-ide') {
|
||||
cachedServers.set(appDataDir, { port: info.port, csrfToken: info.csrfToken })
|
||||
resolved = { port: info.port, csrfToken: info.csrfToken }
|
||||
} else if (info) {
|
||||
cachedServers.set(appDataDir, await resolveEphemeralPort(info.csrfToken, appDataDir))
|
||||
} else {
|
||||
cachedServers.set(appDataDir, null)
|
||||
resolved = await resolveEphemeralPort(info.csrfToken, appDataDir)
|
||||
}
|
||||
return cachedServers.get(appDataDir)!
|
||||
} catch { /* process discovery failed or timed out */ }
|
||||
cachedServers.set(appDataDir, null)
|
||||
return null
|
||||
cachedServers.set(appDataDir, { value: resolved, at: Date.now() })
|
||||
return resolved
|
||||
}
|
||||
|
||||
async function rpc(server: ServerInfo, method: string, body: Record<string, unknown> = {}): Promise<unknown> {
|
||||
|
|
@ -627,14 +644,14 @@ async function rpc(server: ServerInfo, method: string, body: Record<string, unkn
|
|||
|
||||
async function getModelMap(server: ServerInfo): Promise<ModelMap> {
|
||||
const cacheKey = `${server.port}:${server.csrfToken}`
|
||||
const cachedModelMap = cachedModelMaps.get(cacheKey)
|
||||
if (cachedModelMap) return cachedModelMap
|
||||
const cached = cachedModelMaps.get(cacheKey)
|
||||
if (cachedValueIsFresh(cached, value => Object.keys(value).length === 0)) return cached!.value
|
||||
try {
|
||||
const modelMap = extractAntigravityModelMap(await rpc(server, 'GetAvailableModels'))
|
||||
cachedModelMaps.set(cacheKey, modelMap)
|
||||
cachedModelMaps.set(cacheKey, { value: modelMap, at: Date.now() })
|
||||
return modelMap
|
||||
} catch { /* best-effort */ }
|
||||
cachedModelMaps.set(cacheKey, {})
|
||||
cachedModelMaps.set(cacheKey, { value: {}, at: Date.now() })
|
||||
return {}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -533,7 +533,10 @@ async function discoverFromDb(dbPath: string, profile: string): Promise<SessionS
|
|||
let db: SqliteDatabase
|
||||
try {
|
||||
db = openDatabase(dbPath)
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// A busy/locked open is not an empty DB: escalate so discovery is marked
|
||||
// failed rather than sealing an empty period (mirrors the query catch below).
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
return []
|
||||
}
|
||||
|
||||
|
|
@ -600,6 +603,8 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
try {
|
||||
db = openDatabase(decoded.dbPath)
|
||||
} catch (err) {
|
||||
// A busy/locked open must reach the caller, not read as an empty session.
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
process.stderr.write(`codeburn: cannot open Hermes database: ${err instanceof Error ? err.message : err}\n`)
|
||||
return
|
||||
}
|
||||
|
|
@ -719,6 +724,10 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
)
|
||||
|
||||
const cost = resolveHermesCost(row, model, tokens)
|
||||
// Decided rule: a session's cost delta lands on the day it is OBSERVED
|
||||
// (`observedAt`), not the day the session started. A mid-session price
|
||||
// change therefore shows up on the observation day, and a sealed day is
|
||||
// never rewritten to reprice it.
|
||||
const cursor = await recordHermesSnapshot({
|
||||
profile,
|
||||
sessionId: row.id,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { readdir, readFile } from 'fs/promises'
|
||||
import { readdir, readFile, stat } from 'fs/promises'
|
||||
import { basename, join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
|
|
@ -164,6 +164,12 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
|
||||
if (!sessionId) sessionId = basename(source.path, '.jsonl')
|
||||
|
||||
// Fallback for a call whose own timestamp is missing/unparseable: the
|
||||
// file's mtime keeps the call inside the session's window instead of
|
||||
// dropping real spend (matches openclaude.ts/codewhale.ts).
|
||||
const fileStat = await stat(source.path).catch(() => null)
|
||||
const fileMtime = fileStat ? fileStat.mtime : new Date(NaN)
|
||||
|
||||
for (let i = 0; i < calls.length; i++) {
|
||||
const call = calls[i]
|
||||
const dedupKey = `openclaw:${sessionId}:${call.dedupId || i}`
|
||||
|
|
@ -171,12 +177,17 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
seenKeys.add(dedupKey)
|
||||
|
||||
const u = call.usage
|
||||
// OpenClaw writes what the call actually cost, per message (never a
|
||||
// running session total), in USD. Absent or 0 means "not recorded":
|
||||
// those fall back to token pricing and must stay re-priceable.
|
||||
const costFromProvider = u.cost?.total ?? 0
|
||||
const costUSD = costFromProvider > 0
|
||||
const isReported = costFromProvider > 0
|
||||
const costUSD = isReported
|
||||
? costFromProvider
|
||||
: calculateCost(call.model, u.input, u.output, u.cacheWrite, u.cacheRead, 0)
|
||||
|
||||
const ts = new Date(call.timestamp)
|
||||
let ts = new Date(call.timestamp)
|
||||
if (isNaN(ts.getTime()) || ts.getTime() < 1_000_000_000_000) ts = fileMtime
|
||||
if (isNaN(ts.getTime()) || ts.getTime() < 1_000_000_000_000) continue
|
||||
|
||||
yield {
|
||||
|
|
@ -190,6 +201,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
costUSD,
|
||||
...(isReported ? { costFromBilling: true } : {}),
|
||||
tools: [...new Set(call.tools)],
|
||||
bashCommands: [...new Set(call.bashCommands)],
|
||||
timestamp: ts.toISOString(),
|
||||
|
|
|
|||
|
|
@ -210,6 +210,10 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
async *parse(): AsyncGenerator<ParsedProviderCall> {
|
||||
const content = await readSessionFile(source.path)
|
||||
if (content === null) return
|
||||
// Last-resort timestamp so a call whose entry/user/session timestamps are
|
||||
// all missing lands inside the session's window instead of being dropped.
|
||||
const fileStat = await stat(source.path).catch(() => null)
|
||||
const fileMtime = fileStat?.mtime.toISOString() ?? ''
|
||||
const lines = content.split('\n').filter(l => l.trim())
|
||||
let sessionId = basename(source.path, '.jsonl')
|
||||
let resolvedModel = ''
|
||||
|
|
@ -316,10 +320,14 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
// xai-oauth calls, so the alias table and price overrides never apply.
|
||||
// A genuinely free call would recompute to a small nonzero number;
|
||||
// that is the trade-off we accept for fixing the OAuth zero.
|
||||
const costUSD = typeof reportedCost === 'number' && Number.isFinite(reportedCost) && reportedCost !== 0
|
||||
// Per-message USD, never a running session total (verified against
|
||||
// real Pi transcripts: cost.total equals this message's own
|
||||
// input+output+cacheRead+cacheWrite and does not increase monotonically).
|
||||
const isReported = typeof reportedCost === 'number' && Number.isFinite(reportedCost) && reportedCost !== 0
|
||||
const costUSD = isReported
|
||||
? reportedCost
|
||||
: calculateCost(messageModel || resolvedModel || model, input, output, cacheWrite, cacheRead, 0)
|
||||
const timestamp = entry.timestamp || pendingUserTimestamp || sessionTimestamp
|
||||
const timestamp = entry.timestamp || pendingUserTimestamp || sessionTimestamp || fileMtime
|
||||
if (!timestamp) continue
|
||||
yield {
|
||||
provider: source.provider,
|
||||
|
|
@ -332,6 +340,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
costUSD,
|
||||
...(isReported ? { costFromBilling: true } : {}),
|
||||
tools,
|
||||
bashCommands,
|
||||
skills,
|
||||
|
|
|
|||
|
|
@ -58,6 +58,17 @@ function projectNameFromDirName(dirName: string): string {
|
|||
return parts[parts.length - 1] || dirName
|
||||
}
|
||||
|
||||
// Validate the entry timestamp and fall back to the file mtime when it is
|
||||
// missing/unparseable, so the call lands on a real day instead of an empty
|
||||
// string that parser.ts date filters exclude from period reports.
|
||||
function isoTimestamp(value: string | undefined, fallback: string): string {
|
||||
if (value) {
|
||||
const date = new Date(value)
|
||||
if (!Number.isNaN(date.getTime())) return date.toISOString()
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
function extractTools(parts: QwenPart[]): { tools: string[]; bashCommands: string[] } {
|
||||
const tools: string[] = []
|
||||
const bashCommands: string[] = []
|
||||
|
|
@ -81,6 +92,9 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
const raw = await readSessionFile(source.path)
|
||||
if (raw === null) return
|
||||
|
||||
const fileStat = await stat(source.path).catch(() => null)
|
||||
const fileMtime = fileStat?.mtime.toISOString() ?? ''
|
||||
|
||||
const lines = raw.split('\n').filter(l => l.trim())
|
||||
let pendingUserMessage = ''
|
||||
|
||||
|
|
@ -134,7 +148,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
costUSD,
|
||||
tools: [...new Set(tools)],
|
||||
bashCommands: [...new Set(bashCommands)],
|
||||
timestamp: entry.timestamp || '',
|
||||
timestamp: isoTimestamp(entry.timestamp, fileMtime),
|
||||
speed: 'standard',
|
||||
deduplicationKey: dedupKey,
|
||||
userMessage: pendingUserMessage,
|
||||
|
|
|
|||
|
|
@ -202,7 +202,8 @@ function tryQuerySessionTokens(db: SqliteDatabase, sessionId: string, generation
|
|||
model: parsedModel?.model,
|
||||
providerID: parsedModel?.providerID,
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -484,7 +485,11 @@ export async function discoverSqliteSessions(
|
|||
|
||||
try {
|
||||
const generation = detectGeneration(db)
|
||||
if (generation === null) continue
|
||||
if (generation === null) {
|
||||
const schema = validateSchemaDetailed(db)
|
||||
if (!schema.ok) warnUnrecognizedSchemaOnce(config.displayName, schema.missing)
|
||||
continue
|
||||
}
|
||||
|
||||
// Same projection on both generations; only the table name moves.
|
||||
const table = generation === 'v2' ? 'session_v2' : 'session'
|
||||
|
|
@ -514,7 +519,11 @@ export async function discoverSqliteSessions(
|
|||
provider: config.providerName,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// A busy/locked DB (OpenCode or KiloCode open during the scan) is not an
|
||||
// empty DB: let it reach the caller so discovery is marked failed rather
|
||||
// than sealing an empty period as fully scanned.
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
// skip this DB
|
||||
} finally {
|
||||
db.close()
|
||||
|
|
|
|||
|
|
@ -41,6 +41,14 @@ export type ParsedProviderCall = {
|
|||
webSearchRequests: number
|
||||
costUSD: number
|
||||
costIsEstimated?: boolean
|
||||
// True when `costUSD` came from the provider's OWN billing record (charged
|
||||
// dollars, or metered credits at a published rate) instead of being priced
|
||||
// from this call's tokens. Such a cost is preserved through the session
|
||||
// cache (parser.ts providerCallToCachedCall); a call without it stores no
|
||||
// cost and is re-priced from its cached tokens on every read, so a pricing
|
||||
// update still reaches it. Orthogonal to `costIsEstimated`: a credit rate is
|
||||
// an estimate of dollars, but it is still billing-derived.
|
||||
costFromBilling?: boolean
|
||||
tools: string[]
|
||||
bashCommands: string[]
|
||||
// Subagent types spawned in this call (e.g. 'general-purpose'). Feeds the
|
||||
|
|
@ -89,6 +97,11 @@ export type ParsedProviderCall = {
|
|||
// Hermes observation-time deltas persist this flag (and reconstruct it at
|
||||
// serve time from a `:obs:` key). Copilot still assigns it only at serve time.
|
||||
supplementaryAccounting?: boolean
|
||||
// How many requests this one call stands for. Set only by a provider whose
|
||||
// API publishes daily aggregates rather than per-request records (Vercel AI
|
||||
// Gateway's `request_count`); absent everywhere else, which means 1. Cost and
|
||||
// tokens stay whole on the call — this moves request counters only.
|
||||
requestCount?: number
|
||||
// Billing route the provider recorded for this call, as a route id from
|
||||
// `src/models.ts` ROUTES (`bedrock`). Set only from a provider's own
|
||||
// endpoint column (Hermes `billing_provider`); when absent, the model id's
|
||||
|
|
|
|||
|
|
@ -3,6 +3,13 @@ import type { DateRange } from '../types.js'
|
|||
import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
|
||||
import { fetchWithTimeout } from '../fetch-utils.js'
|
||||
|
||||
// The report is a DAILY AGGREGATE per model: no request ids, no timestamps, no
|
||||
// attribution. Nothing in a row can be matched against the local tools that
|
||||
// were pointed at the gateway (Claude Code via ANTHROPIC_BASE_URL, Codex,
|
||||
// OpenCode, Cline/Roo/Kilo, Cursor), which record the same requests
|
||||
// themselves. Gateway spend is therefore shown as its own row and kept out of
|
||||
// headline totals unless `includeGatewayInTotals` is set — see
|
||||
// `excludeProviderFromDay` in src/usage-aggregator.ts.
|
||||
const REPORT_URL = 'https://ai-gateway.vercel.sh/v1/report'
|
||||
|
||||
type ReportRow = {
|
||||
|
|
@ -93,9 +100,14 @@ function createParser(
|
|||
if (seenKeys.has(deduplicationKey)) continue
|
||||
seenKeys.add(deduplicationKey)
|
||||
|
||||
// One row is a whole day of requests for one model, so it stands for
|
||||
// `request_count` of them. Cost and tokens stay whole on this single
|
||||
// call; only request counters read the count (behavioralCallWeight).
|
||||
const requestCount = row.request_count
|
||||
yield {
|
||||
provider: 'vercel-gateway',
|
||||
model,
|
||||
...(typeof requestCount === 'number' && requestCount > 1 ? { requestCount } : {}),
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
|
||||
|
|
|
|||
|
|
@ -3,15 +3,26 @@ import { homedir } from 'os'
|
|||
|
||||
import { extractBashCommands } from '../bash-utils.js'
|
||||
import { calculateCost, getShortModelName } from '../models.js'
|
||||
import { blobToText, getSqliteLoadError, isBlockedDatabaseError, isSqliteAvailable, openDatabase, type SqliteDatabase } from '../sqlite.js'
|
||||
import { blobToText, getSqliteLoadError, isBlockedDatabaseError, isSqliteAvailable, isSqliteBusyError, openDatabase, type SqliteDatabase } from '../sqlite.js'
|
||||
import { estimateTokensFromChars } from '../token-estimate.js'
|
||||
import type { ProbeRoot, ParsedProviderCall, Provider, SessionParser, SessionSource } from './types.js'
|
||||
import { safeNumber } from '../parser.js'
|
||||
import { isPermissionError, safeNumber } from '../parser.js'
|
||||
|
||||
const WARP_GROUP_CONTAINER = '2BBY89MBSN.dev.warp'
|
||||
const WARP_STABLE_BUNDLE_ID = 'dev.warp.Warp-Stable'
|
||||
const WARP_PREVIEW_BUNDLE_ID = 'dev.warp.Warp-Preview'
|
||||
const PRIMARY_AGENT_CATEGORY = 'primary_agent'
|
||||
// Warp bills agent usage in credits, not tokens. Warp's published pricing sets
|
||||
// the base rate at 1,500 credits for $20 (the Build/Business monthly allotment,
|
||||
// described on warp.dev/pricing as "$20 of included agent usage at API rates"),
|
||||
// i.e. $0.013333 per credit. Warp's authoritative per-account rate lives
|
||||
// server-side in `payg_cost_per_thousand_credits_cents` / `AddonCreditsOption`
|
||||
// (github.com/warpdotdev/warp, crates/graphql/src/api/billing.rs) and is NOT
|
||||
// shipped as a client constant, so the published allotment rate is the best
|
||||
// public evidence available.
|
||||
// ponytail: fixed public rate; the real per-account PAYG rate varies with
|
||||
// volume discounts. CONFIRM against Warp's current published pricing.
|
||||
const CREDIT_USD_RATE = 20 / 1500 // $0.013333 per credit ($13.33 / 1000 credits)
|
||||
const modelAliases: Record<string, string> = {
|
||||
'Claude Sonnet 4.6': 'claude-sonnet-4-6',
|
||||
'Claude Sonnet 4.5': 'claude-sonnet-4-5',
|
||||
|
|
@ -57,12 +68,33 @@ type WarpTokenUsageEntry = {
|
|||
byok_token_usage_by_category?: Record<string, unknown>
|
||||
}
|
||||
|
||||
// Warp's ChargedUsageTotals (crates/persistence/src/model.rs): per-category
|
||||
// dollar breakdown Warp actually charged. total_cost_in_cents() sums these six
|
||||
// *_cost_in_cents fields.
|
||||
type WarpChargedUsageTotals = {
|
||||
input_cost_in_cents?: number
|
||||
output_cost_in_cents?: number
|
||||
input_cache_read_cost_in_cents?: number
|
||||
input_cache_write_cost_in_cents?: number
|
||||
platform_cost_in_cents?: number
|
||||
web_search_cost_in_cents?: number
|
||||
}
|
||||
|
||||
type WarpConversationData = {
|
||||
conversation_usage_metadata?: {
|
||||
token_usage?: WarpTokenUsageEntry[]
|
||||
// Server-authoritative cumulative provider cost, in US cents. Absent (not 0)
|
||||
// when the server never provided it.
|
||||
total_provider_cost_in_cents?: number
|
||||
// Cumulative per-category charged usage across the conversation, in cents.
|
||||
total_charged_usage?: WarpChargedUsageTotals
|
||||
// Credits Warp deducted for the conversation (always populated today).
|
||||
credits_spent?: number
|
||||
}
|
||||
}
|
||||
|
||||
type WarpCost = { usd: number; estimated: boolean }
|
||||
|
||||
type ParsedExchange = WarpQueryRow & {
|
||||
startMs: number
|
||||
}
|
||||
|
|
@ -179,6 +211,56 @@ function extractTokenBudget(rawConversationData: string): { tokenBudget: number;
|
|||
return { tokenBudget: Math.max(0, Math.round(tokenBudget)), dominantModel: normalizeModel(dominantModel) }
|
||||
}
|
||||
|
||||
// Warp records what it actually charged in the same blob as the token counts.
|
||||
// Prefer those real dollars over the token-floor estimate. Ladder, most to
|
||||
// least authoritative:
|
||||
// (a) total_provider_cost_in_cents — server-authoritative USD (exact)
|
||||
// (b) sum of total_charged_usage — server per-category USD (exact)
|
||||
// (c) credits_spent × CREDIT_USD_RATE — credits at published rate (heuristic)
|
||||
// (d) null → caller falls back to the token × LiteLLM estimate (floor)
|
||||
// A value of 0/absent at a rung is treated as "not recorded here" and defers to
|
||||
// the next rung, so a zero never masks a real cost recorded elsewhere.
|
||||
function conversationCostUsd(rawConversationData: string): WarpCost | null {
|
||||
let meta: WarpConversationData['conversation_usage_metadata']
|
||||
try {
|
||||
meta = (JSON.parse(rawConversationData) as WarpConversationData).conversation_usage_metadata
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!meta) return null
|
||||
|
||||
const providerCents = safeNumber(meta.total_provider_cost_in_cents)
|
||||
if (providerCents > 0) return { usd: providerCents / 100, estimated: false }
|
||||
|
||||
const charged = meta.total_charged_usage
|
||||
if (charged) {
|
||||
const cents =
|
||||
safeNumber(charged.input_cost_in_cents) +
|
||||
safeNumber(charged.output_cost_in_cents) +
|
||||
safeNumber(charged.input_cache_read_cost_in_cents) +
|
||||
safeNumber(charged.input_cache_write_cost_in_cents) +
|
||||
safeNumber(charged.platform_cost_in_cents) +
|
||||
safeNumber(charged.web_search_cost_in_cents)
|
||||
if (cents > 0) return { usd: cents / 100, estimated: false }
|
||||
}
|
||||
|
||||
const credits = safeNumber(meta.credits_spent)
|
||||
if (credits > 0) return { usd: credits * CREDIT_USD_RATE, estimated: true }
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// Split a conversation-level USD total across exchanges by the same char-based
|
||||
// weights used to split tokens, so per-exchange cost tracks per-exchange size.
|
||||
function allocateCost(weights: number[], totalUsd: number): number[] {
|
||||
if (weights.length === 0) return []
|
||||
if (!(totalUsd > 0)) return weights.map(() => 0)
|
||||
const normalized = weights.map(w => Math.max(0, w))
|
||||
const totalWeight = normalized.reduce((sum, w) => sum + w, 0)
|
||||
if (totalWeight === 0) return normalized.map(() => totalUsd / normalized.length)
|
||||
return normalized.map(w => (totalUsd * w) / totalWeight)
|
||||
}
|
||||
|
||||
function extractUserMessage(rawInput: string): string {
|
||||
try {
|
||||
const parsed = JSON.parse(rawInput) as unknown
|
||||
|
|
@ -327,6 +409,9 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
try {
|
||||
db = openDatabase(dbPath)
|
||||
} catch (err) {
|
||||
// A busy/locked hit on Warp's continuously-written DB must reach the
|
||||
// caller, not read as an empty session that seals the period.
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
process.stderr.write(`codeburn: cannot open Warp database: ${err instanceof Error ? err.message : err}\n`)
|
||||
return
|
||||
}
|
||||
|
|
@ -374,6 +459,8 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
const weights = parsedExchanges.map(exchange => estimateWeight(exchange.input))
|
||||
const fallbackBudget = weights.reduce((sum, weight) => sum + weight, 0)
|
||||
const allocatedTokens = allocateTokens(weights, tokenBudget > 0 ? tokenBudget : fallbackBudget)
|
||||
const conversationCost = conversationCostUsd(conversations[0]!.conversation_data)
|
||||
const allocatedCosts = conversationCost ? allocateCost(weights, conversationCost.usd) : null
|
||||
const toolsByExchange = assignCommandBlocksToExchanges(blocks, parsedExchanges)
|
||||
|
||||
for (let index = 0; index < parsedExchanges.length; index++) {
|
||||
|
|
@ -402,8 +489,11 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
costUSD: calculateCost(model, inputTokens, 0, 0, 0, 0),
|
||||
costIsEstimated: true,
|
||||
costUSD: allocatedCosts ? (allocatedCosts[index] ?? 0) : calculateCost(model, inputTokens, 0, 0, 0, 0),
|
||||
costIsEstimated: conversationCost ? conversationCost.estimated : true,
|
||||
// Rungs (a)-(c) are Warp's own billing record; keep them through
|
||||
// the cache. Rung (d) is the token floor, which stays re-priceable.
|
||||
...(conversationCost ? { costFromBilling: true } : {}),
|
||||
tools: exchangeTools.tools,
|
||||
bashCommands: exchangeTools.bashCommands,
|
||||
timestamp,
|
||||
|
|
@ -427,9 +517,11 @@ async function discoverFromDb(dbPath: string): Promise<SessionSource[]> {
|
|||
try {
|
||||
db = openDatabase(dbPath)
|
||||
} catch (err) {
|
||||
// A blocked database means "unknown", not "no sessions": let it reach the
|
||||
// registry so the run is marked degraded instead of silently empty.
|
||||
if (isBlockedDatabaseError(err)) throw err
|
||||
// A blocked, busy, or permission-denied database means "unknown", not "no
|
||||
// sessions": let it reach the registry so the run is marked degraded
|
||||
// instead of silently empty. A plain EACCES/EPERM (e.g. a WARP_DB_PATH
|
||||
// override the OS won't let us read) is recoverable once access is granted.
|
||||
if (isBlockedDatabaseError(err) || isSqliteBusyError(err) || isPermissionError(err)) throw err
|
||||
return []
|
||||
}
|
||||
|
||||
|
|
@ -462,7 +554,10 @@ async function discoverFromDb(dbPath: string): Promise<SessionSource[]> {
|
|||
provider: 'warp',
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// Warp writes this DB constantly, so a SQLITE_BUSY/LOCKED here is the likely
|
||||
// spot: escalate rather than seal an empty discovery.
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
return []
|
||||
} finally {
|
||||
db.close()
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
import { calculateCost } from '../models.js'
|
||||
import { billableOutputTokens, calculateCost } from '../models.js'
|
||||
import { isSqliteAvailable, getSqliteLoadError, openDatabase, type SqliteDatabase } from '../sqlite.js'
|
||||
import type { Provider, SessionSource, SessionParser, ParsedProviderCall, ProbeRoot } from './types.js'
|
||||
|
||||
|
|
@ -169,7 +169,11 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
}
|
||||
|
||||
const model = row.model_id
|
||||
const costUSD = calculateCost(model, freshInput, output, cacheCreation, cacheRead, 0)
|
||||
// ZCode reports reasoning as a separate bucket and 'zcode' is not in
|
||||
// REASONING_INCLUDED_IN_OUTPUT, so bill it via the output-equivalent
|
||||
// (billableOutputTokens adds it back). Not doing so left reasoning
|
||||
// tokens unbilled.
|
||||
const costUSD = calculateCost(model, freshInput, billableOutputTokens('zcode', output, reasoning), cacheCreation, cacheRead, 0)
|
||||
|
||||
yield {
|
||||
provider: 'zcode',
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ export type ClaudeDeps = {
|
|||
fetch: typeof fetch
|
||||
credentialPath: string
|
||||
readFile: typeof readSecureFile
|
||||
now: () => number
|
||||
keychain?: () => Promise<KeychainOutcome>
|
||||
}
|
||||
|
||||
|
|
@ -21,7 +20,6 @@ const defaults: ClaudeDeps = {
|
|||
fetch: globalThis.fetch,
|
||||
credentialPath: path.join(os.homedir(), '.claude', '.credentials.json'),
|
||||
readFile: readSecureFile,
|
||||
now: Date.now,
|
||||
}
|
||||
|
||||
function empty(connection: QuotaProvider['connection']): QuotaProvider {
|
||||
|
|
@ -134,13 +132,7 @@ export async function fetchClaudeQuota(options: Partial<ClaudeDeps> & { signal?:
|
|||
}
|
||||
if (!credential) return { quota: empty('disconnected') }
|
||||
|
||||
let response: Response
|
||||
if (credential.expiresAt !== undefined && credential.expiresAt - deps.now() <= 5 * 60_000) {
|
||||
const reread = await credentialFromFile(deps)
|
||||
if (!reread || reread.accessToken === credential.accessToken) return { quota: empty('transientFailure') }
|
||||
credential = reread
|
||||
}
|
||||
response = await request(credential.accessToken, deps, options.signal)
|
||||
let response = await request(credential.accessToken, deps, options.signal)
|
||||
if (response.status === 401) {
|
||||
const reread = await credentialFromFile(deps)
|
||||
if (!reread || reread.accessToken === credential.accessToken) return { quota: empty('transientFailure') }
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { fetchGeminiQuota } from './gemini.js'
|
|||
import { fetchGrokQuota } from './grok.js'
|
||||
import { fetchGrokbotQuota, grokbotInstalled } from './grokbot.js'
|
||||
import { fetchKimiQuota } from './kimi.js'
|
||||
import { KEYCHAIN_TIMEOUT_MS } from './security.js'
|
||||
import type { ProviderName, QuotaProvider } from './types.js'
|
||||
import { fetchZaiQuota } from './zai.js'
|
||||
import { fetchZcodeQuota } from './zcode.js'
|
||||
|
|
@ -63,7 +64,12 @@ export function availableReaders(installed: () => boolean = grokbotInstalled): t
|
|||
return READERS.filter(entry => entry.id !== 'grokbot' || installed())
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 5_000
|
||||
// Must cover the slowest documented per-reader allowance - Claude's keychain
|
||||
// fallback waits up to KEYCHAIN_TIMEOUT_MS for the macOS "Allow" dialog - or
|
||||
// this outer race aborts a reader that is still legitimately waiting and
|
||||
// misreports it as disconnected. Derived rather than a separate literal so
|
||||
// the two cannot drift apart; the margin covers the request itself.
|
||||
const DEFAULT_TIMEOUT_MS = KEYCHAIN_TIMEOUT_MS + 5_000
|
||||
|
||||
function errorFor(quota: QuotaProvider): string | undefined {
|
||||
switch (quota.connection) {
|
||||
|
|
@ -89,6 +95,16 @@ function toWindows(quota: QuotaProvider): QuotaCommandWindow[] {
|
|||
|
||||
export function toCommandProvider(id: ProviderName, name: string, quota: QuotaProvider): QuotaCommandProvider {
|
||||
const error = errorFor(quota)
|
||||
// errorFor() only surfaces footerLines on a non-connected state; a connected
|
||||
// read (e.g. Grok Bot's "this is the Cursor account's allowance" disclosure)
|
||||
// still needs its first line said out loud so it isn't shown as fact-free.
|
||||
const baseNotes = quota.notes ?? []
|
||||
const footerNote =
|
||||
quota.connection === 'connected' && quota.footerLines.length > 0 ? quota.footerLines[0] : undefined
|
||||
const notes = [
|
||||
...baseNotes,
|
||||
...(footerNote && !baseNotes.includes(footerNote) ? [footerNote] : []),
|
||||
]
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
|
|
@ -96,7 +112,7 @@ export function toCommandProvider(id: ProviderName, name: string, quota: QuotaPr
|
|||
...(quota.planLabel ? { plan: quota.planLabel } : {}),
|
||||
windows: toWindows(quota),
|
||||
...(error ? { error } : {}),
|
||||
...(quota.notes?.length ? { notes: quota.notes } : {}),
|
||||
...(notes.length ? { notes } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ const execFileAsync = promisify(execFile)
|
|||
// for) blocks until the user answers. Give them time to click Allow before we
|
||||
// give up - the old 10s kill fired while the dialog was still open and got
|
||||
// misread as "disconnected".
|
||||
const KEYCHAIN_TIMEOUT_MS = 90_000
|
||||
export const KEYCHAIN_TIMEOUT_MS = 90_000
|
||||
|
||||
/** Outcome of a keychain lookup. `accessDenied` means the item exists but macOS
|
||||
* needs the user to grant access (dialog dismissed, denied, or not answered). */
|
||||
|
|
|
|||
231
src/serve.ts
231
src/serve.ts
|
|
@ -37,9 +37,82 @@ import { isPathBlocked } from './sqlite.js'
|
|||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Past this resident-set size the serve loop drops its in-memory memos and
|
||||
// re-parses on the next request. 3GB leaves generous room for the largest
|
||||
// observed corpora while bounding a pathological one.
|
||||
const SERVE_MAX_RSS_BYTES = 3 * 1024 * 1024 * 1024
|
||||
// re-parses on the next request. 6GB default leaves generous room for the
|
||||
// largest observed corpora (a warm ~3GB cache survives) while bounding a
|
||||
// pathological one. CODEBURN_SERVE_MAX_RSS_MB (integer MB) overrides it.
|
||||
const DEFAULT_SERVE_MAX_RSS_MB = 6144
|
||||
const SERVE_MAX_RSS_BYTES = (() => {
|
||||
const mb = Number(process.env['CODEBURN_SERVE_MAX_RSS_MB'])
|
||||
return (Number.isInteger(mb) && mb > 0 ? mb : DEFAULT_SERVE_MAX_RSS_MB) * 1024 * 1024
|
||||
})()
|
||||
|
||||
// A warm cache holds RSS above the ceiling as a steady state, so clearing on
|
||||
// every request would thrash the cache. Track the RSS at the last clear and
|
||||
// require meaningful growth before clearing again — clear once per growth
|
||||
// plateau, but still clear on real unbounded growth.
|
||||
const SERVE_RSS_CLEAR_MARGIN_BYTES = 256 * 1024 * 1024
|
||||
let lastClearRss = 0
|
||||
|
||||
// V8 exposes gc() only to a process started with --expose-gc, and no codeburn
|
||||
// launcher passes it — so `globalThis.gc` was never there for the release below
|
||||
// to call. Ask V8 for the function directly instead. It is the difference
|
||||
// between the freed pages going back to the OS and the resident set sitting on
|
||||
// them for the life of the child: measured on a warm 170MB shard set, a release
|
||||
// that dropped 323MB of live objects moved RSS by 0MB without this and by
|
||||
// 712MB with it.
|
||||
let collect: (() => void) | null | undefined
|
||||
async function collectGarbage(): Promise<void> {
|
||||
if (collect === undefined) {
|
||||
try {
|
||||
const v8 = await import('v8')
|
||||
const vm = await import('vm')
|
||||
v8.setFlagsFromString('--expose-gc')
|
||||
collect = vm.runInNewContext('gc') as () => void
|
||||
v8.setFlagsFromString('--no-expose-gc')
|
||||
} catch {
|
||||
collect = null
|
||||
}
|
||||
}
|
||||
collect?.()
|
||||
}
|
||||
|
||||
// V8 hands pages back a batch at a time, and only on a LATER collection: on a
|
||||
// cold start the collection that follows the release took the child from 2767MB
|
||||
// to 1292MB, one a minute after that to 668MB — with no allocation in between,
|
||||
// and with V8 returning none of it on its own across ten minutes of idle.
|
||||
// Calling gc() twice in a row buys nothing; the wait between is what does. So
|
||||
// keep passing while a pass is still worth the margin, bounded so this can
|
||||
// never become a standing timer.
|
||||
const RELEASE_SETTLE_MS = 60_000
|
||||
const RELEASE_SETTLE_MIN_GAIN_BYTES = 64 * 1024 * 1024
|
||||
const RELEASE_SETTLE_PASSES = 4
|
||||
|
||||
/// Drop every in-memory memo this process can re-read from disk, then hand the
|
||||
/// pages back.
|
||||
///
|
||||
/// Ordering is load-bearing, and not the obvious one: the held shard-publish
|
||||
/// window strongly references the whole cache (so clearing without publishing
|
||||
/// it first frees nothing), and clearLoadCacheMemo() makes a later flush see a
|
||||
/// cache that is no longer current and DISCARD the window. Flushing here, while
|
||||
/// the memo still matches, publishes it instead. Dirty state therefore only
|
||||
/// ever leaves memory through a publish; a durable provider never waits in that
|
||||
/// window at all (parser.ts publishes its section on the poll that parsed it).
|
||||
/// Safe to await: requests and the background fill share one promise chain, so
|
||||
/// no parse can be mid-flight.
|
||||
export async function releaseResidentMemos(): Promise<void> {
|
||||
const { clearSessionCache, flushPendingShardPublish } = await import('./parser.js')
|
||||
const { clearLoadCacheMemo } = await import('./session-cache.js')
|
||||
const { clearCodexMemCaches } = await import('./codex-cache.js')
|
||||
const { clearAntigravityCacheStates } = await import('./providers/antigravity.js')
|
||||
const { clearScanFileMemo } = await import('./optimize.js')
|
||||
await flushPendingShardPublish()
|
||||
clearSessionCache()
|
||||
clearLoadCacheMemo()
|
||||
clearCodexMemCaches()
|
||||
clearAntigravityCacheStates()
|
||||
clearScanFileMemo()
|
||||
await collectGarbage()
|
||||
}
|
||||
|
||||
// How long a closing serve child waits for an already-accepted request before
|
||||
// giving up and exiting. CODEBURN_SERVE_DRAIN_MS overrides it so the e2e can
|
||||
|
|
@ -381,6 +454,9 @@ async function getConfigFingerprint(): Promise<string | null> {
|
|||
/// generation; a root absent at setup is rechecked by the parser's hard cap.
|
||||
type RootWatcherState = {
|
||||
startedAt: number
|
||||
/// The roots actually armed. A path outside them has no event source, so the
|
||||
/// incremental sweep must not trust anything it remembered about it.
|
||||
roots: string[]
|
||||
lastEventAt: () => number
|
||||
changedSince: (sinceTs: number) => string[] | null
|
||||
healthy: () => boolean
|
||||
|
|
@ -466,6 +542,7 @@ async function startRootWatchers(): Promise<RootWatcherState | null> {
|
|||
let healthy = true
|
||||
let closed = false
|
||||
const watchers: FSWatcher[] = []
|
||||
const armedRoots: string[] = []
|
||||
// Changed paths, newest write per path, for day-scoped invalidation. An event
|
||||
// that arrives without a filename, or one past the tracking bound, leaves
|
||||
// `unscopedAt` behind: from then on nothing older than it can be day-scoped.
|
||||
|
|
@ -529,6 +606,7 @@ async function startRootWatchers(): Promise<RootWatcherState | null> {
|
|||
const watcher = watch(root, { recursive: info.isDirectory() }, (_event, filename) => { note(root, filename) })
|
||||
watcher.on('error', () => { healthy = false })
|
||||
watchers.push(watcher)
|
||||
armedRoots.push(root)
|
||||
} catch {
|
||||
// stat proved this input exists, so failing to arm it invalidates the
|
||||
// global quiet predicate even when other roots remain watched.
|
||||
|
|
@ -548,6 +626,7 @@ async function startRootWatchers(): Promise<RootWatcherState | null> {
|
|||
const startedAt = Date.now()
|
||||
return {
|
||||
startedAt,
|
||||
roots: armedRoots,
|
||||
lastEventAt: () => lastEventAt,
|
||||
changedSince,
|
||||
healthy: () => healthy && !closed,
|
||||
|
|
@ -574,6 +653,11 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
// `complete: true` — so a consumer never has to infer completeness from a
|
||||
// missing field within a single source.
|
||||
process.env[SERVE_HYDRATION_ENV] = '1'
|
||||
// Shard publication is coalesced for this process only: one-shot CLI runs
|
||||
// keep writing the cache immediately. The flush below is the shutdown half
|
||||
// of that contract.
|
||||
const { setShardPublishCoalescing } = await import('./parser.js')
|
||||
setShardPublishCoalescing(true)
|
||||
// Event-driven reuse: while no watched session root has changed, a previous
|
||||
// parse stays valid past the burst window (capped in parser.ts, so a missed
|
||||
// filesystem event self-heals within minutes). This is what turns a warm
|
||||
|
|
@ -588,7 +672,7 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
const watcherSetup = startRootWatchers().then(async (w) => {
|
||||
watcherLifecycle.state = w
|
||||
if (!w) return
|
||||
const { setParseReuseValidator } = await import('./parser.js')
|
||||
const { setParseReuseValidator, setSweepWatchSource } = await import('./parser.js')
|
||||
// Clean means: the watchers were already armed when the parse happened,
|
||||
// and no filesystem event has landed since. lastEventAt of 0 is a quiet
|
||||
// system (clean for anything parsed after arming), not an unknown.
|
||||
|
|
@ -600,7 +684,11 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
}, range)
|
||||
rootReuseValidation = validate
|
||||
setParseReuseValidator(validate)
|
||||
watcherLifecycle.resetValidator = () => setParseReuseValidator(null)
|
||||
// Same watcher, finer grain: the discovery sweep reuses the listing and
|
||||
// fingerprint of every path no event has named, instead of re-reading the
|
||||
// whole corpus on each poll.
|
||||
setSweepWatchSource({ startedAt: w.startedAt, roots: w.roots, healthy: w.healthy, changedSince: w.changedSince })
|
||||
watcherLifecycle.resetValidator = () => { setParseReuseValidator(null); setSweepWatchSource(null) }
|
||||
}).catch(() => {
|
||||
watcherLifecycle.state?.close()
|
||||
watcherLifecycle.state = null
|
||||
|
|
@ -627,6 +715,19 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
const write = (value: unknown): void => { protocolWrite(JSON.stringify(value) + '\n') }
|
||||
write({ ready: true, pid: process.pid })
|
||||
|
||||
// What this resident child costs, riding along on the answers it already
|
||||
// sends. The desktop app cannot measure it: serve is a plain CLI child, so it
|
||||
// is absent from Electron's app.getAppMetrics(). The parent turns these into
|
||||
// bucket labels for its consent-gated app_close event; the numbers themselves
|
||||
// go no further than the pipe.
|
||||
let peakRss = 0
|
||||
const serveUsage = (): { cpuSec: number; rssMb: number } => {
|
||||
const rss = process.memoryUsage().rss
|
||||
if (rss > peakRss) peakRss = rss
|
||||
const cpu = process.cpuUsage()
|
||||
return { cpuSec: (cpu.user + cpu.system) / 1e6, rssMb: Math.round(peakRss / (1024 * 1024)) }
|
||||
}
|
||||
|
||||
// Strict serialization: each request chains on the previous one.
|
||||
let queue: Promise<void> = Promise.resolve()
|
||||
|
||||
|
|
@ -642,6 +743,21 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
let firstPaintSettled = false
|
||||
let fillTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
/// Pass over the heap again a minute from now, and keep passing while each
|
||||
/// one is still handing pages back. Queued, so a collection cannot land
|
||||
/// inside a request; unref'd, so it cannot hold this child open past its app.
|
||||
const scheduleSettlingCollection = (pass = 0): void => {
|
||||
if (pass >= RELEASE_SETTLE_PASSES) return
|
||||
const timer = setTimeout(() => {
|
||||
queue = queue.then(async () => {
|
||||
const before = process.memoryUsage().rss
|
||||
await collectGarbage()
|
||||
if (before - process.memoryUsage().rss >= RELEASE_SETTLE_MIN_GAIN_BYTES) scheduleSettlingCollection(pass + 1)
|
||||
})
|
||||
}, RELEASE_SETTLE_MS)
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
// The other half of the first paint: the same request, unfloored. It is an
|
||||
// ordinary parse, so what it writes to the session and daily caches is
|
||||
// exactly what a full cold parse would have written — the paint only
|
||||
|
|
@ -654,25 +770,42 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
queue = queue.then(async () => {
|
||||
const { isColdCacheOnDisk } = await import('./session-cache.js')
|
||||
// A request that landed in front of the fill may already have done the
|
||||
// full parse (only the menubar payload is ever floored).
|
||||
if (!await isColdCacheOnDisk()) return
|
||||
const { startProgressKeepalive, stopProgressKeepalive } = await import('./parser.js')
|
||||
startProgressKeepalive()
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const { output, code } = await runCaptured(buildProgram, args, beat)
|
||||
const fingerprint = await getConfigFingerprint()
|
||||
// Memoized so the poll that follows the fill answers instantly with
|
||||
// the converged payload instead of re-deriving it.
|
||||
if (code === 0 && fingerprint !== null) {
|
||||
outputMemo.set(outputMemoKey(args), createOutputMemoEntry(startedAt, Date.now(), output, fingerprint, { n: ++generationCounter, at: new Date().toISOString() }))
|
||||
// full parse (only the menubar payload is ever floored) — then there is
|
||||
// nothing left to fill, but the cold start is over just the same, so the
|
||||
// release below still runs.
|
||||
if (await isColdCacheOnDisk()) {
|
||||
const { startProgressKeepalive, stopProgressKeepalive } = await import('./parser.js')
|
||||
startProgressKeepalive()
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const { output, code } = await runCaptured(buildProgram, args, beat)
|
||||
const fingerprint = await getConfigFingerprint()
|
||||
// Memoized so the poll that follows the fill answers instantly with
|
||||
// the converged payload instead of re-deriving it.
|
||||
if (code === 0 && fingerprint !== null) {
|
||||
outputMemo.set(outputMemoKey(args), createOutputMemoEntry(startedAt, Date.now(), output, fingerprint, { n: ++generationCounter, at: new Date().toISOString() }))
|
||||
}
|
||||
} catch {
|
||||
// Best effort. A failed fill leaves the cache incomplete, which is
|
||||
// exactly the state the next cold start knows how to resume from.
|
||||
} finally {
|
||||
stopProgressKeepalive()
|
||||
}
|
||||
} catch {
|
||||
// Best effort. A failed fill leaves the cache incomplete, which is
|
||||
// exactly the state the next cold start knows how to resume from.
|
||||
} finally {
|
||||
stopProgressKeepalive()
|
||||
}
|
||||
// The cold start's whole product is on disk: the daily cache holds the
|
||||
// per-day summaries and the session cache holds the per-call detail,
|
||||
// and the answers already derived are in the output memo above. What
|
||||
// stays in memory otherwise is the detail those summaries were derived
|
||||
// FROM — an unscoped SessionCache the load memo then serves to every
|
||||
// later request, whatever range it asked for, plus the lifetime
|
||||
// ProjectSummary trees the parse memo keeps with no sweep to retire
|
||||
// them once requests stop. A poll needs neither: it re-reads the month
|
||||
// shards its own range covers. Measured on a cold start over a 170MB
|
||||
// shard set, holding them was 2198MB resident at idle against 364MB of
|
||||
// live heap — and the pages only go back with the collection the
|
||||
// release ends in.
|
||||
await releaseResidentMemos()
|
||||
scheduleSettlingCollection()
|
||||
})
|
||||
}, delayMs)
|
||||
// The app owning this child is gone once stdin closes; an unstarted fill
|
||||
|
|
@ -720,7 +853,7 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
&& Date.now() - memoHit.createdAt < OUTPUT_MEMO_CAP_MS
|
||||
&& rootReuseValidation?.(memoHit.validatedFrom) === 'clean'
|
||||
) {
|
||||
write({ id: request.id, ok: true, output: memoHit.output, generation: memoHit.generation })
|
||||
write({ id: request.id, ok: true, output: memoHit.output, generation: memoHit.generation, usage: serveUsage() })
|
||||
return
|
||||
}
|
||||
// Progressive cold start (#1110): on a cold cache the menubar payload is
|
||||
|
|
@ -734,6 +867,11 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
const { isColdCacheOnDisk } = await import('./session-cache.js')
|
||||
floor = await isColdCacheOnDisk() ? paintFrom : null
|
||||
firstPaintSettled = true
|
||||
// A warm start has no fill behind it to release after, but it has the
|
||||
// same opening burst, and V8 sits on those pages just the same: 900MB
|
||||
// resident against 356MB of live heap, with nothing further returned
|
||||
// across ten minutes of idle. Nothing is dropped here — only collected.
|
||||
if (!floor) scheduleSettlingCollection()
|
||||
}
|
||||
// Heartbeat the WHOLE request, not just its parse: the aggregation and
|
||||
// payload serialization after a parse measured ~8s of further silence, and
|
||||
|
|
@ -764,6 +902,17 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
// A partial answer is never memoized. The roots stay quiet while the
|
||||
// fill converges, so a memo hit would pin the client to the first
|
||||
// paint for the whole memo cap.
|
||||
//
|
||||
// Same invariant, stated generally: nothing DELIBERATELY DEFERRED
|
||||
// may enter this memo. A deferred answer is stale by construction
|
||||
// and the event that would retire it has already landed, so the
|
||||
// reuse check below it stays 'clean' and replays the stale payload
|
||||
// until the cap. The one deferral a served command had was the
|
||||
// status snapshot's settle window; main.ts now bypasses the whole
|
||||
// snapshot path in this process (SERVE_HYDRATION_ENV), so the only
|
||||
// remaining deferral is the cold first paint, counted right here.
|
||||
// Any future debounce must either be bypassed in serve too or
|
||||
// surface a count like `deferredFiles` for this gate.
|
||||
if (configFingerprint !== null && deferredFiles === 0) {
|
||||
outputMemo.set(memoKey, createOutputMemoEntry(parseStartedAt, Date.now(), output, configFingerprint, generation))
|
||||
}
|
||||
|
|
@ -771,7 +920,7 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
const oldest = [...outputMemo.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt)[0]
|
||||
if (oldest) outputMemo.delete(oldest[0])
|
||||
}
|
||||
write({ id: request.id, ok: true, output, generation })
|
||||
write({ id: request.id, ok: true, output, generation, usage: serveUsage() })
|
||||
if (deferredFiles > 0) scheduleBackgroundFill(request.args)
|
||||
}
|
||||
else write({ id: request.id, ok: false, error: `exit ${code}`, output })
|
||||
|
|
@ -786,18 +935,18 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
// threshold, drop the in-memory memos — the next request re-parses
|
||||
// once (seconds), which beats an ever-growing child. The child itself
|
||||
// never exits here, so the client's death counter is untouched.
|
||||
if (process.memoryUsage().rss > SERVE_MAX_RSS_BYTES) {
|
||||
const { clearSessionCache } = await import('./parser.js')
|
||||
const { clearLoadCacheMemo } = await import('./session-cache.js')
|
||||
const { clearCodexMemCaches } = await import('./codex-cache.js')
|
||||
const { clearAntigravityCacheStates } = await import('./providers/antigravity.js')
|
||||
const { clearScanFileMemo } = await import('./optimize.js')
|
||||
clearSessionCache()
|
||||
clearLoadCacheMemo()
|
||||
clearCodexMemCaches()
|
||||
clearAntigravityCacheStates()
|
||||
clearScanFileMemo()
|
||||
if (typeof globalThis.gc === 'function') globalThis.gc()
|
||||
const rss = process.memoryUsage().rss
|
||||
if (rss > peakRss) peakRss = rss
|
||||
if (rss > SERVE_MAX_RSS_BYTES) {
|
||||
// Hysteresis: only clear when RSS has grown past the last clear by a
|
||||
// margin, so a warm cache sitting above the ceiling is not dropped on
|
||||
// every request.
|
||||
if (rss > lastClearRss + SERVE_RSS_CLEAR_MARGIN_BYTES) {
|
||||
await releaseResidentMemos()
|
||||
lastClearRss = rss
|
||||
}
|
||||
} else {
|
||||
lastClearRss = 0
|
||||
}
|
||||
}).finally(() => {
|
||||
if (waitingId !== null) awaiting.delete(waitingId)
|
||||
|
|
@ -831,6 +980,16 @@ export async function runStdioServe(buildProgram: () => Command): Promise<void>
|
|||
let drainTimer: ReturnType<typeof setTimeout> | undefined
|
||||
await Promise.race([queue, new Promise<void>(resolve => { drainTimer = setTimeout(resolve, drainMs) })])
|
||||
clearTimeout(drainTimer)
|
||||
// Publish whatever the coalescing window still holds. Bounded for the same
|
||||
// reason the drain is, and non-fatal: an unpublished window costs the next
|
||||
// start a re-parse of those appends, never a wrong number.
|
||||
let flushTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const { flushPendingShardPublish } = await import('./parser.js')
|
||||
await Promise.race([
|
||||
flushPendingShardPublish().catch(() => undefined),
|
||||
new Promise<void>(resolve => { flushTimer = setTimeout(resolve, drainMs) }),
|
||||
])
|
||||
clearTimeout(flushTimer)
|
||||
// Bounded and non-fatal for the same reason the drain is: the app is gone,
|
||||
// and cleanup that hangs (watcher discovery on a stalled mount) or throws
|
||||
// must not stop this child from reaching its exit.
|
||||
|
|
|
|||
|
|
@ -74,6 +74,8 @@ export type CachedCall = {
|
|||
// depend on the `:obs:` key regex alone. Copilot still assigns the flag
|
||||
// at serve time and does not persist it.
|
||||
supplementaryAccounting?: boolean
|
||||
// Requests this one call stands for (see ParsedProviderCall.requestCount).
|
||||
requestCount?: number
|
||||
// Billing route id the provider recorded (see ParsedProviderCall).
|
||||
// Persisted so the row key survives the cache; a cached call without it is
|
||||
// a direct-door call or one parsed before the provider carried the column
|
||||
|
|
@ -428,6 +430,11 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// `billing` (`included` -> subscription, `actual` -> metered). Cached calls
|
||||
// hold none, so they must re-parse.
|
||||
hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-cost-provenance-v3-billing-route-v1-billing-mode-v1',
|
||||
// reported-cost-v1: OpenClaw's per-message `usage.cost.total` is now
|
||||
// preserved through the cache via `costFromBilling`. This is OpenClaw's
|
||||
// first parse version; adding it moves the provider's env fingerprint,
|
||||
// which is what forces the one re-parse that lands the reported dollars.
|
||||
openclaw: 'reported-cost-v1',
|
||||
'lingtai-tui': 'token-ledger-registry-activity-v3',
|
||||
'ibm-bob': 'worktree-project-grouping-v1',
|
||||
// project-path-v1: the parser now records the session's full working
|
||||
|
|
@ -454,7 +461,12 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// projectPath/workingDirectory instead of basename-only identity.
|
||||
// project-group-by-abs-v1 (#1260): parseProviderSources groups by abs
|
||||
// projectPath/workingDirectory so same-basename distinct roots stay apart.
|
||||
pi: 'cwd-project-path-v1-project-group-by-abs-v1',
|
||||
// reported-cost-v1: Pi writes a per-message `usage.cost.total`, which is now
|
||||
// preserved through the cache via `costFromBilling` instead of being
|
||||
// re-priced from tokens on every read. (omp, the same parser, has carried
|
||||
// reported costs since reported-cost-v2 below.) Cached calls hold
|
||||
// costUSD: undefined, so they must re-parse once.
|
||||
pi: 'cwd-project-path-v1-project-group-by-abs-v1-reported-cost-v1',
|
||||
// project-group-by-abs-v1: shared Pi/OMP serve grouping uses abs identity.
|
||||
omp: 'nested-agent-v1-reported-cost-v2-cwd-project-path-v1-project-group-by-abs-v1',
|
||||
// archived-subtree-v1 (#1362): the subtree walk no longer filters
|
||||
|
|
@ -482,7 +494,13 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// billing-routes-v2: its warm cache must move with both shared route fields.
|
||||
'kilo-code': 'worktree-project-grouping-v1-session-model-v1-archived-subtree-v1-billing-routes-v2',
|
||||
'roo-code': 'worktree-project-grouping-v1',
|
||||
warp: 'worktree-project-grouping-v1-est-cost',
|
||||
// billing-cost-v1: Warp's own billing record (total_provider_cost_in_cents,
|
||||
// total_charged_usage, credits_spent) now rides on each call as
|
||||
// `costFromBilling` and is preserved by providerCallToCachedCall. Entries
|
||||
// cached before this hold costUSD: undefined and are re-priced from the
|
||||
// token floor on every read, so they must re-parse once for the real dollars
|
||||
// to land.
|
||||
warp: 'worktree-project-grouping-v1-est-cost-billing-cost-v1',
|
||||
antigravity: 'worktree-project-grouping-v6',
|
||||
}
|
||||
|
||||
|
|
@ -626,6 +644,17 @@ export function isCacheDirty(cache: SessionCache): boolean {
|
|||
return stateOf(cache).dirty
|
||||
}
|
||||
|
||||
/** True when a dirty bucket belongs to a provider whose cache entry is the ONLY
|
||||
* surviving record of that spend (see {@link DURABLE_PROVIDER_NAMES}): the
|
||||
* source can be pruned before the next publish, so such a window must never be
|
||||
* held back by the resident process's coalescing. */
|
||||
export function hasDirtyDurableProvider(cache: SessionCache): boolean {
|
||||
for (const provider of stateOf(cache).dirtyBuckets.keys()) {
|
||||
if (DURABLE_PROVIDER_NAMES.has(provider)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ── Env Fingerprint ────────────────────────────────────────────────────
|
||||
|
||||
export function computeEnvFingerprint(provider: string): string {
|
||||
|
|
@ -809,6 +838,7 @@ function validateCall(c: unknown): c is CachedCall {
|
|||
&& isOptionalNum(o['toolErrors'])
|
||||
&& isOptionalNum(o['editFailed'])
|
||||
&& isOptionalBool(o['supplementaryAccounting'])
|
||||
&& isOptionalNum(o['requestCount'])
|
||||
&& isOptionalString(o['route'])
|
||||
&& (o['billing'] === undefined || parseBillingMode(o['billing'] as string) !== undefined)
|
||||
&& validateUsage(o['usage'])
|
||||
|
|
@ -972,6 +1002,17 @@ export function clearLoadCacheMemo(): void {
|
|||
clearShardMemo()
|
||||
}
|
||||
|
||||
/// Is this in-memory cache still the one the published envelope describes? A
|
||||
/// holder that deferred its publish (see the coalescing window in parser.ts)
|
||||
/// asks before writing: if another process has published since, this object is
|
||||
/// a stale pre-image and saving it could drop that process's entries. Dropping
|
||||
/// the deferred write instead costs a re-parse, never a wrong number.
|
||||
export async function isCacheCurrent(cache: SessionCache): Promise<boolean> {
|
||||
if (!cacheMemo || cacheMemo.cache !== cache) return false
|
||||
const live = await readEnvelope(cacheMemo.dir)
|
||||
return live?.nonce === cacheMemo.nonce
|
||||
}
|
||||
|
||||
/** Months (UTC `YYYY-MM`, inclusive) a query can possibly report on. The load
|
||||
* widens this by one month BELOW `fromMonth` and none above (see
|
||||
* shardInScope): every cross-range carry in the report reads BACKWARDS from the
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { spendProjectIdentity } from './spend-flow.js'
|
||||
import type { ProjectSummary, SessionSummary } from './types.js'
|
||||
|
|
@ -118,7 +118,7 @@ export function buildSessionContributions(session: SessionSummary): SessionContr
|
|||
const savings = call.savingsUSD ?? 0
|
||||
const inputTokens = call.usage.inputTokens
|
||||
const outputTokens = callBillableOutputTokens(call)
|
||||
const calls = isBehavioralCall(call) ? 1 : 0
|
||||
const calls = behavioralCallWeight(call)
|
||||
if (cost === 0 && calls === 0 && savings === 0 && inputTokens === 0 && outputTokens === 0) continue
|
||||
const day = Number.isNaN(new Date(call.timestamp).getTime()) ? turnDay : dateKey(call.timestamp)
|
||||
const key = modelKeyFor(call)
|
||||
|
|
|
|||
|
|
@ -357,6 +357,10 @@ export function registerSyncCommands(program: Command): void {
|
|||
process.exit(1)
|
||||
}
|
||||
const { range } = getDateRange(period)
|
||||
// No provider scope, so parseAllSessions applies the shared
|
||||
// aggregate-only rule: gateway daily aggregates are not pushed unless
|
||||
// the user opted in. The backend would double count them exactly the
|
||||
// way a local headline would. Payload schema is unchanged either way.
|
||||
const projects = (await parseAllSessions(range))
|
||||
.map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) }))
|
||||
|
||||
|
|
@ -844,6 +848,10 @@ export function registerSyncCommands(program: Command): void {
|
|||
const { getDateRange } = await import('../cli-date.js')
|
||||
|
||||
const range = getDateRange('week').range
|
||||
// No provider scope, so parseAllSessions applies the shared
|
||||
// aggregate-only rule: gateway daily aggregates are not pushed unless
|
||||
// the user opted in. The backend would double count them exactly the
|
||||
// way a local headline would. Payload schema is unchanged either way.
|
||||
const projects = (await parseAllSessions(range))
|
||||
.map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) }))
|
||||
|
||||
|
|
|
|||
|
|
@ -165,6 +165,9 @@ export type ParsedApiCall = {
|
|||
/// model-call / turn counts. Hermes deltas persist the flag on CachedCall;
|
||||
/// Copilot remains serve-time / never cached.
|
||||
supplementaryAccounting?: boolean
|
||||
/// Requests this one call stands for (see ParsedProviderCall.requestCount).
|
||||
/// Absent means 1. Read through `behavioralCallWeight`, never directly.
|
||||
requestCount?: number
|
||||
/// Copilot session-store `total_nano_aiu`. 1e9 nano-AIU = 1 credit = $0.01.
|
||||
/// Threaded from CachedCall / ParsedProviderCall so plan math can sum credits.
|
||||
/// Absent on older stores and on JSONL / shutdown-rollup siblings.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { homedir } from 'node:os'
|
||||
import { CATEGORY_LABELS, type ProjectSummary, type SessionSummary, type TaskCategory, type DateRange } from './types.js'
|
||||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { type PeriodData, type ProviderCost, type BreakdownArrays, type MenubarPayload, type ClaudeConfigSelector, type HydrationState, buildMenubarPayload } from './menubar-json.js'
|
||||
import { type SessionCountBasis } from './session-count-label.js'
|
||||
import { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, makeProjectFilter, type ProjectFilterTarget, sessionHydrationSnapshot } from './parser.js'
|
||||
|
|
@ -25,6 +25,7 @@ import { activityStreak } from './streak.js'
|
|||
import { getDaysInRange, ensureCacheHydrated, loadDailyCache, cachedProjectIdentities, emptyCache, mergeDayEntries, BACKFILL_DAYS, toDateString, type DailyCache, type DailyEntry, type ProjectDayStats, type ProviderDaySlice } from './daily-cache.js'
|
||||
import { buildGranularHistory } from './granular-history.js'
|
||||
import { spendProjectIdentity } from './spend-flow.js'
|
||||
import { AGGREGATE_ONLY_PROVIDER, excludeAggregateOnlyProjects, excludesAggregateOnlyProviders } from './parser.js'
|
||||
|
||||
// Row caps for the by-PR / by-branch payload aggregations, ranked by cost.
|
||||
const TOP_BRANCHES = 15
|
||||
|
|
@ -224,7 +225,10 @@ export function getDailyCacheConfigHash(): string {
|
|||
async function hydrateCache(): Promise<DailyCache> {
|
||||
try {
|
||||
return await ensureCacheHydrated(
|
||||
(range) => parseAllSessions(range, 'all'),
|
||||
// The cache writer seals whole days, gateway slice included: a past
|
||||
// day's aggregate row can never be fetched again, so the opt-in has to
|
||||
// work retroactively off what was stored.
|
||||
(range) => parseAllSessions(range, 'all', { includeAggregateOnly: true }),
|
||||
aggregateProjectsIntoDays,
|
||||
getDailyCacheConfigHash(),
|
||||
// Never finalize the daily history off a partial (interrupted) session
|
||||
|
|
@ -433,6 +437,125 @@ function sliceDayToProvider(day: DailyEntry, provider: string): DailyEntry {
|
|||
}
|
||||
}
|
||||
|
||||
/// Same rule as the parse-level corpus filter (see AGGREGATE_ONLY_PROVIDER in
|
||||
/// parser.ts), applied to day entries. The parse filter cannot be used on the
|
||||
/// paths below: they derive the day entries the daily cache seals, which must
|
||||
/// keep the gateway slice — it can never be re-fetched for a past day — so the
|
||||
/// provider is held out of the day's TOTALS here while its slice survives.
|
||||
export const excludesGatewayFromTotals = excludesAggregateOnlyProviders
|
||||
|
||||
/// The complement of `sliceDayToProvider`: the day with one provider's slice
|
||||
/// subtracted out of every day-level rollup buildPeriodDataFromDays reads,
|
||||
/// while the slice itself stays under `day.providers` so the provider still
|
||||
/// reports its own (clearly labelled) total.
|
||||
///
|
||||
/// Read-side only. The daily cache seals the whole day including the gateway
|
||||
/// slice, so flipping `includeGatewayInTotals` re-includes sealed days with no
|
||||
/// re-fetch — which matters because a gateway row cannot be re-derived from
|
||||
/// anything on disk.
|
||||
export function excludeProviderFromDay(day: DailyEntry, provider: string): DailyEntry {
|
||||
const s = Object.hasOwn(day.providers, provider) ? day.providers[provider] : undefined
|
||||
if (!s) return day
|
||||
// Clamped: a slice adopted from a cache generation that recorded more than
|
||||
// the day-level field can account for must leave a zero, never a negative
|
||||
// headline.
|
||||
const sub = (total: number, part: number | undefined): number => Math.max(0, total - (part ?? 0))
|
||||
|
||||
const models: DailyEntry['models'] = {}
|
||||
for (const [key, m] of Object.entries(day.models)) {
|
||||
const mine = s.models?.[key]
|
||||
const left = {
|
||||
calls: sub(m.calls, mine?.calls),
|
||||
cost: sub(m.cost, mine?.cost),
|
||||
savingsUSD: sub(m.savingsUSD ?? 0, mine?.savingsUSD),
|
||||
inputTokens: sub(m.inputTokens, mine?.inputTokens),
|
||||
outputTokens: sub(m.outputTokens, mine?.outputTokens),
|
||||
cacheReadTokens: sub(m.cacheReadTokens, mine?.cacheReadTokens),
|
||||
cacheWriteTokens: sub(m.cacheWriteTokens, mine?.cacheWriteTokens),
|
||||
}
|
||||
// A model id the gateway shares with a locally-parsed provider keeps its
|
||||
// remainder; one only the gateway saw drops out of the row list entirely.
|
||||
if (Object.values(left).some(v => v > 0)) models[key] = left
|
||||
}
|
||||
|
||||
// The provider's own synthetic project ("Vercel AI Gateway") must leave the
|
||||
// day's project split too, or `buildPayloadProjects` and the JSON
|
||||
// `projects[]` would list spend the headline beside them does not count.
|
||||
const projects: DailyEntry['projects'] = day.projects ? {} : undefined
|
||||
if (day.projects && projects) {
|
||||
for (const [key, p] of Object.entries(day.projects)) {
|
||||
const mine = s.projects?.[key]
|
||||
const left = {
|
||||
cost: sub(p.cost, mine?.cost),
|
||||
calls: sub(p.calls, mine?.calls),
|
||||
savingsUSD: sub(p.savingsUSD ?? 0, mine?.savingsUSD),
|
||||
sessions: sub(p.sessions ?? 0, mine?.sessions),
|
||||
}
|
||||
if (Object.values(left).some(v => v > 0)) {
|
||||
Object.defineProperty(projects, key, {
|
||||
value: { ...left, ...(p.path ? { path: p.path } : {}) },
|
||||
enumerable: true, writable: true, configurable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const categories: DailyEntry['categories'] = {}
|
||||
for (const [key, c] of Object.entries(day.categories)) {
|
||||
const mine = s.categories?.[key]
|
||||
const left = {
|
||||
turns: sub(c.turns, mine?.turns),
|
||||
cost: sub(c.cost, mine?.cost),
|
||||
savingsUSD: sub(c.savingsUSD ?? 0, mine?.savingsUSD),
|
||||
editTurns: sub(c.editTurns, mine?.editTurns),
|
||||
oneShotTurns: sub(c.oneShotTurns, mine?.oneShotTurns),
|
||||
}
|
||||
if (Object.values(left).some(v => v > 0)) categories[key] = left
|
||||
}
|
||||
|
||||
return {
|
||||
...day,
|
||||
cost: sub(day.cost, s.cost),
|
||||
savingsUSD: sub(day.savingsUSD, s.savingsUSD),
|
||||
calls: sub(day.calls, s.calls),
|
||||
sessions: sub(day.sessions, s.sessions),
|
||||
inputTokens: sub(day.inputTokens, s.inputTokens),
|
||||
outputTokens: sub(day.outputTokens, s.outputTokens),
|
||||
cacheReadTokens: sub(day.cacheReadTokens, s.cacheReadTokens),
|
||||
cacheWriteTokens: sub(day.cacheWriteTokens, s.cacheWriteTokens),
|
||||
editTurns: sub(day.editTurns, s.editTurns),
|
||||
oneShotTurns: sub(day.oneShotTurns, s.oneShotTurns),
|
||||
models,
|
||||
categories,
|
||||
...(projects ? { projects } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/// `days` read for totals, with the aggregate-only provider held out when the
|
||||
/// scope and the opt-in say so. The provider slices survive untouched, so the
|
||||
/// provider list built from the same day set still reports the full amount.
|
||||
export function excludeGatewayFromDays(days: DailyEntry[], providerFilter: string): DailyEntry[] {
|
||||
if (!excludesGatewayFromTotals(providerFilter)) return days
|
||||
return days.map(day => excludeProviderFromDay(day, AGGREGATE_ONLY_PROVIDER))
|
||||
}
|
||||
|
||||
/// What the caller's day set is NOT counting, so every surface can show the
|
||||
/// gateway once, clearly labelled. All zero whenever nothing is excluded.
|
||||
export type ExcludedGatewayTotals = { costUSD: number; calls: number; tokens: number }
|
||||
|
||||
export function excludedGatewayTotals(days: DailyEntry[], providerFilter: string): ExcludedGatewayTotals {
|
||||
const totals: ExcludedGatewayTotals = { costUSD: 0, calls: 0, tokens: 0 }
|
||||
if (!excludesGatewayFromTotals(providerFilter)) return totals
|
||||
for (const day of days) {
|
||||
const s = Object.hasOwn(day.providers, AGGREGATE_ONLY_PROVIDER) ? day.providers[AGGREGATE_ONLY_PROVIDER] : undefined
|
||||
if (!s) continue
|
||||
totals.costUSD += s.cost
|
||||
totals.calls += s.calls
|
||||
totals.tokens += (s.inputTokens ?? 0) + (s.outputTokens ?? 0) + (s.cacheReadTokens ?? 0) + (s.cacheWriteTokens ?? 0)
|
||||
}
|
||||
return totals
|
||||
}
|
||||
|
||||
/// Overlay surviving provider-scoped source data onto the durable all-provider
|
||||
/// cache without touching unrelated providers. The result is provider-sliced so
|
||||
/// headline and history consumers cannot accidentally count unrelated providers.
|
||||
|
|
@ -617,6 +740,7 @@ export type IndexedDurableOverview = {
|
|||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
carriedCostUSD: number
|
||||
excludedGateway: ExcludedGatewayTotals
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -636,7 +760,10 @@ export function buildDurableOverviewFromNormalizedIndex(
|
|||
const hasProjectFilter = (opts.project?.length ?? 0) > 0 || (opts.exclude?.length ?? 0) > 0
|
||||
const matchesFilter = makeProjectFilter(opts.project, opts.exclude)
|
||||
const filteredProjects = filterProjectsByName(normalizedProjects, opts.project ?? [], opts.exclude ?? [])
|
||||
const scanProjects = filterProjectsByDateRange(filteredProjects, periodInfo.range)
|
||||
// Detail/enrichment population only: same exclusion as the headline below,
|
||||
// while `normalizedDays` keeps the whole corpus so the day entries (and the
|
||||
// durable cache they fill) still carry the gateway slice.
|
||||
const scanProjects = excludeAggregateOnlyProjects(filterProjectsByDateRange(filteredProjects, periodInfo.range), pf)
|
||||
const now = new Date()
|
||||
const todayStr = toDateString(now)
|
||||
const normalizedDays = aggregateProjectsIntoDays(filteredProjects)
|
||||
|
|
@ -671,7 +798,7 @@ export function buildDurableOverviewFromNormalizedIndex(
|
|||
: []
|
||||
const allDays = [...cachedAllDays, ...normalizedHistoricalDays].sort((a, b) => a.date.localeCompare(b.date))
|
||||
const normalizedByDate = new Map(normalizedDays.map(day => [day.date, day]))
|
||||
const days = pf === 'all' ? allDays : allDays.map(day => {
|
||||
const days = excludeGatewayFromDays(pf === 'all' ? allDays : allDays.map(day => {
|
||||
if (Object.hasOwn(day.providers, pf)) return sliceDayToProvider(day, pf)
|
||||
const normalized = normalizedByDate.get(day.date)
|
||||
// The shared cache can be complete for a date while lacking this selected
|
||||
|
|
@ -683,7 +810,7 @@ export function buildDurableOverviewFromNormalizedIndex(
|
|||
return normalized && Object.hasOwn(normalized.providers, pf)
|
||||
? sliceDayToProvider(normalized, pf)
|
||||
: sliceDayToProvider(day, pf)
|
||||
})
|
||||
}), pf)
|
||||
const data = buildPeriodDataFromDays(days, periodInfo.label)
|
||||
|
||||
// Fields whose durable day rows cannot project under a project filter come
|
||||
|
|
@ -710,6 +837,7 @@ export function buildDurableOverviewFromNormalizedIndex(
|
|||
cacheReadTokens: data.cacheReadTokens,
|
||||
cacheWriteTokens: data.cacheWriteTokens,
|
||||
carriedCostUSD: days.reduce((sum, day) => sum + (day.carried ? day.cost : 0), 0),
|
||||
excludedGateway: excludedGatewayTotals(days, pf),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -741,6 +869,11 @@ export type DurablePeriod = {
|
|||
/// project filter is active. Reported so a filtered total that is short of the
|
||||
/// unfiltered one says so instead of just looking wrong.
|
||||
unattributedCostUSD: number
|
||||
/// What `data` deliberately does NOT count (see `excludeProviderFromDay`).
|
||||
/// All zero under `--provider vercel-gateway` or with
|
||||
/// `includeGatewayInTotals` on, so a surface renders the labelled row
|
||||
/// whenever `costUSD` is non-zero.
|
||||
excludedGateway: ExcludedGatewayTotals
|
||||
/// Fresh per-period parse (provider + name filtered) for detail views that
|
||||
/// still need surviving session files.
|
||||
liveProjects: ProjectSummary[]
|
||||
|
|
@ -796,12 +929,12 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
let scanRange: DateRange
|
||||
if (pf === 'all') {
|
||||
if (isTodayOnly) {
|
||||
const raw = fp(await parseAllSessions(todayRange, 'all'))
|
||||
const raw = fp(await parseAllSessions(todayRange, 'all', { includeAggregateOnly: true }))
|
||||
liveProjects = raw
|
||||
scanRange = todayRange
|
||||
todayAllDays = aggregateProjectsIntoDays(raw).filter(d => d.date === todayStr)
|
||||
} else {
|
||||
const raw = fp(await parseAllSessions(periodInfo.range, 'all'))
|
||||
const raw = fp(await parseAllSessions(periodInfo.range, 'all', { includeAggregateOnly: true }))
|
||||
liveProjects = daysSelection ? filterProjectsByDays(raw, daysSelection.days) : raw
|
||||
scanRange = periodInfo.range
|
||||
// A period that reaches today contains today's turns already, so derive the
|
||||
|
|
@ -813,7 +946,7 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
// JSON daily turn count while the per-call cost/calls still bucket to today.
|
||||
todayAllDays = rangeEndStr >= todayStr
|
||||
? aggregateProjectsIntoDays(filterProjectsByDays(raw, new Set([todayStr]))).filter(d => d.date === todayStr)
|
||||
: aggregateProjectsIntoDays(fp(await parseAllSessions(todayRange, 'all'))).filter(d => d.date === todayStr)
|
||||
: aggregateProjectsIntoDays(fp(await parseAllSessions(todayRange, 'all', { includeAggregateOnly: true }))).filter(d => d.date === todayStr)
|
||||
}
|
||||
} else {
|
||||
// Provider-filtered: one provider-scoped parse feeds both today's union
|
||||
|
|
@ -858,15 +991,24 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
// the union takes it from `todayAllDays`, which re-anchors a turn straddling
|
||||
// midnight (see the todayAllDays note above) and must stay the today source.
|
||||
const liveHistoricalDays = aggregateProjectsIntoDays(liveProjects).filter(d => d.date < todayStr)
|
||||
// Day derivation above needed the whole corpus (the cache seals the gateway
|
||||
// slice). Everything downstream of here is a DETAIL view of the same period
|
||||
// the headline reports, so it drops the aggregate-only provider under the
|
||||
// same rule — otherwise By Project / By Model / By Activity / topProjects /
|
||||
// the JSON `projects[]` would over-report beside an excluded headline.
|
||||
liveProjects = excludeAggregateOnlyProjects(liveProjects, pf)
|
||||
const allDays = unionDaysForPeriod(cache, todayAllDays, periodInfo, daysSelection?.days ?? null, sliceHistorical, liveHistoricalDays)
|
||||
const freshDaysInSelection = freshProviderDays.filter(day =>
|
||||
day.date >= rangeStartStr
|
||||
&& day.date <= rangeEndStr
|
||||
&& (!daysSelection || daysSelection.days.has(day.date)),
|
||||
)
|
||||
const days = pf === 'all'
|
||||
? allDays
|
||||
: overlayProviderDaySlices(allDays, freshDaysInSelection, pf)
|
||||
// Slices stay on the day (the provider list below reads them); only the
|
||||
// day-level rollups the headline is built from drop the gateway.
|
||||
const days = excludeGatewayFromDays(
|
||||
pf === 'all' ? allDays : overlayProviderDaySlices(allDays, freshDaysInSelection, pf),
|
||||
pf,
|
||||
)
|
||||
const data = buildPeriodDataFromDays(days, periodInfo.label)
|
||||
|
||||
// Enrich the cache-authoritative headline with fields DailyEntry cannot carry.
|
||||
|
|
@ -924,7 +1066,10 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
.map(period => [period, getDateRange(period)] as const)
|
||||
.filter(([, info]) => toDateString(info.range.start) >= scanStartStr)
|
||||
.map(([period, info]) => {
|
||||
const windowDays = unionDaysForPeriod(cache, todayAllDays, info, null, undefined, liveHistoricalDays)
|
||||
const windowDays = excludeGatewayFromDays(
|
||||
unionDaysForPeriod(cache, todayAllDays, info, null, undefined, liveHistoricalDays),
|
||||
pf,
|
||||
)
|
||||
const windowData = buildPeriodDataFromDays(windowDays, info.label)
|
||||
return [period, {
|
||||
cost: windowData.cost,
|
||||
|
|
@ -936,7 +1081,7 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
}]
|
||||
})) as PeriodTotals
|
||||
: undefined
|
||||
return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, knownProjects, cache, todayAllDays, scanRange, periodTotals }
|
||||
return { data, days, carriedCostUSD, unattributedCostUSD, excludedGateway: excludedGatewayTotals(days, pf), liveProjects, knownProjects, cache, todayAllDays, scanRange, periodTotals }
|
||||
}
|
||||
|
||||
type PayloadProject = NonNullable<PeriodData['projects']>[number]
|
||||
|
|
@ -1438,7 +1583,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
|
|||
|
||||
const getTodayAllProjects = async (): Promise<ProjectSummary[]> => {
|
||||
if (!todayAllProjects) {
|
||||
todayAllProjects = fp(await parseAllSessions(todayRange, 'all'))
|
||||
todayAllProjects = fp(await parseAllSessions(todayRange, 'all', { includeAggregateOnly: true }))
|
||||
}
|
||||
return todayAllProjects
|
||||
}
|
||||
|
|
@ -1559,8 +1704,16 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
|
|||
for (const d of allDaysForProviders) {
|
||||
for (const [name, p] of Object.entries(d.providers)) addProviderSlice(providerTotals, name, p)
|
||||
}
|
||||
// The gateway slice is still on every day (only the day-level rollups drop
|
||||
// it), so its row carries the full amount and says it is not in the total.
|
||||
const gatewayExcluded = excludesGatewayFromTotals(pf)
|
||||
for (const [name, total] of Object.entries(providerTotals)) {
|
||||
providers.push({ name, displayName: displayNameByName.get(name) ?? name, ...total })
|
||||
providers.push({
|
||||
name,
|
||||
displayName: displayNameByName.get(name) ?? name,
|
||||
...total,
|
||||
...(gatewayExcluded && name === AGGREGATE_ONLY_PROVIDER ? { excludedFromTotal: true as const } : {}),
|
||||
})
|
||||
}
|
||||
for (const p of allProviders) {
|
||||
if (providers.some(pc => pc.name === p.name)) continue
|
||||
|
|
@ -1630,7 +1783,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
|
|||
dailyHistory = dailyEntriesToHistory(aggregateProjectsIntoDays(historyProjects))
|
||||
} else if (isAllProviders) {
|
||||
const todayDays = (await getTodayAllDays()).filter(d => d.date === todayStr)
|
||||
const fullHistory = [...allCacheDays, ...todayDays]
|
||||
const fullHistory = excludeGatewayFromDays([...allCacheDays, ...todayDays], pf)
|
||||
dailyHistory = dailyEntriesToHistory(fullHistory)
|
||||
} else {
|
||||
const freshHistory = [...aggregateProjectsIntoDays(scanProjects), ...(todayAllDays ?? [])]
|
||||
|
|
@ -1816,7 +1969,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts:
|
|||
// request counts: a supplementary accounting call (copilot rollup /
|
||||
// paired store row) can carry configured model-savings too and must
|
||||
// not count as a request.
|
||||
const callWeight = isBehavioralCall(call) ? 1 : 0
|
||||
const callWeight = behavioralCallWeight(call)
|
||||
totalSavings += call.savingsUSD
|
||||
totalSavingsCalls += callWeight
|
||||
const modelKey = modelRowKey(call.model, call.route)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue