diff --git a/CHANGELOG.md b/CHANGELOG.md index 69d36c94..1e8d75b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Copilot AI Credit plans.** `codeburn plan set copilot-pro` (1,500 credits / $15 equivalent, not the $10 sticker), `copilot-pro-plus` (7,000), `copilot-max` (20,000), and `custom --credits N --provider copilot`. Spend is `sum(finite nanoAiu) / 1e9`. Token-priced `costUSD` does not fill the credits bar. Claude / cursor / grok / custom-USD plans stay on `costUSD`. (#943) - **`codeburn models --unpriced`.** The dashboard warns about models that price at $0 and points at `codeburn model-alias`, but the list itself was hard to get out of the TUI. This filters the plain-stdout `models` report to exactly those rows, reusing `findUnpricedModels` so local, free, aliased and price-overridden models are treated the same way the warning treats them, and defaulting that mode's min-cost to 0 so $0 rows are not pre-filtered away. Thanks @kocaemre. (#969) - **`optimize` spots the same long block pasted at the start of many sessions.** The new `recurring-context` detector groups sessions by their opening block — normalized for whitespace and ANSI, hashed over the first 2 KB — and reports a block of at least 1.5 KB that opens 5 or more sessions, with the top three by tokens, their session counts and the project each is confined to. It is a habit, not an apply-able fix: CodeBurn will not move your own text into `CLAUDE.md` for you, so the finding asks Claude to give the block a permanent home (a `CLAUDE.md` rule, or a file read on demand) and hand back a one-line pointer to open sessions with instead. Savings count the repeats only, never the first paste, and are marked `estimated`: provider usage is counted per API call, where the pasted block is mixed in with the system prompt, tool schemas and `CLAUDE.md`, so the block is sized from its own bytes. Injected system reminders and slash-command wrappers are not pastes and are skipped, and neither is a prompt a program wrote — an SDK session or a subagent task — read from the entry's flags, which survive the parser's large-line path. The opening block comes from the session scan that already runs, so nothing extra is read from disk. - **Applied fixes get re-measured on every `optimize` run, and told plainly whether they worked.** After `codeburn optimize --apply`, every still-applied fix comes back in an `Applied fixes` section on subsequent `codeburn optimize` runs, carrying the verdict `act report` already computes from the same reconciliation: `worked` (at least 70% of its window-scaled estimate realized), `partial` (something, but under that), `no-effect` (no measured reduction, printed with the exact `codeburn act undo ` that puts it back), or `measuring` for anything younger than the 3-day measurement window. The numbers are measured — provider-counted usage over the post-apply window — not re-estimated. `--apply` now says when the re-measure will happen, `--format json` gains `appliedFixes[]` (add-only), and the same section appears in the dashboard TUI and the desktop app. New `codeburn optimize --auto-revert` undoes the fixes that measured no reduction at all through the same code path as `codeburn act undo`; it never touches `partial` or still-measuring fixes, and never auto-reverts a `CLAUDE.md` rule (it prints the undo command instead), matching the `--yes` guardrail. @@ -10,6 +11,9 @@ - **`CODEBURN_CACHE_SCOPE=all` forces a full session-cache read.** A ranged query reads only the month shards that can contribute a turn to it, which is a real behaviour change on a warm cache; this is the escape hatch for the case where a number looks wrong and you want to know whether the scoped read is why. Set it and every load ignores its scope and reads every shard, one-shot runs and the resident `codeburn serve` alike. It is a read policy, not an input to any cache fingerprint: setting or unsetting it re-parses nothing and invalidates nothing. +### Added (OrcaRouter) +- **OrcaRouter sessions now price and label like the model they route to.** OrcaRouter is a gateway that exposes route ids (`orcarouter/auto`, `orcarouter/fusion`, …) plus plain upstream ids (`deepseek/deepseek-v4-pro`), and reports the upstream id that actually ran in the completion response's `model` field. The `orcarouter/` prefix is now a routing wrapper like `cmd/` / `antigravity/`, so a routed spelling prices at its upstream LiteLLM row instead of $0; `orcarouter/auto` stays unpriced (the smart route lands on a Qwen/Llama flash model — a Sonnet alias would overprice it) and the fusion routes alias to their current `openai/gpt-oss-120b` target (live completion `model` field, 2026-08); and an unknown vendor nested inside the route still fails closed. Daily cache v29 so warm days re-derive the new prices. + ### Added (Windows) - **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls. - **A menubar app for Windows.** `windows/` is a Tauri 2 tray app — Rust binary, React popover — that puts today's spend in the notification area and mirrors the macOS menubar screen for screen: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, CSV/JSON export, launch at login, currency, and theme. Windows has no menubar title, so the number lives in a second tray icon rendered from the system font at the panel's native icon size (Settings can turn it off; the tooltip always carries it). It reads everything through the CLI like the macOS and GNOME clients do, and gates on **codeburn 0.9.9 or newer** — the first release accepting `status --format menubar-json --no-optimize` — showing a setup screen with the install command until it finds one. Refresh follows popover visibility the way the macOS app does: 60 s with optimize findings while open, 2 minutes for today's total while closed, and immediately on open when what you are looking at has gone stale. The Claude quota view never spends Claude's single-use refresh token; on a 401 it re-reads Claude Code's own credential file for a token it has already rotated, matching the macOS client. Ships as an unsigned `.msi` from the `windows-v*` tag, which `codeburn menubar` now installs for you. The same crate still builds and runs a tray on Linux, but that stays experimental and unreleased — `gnome/` is the supported Linux surface. @@ -23,7 +27,7 @@ - **The desktop app's cold start paints as soon as the selected period is readable, instead of after the whole history.** The resident `codeburn serve` child now does for its JSON clients what the TUI got in #1107: on a cold cache it answers the first `status --format menubar-json` from the files whose mtime allows them to hold data the requested period can show (the same floor and 48h clock-skew margin), then indexes the rest behind the answer. The payload says so in-band through a new optional `hydration: { complete, indexedFiles, totalFiles }` block, and the desktop app and web dashboard render `indexing history · N/M files · totals below cover what is indexed so far` until it reports `complete: true`. On a 21k-file corpus the app's first payload lands in 7.3s instead of 31.3s, fully indexed at 36.2s. Only the resident serve process ever emits `hydration`, and only it may answer partially — its clients poll, so they converge. Every one-shot output is unchanged and always a full parse: `--format json`/`csv`/`markdown`, `report`, `sessions`, `models`, MCP, the Swift menubar and GNOME clients, and the desktop app's own spawn fallback, none of which have a second poll to converge with. Absence of `hydration` therefore always means complete, which is also what an older CLI's payload means. It is not `stale` (#1100) and never sets it: a first paint is fresh but partial, where a stale payload is complete but old. Nothing is stamped complete until the fill has actually parsed everything, so a process killed mid-fill comes back cold and finishes the job. (#1110) - **The discovery sweep issues its metadata syscalls concurrently.** Every dated command re-walks and re-stats every provider tree before it can decide what is already cached, and that sweep was strictly serial: one `readdir`, one `stat`, one `state.json` read at a time, per provider, one provider after another. On a 21k-file / 9-provider corpus it owned most of a warm run's wall clock while the machine sat idle waiting on the kernel. Provider discovery now runs across providers at once, and the four walks that dominate it (claude, codex, kimicode, grok) plus the Claude project-dir walk and both fingerprint passes fan out through a shared bounded-concurrency helper. Order is unchanged everywhere — each level is re-concatenated in registry/`readdir` order before anything reconciles against the cache — so what is discovered, in what sequence, is byte-identical to the serial walk. Two smaller cuts ride along: the Claude walk reads directory entries with their types so a plain file no longer costs a wasted `subagents/` probe, and the Codex result cache (a single file that can reach hundreds of MB) now shares one in-flight load between concurrent readers instead of letting each one re-read and re-parse it. Warm `codeburn today` on that corpus: 5.30s to 2.99s; a cold parse 34.7s to 31.1s. (#1104) - **A kill mid-way through a non-Claude provider phase no longer restarts that whole phase.** `scanProjectDirs` (Claude) has long taken a throttled `saveProgress` callback so a killed cold parse resumes from a warm cache; `parseProviderSources` (every other provider — codex, cursor, gemini, and the rest) did not, and only persisted at the whole-provider boundary. On a large single-provider corpus (a multi-GB codex history is the common case) an app-timeout SIGKILL, crash, or force-quit during that phase discarded everything parsed since the last provider finished, forcing the entire phase to re-parse from zero on the next run. `parseProviderSources` now takes the same callback, invoked once per source right after that source's cache entry lands (mirroring `scanProjectDirs`' placement, outside the per-file try/catch), on the same file-count/wall-clock throttle. A file only ever gets a fingerprint once it has fully parsed, so a mid-file kill can never leave a half-parsed file's entry looking complete on resume. -- **Routed model ids price as the model they wrap, and an unknown vendor prefix no longer prices by blind stripping.** Token-plan and gateway spellings of the same model (`omniroute:`, `cp/`, `cline-pass/`, `cline-free/`, `cmd/`, `antigravity/`) are peeled and the remaining id is priced, so a Cline Pass or OmniRoute session shows a `~` estimate instead of $0. In exchange, `provider/model` is no longer treated as authority on its own: the leading segment is stripped only when it is a namespace the bundled pricing catalog itself uses (`anthropic/`, `openai/`, `google/`, `x-ai/`, `qwen/`, `moonshotai/`, `nousresearch/`, `xiaomi/`, `z-ai/`, and every other vendor prefix in the LiteLLM snapshot), one of the routing wrappers above, or one of the client-side spellings `kimi/`, `mimo/`, `zhipu/`, `litellm_proxy/` and `openai_like/`. Anything else stays unpriced and is reported as unpriced rather than inheriting the price of a same-named cloud row, and local-runner prefixes (`ollama/`, `lmstudio/`, `hosted_vllm/`, `local/`) are excluded on purpose so an unlisted local tag can never invent cloud spend. A user price override for the bare id wins over the catalog row a routed spelling would otherwise hit. +- **Routed model ids price as the model they wrap, and an unknown vendor prefix no longer prices by blind stripping.** Token-plan and gateway spellings of the same model (`omniroute:`, `cp/`, `cline-pass/`, `cline-free/`, `cmd/`, `antigravity/`, `orcarouter/`) are peeled and the remaining id is priced, so a Cline Pass or OmniRoute session shows a `~` estimate instead of $0. In exchange, `provider/model` is no longer treated as authority on its own: the leading segment is stripped only when it is a namespace the bundled pricing catalog itself uses (`anthropic/`, `openai/`, `google/`, `x-ai/`, `qwen/`, `moonshotai/`, `nousresearch/`, `xiaomi/`, `z-ai/`, and every other vendor prefix in the LiteLLM snapshot), one of the routing wrappers above, or one of the client-side spellings `kimi/`, `mimo/`, `zhipu/`, `litellm_proxy/` and `openai_like/`. Anything else stays unpriced and is reported as unpriced rather than inheriting the price of a same-named cloud row, and local-runner prefixes (`ollama/`, `lmstudio/`, `hosted_vllm/`, `local/`) are excluded on purpose so an unlisted local tag can never invent cloud spend. A user price override for the bare id wins over the catalog row a routed spelling would otherwise hit. - **SQLite providers now survive read-only database parents.** A read-only SQLite open is not read-only on disk: on a WAL database SQLite must create `-shm` and `-wal` in the database's own directory, so a source on read-only media, under restrictive permissions, or inside a Flatpak/snap confinement failed with `attempt to write a readonly database` (or `unable to open database file` when a `-wal` was present without its `-shm`), and both discovery sites swallowed it — the provider read as "not installed" rather than as an error. That covers cursor, cursor-agent, opencode, goose, warp, kilo-code, zerostack and the copilot agent-traces database. The direct open stays the fast path and is byte-identical when it succeeds. When it fails for want of sidecars: a database with no WAL frames to lose is opened in place with `immutable=1`, which costs nothing and cannot go stale; a database with a non-empty `-wal` is copied with its `-wal` into the CodeBurn cache and read there, so its un-checkpointed rows are never silently dropped. The copy costs one database's worth of disk and is taken once per change — it is keyed by the main-plus-WAL fingerprint, published under a fingerprint-stamped name so a refresh never overwrites a copy another process is reading, and superseded copies are evicted once a day has passed without a read, keeping at most one predecessor. If the cache itself cannot be written, the database is skipped with a notice naming it and the reason rather than in silence. The original provider database is never opened writable or modified. - **Grok Build now reads the CLI's own completed-turn usage instead of estimating it.** Usage comes from the `turn_completed.usage` records Grok CLI already writes into `updates.jsonl` (`inputTokens`, `outputTokens`, `cachedReadTokens`, `cacheCreationTokens`, `reasoningTokens`), deduplicated by `prompt_id` and emitted as one session-level call from the top-level totals. The previous parser reconstructed an estimate from the running `_meta.totalTokens` context counter, so **existing Grok totals will change materially on upgrade** - on one real 568-session corpus cache-read went from 150K to 96.3M tokens, total tokens from 20.0M to 113.9M, and cost from $36.98 to $56.79. Cache read and cache creation are subsets of input and reasoning is a subset of output, so reasoning is clamped to the record's reported output and split back out to match this repo's exclusive-reasoning contract. `modelUsage` only selects a priced attribution id; multi-model rate attribution stays out of scope, so one session is priced at one model's rate. `costUsdTicks` is ignored because its scale is undocumented. Sessions with no usable record - older CLI versions - keep the old context-curve heuristic and stay flagged estimated. **In a session that has at least one `turn_completed` record, turns without one are not counted at all** (their tokens are dropped rather than estimated), and the session is marked estimated instead of claiming full provider coverage. Cached Grok sessions re-parse once. The daily cache re-derives once on first run after upgrade: this is a global re-derivation of every day and every provider, since the daily cache has no per-provider invalidation, but it reads the warm session cache rather than re-parsing transcripts, so it costs seconds (~3s on the corpus above), and the superseded cache file is retained on disk as the baseline for days no source can still re-derive. (#998) - **Codex rollouts parse across worker threads too, and the workload gate now takes bytes or files.** Codex is the bigger half of a real cold parse — a 4 GB rollout corpus against 1.8 GB of Claude sessions — and it was still decoding one file at a time. A whole-file rollout decode now runs on the same pool, against an empty dedup set, and comes back with the calls, the dedup keys it claimed, and the codex-cache entry it would have written; the parent installs all three in the serial loop's order, so `codex-results.json` and every payload come out byte-identical to a serial run. Cross-file state stays where it was: a forked rollout replaying its parent's token_count history collides on the parent's keys and is re-parsed in-process, and no worker ever touches the cache module's per-directory state. Files the Codex cache can serve exactly or resume into from a byte offset never reach a worker — they read a few KB and the resume state belongs to the parent. The workload gate is now pending BYTES alone (200 MB), not file count: 250 pending files holding under a megabyte between them spawned threads that made the run ~5% slower, while a few hundred huge rollouts were being turned away. The count takes `max(pendingFiles / 50, pendingBytes / 200 MB)`, and the per-thread memory budget is derived per parse as `clamp(256 MB, 2 × average pending file + 128 MB, 1 GB)` rather than a flat 256 MB — a 260 MB rollout peaks near 430 MB in its worker and scales linearly with the pool, so the flat figure over-subscribed exactly the workload this adds. The decision is per provider, and at most one pool is alive at a time. diff --git a/README.md b/README.md index 78ac72f1..c1ca15c2 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,16 @@ gnome-extensions enable codeburn@codeburn.dev See [gnome/README.md](gnome/README.md) for settings and development notes. The Tauri tray app in `windows/` also builds and runs on Linux, but it is experimental and unreleased there — the GNOME extension is the supported Linux surface. +### Omarchy + +Install the [CodeBurn Omarchy plugin](https://omarchyplugins.com/plugin.html?id=codeburn) to add CodeBurn to Omarchy: + +Community-maintained by [@erzz](https://github.com/erzz) — issues and feature requests go to [erzz/omarchy-codeburn](https://github.com/erzz/omarchy-codeburn). + +```bash +omarchy plugin add https://github.com/erzz/omarchy-codeburn.git --enable +``` + ## CodeBurn in your agent (MCP) ```bash @@ -532,7 +542,7 @@ Left/right arrow keys switch between Today, 7 Days, 30 Days, Month, 6 Months, an ### Pricing -Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. +Prices every API call using input, output, cache read, cache write, and web search token counts, with a fast mode multiplier for Claude. Prices are fetched from [LiteLLM](https://github.com/BerriAI/litellm) and cached locally for 24 hours at `~/.cache/codeburn/`. Hardcoded fallbacks for all Claude and GPT-5 models prevent fuzzy-matching mispricing. Routing-gateway model ids are priced as the model they wrap: [OrcaRouter](https://www.orcarouter.ai) fusion route ids peel to their current upstream (`openai/gpt-oss-120b`), `orcarouter/auto` stays unpriced until a live probe pins the rotating target, and a nested upstream spelling (`orcarouter/deepseek/deepseek-v4-pro`) prices at that exact row, so a gateway-routed session reports real spend instead of $0. ### Task Categories @@ -568,14 +578,16 @@ For categories that involve code edits, CodeBurn tracks file-aware retry cycles. codeburn plan set claude-max # $200/month codeburn plan set claude-pro # $20/month codeburn plan set cursor-pro # $20/month +codeburn plan set copilot-pro # 1500 AI Credits ($15 equivalent) codeburn plan set custom --monthly-usd 200 --provider codex # ChatGPT Pro-style custom plan +codeburn plan set custom --credits 20000 --provider copilot # org Copilot allotment codeburn plan reset --provider codex # remove one provider plan codeburn plan set none # disable plan view codeburn plan # show configured plans codeburn plan reset # remove plan config ``` -Subscription tracking for Claude Pro, Claude Max, Cursor Pro, and custom provider plans. Plans are stored per provider, so you can track Claude and Codex/Cursor subscriptions at the same time; the dashboard shows one overage line per active provider plan. A legacy/custom `all` plan remains a single aggregate plan and is replaced when you add a provider-specific plan, avoiding double-counted overage rows. Existing single-plan config is still read as a fallback. Presets use publicly stated plan prices (as of April 2026); they do not model exact token allowances, because vendors do not publish precise consumer-plan limits. +Subscription tracking for Claude Pro, Claude Max, Cursor Pro, Copilot (AI credits), and custom provider plans. Plans are stored per provider, so you can track Claude and Codex/Cursor subscriptions at the same time; the dashboard shows one overage line per active provider plan. A legacy/custom `all` plan remains a single aggregate plan and is replaced when you add a provider-specific plan, avoiding double-counted overage rows. Existing single-plan config is still read as a fallback. USD presets use publicly stated plan prices (as of April 2026). Copilot presets use official individual AI-credit allotments (Pro 1,500 / Pro+ 7,000 / Max 20,000; fetched 2026-08-23) — not the $10 / $39 / $100 sticker prices — and spend is `total_nano_aiu / 1e9`, never token-priced USD. ### Currency diff --git a/app/demo-bridge.mjs b/app/demo-bridge.mjs new file mode 100644 index 00000000..8e9404ca --- /dev/null +++ b/app/demo-bridge.mjs @@ -0,0 +1,86 @@ +// DEMO HARNESS — NOT SHIPPED. Serves the Electron renderer's bridge calls over +// HTTP so the desktop app runs in a plain browser tab for demo recording. +// Read-only: every mutation channel is answered with a benign no-op. +import { createServer } from 'node:http' +import { spawn, execFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path' + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..') +const CLI = join(ROOT, 'dist', 'cli.js') + +// ── resident serve child for the hot panel queries ── +const serve = spawn('node', [CLI, 'serve', '--stdio'], { stdio: ['pipe', 'pipe', 'inherit'] }) +let buf = '' +const waiters = new Map() +let nextId = 1 +serve.stdout.setEncoding('utf8') +serve.stdout.on('data', (c) => { + buf += c + let i + while ((i = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, i); buf = buf.slice(i + 1) + if (!line.trim()) continue + let m; try { m = JSON.parse(line) } catch { continue } + const w = waiters.get(m.id); if (w) { waiters.delete(m.id); w(m) } + } +}) +const serveCall = (args) => new Promise((resolve, reject) => { + const id = nextId++ + waiters.set(id, (m) => m.ok ? resolve(JSON.parse(m.output)) : reject(new Error(m.error))) + serve.stdin.write(JSON.stringify({ id, args }) + '\n') +}) +const execCall = (args) => new Promise((resolve, reject) => { + execFile('node', [CLI, ...args], { maxBuffer: 1 << 28 }, (err, stdout) => { + if (err) return reject(err) + try { resolve(JSON.parse(stdout)) } catch (e) { reject(e) } + }) +}) + +const range = (r) => r ? ['--from', r.from, '--to', r.to] : [] +const prov = (p) => p && p !== 'all' ? ['--provider', p] : ['--provider', 'all'] + +// channel → argv, mirroring app/electron/main.ts builders +const ROUTES = { + getOverview: (period, provider, r) => ['status', '--format', 'menubar-json', '--period', period, '--no-timeline', ...prov(provider), ...range(r)], + getTimeline: (period, provider, r) => ['status', '--format', 'menubar-json', '--period', period, ...prov(provider), ...range(r)], + getPlans: (period) => ['status', '--format', 'json', '--period', period], + getModels: (period, provider, byTask, r) => ['models', '--format', 'json', '--period', period, ...prov(provider), ...(byTask ? ['--by-task'] : []), ...range(r)], + getSessions: (period, provider, r) => ['sessions', '--format', 'json', '--period', period, ...prov(provider), ...range(r)], + getCompareModels: (period, provider) => ['compare', '--format', 'json', '--period', period, ...prov(provider)], + getCompare: (period, provider, a, b) => ['compare', '--format', 'json', '--period', period, ...prov(provider), '--model-a', a, '--model-b', b], + getYield: (period, provider, r) => ['yield', '--format', 'json', '--period', period, ...prov(provider), ...range(r)], + getSpendFlow: (period, provider, r) => ['spend', '--format', 'flow-json', '--period', period, ...prov(provider), ...range(r)], + getOptimizeReport: (period, provider, r) => ['optimize', '--format', 'json', '--period', period, ...prov(provider), ...range(r)], + getAudit: (period, provider, r) => ['audit', '--format', 'json', '--period', period, ...prov(provider), ...range(r)], + getActReport: () => ['act', 'report', '--json'], + getShareStatus: () => ['share', 'status', '--format', 'json'], + getIdentity: () => ['identity', '--format', 'json'], + getAliases: () => ['model-alias', '--list', '--format', 'json'], + getProxyPaths: () => ['proxy-path', '--list', '--format', 'json'], + getPriceOverrides: () => ['price-override', '--list', '--format', 'json'], + getDevices: (period) => ['devices', '--format', 'json', '--period', period], +} +const SERVED = new Set(['getOverview', 'getTimeline', 'getPlans', 'getModels', 'getSessions', 'getCompareModels', 'getCompare', 'getYield', 'getSpendFlow', 'getOptimizeReport', 'getAudit']) + +createServer((req, res) => { + res.setHeader('Access-Control-Allow-Origin', '*') + res.setHeader('Access-Control-Allow-Headers', 'content-type') + if (req.method === 'OPTIONS') { res.end(); return } + let body = '' + req.on('data', (c) => { body += c }) + req.on('end', async () => { + try { + const { channel, args } = JSON.parse(body || '{}') + const build = ROUTES[channel] + if (!build) { res.writeHead(200, { 'content-type': 'application/json' }); res.end('null'); return } + const argv = build(...(args ?? [])) + const value = SERVED.has(channel) ? await serveCall(argv) : await execCall(argv) + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify(value)) + } catch (err) { + res.writeHead(500, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: String(err?.message ?? err) })) + } + }) +}).listen(4900, '127.0.0.1', () => console.log('demo bridge on http://127.0.0.1:4900')) diff --git a/app/renderer/public/demo-shim.js b/app/renderer/public/demo-shim.js new file mode 100644 index 00000000..b6ba39c9 --- /dev/null +++ b/app/renderer/public/demo-shim.js @@ -0,0 +1,58 @@ +// DEMO HARNESS — NOT SHIPPED. Stands in for the Electron preload bridge so the +// renderer runs in a plain browser tab against demo-bridge.mjs. Read-only: +// mutations resolve as successful no-ops, subscriptions return no-op +// unsubscribers, and anything unimplemented resolves null via the Proxy. +(() => { + const call = (channel) => (...args) => + fetch('http://127.0.0.1:4900/call', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ channel, args }), + }).then((r) => { + if (!r.ok) throw { kind: 'nonzero', message: 'demo bridge error' } + return r.json() + }) + + const okAction = () => Promise.resolve({ ok: true, stdout: '', stderr: '', code: 0 }) + const unsub = () => () => {} + + const base = { + platform: 'darwin', + arch: 'arm64', + onProgress: unsub, + onUpdateStatus: unsub, + getUpdateStatus: () => Promise.resolve({ currentVersion: '0.9.20', latestVersion: null, updateAvailable: false, tag: null }), + getQuota: () => Promise.resolve([]), + getDevicesScan: () => Promise.resolve({ devices: [] }), + cliStatus: () => Promise.resolve({ found: true, path: 'bundled (demo)' }), + telemetryStatus: () => Promise.resolve({ enabled: false, onboarded: true }), + setTelemetryEnabled: () => Promise.resolve(null), + completeOnboarding: () => Promise.resolve(null), + telemetryTrack: () => Promise.resolve(false), + openExternal: (url) => { window.open(url, '_blank'); return Promise.resolve() }, + chooseDirectory: () => Promise.resolve(null), + setCurrency: okAction, resetCurrency: okAction, + addAlias: okAction, removeAlias: okAction, + setPriceOverride: okAction, removePriceOverride: okAction, + removeDevice: okAction, setPlan: okAction, resetPlan: okAction, + exportData: okAction, + } + + const READ_CHANNELS = [ + 'getOverview', 'getTimeline', 'getPlans', 'getModels', 'getSessions', + 'getCompareModels', 'getCompare', 'getYield', 'getSpendFlow', + 'getOptimizeReport', 'getAudit', 'getActReport', 'getShareStatus', + 'getIdentity', 'getAliases', 'getProxyPaths', 'getPriceOverrides', 'getDevices', + ] + for (const channel of READ_CHANNELS) base[channel] = call(channel) + + window.codeburn = new Proxy(base, { + get: (target, key) => key in target ? target[key] : () => Promise.resolve(null), + }) + + // Background tabs never tick CSS animations, so the section entrance fade + // freezes at opacity 0 during automated capture. Skip it entirely in the demo. + const style = document.createElement('style') + style.textContent = '.section-fade { animation: none !important; opacity: 1 !important; }' + document.addEventListener('DOMContentLoaded', () => document.head.appendChild(style)) +})() diff --git a/docs/providers/copilot.md b/docs/providers/copilot.md index 62926388..45fbdeab 100644 --- a/docs/providers/copilot.md +++ b/docs/providers/copilot.md @@ -140,8 +140,9 @@ see the #927 ruling in `src/session-cache.ts`). still re-derive its pruned rows. - **Billing metadata.** Each row's `total_nano_aiu` and `request_multiplier` are captured onto the cached call when the store's schema has them (older - stores parse identically without). Nothing prices or displays them yet — - billing-grade cost is upstream #890. + stores parse identically without). Plan math sums finite `nanoAiu` into + Copilot AI credits (`codeburn plan set copilot-pro`). Billing-grade cost + rewrite of every report is still upstream #890. - **Sync.** `codeburn sync push` holds a copilot session until it has been quiet for 24 hours. The reconciliation output is mutable (a residual shrinks as rows land, a rollup is dropped once rows cover its leg, a row's pairing diff --git a/scripts/upgrade-path/run.mjs b/scripts/upgrade-path/run.mjs index c7af2816..74721d3d 100644 --- a/scripts/upgrade-path/run.mjs +++ b/scripts/upgrade-path/run.mjs @@ -33,7 +33,7 @@ const WORK = process.env['UPGRADE_PATH_WORK'] || join(tmpdir(), 'codeburn upgrad const OLD_SESSION_CACHE = 'session-cache.v7.json' const OLD_DAILY_CACHE = 'daily-cache.v17.json' const NEW_SESSION_CACHE_DIR = 'session-cache.v9' -const NEW_DAILY_CACHE = 'daily-cache.v28.json' +const NEW_DAILY_CACHE = 'daily-cache.v29.json' const HOME = join(WORK, 'user home') const PAYLOADS = join(WORK, 'payloads') diff --git a/src/config.ts b/src/config.ts index 742a7d65..d96c0442 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,12 +4,15 @@ import { homedir } from 'os' import { randomBytes } from 'crypto' import { PLAN_PROVIDERS } from './plans.js' -export type PlanId = 'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'custom' | 'none' -export type PlanProvider = 'claude' | 'codex' | 'cursor' | 'grok' | 'all' +export type PlanId = 'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'copilot-pro' | 'copilot-pro-plus' | 'copilot-max' | 'custom' | 'none' +export type PlanProvider = 'claude' | 'codex' | 'cursor' | 'grok' | 'copilot' | 'all' export type Plan = { id: PlanId monthlyUsd: number + // Copilot plans budget in AI credits. monthlyUsd stays as credits × $0.01 so + // isActivePlan and add-only JSON keep working. Absent on USD plans. + monthlyCredits?: number provider: PlanProvider resetDay?: number setAt: string diff --git a/src/copilot-aiu.ts b/src/copilot-aiu.ts new file mode 100644 index 00000000..115da442 --- /dev/null +++ b/src/copilot-aiu.ts @@ -0,0 +1,19 @@ +// Copilot AI credits. Official rate from GitHub Docs, *Usage-based billing +// for individuals*, fetched 2026-08-23: +// https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals +// 1e9 nano-AIU = 1 credit = $0.01. No per-model rate table in this slice. + +export const NANO_AIU_PER_CREDIT = 1e9 +export const AI_CREDIT_USD = 0.01 + +export function isFiniteNanoAiu(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) +} + +export function nanoAiuToCredits(nanoAiu: number): number { + return nanoAiu / NANO_AIU_PER_CREDIT +} + +export function creditsToUsd(credits: number): number { + return credits * AI_CREDIT_USD +} diff --git a/src/daily-cache.ts b/src/daily-cache.ts index 400806bc..1644baf5 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -172,7 +172,9 @@ import type { DateRange, ProjectSummary } from './types.js' // Exclusive providers (Grok and the rest) were under-counted by reasoningTokens // in finalized daily rows; inclusive {claude,codex,copilot} were correct there // but optimize added reasoning again. Re-derive so report matches the live parse. -export const DAILY_CACHE_VERSION = 28 +// v29: #1118 OrcaRouter route pricing (fusion aliases + peel; auto stays unpriced). +// v28 on main already shipped #1115. +export const DAILY_CACHE_VERSION = 29 const MIN_SUPPORTED_VERSION = 28 /// Providers whose per-day CALL COUNT means something different at @@ -1179,6 +1181,15 @@ export function toDateString(date: Date): string { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` } +/// A day whose ONLY content is turn-anchored residue (one straddling turn's +/// category/edit counts, no calls) is not a derived day — it is a day the parse +/// under-read. Re-derive it instead of serving it. +export function isTurnResidueOnly(day: DailyEntry): boolean { + if (day.cost > 0 || day.calls > 0 || day.sessions > 0) return false + if (day.inputTokens + day.outputTokens + day.cacheReadTokens + day.cacheWriteTokens > 0) return false + return Object.values(day.categories).some(c => c.turns > 0) +} + export async function ensureCacheHydrated( parseSessions: (range: DateRange) => Promise, aggregateDays: (projects: ProjectSummary[]) => DailyEntry[], @@ -1241,6 +1252,34 @@ export async function ensureCacheHydrated( c = { ...c, lastComputedDate: newestCachedDate } } + // Never seal a residue-only day (issue #1127): a day whose only content is + // turn-anchored residue was under-read by the parse that produced it, so + // trust the DATA over the marker again — pull the watermark back to just + // before the oldest such day and let the ordinary gap parse re-derive it. + // This is what heals every already-broken cache on the next launch, with + // no version bump. + // + // Caveat: a day that GENUINELY held only one straddling turn and no other + // activity re-derives to the same residue shape and would be re-parsed on + // every launch. Bound that cost: skip the pull-back when the residue day + // is the oldest day in the cache, and only pull back inside the settle + // window — outside it the source files are gone and re-deriving cannot + // recover the day anyway. + const oldestCachedDate = c.days.reduce((min, d) => (min === null || d.date < min ? d.date : min), null) + const residueSettleCutoff = settleCutoffDate(now) + const oldestResidueDate = c.days.reduce( + (min, d) => (d.date >= residueSettleCutoff && d.date !== oldestCachedDate && isTurnResidueOnly(d) && (min === null || d.date < min) ? d.date : min), + null, + ) + if (oldestResidueDate !== null && c.lastComputedDate !== null && c.lastComputedDate >= oldestResidueDate) { + const pulledBack = new Date( + parseInt(oldestResidueDate.slice(0, 4)), + parseInt(oldestResidueDate.slice(5, 7)) - 1, + parseInt(oldestResidueDate.slice(8, 10)) - 1 + ) + c = { ...c, lastComputedDate: toDateString(pulledBack) } + } + // Three reasons to re-derive the whole retention window: // 1. Savings config changed — cached `savingsUSD` totals are stale. // 2. The cache was never finalized against a COMPLETE session parse (an old @@ -1354,7 +1393,17 @@ export async function ensureCacheHydrated( const gapDays = aggregateDays(gapProjects) const parseWasComplete = sessionComplete() const priorWatermark = c.lastComputedDate - c = addNewDays(c, gapDays, yesterdayStr) + // Gate the merge on parse completeness (issue #1127): replacing cached + // days wholesale with the gap parse's days let a PARTIAL parse overwrite + // a populated baseline day with its under-read version — and if the + // day's sources die before the next complete parse, the undercount is + // what survives. A complete parse still wins per (date, provider) + // exactly as the re-derive path does (partial-survival guarded); a + // partial one only fills days and slices the baseline lacks, so the gap + // merge is strictly additive and no cached data can shrink. + const merged = parseWasComplete + ? mergeDayEntries(gapDays, c.days, false, undefined, true) + : mergeDayEntries(c.days, gapDays, false) // Finalize as complete ONLY when the session parse that produced these days // was itself complete. If it was partial, leave `complete: false` so the // next launch (once the session cache is whole) re-backfills instead of @@ -1362,7 +1411,7 @@ export async function ensureCacheHydrated( // the same reason as the re-derive path above: a partial parse cannot // vouch for the days it never read, and gapStart is the only thing that // will ever bring them back. - c = { ...c, lastComputedDate: parseWasComplete ? c.lastComputedDate : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } + c = { ...c, days: applyRetention(merged, yesterdayStr), lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } await saveDailyCache(c) } else if (c.complete !== true && sessionComplete()) { // No gap to fill (already current through yesterday) but not yet marked — diff --git a/src/dashboard.tsx b/src/dashboard.tsx index b67f3b97..f902727f 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -488,9 +488,20 @@ function planColor(planUsage: PlanUsage): string { // end-first, so the headline stays short enough to keep the percentage visible // at 80 columns and the status leads with the disclaimer, not the arithmetic. export function planBudgetHeadline(planUsage: PlanUsage): string { + if (planUsage.plan.provider === 'copilot') { + const spent = planUsage.spentCredits ?? 0 + const budget = planUsage.budgetCredits ?? planUsage.plan.monthlyCredits ?? 0 + return `${planLabel(planUsage)}: ${formatCredits(spent)} / ${formatCredits(budget)} AI Credits` + } return `${planLabel(planUsage)}: ${formatCost(planUsage.spentApiEquivalentUsd)} API-equivalent / ${formatCost(planUsage.budgetUsd)} budget` } +function formatCredits(n: number): string { + if (Number.isInteger(n)) return String(n) + const rounded = Math.round(n * 1e6) / 1e6 + return String(rounded) +} + export function planStatusText(planUsage: PlanUsage): string { // The period is anniversary-based (plan.resetDay, 1-28, settable per plan via // `codeburn plan set --reset-day`), so this is a monthly budget window, not a diff --git a/src/doctor.ts b/src/doctor.ts index 95a3d44d..6505c11f 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -7,6 +7,7 @@ import { Chalk } from 'chalk' import { getClaudeConfigDirs } from './providers/claude.js' import { getAllProviders } from './providers/index.js' import type { Provider } from './providers/types.js' +import { dailyCachePath, isTurnResidueOnly, type DailyEntry } from './daily-cache.js' import { PROVIDER_ENV_VARS, PROVIDER_PARSE_VERSIONS, @@ -14,6 +15,7 @@ import { type SessionCache, } from './session-cache.js' import { renderTable } from './text-table.js' +import { collectLauncherNotes, type LauncherNote } from './launcher-homes.js' // ── Types ────────────────────────────────────────────────────────────── @@ -68,13 +70,35 @@ export type ClaudeRetentionNote = { settingsPath: string } +export type DoctorSessionCacheIssue = { + provider: string + /// Session-cache file key (the source path, including any virtual suffix). + path: string + reason: 'failed' | 'no-turns' +} + +export type DoctorCacheHealth = { + /// Daily-cache dates whose only content is turn-anchored residue — a day the + /// parse under-read (isTurnResidueOnly, issue #1127). ensureCacheHydrated + /// re-derives them on the next launch; they are listed here so the state is + /// visible without an archaeology dig. + residueOnlyDays: string[] + /// Session-cache entries flagged as parse failures or cached with zero + /// turns — the under-read entries residue days come from. + sessionCacheIssues: DoctorSessionCacheIssue[] +} + export type DoctorReport = { generatedAt: string providers: DoctorProviderReport[] + /** Nests that drive another billed store. Never given a session count. */ + launchers?: LauncherNote[] /// Present when the Claude provider is in the report and a config dir was /// found. Surfaced because deleted transcripts are unrecoverable: daily /// totals survive in CodeBurn's cache, but per-session detail does not. claudeRetention?: ClaudeRetentionNote + /// Present only when there is something to list. + cacheHealth?: DoctorCacheHealth } export type CollectDoctorOptions = { @@ -82,8 +106,12 @@ export type CollectDoctorOptions = { providers?: Provider[] /** Injectable cache snapshot (defaults to reading session-cache.json). */ cache?: SessionCache + /** Injectable daily-cache days (defaults to reading the daily cache file). */ + dailyCacheDays?: DailyEntry[] /** Max discovered sources to parse-sample per provider. */ sampleLimit?: number + /** Injectable launcher notes (defaults to scanning the real home). */ + launchers?: LauncherNote[] } // Bound the parse sample: at most this many discovered sources per provider, @@ -330,10 +358,17 @@ export async function collectDoctorReport( providers.sort((a, b) => (a.displayName < b.displayName ? -1 : a.displayName > b.displayName ? 1 : 0)) const report: DoctorReport = { generatedAt: new Date().toISOString(), providers } + const launchers = opts.launchers ?? collectLauncherNotes() + if (launchers.length > 0) report.launchers = launchers if (providers.some(p => p.provider === 'claude')) { const retention = await collectClaudeRetention() if (retention) report.claudeRetention = retention } + const residueOnlyDays = collectResidueOnlyDays(opts.dailyCacheDays ?? await readDailyCacheDays()) + const sessionCacheIssues = collectSessionCacheIssues(cache) + if (residueOnlyDays.length > 0 || sessionCacheIssues.length > 0) { + report.cacheHealth = { residueOnlyDays, sessionCacheIssues } + } return report } finally { if (prevSuppress === undefined) delete process.env['CODEBURN_SUPPRESS_CACHE_WRITES'] @@ -347,6 +382,45 @@ const CLAUDE_DEFAULT_CLEANUP_DAYS = 30 // the doctor line turns into a warning. const CLAUDE_RETENTION_WARN_DAYS = 365 +/// Read-only peek at the daily cache's days: loadDailyCache can WRITE +/// (adoption / migration), which doctor's read-only promise forbids, so the +/// file is read and parsed directly. Anything unreadable or foreign simply +/// yields no days — doctor must never crash on a corrupt cache. +async function readDailyCacheDays(): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(dailyCachePath(), 'utf-8')) + const days = (parsed as { days?: unknown } | null)?.days + if (!Array.isArray(days)) return [] + return days.filter((d): d is DailyEntry => !!d && typeof d === 'object' && typeof (d as DailyEntry).date === 'string') + } catch { + return [] + } +} + +function collectResidueOnlyDays(days: DailyEntry[]): string[] { + const out: string[] = [] + for (const d of days) { + try { + if (isTurnResidueOnly(d)) out.push(d.date) + } catch { + // Foreign junk in a hand-edited cache: skip the day, keep diagnosing. + } + } + return out.sort() +} + +function collectSessionCacheIssues(cache: SessionCache): DoctorSessionCacheIssue[] { + const out: DoctorSessionCacheIssue[] = [] + for (const [provider, section] of Object.entries(cache.providers)) { + for (const [path, f] of Object.entries(section.files)) { + // A failed entry carries no turns by construction; report it once, as failed. + if (f.failed) out.push({ provider, path, reason: 'failed' }) + else if (Array.isArray(f.turns) && f.turns.length === 0) out.push({ provider, path, reason: 'no-turns' }) + } + } + return out +} + async function collectClaudeRetention(): Promise { for (const dir of await getClaudeConfigDirs()) { const settingsPath = join(dir, 'settings.json') @@ -445,6 +519,28 @@ export function renderDoctorTable( } } + if (report.launchers && report.launchers.length > 0) { + out.push('') + out.push(c.bold('Launchers')) + for (const launcher of report.launchers) { + out.push(` ${launcher.name} ${c.dim(launcher.path)} ${launcher.verdict}`) + } + } + + if (report.cacheHealth) { + out.push('') + out.push(c.bold('Cache health') + c.dim(' (issue #1127 diagnostics — under-read cache entries)')) + for (const date of report.cacheHealth.residueOnlyDays) { + out.push(' ' + c.yellow(date) + c.dim(' residue-only day (turn counts but no calls/cost); re-derived on next launch')) + } + for (const issue of report.cacheHealth.sessionCacheIssues) { + out.push( + ' ' + c.dim(`${issue.provider} `) + issue.path + + c.dim(issue.reason === 'failed' ? ' (cached parse failure)' : ' (cached with 0 turns)'), + ) + } + } + if (report.claudeRetention) { const r = report.claudeRetention const source = r.configured ? 'cleanupPeriodDays' : 'cleanupPeriodDays not set; Claude Code default' diff --git a/src/launcher-homes.ts b/src/launcher-homes.ts new file mode 100644 index 00000000..191afb34 --- /dev/null +++ b/src/launcher-homes.ts @@ -0,0 +1,152 @@ +import { closeSync, existsSync, openSync, readdirSync, readSync, realpathSync } from 'fs' +import { homedir } from 'os' +import { join, resolve, sep } from 'path' + +export type LauncherNote = { + name: string + path: string + billedVia: string + verdict: string +} + +function resolveHome(dir: string): string { + try { + return realpathSync(dir) + } catch { + return resolve(dir) + } +} + +/** True when two Codex homes are the same physical tree. */ +export function sameCodexHome(a: string, b: string): boolean { + return resolveHome(a) === resolveHome(b) +} + +/** True when `dir` is a Codex home nested under a launcher nest, and a distinct + * primary Codex home exists. Gate for overlap-only filtering — it does not by + * itself drop sessions. The production no-arg factory uses this to walk both + * trees; an explicit nest factory uses it to drop overlapping nest ids. */ +export function isNestedLauncherCodexHome( + dir: string, + opts: { primaryDir: string; launcherRoots: string[] }, +): boolean { + const resolved = resolveHome(dir) + const primary = resolveHome(opts.primaryDir) + if (resolved === primary) return false + const underLauncher = opts.launcherRoots.some(root => { + const r = resolveHome(root) + return resolved === r || resolved.startsWith(r + sep) + }) + if (!underLauncher) return false + return existsSync(primary) +} + +// Same bound as `readFirstLine` in providers/codex.ts. Real Codex +// session_meta first lines are ~22–27 KB; 8 KiB truncates them mid-JSON. +export const FIRST_LINE_READ_CAP = 1024 * 1024 + +/** Session id from the first `session_meta` line of a Codex rollout file. + * Missing / unreadable files return undefined — callers must not drop those. */ +export function rolloutFileSessionId(filePath: string): string | undefined { + try { + const fd = openSync(filePath, 'r') + try { + const buf = Buffer.alloc(FIRST_LINE_READ_CAP) + const n = readSync(fd, buf, 0, buf.length, 0) + if (n === 0) return undefined + const slice = buf.subarray(0, n) + const nl = slice.indexOf(0x0a) + // Hit the 1 MiB cap without a newline: incomplete, not a parseable id. + if (nl === -1 && n === FIRST_LINE_READ_CAP) return undefined + const line = (nl === -1 ? slice : slice.subarray(0, nl)).toString('utf8') + if (!line) return undefined + const parsed: unknown = JSON.parse(line) + if (!parsed || typeof parsed !== 'object') return undefined + const payload = (parsed as { payload?: { session_id?: unknown } }).payload + const id = payload?.session_id + return typeof id === 'string' && id.length > 0 ? id : undefined + } finally { + closeSync(fd) + } + } catch { + return undefined + } +} + +function walkRolloutFiles(codexDir: string, visit: (filePath: string) => void): void { + const take = (dir: string, file: string) => { + if (file.startsWith('rollout-') && file.endsWith('.jsonl')) visit(join(dir, file)) + } + const sessionsDir = join(codexDir, 'sessions') + try { + for (const year of readdirSync(sessionsDir)) { + if (!/^\d{4}$/.test(year)) continue + const yearDir = join(sessionsDir, year) + for (const month of readdirSync(yearDir)) { + if (!/^\d{2}$/.test(month)) continue + const monthDir = join(yearDir, month) + for (const day of readdirSync(monthDir)) { + if (!/^\d{2}$/.test(day)) continue + const dayDir = join(monthDir, day) + for (const file of readdirSync(dayDir)) take(dayDir, file) + } + } + } + } catch { + // missing tree + } + const archivedDir = join(codexDir, 'archived_sessions') + try { + for (const file of readdirSync(archivedDir)) take(archivedDir, file) + } catch { + // missing archive + } +} + +/** Session ids under a Codex home (sessions/YYYY/MM/DD + archived). + * Identity is the rollout's `payload.session_id`, not the filename: Codex + * names embed a timestamp+uuid so basename collisions are rare, but a + * dollar-protecting dedup cannot treat 'unlikely' as identity. */ +export function listRolloutSessionIds(codexDir: string): Set { + const ids = new Set() + walkRolloutFiles(codexDir, filePath => { + const id = rolloutFileSessionId(filePath) + if (id) ids.add(id) + }) + return ids +} + +export function defaultBilledCodexHome(): string { + return join(homedir(), '.codex') +} + +export function defaultLauncherRoots(): string[] { + return [join(homedir(), '.buzz')] +} + +/** Surfaces that drive another billed store. Not providers. No session count. + * Presence of `~/.buzz` is the heuristic — we do not inspect a nested Codex + * tree here (that store is billed via the Codex provider). */ +export function collectLauncherNotes(home = homedir()): LauncherNote[] { + const notes: LauncherNote[] = [] + const buzz = join(home, '.buzz') + if (existsSync(buzz)) { + notes.push({ + name: 'buzz', + path: buzz, + billedVia: 'codex', + verdict: 'LAUNCHER (heuristic; billed via Codex)', + }) + } + const grokStore = join(home, '.grok') + const grokBot = join(home, 'Library', 'Application Support', 'Grok Bot') + if (existsSync(grokBot) && existsSync(grokStore)) { + notes.push({ + name: 'grok-bot', + path: grokBot, + billedVia: 'grok', + verdict: 'LAUNCHER (Electron cache; billed via ~/.grok)', + }) + } + return notes +} diff --git a/src/main.ts b/src/main.ts index 174239d4..eecb834b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -145,10 +145,16 @@ type JsonPlanSummary = { daysUntilReset: number periodStart: string periodEnd: string + monthlyCredits?: number + spentCredits?: number + budgetCredits?: number + creditsIncomplete?: boolean + monthlyUsd?: number + spentApiEquivalentUsd?: number } function toJsonPlanSummary(planUsage: PlanUsage): JsonPlanSummary { - return { + const summary: JsonPlanSummary = { id: planUsage.plan.id, provider: planUsage.plan.provider, budget: convertCost(planUsage.budgetUsd), @@ -160,6 +166,15 @@ function toJsonPlanSummary(planUsage: PlanUsage): JsonPlanSummary { periodStart: planUsage.periodStart.toISOString(), periodEnd: planUsage.periodEnd.toISOString(), } + if (planUsage.plan.provider === 'copilot') { + summary.monthlyCredits = planUsage.plan.monthlyCredits + summary.spentCredits = planUsage.spentCredits + summary.budgetCredits = planUsage.budgetCredits + summary.creditsIncomplete = planUsage.creditsIncomplete + summary.monthlyUsd = planUsage.plan.monthlyUsd + summary.spentApiEquivalentUsd = planUsage.spentApiEquivalentUsd + } + return summary } type JsonPlanSummaryMap = Partial> @@ -384,6 +399,7 @@ function toPlanDisplay(plan: Plan) { return { id: plan.id, monthlyUsd: plan.monthlyUsd, + ...(plan.monthlyCredits != null ? { monthlyCredits: plan.monthlyCredits } : {}), provider: plan.provider, resetDay: clampResetDay(plan.resetDay), setAt: plan.setAt || null, @@ -1703,14 +1719,15 @@ program .description('Show or configure a subscription plan for overage tracking') .option('--format ', 'Output format: text or json', 'text') .option('--monthly-usd ', 'Monthly plan price in USD (for custom)', parseNumber) - .option('--provider ', 'Provider scope: all, claude, codex, cursor') + .option('--credits ', 'Monthly AI credits (copilot custom plans)', parseNumber) + .option('--provider ', `Provider scope: ${PLAN_PROVIDERS.join(', ')}`) .option('--reset-day ', 'Day of month plan resets (1-28)', parseInteger, 1) - .action(async (action?: string, id?: string, opts?: { format?: string; monthlyUsd?: number; provider?: string; resetDay?: number }) => { + .action(async (action?: string, id?: string, opts?: { format?: string; monthlyUsd?: number; credits?: number; provider?: string; resetDay?: number }) => { assertFormat(opts?.format ?? 'text', ['text', 'json'], 'plan') const mode = action ?? 'show' const providerOption = opts?.provider if (providerOption !== undefined && !isPlanProvider(providerOption)) { - console.error(`\n --provider must be one of: all, claude, codex, cursor; got "${providerOption}".\n`) + console.error(`\n --provider must be one of: ${PLAN_PROVIDERS.join(', ')}; got "${providerOption}".\n`) process.exitCode = 1 return } @@ -1739,7 +1756,7 @@ program console.log(`\n Plans: ${plans.length}`) for (const plan of plans) { console.log(` ${plan.provider}: ${planLabel(plan)} (${plan.id})`) - console.log(` Budget: $${plan.monthlyUsd}/month`) + console.log(` Budget: ${plan.provider === 'copilot' && plan.monthlyCredits != null ? `${plan.monthlyCredits} AI Credits` : `$${plan.monthlyUsd}/month`}`) console.log(` Reset day: ${clampResetDay(plan.resetDay)}`) if (plan.setAt) console.log(` Set at: ${plan.setAt}`) } @@ -1787,18 +1804,56 @@ program } if (id === 'custom') { - if (opts?.monthlyUsd === undefined) { + const credits = opts?.credits + const monthlyUsdOpt = opts?.monthlyUsd + const provider = providerOption ?? 'all' + + if (credits !== undefined && provider !== 'copilot') { + console.error('\n --credits is only valid with --provider copilot.\n') + process.exitCode = 1 + return + } + + if (provider === 'copilot') { + if (monthlyUsdOpt !== undefined) { + console.error('\n Copilot custom plans take --credits, not --monthly-usd (units mixed).\n') + process.exitCode = 1 + return + } + if (credits === undefined) { + console.error('\n Custom copilot plans require --credits .\n') + process.exitCode = 1 + return + } + if (!Number.isFinite(credits) || credits <= 0) { + console.error(`\n --credits must be a positive finite number; got ${credits}.\n`) + process.exitCode = 1 + return + } + await savePlan({ + id: 'custom', + monthlyCredits: credits, + monthlyUsd: credits * 0.01, + provider: 'copilot', + resetDay, + setAt: new Date().toISOString(), + }) + console.log(`\n Plan set to custom (${credits} AI Credits, copilot, reset day ${resetDay}).`) + console.log(` Config saved to ${getConfigFilePath()}\n`) + return + } + + if (monthlyUsdOpt === undefined) { console.error('\n Custom plans require --monthly-usd .\n') process.exitCode = 1 return } - const monthlyUsd = opts.monthlyUsd + const monthlyUsd = monthlyUsdOpt if (!Number.isFinite(monthlyUsd) || monthlyUsd <= 0) { - console.error(`\n --monthly-usd must be a positive number; got ${opts.monthlyUsd}.\n`) + console.error(`\n --monthly-usd must be a positive number; got ${monthlyUsdOpt}.\n`) process.exitCode = 1 return } - const provider = providerOption ?? 'all' await savePlan({ id: 'custom', monthlyUsd, diff --git a/src/models.ts b/src/models.ts index 652a1924..775d680e 100644 --- a/src/models.ts +++ b/src/models.ts @@ -290,8 +290,9 @@ export async function loadPricing(): Promise { // Known model name variants that providers emit but LiteLLM/fallback don't index under. // OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last). -// getCanonicalName strips a KNOWN vendor/router prefix first, so only the -// post-strip forms need to be listed here. +// getCanonicalName strips a KNOWN vendor/router prefix first unless the +// full cleaned id itself is an alias (orcarouter/fusion). Post-strip forms +// still cover every other entry here. const BUILTIN_ALIASES: Record = { 'anthropic--claude-4.6-opus': 'claude-opus-4-6', 'anthropic--claude-4.6-sonnet': 'claude-sonnet-4-6', @@ -344,6 +345,14 @@ const BUILTIN_ALIASES: Record = { 'claude-4-7-opus-xhigh': 'claude-opus-4-7', 'claude-4-7-opus-xhigh-fast': 'claude-opus-4-7', 'qwen-auto': 'claude-sonnet-4-5', + // OrcaRouter fusion routes. Provenance: live OrcaRouter completion `model` + // field, 2026-08 (community #1058 / house #1118). Re-verify if the gateway + // rotates targets. `orcarouter/auto` is intentionally unaliased: the smart + // route currently lands on a Qwen/Llama flash model, so a Sonnet alias + // would overprice ~3–30×. Fail closed until a live probe pins that target. + 'orcarouter/fusion': 'openai/gpt-oss-120b', + 'orcarouter/fusion-flash': 'openai/gpt-oss-120b', + 'orcarouter/fusion-mini': 'openai/gpt-oss-120b', 'kimi-auto': 'kimi-k2-thinking', 'kimi-code': 'kimi-k2-thinking', 'kimi-for-coding': 'kimi-k2-thinking', @@ -774,12 +783,21 @@ function resolveAlias(model: string): string { return model } function getCanonicalName(model: string): string { - return stripKnownFirstNamespace( - model - .replace(/@.*$/, '') - .replace(/-\d{8}$/, '') - .replace(/\[[^\]]*\]$/, ''), - ) + const cleaned = model + .replace(/@.*$/, '') + .replace(/-\d{8}$/, '') + .replace(/\[[^\]]*\]$/, '') + // Full-id aliases (orcarouter/fusion) must stay visible so resolveAlias can + // see them. Stripping first would leave a leaf (`fusion`) with no mapping. + // Nested wrappers without an alias still peel as before. + if (Object.hasOwn(userAliases, cleaned) || Object.hasOwn(BUILTIN_ALIASES, cleaned)) { + return cleaned + } + const lowercase = cleaned.toLowerCase() + if (lowercase !== cleaned && Object.hasOwn(BUILTIN_ALIASES, lowercase)) { + return cleaned + } + return stripKnownFirstNamespace(cleaned) } /// Alias-resolved identity for report merge. Display names stay cosmetic — @@ -801,7 +819,7 @@ export function resolveCanonicalModelId(model: string): string { // `nousresearch/`, …) is never dropped by a stale list. const EXTRA_NAMESPACES = [ // Routing wrappers (see ROUTER_PREFIXES); no catalog lists them. - 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', + 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter', // LiteLLM route prefixes that never appear as a key prefix. 'litellm_proxy', 'openai_like', // Vendor spellings the catalog indexes under another name: `zhipu` is `z-ai`, @@ -840,6 +858,12 @@ function stripKnownFirstNamespace(model: string): string { // Routing wrappers (OmniRoute, Cline Pass, cmd/, …) are not model ids. // Peel them so any plan/gateway spelling of the same model shares one price. +// OrcaRouter is a gateway that routes to many vendors. Its catalog exposes +// route ids (`orcarouter/auto`, `orcarouter/fusion`, …) and plain vendor ids +// (`deepseek/deepseek-v4-pro`); a route id can also spell a nested upstream +// (`orcarouter/deepseek/deepseek-v4-pro`), and the completion response's +// `model` field reports the upstream id that actually ran. Peeling the prefix +// lets every routed spelling price at the upstream row. const ROUTER_PREFIXES = [ /^omniroute:/i, /^cp\//i, @@ -847,6 +871,7 @@ const ROUTER_PREFIXES = [ /^cline-free\//i, /^cmd\//i, /^antigravity\//i, + /^orcarouter\//i, // `xiaomi/` is NOT peeled: it is the vendor namespace LiteLLM prices under, // and BUILTIN_ALIASES maps the bare MiMo ids INTO it. Peeling would pull the // opposite way. It stays a known namespace via the catalog-derived set. diff --git a/src/parser.ts b/src/parser.ts index 4d549520..572b7cdf 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -2504,6 +2504,7 @@ function providerCallToTurn(call: ParsedProviderCall): ParsedTurn { bashCommands: call.bashCommands, deduplicationKey: call.deduplicationKey, isEstimated: call.costIsEstimated, + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), }) const prRefs = extractPrUrlsFromText(call.userMessage) @@ -2596,6 +2597,7 @@ function apiCallToCachedCall(call: ParsedApiCall): CachedCall { ...(call.interrupted ? { interrupted: true } : {}), ...(call.userModified ? { userModified: true } : {}), ...(call.toolErrors ? { toolErrors: call.toolErrors } : {}), + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, @@ -2716,6 +2718,7 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall { activeDurationMs: call.activeDurationMs, activeGeneratedTokens: call.activeGeneratedTokens, toolWaitMs: call.toolWaitMs, + ...(call.nanoAiu != null ? { nanoAiu: call.nanoAiu } : {}), ...(call.supplementaryAccounting || isHermesObservationKey(call.deduplicationKey) ? { supplementaryAccounting: true } : {}), diff --git a/src/plan-usage.ts b/src/plan-usage.ts index 85444124..50a14211 100644 --- a/src/plan-usage.ts +++ b/src/plan-usage.ts @@ -1,8 +1,9 @@ import { behavioralCallCount } from './behavioral-weight.js' import { readPlans, type Plan, type PlanMap } from './config.js' +import { creditsToUsd, isFiniteNanoAiu, nanoAiuToCredits } from './copilot-aiu.js' import { parseAllSessions } from './parser.js' import { PLAN_PROVIDERS } from './plans.js' -import type { DateRange, ProjectSummary } from './types.js' +import type { DateRange, ParsedApiCall, ProjectSummary } from './types.js' const MS_PER_DAY = 24 * 60 * 60 * 1000 const PLAN_NEAR_THRESHOLD_PCT = 80 @@ -19,6 +20,10 @@ export type PlanUsage = { status: PlanStatus projectedMonthUsd: number daysUntilReset: number + // Copilot credit-plan fields. Absent on Claude / cursor / grok / custom-USD. + spentCredits?: number + budgetCredits?: number + creditsIncomplete?: boolean } export function clampResetDay(resetDay: number | undefined): number { @@ -69,12 +74,55 @@ function diffCalendarDays(from: Date, to: Date): number { return toDayIndex(to) - toDayIndex(from) } +export function isCopilotCreditsPlan(plan: Plan): boolean { + return plan.provider === 'copilot' +} + +function planCallSpend(plan: Plan, call: { costUSD: number; nanoAiu?: number }): number { + if (!isCopilotCreditsPlan(plan)) return call.costUSD + return isFiniteNanoAiu(call.nanoAiu) ? creditsToUsd(nanoAiuToCredits(call.nanoAiu)) : 0 +} + +function forEachPlanSession(projects: ProjectSummary[], visit: (calls: ParsedApiCall[]) => void): void { + for (const project of projects) { + for (const session of project.sessions ?? []) { + const calls: ParsedApiCall[] = [] + for (const turn of session.turns ?? []) { + calls.push(...(turn.assistantCalls ?? [])) + } + visit(calls) + } + } +} + +export function copilotCreditSpend(projects: ProjectSummary[]): { spentCredits: number; creditsIncomplete: boolean } { + let nanoSum = 0 + let creditsIncomplete = false + // Pairing is session-wide. foldCopilotSupplementaryTurns will not fold a + // supplementary twin across a local-day boundary, so both nanoAiu rows can + // occupy separate turns of the same session. Close the twin once here. + forEachPlanSession(projects, calls => { + const copilot = calls.filter(call => call.provider === 'copilot') + if (copilot.length === 0) return + const primaryNano = copilot.filter(call => !call.supplementaryAccounting && isFiniteNanoAiu(call.nanoAiu)) + const suppNano = copilot.filter(call => call.supplementaryAccounting && isFiniteNanoAiu(call.nanoAiu)) + // Store rows are supplementary and are the bill when the JSONL twin has + // no nanoAiu. If both sides carry nanoAiu, count the behavioral row only + // so a paired rollup cannot double the credits. + const counted = primaryNano.length > 0 && suppNano.length > 0 ? primaryNano : [...primaryNano, ...suppNano] + for (const call of counted) nanoSum += call.nanoAiu! + if (copilot.some(call => !isFiniteNanoAiu(call.nanoAiu))) creditsIncomplete = true + }) + return { spentCredits: nanoAiuToCredits(nanoSum), creditsIncomplete } +} + export function projectMonthEnd( projects: ProjectSummary[], periodStart: Date, periodEnd: Date, today: Date, spent: number, + spendOf: (call: { costUSD: number; nanoAiu?: number }) => number = (call) => call.costUSD, ): number { const dayCosts = new Map() @@ -88,7 +136,7 @@ export function projectMonthEnd( if (Number.isNaN(ts.getTime())) continue if (ts < periodStart || ts > today) continue const dayKey = toLocalDateKey(ts) - dayCosts.set(dayKey, (dayCosts.get(dayKey) ?? 0) + call.costUSD) + dayCosts.set(dayKey, (dayCosts.get(dayKey) ?? 0) + spendOf(call)) } } } @@ -110,12 +158,36 @@ export function projectMonthEnd( export function getPlanUsageFromProjects(plan: Plan, projects: ProjectSummary[], today = new Date()): PlanUsage { const { periodStart, periodEnd } = computePeriodFromResetDay(plan.resetDay, today) - const spent = projects.reduce((sum, p) => sum + p.totalCostUSD, 0) const budgetUsd = plan.monthlyUsd + const daysUntilReset = Math.max(0, diffCalendarDays(today, periodEnd)) + + if (isCopilotCreditsPlan(plan)) { + const { spentCredits, creditsIncomplete } = copilotCreditSpend(projects) + const budgetCredits = plan.monthlyCredits ?? 0 + const percentUsed = budgetCredits > 0 ? (spentCredits / budgetCredits) * 100 : 0 + const spent = creditsToUsd(spentCredits) + const status: PlanStatus = percentUsed > 100 ? 'over' : percentUsed >= PLAN_NEAR_THRESHOLD_PCT ? 'near' : 'under' + const projectedMonthUsd = projectMonthEnd(projects, periodStart, periodEnd, today, spent, call => planCallSpend(plan, call)) + return { + plan, + periodStart, + periodEnd, + spentApiEquivalentUsd: spent, + budgetUsd, + percentUsed, + status, + projectedMonthUsd, + daysUntilReset, + spentCredits, + budgetCredits, + creditsIncomplete, + } + } + + const spent = projects.reduce((sum, p) => sum + p.totalCostUSD, 0) const percentUsed = budgetUsd > 0 ? (spent / budgetUsd) * 100 : 0 const status: PlanStatus = percentUsed > 100 ? 'over' : percentUsed >= PLAN_NEAR_THRESHOLD_PCT ? 'near' : 'under' const projectedMonthUsd = projectMonthEnd(projects, periodStart, periodEnd, today, spent) - const daysUntilReset = Math.max(0, diffCalendarDays(today, periodEnd)) return { plan, @@ -157,17 +229,23 @@ export function getPlanScopedProjects(plan: Plan, projects: ProjectSummary[], to (sum, turn) => sum + turn.assistantCalls.reduce((turnSum, call) => turnSum + call.costUSD, 0), 0, ) + const hasNanoAiu = turns.some(turn => turn.assistantCalls.some(call => isFiniteNanoAiu(call.nanoAiu))) const apiCalls = turns.reduce((sum, turn) => sum + behavioralCallCount(turn.assistantCalls), 0) // Keep on cost as well as calls: a copilot rollup-only session has // zero behavioral calls but real spend, and dropping it would erase - // that spend from the plan window. - return apiCalls > 0 || totalCostUSD > 0 ? { ...session, turns, totalCostUSD, apiCalls } : null + // that spend from the plan window. A store-row with nanoAiu and $0 + // token cost still has to reach credit math — but only on a copilot + // credit plan. Claude/cursor/grok USD plans keep the old + // cost-or-calls predicate so a $0 nanoAiu-only session is not an + // unannounced retain on providers this PR is not about. + const keepForCredits = isCopilotCreditsPlan(plan) && hasNanoAiu + return apiCalls > 0 || totalCostUSD > 0 || keepForCredits ? { ...session, turns, totalCostUSD, apiCalls } : null }) .filter((session): session is NonNullable => session !== null) const totalCostUSD = sessions.reduce((sum, session) => sum + session.totalCostUSD, 0) const totalApiCalls = sessions.reduce((sum, session) => sum + session.apiCalls, 0) - return totalApiCalls > 0 || totalCostUSD > 0 ? { ...project, sessions, totalCostUSD, totalApiCalls } : null + return sessions.length > 0 ? { ...project, sessions, totalCostUSD, totalApiCalls } : null }) .filter((project): project is NonNullable => project !== null) } diff --git a/src/plans.ts b/src/plans.ts index e384e75c..7488c3a1 100644 --- a/src/plans.ts +++ b/src/plans.ts @@ -1,9 +1,19 @@ import type { Plan, PlanId, PlanProvider } from './config.js' +import { AI_CREDIT_USD } from './copilot-aiu.js' -export const PLAN_PROVIDERS: PlanProvider[] = ['all', 'claude', 'codex', 'cursor', 'grok'] -export const PLAN_IDS: PlanId[] = ['claude-pro', 'claude-max', 'claude-max-5x', 'cursor-pro', 'supergrok', 'supergrok-heavy', 'custom', 'none'] +export const PLAN_PROVIDERS: PlanProvider[] = ['all', 'claude', 'codex', 'cursor', 'grok', 'copilot'] +export const PLAN_IDS: PlanId[] = ['claude-pro', 'claude-max', 'claude-max-5x', 'cursor-pro', 'supergrok', 'supergrok-heavy', 'copilot-pro', 'copilot-pro-plus', 'copilot-max', 'custom', 'none'] -export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy', Omit> = { +// Official Copilot individual allotments from GitHub Docs, *Usage-based +// billing for individuals*, fetched 2026-08-23. Flex is documented as +// variable — pin this table, do not invent a later flex number. +// https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals +// monthlyUsd is credits × $0.01 (the budget equivalent), not the sticker price. +const COPILOT_PRO_CREDITS = 1500 +const COPILOT_PRO_PLUS_CREDITS = 7000 +const COPILOT_MAX_CREDITS = 20000 + +export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' | 'cursor-pro' | 'supergrok' | 'supergrok-heavy' | 'copilot-pro' | 'copilot-pro-plus' | 'copilot-max', Omit> = { 'claude-pro': { id: 'claude-pro', monthlyUsd: 20, @@ -40,6 +50,27 @@ export const PRESET_PLANS: Record<'claude-pro' | 'claude-max' | 'claude-max-5x' provider: 'grok', resetDay: 1, }, + 'copilot-pro': { + id: 'copilot-pro', + monthlyCredits: COPILOT_PRO_CREDITS, + monthlyUsd: COPILOT_PRO_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, + 'copilot-pro-plus': { + id: 'copilot-pro-plus', + monthlyCredits: COPILOT_PRO_PLUS_CREDITS, + monthlyUsd: COPILOT_PRO_PLUS_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, + 'copilot-max': { + id: 'copilot-max', + monthlyCredits: COPILOT_MAX_CREDITS, + monthlyUsd: COPILOT_MAX_CREDITS * AI_CREDIT_USD, + provider: 'copilot', + resetDay: 1, + }, } export function isPlanProvider(value: string): value is PlanProvider { @@ -71,6 +102,12 @@ export function planDisplayName(id: PlanId): string { return 'SuperGrok' case 'supergrok-heavy': return 'SuperGrok Heavy' + case 'copilot-pro': + return 'Copilot Pro' + case 'copilot-pro-plus': + return 'Copilot Pro+' + case 'copilot-max': + return 'Copilot Max' case 'custom': return 'Custom' case 'none': diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 71bc9a28..fb1d4978 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -1,7 +1,7 @@ import { readdir, stat } from 'fs/promises' import { createReadStream } from 'fs' import { createInterface } from 'readline' -import { basename, join } from 'path' +import { basename, join, resolve } from 'path' import { homedir } from 'os' import { FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from '../fs-utils.js' @@ -12,6 +12,7 @@ import { normalizeContentBlocks } from '../content-utils.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { ToolCall } from '../types.js' import type { Provider, ProbeRoot, SessionSource, SessionParser, ParsedProviderCall } from './types.js' +import { defaultBilledCodexHome, defaultLauncherRoots, FIRST_LINE_READ_CAP, isNestedLauncherCodexHome, listRolloutSessionIds, rolloutFileSessionId, sameCodexHome } from '../launcher-homes.js' const modelDisplayNames: Record = { 'codex-auto-review': 'Codex Auto Review', @@ -177,7 +178,7 @@ function sanitizeProject(cwd: string): string { // Cap how many bytes we'll read while looking for the first newline. Real // Codex session_meta lines are ~22-27 KB; this leaves plenty of headroom while // keeping memory bounded if a corrupt file has no newline at all. -const FIRST_LINE_READ_CAP = 1024 * 1024 +// FIRST_LINE_READ_CAP is shared with rolloutFileSessionId. async function readFirstLine(filePath: string): Promise { // Codex CLI 0.128+ writes a session_meta line that can exceed 20 KB because @@ -1328,8 +1329,40 @@ export async function parseCodexFileFull(source: SessionSource, seenKeys: Set { + const id = rolloutFileSessionId(source.path) + return !(id && billedIds.has(id)) + }) +} + +export function createCodexProvider( + codexDir?: string, + opts?: { primaryDir?: string; launcherRoots?: string[] }, +): Provider { const dir = getCodexDir(codexDir) + const primaryDir = opts?.primaryDir ?? defaultBilledCodexHome() + const launcherRoots = opts?.launcherRoots ?? defaultLauncherRoots() + // Explicit nest factory whose path is a realpath alias of the billed home: + // empty so a second factory cannot double-count the same tree. The no-arg + // singleton must not take this branch — CODEX_HOME may be that alias. + const duplicateHome = + codexDir !== undefined && + sameCodexHome(dir, primaryDir) && + resolve(dir) !== resolve(primaryDir) + const nestHome = isNestedLauncherCodexHome(dir, { primaryDir, launcherRoots }) + // Production `codex` singleton is createCodexProvider() with no args. When + // the resolved dir is a launcher nest and ~/.codex is a distinct existing + // tree, walk BOTH and drop nest sources whose session id is already billed. + const scanBoth = nestHome && codexDir === undefined return { name: 'codex', @@ -1346,17 +1379,25 @@ export function createCodexProvider(codexDir?: string): Provider { return toolNameMap[rawTool] ?? rawTool }, - // Same `dir` discoverSessionsInDir walks: /sessions (dated - // rollout files) and /archived_sessions. Honors CODEX_HOME. + // Trees discoverSessions actually walks. Honors CODEX_HOME; when the + // production singleton scans nest + billed home, both appear here. async probeRoots(): Promise { - return [ - { path: join(dir, 'sessions'), label: 'sessions' }, - { path: join(dir, 'archived_sessions'), label: 'archived' }, - ] + if (duplicateHome) return [] + if (scanBoth) return [...rootsFor(primaryDir), ...rootsFor(dir)] + return rootsFor(dir) }, async discoverSessions(): Promise { - return discoverSessionsInDir(dir) + // Same physical tree via two factories is complete overlap, not a + // distinct nest. isNestedLauncherCodexHome is false in that case. + if (duplicateHome) return [] + const sources = await discoverSessionsInDir(dir) + if (scanBoth) { + const billed = await discoverSessionsInDir(primaryDir) + return [...billed, ...dropOverlappingNestSources(sources, primaryDir)] + } + if (!nestHome) return sources + return dropOverlappingNestSources(sources, primaryDir) }, createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { diff --git a/src/providers/types.ts b/src/providers/types.ts index 45e5456b..52f68196 100644 --- a/src/providers/types.ts +++ b/src/providers/types.ts @@ -67,11 +67,10 @@ export type ParsedProviderCall = { // starts the leg's store-row subtraction interval here instead of at the // previous leg. Omitted when the leg contains no compaction. compactedAt?: string - // Copilot session-store billing metadata, captured only — no report consumes - // these yet (pricing/display design is upstream #890). total_nano_aiu is the - // request's charged AI-credit amount in nano-AIU (1e9 nano-AIU = 1 credit = - // $0.01); request_multiplier is the model's plan multiplier. Captured now so - // a future consumer needs no re-parse of rows the CLI may prune meanwhile. + // Copilot session-store billing metadata. total_nano_aiu is the request's + // charged AI-credit amount in nano-AIU (1e9 nano-AIU = 1 credit = $0.01); + // plan math sums finite nanoAiu. request_multiplier stays capture-only + // (billing-grade cost rewrite is upstream #890). nanoAiu?: number requestMultiplier?: number turnId?: string diff --git a/src/session-cache.ts b/src/session-cache.ts index 52806d4f..672c46eb 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -56,9 +56,9 @@ export type CachedCall = { activeDurationMs?: number activeGeneratedTokens?: number toolWaitMs?: number - // Copilot session-store billing metadata (capture-only; no report consumes - // these yet — see ParsedProviderCall). Omitted when the store's schema - // predates the columns. + // Copilot session-store billing metadata. Plan math reads nanoAiu (1e9 = 1 + // credit). requestMultiplier stays capture-only. Omitted when the store's + // schema predates the columns. nanoAiu?: number requestMultiplier?: number // Copilot shutdown rollups only: stamp of the last successful in-session diff --git a/src/sync/cli.ts b/src/sync/cli.ts index 1c40ec1d..509a112f 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -23,7 +23,7 @@ import { import { createCredentialStore } from './credentials.js' import { readSyncConfig, writeSyncConfig, deleteSyncConfig, updateLastSync } from './config.js' import { collectUnsentCalls, collectUnsentAttribution, sendBatches, sendAttributionBatches, batchCalls, MAX_PER_PUSH, MAX_ATTRIBUTION_PER_PUSH, type PushResult } from './push.js' -import { batchAttributionItems } from './otlp.js' +import { batchAttributionItems, wireProjectName } from './otlp.js' export function registerSyncCommands(program: Command): void { const sync = program @@ -274,7 +274,8 @@ export function registerSyncCommands(program: Command): void { process.exit(1) } const { range } = getDateRange(period) - const projects = await parseAllSessions(range) + const projects = (await parseAllSessions(range)) + .map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) })) // Flatten + filter against sent-ledger const { allCalls, unsent, held, frozen } = collectUnsentCalls(projects) diff --git a/src/sync/otlp.ts b/src/sync/otlp.ts index c41271ed..962fcde9 100644 --- a/src/sync/otlp.ts +++ b/src/sync/otlp.ts @@ -10,6 +10,7 @@ import { hostname, userInfo } from 'os' import { posix, win32 } from 'path' import { isTrustedAbsoluteWorkingDirectory } from '../path-privacy.js' import type { ParsedApiCall } from '../types.js' +import { billableOutputTokens } from '../models.js' import type { SessionAttributionRecord } from '../yield.js' export interface OtlpSpan { @@ -67,6 +68,16 @@ export function deriveTraceId(sessionId: string): string { return createHash('sha256').update(sessionId).digest('hex').slice(0, 32) } +/** + * Wire-safe project identity: the leaf directory name. Several providers key a + * project by its sanitized absolute path ("-Users-me-Projects-app"), and + * docs/sync/README.md promises file paths stay local. + */ +export function wireProjectName(projectPath: string, fallback: string): string { + const normalized = projectPath.trim().replace(/\\/g, '/').replace(/\/+$/, '') + return normalized.split('/').filter(Boolean).pop() ?? fallback +} + // --- Timestamp conversion --- function toUnixNano(isoTimestamp: string): string { @@ -184,7 +195,10 @@ export function buildOtlpPayload(calls: CallWithSession[]): OtlpPayload { { key: 'ai.provider', value: { stringValue: provider } }, { key: 'ai.model', value: { stringValue: model } }, { key: 'ai.input_tokens', value: { intValue: String(call.usage.inputTokens) } }, - { key: 'ai.output_tokens', value: { intValue: String(call.usage.outputTokens) } }, + // Billable output, not raw: for providers that bill reasoning separately + // the raw output under-reports by the reasoning volume. Same routing the + // display layer adopted in #1115/#1116. + { key: 'ai.output_tokens', value: { intValue: String(billableOutputTokens(call.provider, call.usage.outputTokens, call.usage.reasoningTokens)) } }, { key: 'ai.cost_usd', value: { doubleValue: call.costUSD } }, { key: 'ai.speed', value: { stringValue: call.speed } }, ] diff --git a/src/types.ts b/src/types.ts index f869fd65..5c12ab2e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -163,6 +163,10 @@ export type ParsedApiCall = { /// model-call / turn counts. Hermes deltas persist the flag on CachedCall; /// Copilot remains serve-time / never cached. supplementaryAccounting?: boolean + /// 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. + nanoAiu?: number } export type ToolCall = { diff --git a/tests/cli-plan.test.ts b/tests/cli-plan.test.ts index 14e2b121..cae7d051 100644 --- a/tests/cli-plan.test.ts +++ b/tests/cli-plan.test.ts @@ -147,4 +147,55 @@ describe('codeburn plan command', () => { await rm(home, { recursive: true, force: true }) } }, CLI_PLAN_TIMEOUT_MS) + + it('sets copilot-pro as 1500 credits / $15 equivalent', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-plan-')) + + try { + const result = runCli(['plan', 'set', 'copilot-pro'], home) + expect(result.status).toBe(0) + + const configPath = join(home, '.config', 'codeburn', 'config.json') + const config = JSON.parse(await readFile(configPath, 'utf-8')) as { + plans?: { copilot?: { id?: string; monthlyCredits?: number; monthlyUsd?: number; provider?: string; resetDay?: number } } + } + expect(config.plans?.copilot).toMatchObject({ + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + }) + } finally { + await rm(home, { recursive: true, force: true }) + } + }, CLI_PLAN_TIMEOUT_MS) + + it('writes custom copilot credits and rejects mixed units', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-plan-')) + + try { + const ok = runCli(['plan', 'set', 'custom', '--credits', '20000', '--provider', 'copilot'], home) + expect(ok.status).toBe(0) + const configPath = join(home, '.config', 'codeburn', 'config.json') + const config = JSON.parse(await readFile(configPath, 'utf-8')) as { + plans?: { copilot?: { monthlyCredits?: number; monthlyUsd?: number; provider?: string } } + } + expect(config.plans?.copilot).toMatchObject({ + monthlyCredits: 20000, + monthlyUsd: 200, + provider: 'copilot', + }) + + const mixed = runCli(['plan', 'set', 'custom', '--monthly-usd', '200', '--provider', 'copilot'], home) + expect(mixed.status).not.toBe(0) + expect(mixed.stderr).toContain('units mixed') + + const wrongProvider = runCli(['plan', 'set', 'custom', '--credits', '20000', '--provider', 'claude'], home) + expect(wrongProvider.status).not.toBe(0) + expect(wrongProvider.stderr).toContain('--credits is only valid with --provider copilot') + } finally { + await rm(home, { recursive: true, force: true }) + } + }, CLI_PLAN_TIMEOUT_MS) }) diff --git a/tests/copilot-aiu-serve.test.ts b/tests/copilot-aiu-serve.test.ts new file mode 100644 index 00000000..5d502a3f --- /dev/null +++ b/tests/copilot-aiu-serve.test.ts @@ -0,0 +1,93 @@ +// Serve-hole proof for #943: CachedCall.nanoAiu already survives disk. +// cachedCallToApiCall must thread it onto ParsedApiCall with no CACHE_VERSION bump. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mkdtemp, rm } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { createRequire } from 'node:module' + +import { isSqliteAvailable } from '../src/sqlite.js' +import { CACHE_VERSION, clearLoadCacheMemo } from '../src/session-cache.js' +import { clearSessionCache, parseAllSessions } from '../src/parser.js' + +const requireForTest = createRequire(import.meta.url) +type TestDb = { + exec(sql: string): void + prepare(sql: string): { run(...p: unknown[]): void } + close(): void +} + +function collectNanoAiu(projects: Awaited>): number[] { + return projects + .flatMap(p => p.sessions) + .flatMap(s => s.turns) + .flatMap(t => t.assistantCalls) + .map(c => c.nanoAiu) + .filter((n): n is number => typeof n === 'number') +} + +describe.skipIf(!isSqliteAvailable())('cachedCallToApiCall threads nanoAiu', () => { + let tmpHome: string + let tmpCache: string + let dbPath: string + + beforeEach(async () => { + tmpHome = await mkdtemp(join(tmpdir(), 'cb-aiu-serve-home-')) + tmpCache = await mkdtemp(join(tmpdir(), 'cb-aiu-serve-cache-')) + dbPath = join(tmpHome, 'session-store.db') + + process.env['HOME'] = tmpHome + process.env['USERPROFILE'] = tmpHome + process.env['CODEBURN_CACHE_DIR'] = tmpCache + process.env['CODEBURN_COPILOT_SESSION_STORE_DB'] = dbPath + process.env['CODEBURN_COPILOT_DISABLE_OTEL'] = '1' + process.env['CODEBURN_COPILOT_SESSION_STATE_DIR'] = join(tmpHome, 'no-jsonl') + process.env['CODEBURN_COPILOT_WS_STORAGE_DIR'] = join(tmpHome, 'no-ws') + process.env['CODEBURN_COPILOT_GLOBAL_STORAGE_DIR'] = join(tmpHome, 'no-global') + process.env['CODEBURN_COPILOT_JETBRAINS_DIR'] = join(tmpHome, 'no-jb') + + const { DatabaseSync } = requireForTest('node:sqlite') as { DatabaseSync: new (path: string) => TestDb } + const db = new DatabaseSync(dbPath) + db.exec(` + CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, repository TEXT, branch TEXT, created_at TEXT DEFAULT (datetime('now'))); + CREATE TABLE assistant_usage_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL REFERENCES sessions(id), + model TEXT NOT NULL, + input_tokens INTEGER, output_tokens INTEGER, + cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER, + total_nano_aiu INTEGER, request_multiplier REAL, + created_at TEXT DEFAULT (datetime('now')) + ); + `) + db.prepare(`INSERT INTO sessions (id, cwd) VALUES ('sess-aiu', '/tmp/codeburn')`).run() + db.prepare( + `INSERT INTO assistant_usage_events + (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, total_nano_aiu, request_multiplier, created_at) + VALUES ('sess-aiu', 'claude-sonnet-4-5', 1000, 20, 600, 300, 0, 1500000000, 1.0, '2026-08-05T12:00:00.000Z')`, + ).run() + db.close() + }) + + afterEach(async () => { + clearSessionCache() + clearLoadCacheMemo() + await rm(tmpHome, { recursive: true, force: true }) + await rm(tmpCache, { recursive: true, force: true }) + }) + + it('serves nanoAiu on a cold parse and a warm cache read without a CACHE_VERSION bump', async () => { + expect(CACHE_VERSION).toBe(9) + + clearSessionCache() + const cold = await parseAllSessions(undefined, 'copilot') + expect(collectNanoAiu(cold)).toEqual([1_500_000_000]) + + // Drop the in-memory memo only. Disk cache now serves via cachedCallToApiCall. + clearSessionCache() + const warm = await parseAllSessions(undefined, 'copilot') + expect(collectNanoAiu(warm)).toEqual([1_500_000_000]) + expect(CACHE_VERSION).toBe(9) + }) +}) diff --git a/tests/copilot-aiu.test.ts b/tests/copilot-aiu.test.ts new file mode 100644 index 00000000..88d9f9b9 --- /dev/null +++ b/tests/copilot-aiu.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest' + +import { AI_CREDIT_USD, creditsToUsd, isFiniteNanoAiu, nanoAiuToCredits } from '../src/copilot-aiu.js' + +describe('copilot AIU helpers', () => { + it('converts 1.5e9 nano-AIU to 1.5 credits and $0.015', () => { + expect(nanoAiuToCredits(1_500_000_000)).toBe(1.5) + expect(creditsToUsd(1.5)).toBeCloseTo(0.015, 12) + expect(1.5 / 1500 * 100).toBeCloseTo(0.1, 12) + expect(1.5 * AI_CREDIT_USD).toBeCloseTo(0.015, 12) + }) + + it('accepts only finite nanoAiu', () => { + expect(isFiniteNanoAiu(1_500_000_000)).toBe(true) + expect(isFiniteNanoAiu(0)).toBe(true) + expect(isFiniteNanoAiu(undefined)).toBe(false) + expect(isFiniteNanoAiu(Number.NaN)).toBe(false) + expect(isFiniteNanoAiu(Number.POSITIVE_INFINITY)).toBe(false) + }) +}) diff --git a/tests/daily-cache-degraded-completeness.test.ts b/tests/daily-cache-degraded-completeness.test.ts index d3df6cce..af7f2573 100644 --- a/tests/daily-cache-degraded-completeness.test.ts +++ b/tests/daily-cache-degraded-completeness.test.ts @@ -14,6 +14,7 @@ import { currentTzKey, ensureCacheHydrated, saveDailyCache, + toDateString, } from '../src/daily-cache.js' const TMP_CACHE_ROOT = join(tmpdir(), `codeburn-degraded-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`) @@ -185,3 +186,92 @@ describe('daily cache: a complete cache that outruns its own data is not trusted expect(out.complete).toBe(true) }) }) + +/// A day whose only content is turn-anchored residue: one straddling turn's +/// category counts, zero cost/calls/sessions/tokens (isTurnResidueOnly). +function residueDay(date: string): DailyEntry { + return day(date, {}, { + categories: { conversation: { turns: 1, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 } }, + }) +} + +describe('daily cache: the gap path never shrinks a populated baseline day', () => { + // A populated baseline day inside the gap window (carried there by an older + // cache generation while the watermark sat behind it). The gap parse + // under-reads it: 5 calls / $5 where the baseline holds 500 / $50. + async function seedGapDay(): Promise { + await seed({ + days: [ + VANISHED, + day(daysAgoStr(4), { claude: slice(120, 900) }), + day(daysAgoStr(2), { claude: slice(50, 500), grok: slice(9, 60) }), + ], + }) + } + + it('a partial gap parse only fills what the baseline lacks', async () => { + await seedGapDay() + const underRead = [day(daysAgoStr(2), { claude: slice(5, 10) })] + const out = await ensureCacheHydrated(noSessions, () => underRead, 'cfg-A', () => false) + const kept = out.days.find(d => d.date === daysAgoStr(2))! + // Baseline wins wholesale: the partial parse's undercount must not replace it. + expect(kept.cost).toBe(59) + expect(kept.calls).toBe(560) + expect(kept.providers['claude']).toMatchObject({ cost: 50, calls: 500 }) + expect(kept.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + // Watermark held and not finalized, so a later complete parse re-covers the gap. + expect(out.lastComputedDate).toBe(daysAgoStr(4)) + expect(out.complete).toBe(false) + expectPreserved(out) + }) + + it('a complete gap parse still wins per (date, provider)', async () => { + await seedGapDay() + const fresh = [day(daysAgoStr(2), { claude: slice(75, 620) })] + const out = await ensureCacheHydrated(noSessions, () => fresh, 'cfg-A', () => true) + const rederived = out.days.find(d => d.date === daysAgoStr(2))! + // The fresh claude slice replaces the baseline one; the grok slice the + // parse did not produce is carried, not wiped. + expect(rederived.providers['claude']).toMatchObject({ cost: 75, calls: 620 }) + expect(rederived.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + expect(rederived.cost).toBe(84) + expect(rederived.calls).toBe(680) + expect(out.days.map(d => d.date)).toEqual([daysAgoStr(40), daysAgoStr(4), daysAgoStr(2)]) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + expectPreserved(out) + }) +}) + +describe('daily cache: a residue-only day is re-derived, not served', () => { + it('pulls the watermark back to just before the residue day so the gap parse re-derives it', async () => { + // The broken-cache shape issue #1127 leaves behind: complete and stamped, + // watermark at yesterday, and a residue-only day sealed behind it. The + // oldest-day exemption does not apply (an older populated day exists) and + // the residue day is inside the settle window. + await seed({ + lastComputedDate: daysAgoStr(1), + watermarkTrusted: true, + days: [day(daysAgoStr(10), { claude: slice(80, 700) }), residueDay(daysAgoStr(3))], + }) + const ranges: DateRange[] = [] + const rederived = [day(daysAgoStr(3), { claude: slice(33, 210) })] + const out = await ensureCacheHydrated( + async (range) => { ranges.push(range); return [] }, + () => rederived, + 'cfg-A', + () => true, + ) + // The watermark moved back to daysAgoStr(4), so the gap parse started on + // the residue day itself instead of skipping it forever. + expect(ranges).toHaveLength(1) + expect(toDateString(ranges[0]!.start)).toBe(daysAgoStr(3)) + const healed = out.days.find(d => d.date === daysAgoStr(3))! + expect(healed.providers['claude']).toMatchObject({ cost: 33, calls: 210 }) + expect(healed.cost).toBe(33) + expect(healed.calls).toBe(210) + expect(out.days.find(d => d.date === daysAgoStr(10))).toMatchObject({ cost: 80, calls: 700 }) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + }) +}) diff --git a/tests/day-aggregator.test.ts b/tests/day-aggregator.test.ts index f561a877..874dee97 100644 --- a/tests/day-aggregator.test.ts +++ b/tests/day-aggregator.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { aggregateProjectsIntoDays, buildPeriodDataFromDays, dateKey } from '../src/day-aggregator.js' +import { isTurnResidueOnly } from '../src/daily-cache.js' import type { ProjectSummary } from '../src/types.js' function makeProject(overrides: Partial & { sessions: ProjectSummary['sessions'] }): ProjectSummary { @@ -220,6 +221,65 @@ describe('aggregateProjectsIntoDays', () => { expect(days[0]!.providers).toEqual({}) }) + it("pins the residue shape: a sliced straddling turn leaves turn counts but zero cost/calls on the anchor day", () => { + // The contract isTurnResidueOnly keys off (issue #1127). A history parse + // that ends at midnight slices a straddling turn to its in-range calls; + // when the surviving half carries the turn-level judgments (category, + // editTurns) onto day A but every call landed on day B, day A is left + // holding ONLY residue: categories.conversation.turns === 1 with + // cost/calls/sessions all 0. Construct in LOCAL time so the turn + // genuinely straddles local midnight on any machine TZ. + const iso = (y: number, mo: number, d: number, h: number, mi: number) => + new Date(y, mo, d, h, mi, 0).toISOString() + const turnTs = iso(2026, 3, 16, 23, 58) // day A, just before midnight + const callTs = iso(2026, 3, 17, 0, 5) // day B: every call past midnight + const dayA = dateKey(turnTs) + const dayB = dateKey(callTs) + expect(dayA).not.toBe(dayB) // sanity: the fixture really straddles local midnight + + const projects: ProjectSummary[] = [ + makeProject({ + sessions: [{ + sessionId: 's1', + project: 'p', + firstTimestamp: callTs, + lastTimestamp: callTs, + totalCostUSD: 6, + totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, + apiCalls: 1, + turns: [ + { + userMessage: 'one more thing before bed', timestamp: turnTs, sessionId: 's1', + category: 'conversation', retries: 0, hasEdits: false, + assistantCalls: [makeCall(callTs, 6)], + }, + ], + modelBreakdown: {}, toolBreakdown: {}, mcpBreakdown: {}, bashBreakdown: {}, + categoryBreakdown: {} as never, + skillBreakdown: {} as never, + }], + }), + ] + + const days = aggregateProjectsIntoDays(projects) + const anchor = days.find(d => d.date === dayA)! + const next = days.find(d => d.date === dayB)! + + // Anchor day: ONLY turn-anchored residue — no cost, calls, sessions, or tokens. + expect(anchor.cost).toBe(0) + expect(anchor.calls).toBe(0) + expect(anchor.sessions).toBe(0) + expect(anchor.inputTokens + anchor.outputTokens + anchor.cacheReadTokens + anchor.cacheWriteTokens).toBe(0) + expect(anchor.categories['conversation']!.turns).toBe(1) + expect(isTurnResidueOnly(anchor)).toBe(true) + + // Next day: the full cost/calls of the same turn. + expect(next.cost).toBe(6) + expect(next.calls).toBe(1) + expect(next.sessions).toBe(1) + expect(isTurnResidueOnly(next)).toBe(false) + }) + it('counts a session under its firstTimestamp date', () => { const projects: ProjectSummary[] = [ makeProject({ diff --git a/tests/launcher-homes.test.ts b/tests/launcher-homes.test.ts new file mode 100644 index 00000000..0bc39449 --- /dev/null +++ b/tests/launcher-homes.test.ts @@ -0,0 +1,280 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm, symlink } from 'fs/promises' +import { join } from 'path' +import { tmpdir } from 'os' + +import { collectLauncherNotes, isNestedLauncherCodexHome } from '../src/launcher-homes.js' +import { collectDoctorReport, renderDoctorTable } from '../src/doctor.js' +import { createCodexProvider } from '../src/providers/codex.js' +import { emptyCache } from '../src/session-cache.js' + +function sessionMeta(sessionId: string, extra: Record = {}): string { + return JSON.stringify({ + type: 'session_meta', + timestamp: '2026-04-14T10:00:00Z', + payload: { cwd: '/Users/test/proj', originator: 'codex-cli', session_id: sessionId, model: 'gpt-5.3-codex', ...extra }, + }) +} + +/** Production Codex session_meta first lines are ~22–27 KB. */ +function longSessionMeta(sessionId: string): string { + return sessionMeta(sessionId, { base_instructions: 'x'.repeat(30 * 1024) }) +} + +async function writeCodexSession(codexDir: string, name: string, sessionId?: string, meta?: string): Promise { + const id = sessionId ?? name.replace(/^rollout-/, '').replace(/\.jsonl$/, '') + const dayDir = join(codexDir, 'sessions', '2026', '04', '14') + await mkdir(dayDir, { recursive: true }) + await writeFile(join(dayDir, name), `${meta ?? sessionMeta(id)}\n`) +} + +function names(sources: { path: string }[]): string[] { + return sources.map(s => s.path.split('/').pop()!) +} + +describe('isNestedLauncherCodexHome', () => { + it('skips a Codex home under .buzz when a distinct primary home exists', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const primary = join(root, 'real-codex') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(primary, { recursive: true }) + await mkdir(nested, { recursive: true }) + expect(isNestedLauncherCodexHome(nested, { primaryDir: primary, launcherRoots: [buzz] })).toBe(true) + await rm(root, { recursive: true, force: true }) + }) + + it('does not skip the sole Codex home even if it sits under .buzz', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(nested, { recursive: true }) + expect(isNestedLauncherCodexHome(nested, { primaryDir: nested, launcherRoots: [buzz] })).toBe(false) + await rm(root, { recursive: true, force: true }) + }) + + it('treats a realpath-equivalent nest as the same home', async () => { + const root = await mkdtemp(join(tmpdir(), 'launch-')) + const primary = join(root, 'real-codex') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await mkdir(primary, { recursive: true }) + await mkdir(buzz, { recursive: true }) + await symlink(primary, nested) + expect(isNestedLauncherCodexHome(nested, { primaryDir: primary, launcherRoots: [buzz] })).toBe(false) + await rm(root, { recursive: true, force: true }) + }) +}) + +describe('Codex discover overlap-only nest filter', () => { + let root: string + beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'codex-buzz-')) }) + afterEach(async () => { await rm(root, { recursive: true, force: true }) }) + + it('keeps a distinct nest rollout on the second factory', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl') + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const real = createCodexProvider(primary, { primaryDir: primary, launcherRoots: [buzz] }) + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await real.discoverSessions())).toEqual(['rollout-primary.jsonl']) + expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + }) + + it('filters only a nest rollout whose session id overlaps the primary tree', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-shared.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await nest.discoverSessions())).toEqual(['rollout-buzz-only.jsonl']) + }) + + it('keeps a nest rollout whose basename collides but session id is unique', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-shared.jsonl', 'sess-primary') + await writeCodexSession(nested, 'rollout-shared.jsonl', 'sess-nest') + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await nest.discoverSessions())).toEqual(['rollout-shared.jsonl']) + }) + + it('default factory with CODEX_HOME=nest and a stub ~/.codex still discovers the nest', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await mkdir(primary, { recursive: true }) + await writeCodexSession(nested, 'rollout-buzz.jsonl') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + try { + const provider = createCodexProvider() + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + const roots = await provider.probeRoots!() + expect(roots.map(r => r.path)).toEqual([ + join(primary, 'sessions'), + join(primary, 'archived_sessions'), + join(nested, 'sessions'), + join(nested, 'archived_sessions'), + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('no-arg factory discovers billed + unique nest and drops overlapping nest ids', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-billed.jsonl', 'sess-shared') + await writeCodexSession(primary, 'rollout-billed-only.jsonl', 'sess-billed') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + try { + const provider = createCodexProvider() + expect(names(await provider.discoverSessions()).sort()).toEqual([ + 'rollout-billed-only.jsonl', + 'rollout-billed.jsonl', + 'rollout-buzz-only.jsonl', + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('exported codex singleton dedups nest ids against billed home', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-billed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz-only.jsonl', 'sess-buzz') + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + vi.resetModules() + try { + const { codex } = await import('../src/providers/codex.js') + expect(names(await codex.discoverSessions()).sort()).toEqual([ + 'rollout-billed.jsonl', + 'rollout-buzz-only.jsonl', + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('exported no-arg singleton dedups production-size session_meta first lines', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + const billedA = longSessionMeta('sess-A') + const nestA = longSessionMeta('sess-A') + const nestB = longSessionMeta('sess-B') + expect(Buffer.byteLength(billedA, 'utf8')).toBeGreaterThan(8 * 1024) + expect(Buffer.byteLength(nestA, 'utf8')).toBeGreaterThan(8 * 1024) + expect(Buffer.byteLength(nestB, 'utf8')).toBeGreaterThan(8 * 1024) + await writeCodexSession(primary, 'rollout-billed-A-long.jsonl', 'sess-A', billedA) + await writeCodexSession(nested, 'rollout-nest-A-long.jsonl', 'sess-A', nestA) + await writeCodexSession(nested, 'rollout-nest-B-long.jsonl', 'sess-B', nestB) + const prevHome = process.env.HOME + const prevCodex = process.env.CODEX_HOME + process.env.HOME = home + process.env.CODEX_HOME = nested + vi.resetModules() + try { + const { createCodexProvider: noArgFactory, codex } = await import('../src/providers/codex.js') + expect(names(await noArgFactory().discoverSessions()).sort()).toEqual([ + 'rollout-billed-A-long.jsonl', + 'rollout-nest-B-long.jsonl', + ]) + expect(names(await codex.discoverSessions()).sort()).toEqual([ + 'rollout-billed-A-long.jsonl', + 'rollout-nest-B-long.jsonl', + ]) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevCodex === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = prevCodex + } + }) + + it('second factory on a realpath-equivalent nest emits no duplicate sources', async () => { + const primary = join(root, 'primary') + const buzz = join(root, '.buzz') + const nested = join(buzz, '.codex') + await writeCodexSession(primary, 'rollout-same-physical-tree.jsonl') + await mkdir(buzz, { recursive: true }) + await symlink(primary, nested) + const real = createCodexProvider(primary, { primaryDir: primary, launcherRoots: [buzz] }) + const nest = createCodexProvider(nested, { primaryDir: primary, launcherRoots: [buzz] }) + expect(names(await real.discoverSessions())).toEqual(['rollout-same-physical-tree.jsonl']) + expect(await nest.discoverSessions()).toEqual([]) + }) + + it('explicit nest path without second-factory opts uses default launcher roots', async () => { + const home = root + const primary = join(home, '.codex') + const nested = join(home, '.buzz', '.codex') + await writeCodexSession(primary, 'rollout-primary.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-renamed.jsonl', 'sess-shared') + await writeCodexSession(nested, 'rollout-buzz.jsonl', 'sess-buzz') + const prevHome = process.env.HOME + process.env.HOME = home + try { + const provider = createCodexProvider(nested) + expect(names(await provider.discoverSessions())).toEqual(['rollout-buzz.jsonl']) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + } + }) +}) + +describe('doctor launchers', () => { + it('lists Buzz as a launcher with no session count', async () => { + const home = await mkdtemp(join(tmpdir(), 'home-')) + await mkdir(join(home, '.buzz'), { recursive: true }) + const notes = collectLauncherNotes(home) + expect(notes).toEqual([expect.objectContaining({ name: 'buzz', billedVia: 'codex' })]) + expect(notes[0]!.verdict).toMatch(/LAUNCHER/) + expect(notes[0]!.verdict).not.toMatch(/\d+\s+session/) + + const report = await collectDoctorReport('all', { + providers: [createCodexProvider(join(home, 'empty-codex'))], + cache: emptyCache(), + launchers: notes, + }) + expect(report.launchers).toEqual(notes) + const table = renderDoctorTable(report, { color: false }) + expect(table).toContain('Launchers') + expect(table).toContain('buzz') + expect(table).toContain('billed via Codex') + const buzzLine = table.split('\n').find(line => /^\s*buzz\s/.test(line)) + expect(buzzLine).toBeDefined() + expect(buzzLine).not.toMatch(/\d+\s+session/) + await rm(home, { recursive: true, force: true }) + }) +}) diff --git a/tests/models.test.ts b/tests/models.test.ts index 5580ea0a..d1bef7e8 100644 --- a/tests/models.test.ts +++ b/tests/models.test.ts @@ -138,7 +138,7 @@ describe('getModelCosts', () => { const known = ['anthropic', 'x-ai', 'xai', 'qwen', 'moonshotai', 'nousresearch', 'kimi', 'litellm_proxy', 'openai_like', 'zhipu', 'mimo', 'xiaomi', - 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity'] + 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter'] for (const ns of known) { expect(getModelCosts(`${ns}/zzz-namespace-probe`), ns).not.toBeNull() } @@ -159,10 +159,13 @@ describe('getModelCosts', () => { 'omniroute:cline-free/zzz-router-probe', 'omniroute:antigravity/zzz-router-probe', 'omniroute:cmd/zzz-router-probe', + 'omniroute:orcarouter/zzz-router-probe', ] for (const id of routed) expect(getModelCosts(id), id).not.toBeNull() expect(getModelCosts('omniroute:nosuchvendor/zzz-router-probe')).toBeNull() + // A nested unknown vendor inside a known routing wrapper must fail closed. + expect(getModelCosts('omniroute:orcarouter/nosuchvendor/zzz-router-probe')).toBeNull() }) it('lets a user price override for a bare id win over the routed catalog row', () => { @@ -170,6 +173,34 @@ describe('getModelCosts', () => { expect(getModelCosts('cp/cline-pass/glm-5.3')!.inputCostPerToken).toBe(99 / 1_000_000) expect(getModelCosts('omniroute:cp/cline-pass/glm-5.3')!.outputCostPerToken).toBe(99 / 1_000_000) }) + + it('prices OrcaRouter fusion and nested upstreams; auto stays fail-closed', () => { + // `orcarouter/auto` rotates onto a Qwen/Llama flash model. No live probe + // pins a rate, so it stays unpriced rather than inheriting Sonnet. + expect(getModelCosts('orcarouter/auto')).toBeNull() + + // The fusion routes currently resolve to openai/gpt-oss-120b (live 2026-08). + expect(getModelCosts('orcarouter/fusion')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/fusion-flash')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/fusion-mini')!.inputCostPerToken).toBe( + getModelCosts('openai/gpt-oss-120b')!.inputCostPerToken, + ) + + // Fully-qualified upstream ids peel to the exact LiteLLM row. + expect(getModelCosts('orcarouter/deepseek/deepseek-v4-pro')!.inputCostPerToken).toBe( + getModelCosts('deepseek/deepseek-v4-pro')!.inputCostPerToken, + ) + expect(getModelCosts('orcarouter/deepseek/deepseek-v4-flash')!.outputCostPerToken).toBe( + getModelCosts('deepseek/deepseek-v4-flash')!.outputCostPerToken, + ) + + // A route id for an unknown upstream stays unpriced (fail closed). + expect(getModelCosts('orcarouter/nosuchvendor/zzz-router-probe')).toBeNull() + }) }) describe('resolveCanonicalModelId', () => { @@ -185,6 +216,13 @@ describe('resolveCanonicalModelId', () => { expect(resolveCanonicalModelId('claude-opus-4.6')).toBe('claude-opus-4-6') expect(resolveCanonicalModelId('kimi-code')).toBe('kimi-k2-thinking') expect(resolveCanonicalModelId('cline-pass/kimi-k3')).toBe('kimi-k3') + expect(resolveCanonicalModelId('orcarouter/auto')).not.toBe(resolveCanonicalModelId('claude-sonnet-4-5')) + expect(resolveCanonicalModelId('orcarouter/fusion')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/fusion-flash')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/fusion-mini')).toBe(resolveCanonicalModelId('openai/gpt-oss-120b')) + expect(resolveCanonicalModelId('orcarouter/deepseek/deepseek-v4-pro')).toBe( + resolveCanonicalModelId('deepseek/deepseek-v4-pro'), + ) }) }) @@ -247,6 +285,13 @@ describe('getShortModelName', () => { expect(getShortModelName('z-ai/glm-5.3')).toBe('GLM-5.3') expect(getShortModelName('xiaomi/glm-5.3')).toBe('GLM-5.3') expect(getShortModelName('cp/cline-pass/glm-5.3')).toBe('GLM-5.3') + // OrcaRouter route ids peel to the upstream id, which keeps the upstream label. + expect(getShortModelName('orcarouter/deepseek/deepseek-v4-pro')).toBe('DeepSeek v4 Pro') + // Route ids display as the model they route to, not a branded gateway label. + expect(getShortModelName('orcarouter/auto')).not.toBe(getShortModelName('claude-sonnet-4-5')) + expect(getShortModelName('orcarouter/fusion')).toBe(getShortModelName('openai/gpt-oss-120b')) + expect(getShortModelName('orcarouter/fusion-flash')).toBe(getShortModelName('openai/gpt-oss-120b')) + expect(getShortModelName('orcarouter/fusion-mini')).toBe(getShortModelName('openai/gpt-oss-120b')) // Grok Build prices via the grok-build-0.1 sibling. expect(getShortModelName('grok-build')).toBe('Grok Build') expect(getShortModelName('grok-build-0.1')).toBe('Grok Build') diff --git a/tests/plan-budget-copy.test.ts b/tests/plan-budget-copy.test.ts index 787df94f..c6bc8793 100644 --- a/tests/plan-budget-copy.test.ts +++ b/tests/plan-budget-copy.test.ts @@ -55,6 +55,30 @@ describe('plan budget copy', () => { expect(planStatusText(cursor)).toContain('Approaching budget') }) + it('labels Copilot as AI Credits, not API-equivalent USD', () => { + const copilot = usage({ + plan: { + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, + budgetUsd: 15, + spentApiEquivalentUsd: 0.015, + spentCredits: 1.5, + budgetCredits: 1500, + percentUsed: 0.1, + creditsIncomplete: false, + }) + expect(planBudgetHeadline(copilot)).toBe('Copilot Pro: 1.5 / 1500 AI Credits') + const status = planStatusText(copilot) + expect(status).toContain('Not a live provider window.') + expect(status).not.toMatch(/GitHub|UTC|copilot_internal/i) + expect(status).not.toMatch(/calendar/i) + }) + // computePeriodFromResetDay builds an anniversary window from plan.resetDay // (1-28, settable with `codeburn plan set --reset-day`), so a plan that resets // on the 15th is NOT on a calendar month and must never be called one. diff --git a/tests/plan-usage.test.ts b/tests/plan-usage.test.ts index 94cc7521..91b85ee3 100644 --- a/tests/plan-usage.test.ts +++ b/tests/plan-usage.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { describe, it, expect, vi, beforeEach } from 'vitest' import { savePlan, type Plan } from '../src/config.js' -import { activePlansFromMap, computePeriodFromResetDay, getPlanScopedProjects, getPlanUsage, getPlanUsageFromProjects, getPlanUsages } from '../src/plan-usage.js' +import { activePlansFromMap, computePeriodFromResetDay, copilotCreditSpend, getPlanScopedProjects, getPlanUsage, getPlanUsageFromProjects, getPlanUsages } from '../src/plan-usage.js' import type { ProjectSummary } from '../src/types.js' const { parseAllSessionsMock } = vi.hoisted(() => ({ @@ -410,3 +410,267 @@ describe('getPlanUsage', () => { } }) }) + +function usageCall(overrides: { + provider: string + costUSD: number + timestamp: string + nanoAiu?: number + supplementaryAccounting?: boolean +}) { + return { + provider: overrides.provider, + model: 'claude-sonnet-4-5', + usage: { + inputTokens: 100, + outputTokens: 20, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, + }, + costUSD: overrides.costUSD, + tools: [], + mcpTools: [], + skills: [], + subagentTypes: [], + hasAgentSpawn: false, + hasPlanMode: false, + speed: 'standard' as const, + timestamp: overrides.timestamp, + bashCommands: [], + deduplicationKey: `${overrides.provider}-${overrides.timestamp}-${overrides.nanoAiu ?? 'none'}`, + ...(overrides.nanoAiu != null ? { nanoAiu: overrides.nanoAiu } : {}), + ...(overrides.supplementaryAccounting ? { supplementaryAccounting: true } : {}), + } +} + +function usageProjectFromTurns(turns: ReturnType[][]): ProjectSummary { + const calls = turns.flat() + return { + project: 'codeburn', + projectPath: '/tmp/codeburn', + totalCostUSD: calls.reduce((sum, call) => sum + call.costUSD, 0), + totalApiCalls: calls.length, + sessions: [{ + turns: turns.map(assistantCalls => ({ + timestamp: assistantCalls[0]!.timestamp, + assistantCalls, + })), + }], + } as ProjectSummary +} + +function usageProject(calls: ReturnType[]): ProjectSummary { + return usageProjectFromTurns([calls]) +} + +describe('copilot AI credit plan math', () => { + const today = new Date('2026-08-10T12:00:00.000Z') + const copilotPro: Plan = { + id: 'copilot-pro', + monthlyCredits: 1500, + monthlyUsd: 15, + provider: 'copilot', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + const claudePro: Plan = { + id: 'claude-pro', + monthlyUsd: 20, + provider: 'claude', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + + it('turns 1.5e9 nanoAiu into 1.5 / 1500 credits (0.1%)', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.budgetCredits).toBe(1500) + expect(usage.percentUsed).toBeCloseTo(0.1, 10) + expect(usage.spentApiEquivalentUsd).toBeCloseTo(0.015, 10) + expect(usage.creditsIncomplete).toBe(false) + expect(usage.status).toBe('under') + }) + + it('does not fill the credits bar from token costUSD when nanoAiu is missing', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(0) + expect(usage.creditsIncomplete).toBe(true) + expect(usage.percentUsed).toBe(0) + expect(usage.spentApiEquivalentUsd).toBe(0) + }) + + it('counts a paired store-row once and ignores JSONL / rollup siblings', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:01.000Z', + }), + usageCall({ + provider: 'copilot', + costUSD: 0.25, + timestamp: '2026-08-06T12:00:00.000Z', + supplementaryAccounting: true, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.percentUsed).toBeCloseTo(0.1, 10) + expect(usage.creditsIncomplete).toBe(true) + }) + + it('does not double credits when a paired rollup also carries nanoAiu', () => { + const usage = getPlanUsageFromProjects(copilotPro, [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T12:00:01.000Z', + nanoAiu: 1_500_000_000, + }), + ]), + ], today) + + expect(usage.spentCredits).toBe(1.5) + expect(usage.creditsIncomplete).toBe(false) + }) + + it('does not double credits when nanoAiu twins sit in separate session turns', () => { + // foldCopilotSupplementaryTurns refuses a local-day-boundary pair, so the + // supplementary twin stays on its own turn. Credit math must still close + // once at session scope. + const projects = [ + usageProjectFromTurns([ + [usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T18:25:00.000Z', + nanoAiu: 1_500_000_000, + })], + [usageCall({ + provider: 'copilot', + costUSD: 0.001605, + timestamp: '2026-08-05T18:35:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + })], + ]), + ] + + expect(copilotCreditSpend(projects).spentCredits).toBe(1.5) + const usage = getPlanUsageFromProjects(copilotPro, projects, today) + expect(usage.spentCredits).toBe(1.5) + expect(usage.creditsIncomplete).toBe(false) + }) + + it('keeps a $0 nanoAiu-only session on copilot plans and drops it on USD plans', () => { + const projects = [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 0, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + supplementaryAccounting: true, + }), + ]), + ] + const allUsd: Plan = { + id: 'custom', + monthlyUsd: 100, + provider: 'all', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + } + expect(getPlanScopedProjects(copilotPro, projects, today)).toHaveLength(1) + expect(getPlanScopedProjects(allUsd, projects, today)).toHaveLength(0) + expect(getPlanScopedProjects(claudePro, projects, today)).toHaveLength(0) + }) + + it('keeps Claude plans on costUSD against the same mixed fixture', () => { + const projects = [ + usageProject([ + usageCall({ + provider: 'copilot', + costUSD: 42, + timestamp: '2026-08-05T12:00:00.000Z', + nanoAiu: 1_500_000_000, + }), + usageCall({ + provider: 'claude', + costUSD: 5, + timestamp: '2026-08-05T12:00:00.000Z', + }), + ]), + ] + const scopedClaude = getPlanScopedProjects(claudePro, projects, today) + const claudeUsage = getPlanUsageFromProjects(claudePro, scopedClaude, today) + const copilotUsage = getPlanUsageFromProjects(copilotPro, getPlanScopedProjects(copilotPro, projects, today), today) + + expect(claudeUsage.spentApiEquivalentUsd).toBe(5) + expect(claudeUsage.spentCredits).toBeUndefined() + expect(claudeUsage.percentUsed).toBe(25) + expect(copilotUsage.spentCredits).toBe(1.5) + expect(copilotUsage.percentUsed).toBeCloseTo(0.1, 10) + }) + + it('leaves cursor and grok USD siblings at 25%', () => { + const cursor = getPlanUsageFromProjects({ + id: 'cursor-pro', + monthlyUsd: 20, + provider: 'cursor', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, [usageProject([usageCall({ provider: 'cursor', costUSD: 5, timestamp: '2026-08-05T12:00:00.000Z' })])], today) + const grok = getPlanUsageFromProjects({ + id: 'supergrok', + monthlyUsd: 30, + provider: 'grok', + resetDay: 1, + setAt: '2026-08-01T00:00:00.000Z', + }, [usageProject([usageCall({ provider: 'grok', costUSD: 7.5, timestamp: '2026-08-05T12:00:00.000Z' })])], today) + + expect(cursor.percentUsed).toBe(25) + expect(grok.percentUsed).toBe(25) + expect(cursor.spentCredits).toBeUndefined() + expect(grok.spentCredits).toBeUndefined() + }) +}) diff --git a/tests/plans.test.ts b/tests/plans.test.ts index ca4553b3..2a4c7e49 100644 --- a/tests/plans.test.ts +++ b/tests/plans.test.ts @@ -12,6 +12,9 @@ describe('plan presets', () => { expect(getPresetPlan('claude-pro')).toMatchObject({ id: 'claude-pro', monthlyUsd: 20, provider: 'claude' }) expect(getPresetPlan('claude-max')).toMatchObject({ id: 'claude-max', monthlyUsd: 200, provider: 'claude' }) expect(getPresetPlan('cursor-pro')).toMatchObject({ id: 'cursor-pro', monthlyUsd: 20, provider: 'cursor' }) + expect(getPresetPlan('copilot-pro')).toMatchObject({ id: 'copilot-pro', monthlyCredits: 1500, monthlyUsd: 15, provider: 'copilot' }) + expect(getPresetPlan('copilot-pro-plus')).toMatchObject({ id: 'copilot-pro-plus', monthlyCredits: 7000, monthlyUsd: 70, provider: 'copilot' }) + expect(getPresetPlan('copilot-max')).toMatchObject({ id: 'copilot-max', monthlyCredits: 20000, monthlyUsd: 200, provider: 'copilot' }) expect(getPresetPlan('custom')).toBeNull() }) @@ -22,7 +25,9 @@ describe('plan presets', () => { expect(isPlanProvider('all')).toBe(true) expect(isPlanProvider('claude')).toBe(true) + expect(isPlanProvider('copilot')).toBe(true) expect(isPlanProvider('invalid')).toBe(false) + expect(isPlanId('copilot-pro')).toBe(true) }) }) diff --git a/tests/sync-attribution-cli.test.ts b/tests/sync-attribution-cli.test.ts index 90bb64de..79bd99e0 100644 --- a/tests/sync-attribution-cli.test.ts +++ b/tests/sync-attribution-cli.test.ts @@ -10,7 +10,7 @@ import { execFileSync } from 'node:child_process' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest' import { Command } from 'commander' @@ -155,4 +155,24 @@ describe('sync push --attribution (CLI level)', () => { const wire = JSON.stringify(idp.tracesRequests) expect(wire).toContain('github.com/acme/cli-widget') }) + + it('never puts a filesystem path on the wire as ai.project', async () => { + const now = Date.now() + const first = new Date(now - 90 * 60 * 1000).toISOString() + const last = new Date(now - 30 * 60 * 1000).toISOString() + const session = makeSession('cli-sess-1', first, last, [makeCall(`call-${now}`, first)]) + parseAllSessionsMock.mockResolvedValue([ + { project: `-${repoDir.replace(/^\//, '').replace(/\//g, '-')}`, projectPath: repoDir, sessions: [session] } as ProjectSummary, + ]) + await runPush(['--attribution']) + const wire = JSON.stringify(idp.tracesRequests) + expect(wire).not.toContain(repoDir) // no absolute path + expect(wire).not.toContain(repoDir.replace(/\//g, '-')) // no slugified path + const projects = idp.tracesRequests.flatMap(r => (r.body as any).resourceSpans + .flatMap((rs: any) => rs.scopeSpans.flatMap((ss: any) => ss.spans)) + .flatMap((s: any) => s.attributes.filter((a: any) => a.key === 'ai.project') + .map((a: any) => a.value.stringValue))) + expect(projects.length).toBeGreaterThanOrEqual(2) // usage + attribution spans + expect(new Set(projects)).toEqual(new Set([basename(repoDir)])) + }) }) diff --git a/tests/sync-ledger-otlp.test.ts b/tests/sync-ledger-otlp.test.ts index 0a99f938..500d75a2 100644 --- a/tests/sync-ledger-otlp.test.ts +++ b/tests/sync-ledger-otlp.test.ts @@ -160,6 +160,44 @@ describe('buildOtlpPayload', () => { expect(attrMap['ai.session_id']).toBeUndefined() }) + it('bills reasoning into ai.output_tokens for exclusive providers (opencode)', () => { + const payload = buildOtlpPayload([makeCallWithSession({ + provider: 'opencode', + usage: { + inputTokens: 1000, + outputTokens: 500, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 250, + webSearchRequests: 0, + }, + })]) + const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes + const attrMap = Object.fromEntries(attrs.map(a => [a.key, a.value])) + + expect(attrMap['ai.output_tokens']).toEqual({ intValue: '750' }) + }) + + it('keeps ai.output_tokens raw for inclusive providers (claude)', () => { + const payload = buildOtlpPayload([makeCallWithSession({ + provider: 'claude', + usage: { + inputTokens: 1000, + outputTokens: 500, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 250, + webSearchRequests: 0, + }, + })]) + const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes + const attrMap = Object.fromEntries(attrs.map(a => [a.key, a.value])) + + expect(attrMap['ai.output_tokens']).toEqual({ intValue: '500' }) + }) + it('includes tools as array attribute', () => { const payload = buildOtlpPayload([makeCallWithSession()]) const attrs = payload.resourceSpans[0]!.scopeSpans[0]!.spans[0]!.attributes