Commit graph

194 commits

Author SHA1 Message Date
AgentSeal
8d727d9cc4 feat(overview): full comma-grouped numbers for a precise, spacious look
Render token counts as full thousands-grouped integers (e.g.
3,926,923,819) instead of abbreviated M/B, so the roomy tables read like
a precise statement. Update the overview test to match.
2026-06-20 19:12:26 +02:00
Resham Joshi
1dba4e0aa4
feat(web): in-dashboard device discovery, share-from-browser, redesign + hardening (#534)
* feat(web): device discovery + pairing endpoints for the dashboard

Add /api/identity, /api/devices/scan (mDNS browse with confirm code and
paired status), and /api/devices/pair (approve-style pairing via
linkRemote). Backs the Search local devices button so pairing can happen
from the browser instead of the CLI.

* feat(web): two-panel dashboard with eywa-inspired warm theme

Redesign the dashboard into a left sidebar (device switcher + Search
local devices) and a right content panel, restyled to a warm-paper,
forest-green archival theme (serif display numbers, ink text, hairline
borders) in place of the dark midnight theme. The Search local devices
modal discovers nearby devices over mDNS and pairs in one click (approve
on the other device), backed by /api/devices/scan and /api/devices/pair.

* feat(web): use the CodeBurn flame logo in the dashboard header

Replace the placeholder triangle with the flame mark (the repo's
codeburn-symbolic vector), tinted the theme's forest green, and set the
same flame as the favicon.

* feat(web): color the All-devices chart by device, add task-level combined views

In the All devices view the daily chart now stacks by device (one color
per device) instead of by model, and the combined panels add a By task
breakdown plus in/out token detail. Devices that cannot be reached are
hidden entirely rather than shown as error rows.

* feat(web): use the flame image as the dashboard logo and favicon

Replace the inline vector flame with the brand flame PNG
(public/codeburn-flame.png) in the header and as the favicon.

* fix(web): trim flame logo padding and tighten brand spacing

Crop the transparent border off the flame PNG (it was 184px of padding
each side) and reduce the header gap so the mark sits close to the
wordmark.

* feat(web): cost/tokens toggle, cache read/write, full feature panels

Add a Cost/Tokens unit toggle that switches the hero number and the chart
between dollars and tokens. Surface cache write/read token totals as
metric cards. Add per-device panels for subagents, skills, MCP servers,
and a savings / retry-tax / routing-waste summary. The combined view
gains cache totals and the unit toggle too.

* feat(web): use CodeBurn website logos and add community links

Use the website's navbar flame (logo.png) with the Code+Burn wordmark in
the header, and the three-flame app icon (icon.png) as the favicon.
Add Website, Discord, and X links to the sidebar footer.

* fix(web): use the single-flame logo for the favicon too

The three-flame icon was wrong for the tab; use the same single flame as
the navbar everywhere and drop the unused three-flame asset.

* chore(web): set dashboard title to CodeBurn - Local Dashboard

* harden sharing + dashboard for public launch

Security:
- pairing: cap PIN attempts (close window after 5 wrong guesses) so a
  6-digit PIN cannot be brute-forced within the TTL on a 0.0.0.0 listener.
- web dashboard: reject non-loopback Host (defeats DNS rebinding that
  could read unsanitized local usage) and cross-origin requests (CSRF);
  require application/json on the pair endpoint.
- store tokens with 0600 perms (was world-readable), 0700 dir.

Robustness:
- client: per-request timeout so a hung/asleep peer cannot hang a pull;
  pullDevices fetches remotes concurrently and isolates failures.
- dashboard: normalize peer payloads at the boundary and add an error
  boundary so a peer on a different version cannot white-screen the SPA;
  finite-guard fmtNum/compactUsd.

Tests: PIN attempt-cap test added (1269 pass).

* feat(web): share this device from the dashboard, with browser approval

Add a Share this device toggle to the dashboard sidebar. It runs the
secure share server in-process (mTLS + mDNS advertise) so no terminal is
needed, with a Keep sharing always option (persisted; otherwise it stops
after idle). Incoming approve-style pairings are queued and surfaced in
the browser as an Approve/Deny prompt with the matching code, instead of
a terminal prompt. The shared payload is sanitized; start degrades
gracefully if the port is already held by a CLI share.

* fix(sharing): keep a paired device from dropping on a transient pull

- client: 8s -> 15s timeout and a fresh socket per request (agent:false) so
  the pinned-fingerprint check always reads this connection's cert.
- share server: wrap request handling so a getUsage error returns a fast
  500 instead of hanging the caller (which times out and drops the device).
- dashboard: re-pull paired devices every 20s so a brief drop self-heals
  instead of staying gone until you change tabs.

* fix(sharing): re-sanitize remote payloads on receipt

A peer might run an older build that does not strip its own project
names/sessions. Sanitize every remote payload when we receive it too, so
project names never cross into our dashboard regardless of the sender's
version. Aggregate numbers (cost, tokens, models, tools, daily) are kept.

* harden dashboard sharing: version-skew, lifecycle, server errors

- normalize remote daily-history entries so a peer on an older build (daily
  rows missing topModels) can no longer crash the chart / brick the page.
- ShareController: commit always/sharing state only after listen() binds, so
  a port-in-use start no longer reports sharing when it is not.
- attach durable error/tlsClientError handlers to both HTTPS servers so a
  malformed peer connection cannot crash the process.
- reset view/provider selection when the viewed device disappears or lacks
  the selected provider (no more empty/no-selection state on sleep-wake).
- by-device chart: stable per-device color/key so bars do not reshuffle when
  a device drops or returns between polls.

* polish: device identity, approval guard, queue cap, formatting

- give each device a stable unique id (cert fingerprint for remotes,
  'local' for this device); key the sidebar, selection, and by-device
  chart by id so two devices sharing a hostname no longer collide.
- approval prompt: drop a request from the UI the moment it is answered
  so it cannot be double-clicked.
- share controller: cap concurrent pending approvals and allow only one
  per device, so a LAN peer cannot flood the prompt.
- usd(): render negatives as -$5.00, consistent with compactUsd.
2026-06-20 19:02:03 +02:00
Resham Joshi
887374de2c
feat(sharing): securely combine usage across your own devices (#532)
* feat(sharing): pairing, token, and device-identity core

First piece of local device sharing: self-cert fingerprint identity
(trust-on-first-use), a one-time expiring pairing PIN, fingerprint-bound
tokens, and a peer store that authorizes a pull only when both the token
and the TLS peer fingerprint match the same paired device. Pure logic,
fully unit-tested; the TLS share server and host pull build on this.

* feat(sharing): secure mutual-TLS transport + pairing handshake

Add device identity (self-signed cert, persisted; fingerprint = sha256 of
the cert DER), an HTTPS share server (mutual TLS: presents its cert, reads
the client's, and serves /api/usage only when the bearer token AND the
client fingerprint match the same paired peer), a one-time-PIN pairing
endpoint, and a fingerprint-pinning client. Verified end to end on
loopback: PIN pairing, pinned authed pull, and rejection of a wrong PIN,
a token replayed from another device, and a mismatched server
fingerprint. Adds the selfsigned dep (Node cannot generate certs natively).

* feat(sharing): share + devices CLI (pair, pull, combine)

Phase 3 terminal flow: codeburn share runs the secure server on-demand
(stops after 10 min idle; --always to persist, --pair to add a device),
and codeburn devices add <host> --pin <pin> pairs and pins a remote.
codeburn devices pulls this machine plus every paired device, keeps each
separate, and prints a per-device table with a simple summed Combined
row (no server-side merge). Persists identity and peers under the config
dir. Host pair-and-pull flow covered by a loopback integration test.

* feat(sharing): mDNS discovery + approve-style (no-PIN) pairing

Add bonjour-service discovery (advertise/browse over the LAN), a short
confirmation code derived from both cert fingerprints (Bluetooth-style
'do these match?' check), and an approve-style pairing endpoint that
prompts the owner instead of requiring a typed PIN. Loopback-tested:
approved device gets a working token with a matching code on both sides,
declined device is rejected.

* feat(sharing): AirDrop-style discover + approve UX

codeburn share now advertises on the LAN and approves incoming devices
interactively (confirm the matching code, no typed PIN). codeburn devices
add (no args) discovers nearby devices, lets you pick one, shows the
confirmation code, and waits for the owner to approve. Manual
add <host> --pin stays as a fallback for networks that block mDNS.

* feat(sharing): share only aggregates, never project names or paths

Sanitize each device's payload before it leaves the machine: drop
topProjects and topSessions (project names + session detail) and send
only aggregate numbers (cost, tokens, models, tools, activities, daily).
What you are working on stays local; only the totals travel.
2026-06-20 16:24:53 +02:00
Tiago Santos
75c32e6d65
fix: fix and improve test isolation and collision with environment (#530)
* fix: fix and improve test isolation and collision with environment

* docs: remove unnecessary comment

* test(env-isolation): clear CODEBURN_FORCE_MACOS_MAJOR and pin TZ

Two env vars read in src/ were not isolated: CODEBURN_FORCE_MACOS_MAJOR
(now cleared so it cannot leak between tests) and TZ (now pinned to UTC,
since clearing it falls back to the OS zone and would shift date buckets
versus a clean CI runner).

---------

Co-authored-by: AgentSeal <hello@agentseal.org>
2026-06-20 13:42:10 +02:00
Resham Joshi
c55dba2dd2
feat(overview): plain-text monthly usage overview command (#528)
* feat(overview): plain-text monthly usage overview command

Add 'codeburn overview', a copy-pasteable text report. Defaults to the
current month, with --from/--to to filter and --no-color for plain
output. Renders Totals, By tool, Top models, Highest-value days, Top
projects, a daily table, By activity, and Tools, with colored section
headings (stripped under --no-color or when piped).

Reuses the existing session aggregation. Cost gains thousands
separators and tokens roll up to a B unit for readability via
display-only wrappers, without changing the shared formatters. Project
names use the path basename instead of the sanitized full path.

* fix(cli): exit cleanly on EPIPE when the stdout pipe closes early

Piping output to a reader that closes early (| head, quitting less, a
missing command) made stdout writes throw EPIPE and crash with an
unhandled error event. Handle EPIPE on process.stdout and exit 0 so
piping the overview and other commands behaves normally.

* docs(readme): document and highlight the overview command

Add a 'Your month at a glance' section featuring codeburn overview with
examples and sample output, a Commands-table entry, and the provider
flag note.
2026-06-20 11:46:45 +02:00
Resham Joshi
6a26ee8284
feat(opencode): read file-based JSON sessions (OpenCode 1.1+) (#523)
OpenCode 1.1+ stores sessions as file-based JSON under
storage/{session,message,part}/ instead of a SQLite DB, so the
SQLite-only provider discovered zero sessions on current installs and
reported no usage at all.

Add a file-based discovery and parser path, preferred when present and
falling back to the SQLite DB for pre-migration installs. Extract the
shared message-to-call logic (token extraction, tool and bash parsing,
cost) into session-message.ts so the file path, the SQLite path, and
Kilo Code stay identical.
2026-06-19 19:04:51 +02:00
Resham Joshi
ebfb1de0cb
feat(providers): add Grok Build provider (#521)
Adds Grok Build (xAI coding CLI) as an eager provider with caching- and compaction-aware token estimation, real tool/shell extraction, Skills & Agents from spawn_subagent, grok-build pricing, and SuperGrok plan presets. Tested against real sessions; full suite green.
2026-06-19 17:21:41 +02:00
kevinpauer
7c42534910
Add zerostack provider (#519)
* Add zerostack provider scaffold

Register zerostack (gi-dellav/zerostack) as a core provider reading
plain-text sessions from $XDG_DATA_HOME/zerostack/sessions/. Parser is
modeled on pi.ts; on-disk schema is unverified and must be confirmed
against real sessions before a PR (see docs/providers/zerostack.md).

* Rework zerostack provider against real session schema

Replace the initial scaffold (modeled on pi.ts JSONL) with the verified
format from a real local run and the zerostack source:

- Sessions are one JSON file per session under the platform data dir
  (~/Library/Application Support/zerostack/sessions on macOS,
  $XDG_DATA_HOME/zerostack/sessions on Linux; ZS_DATA_DIR overrides).
- Tokens are cumulative session totals, not per-call, so emit one
  ParsedProviderCall per session from total_input/output_tokens.
- Recompute cost via LiteLLM (calculateCost); OpenRouter ids arrive
  route-prefixed and resolve through canonical names.
- zerostack persists only final assistant text, so tools/bash are empty.

Verified against a real session (DeepSeek v4 Pro via OpenRouter):
34.1K in / 961 out / $0.016, matching the recorded total_cost. Adds a
fixture-based test and rewrites the provider doc to match.
2026-06-19 14:44:45 +02:00
Resham Joshi
808a149bd6
feat(export): surface MCP server usage in JSON and CSV exports (#514)
Some checks are pending
CI / semgrep (push) Waiting to run
The export schema emitted tools and shell-commands but no MCP section, and
the tools list is built from extractCoreTools which strips mcp__ names, so
MCP usage never appeared in codeburn export output even when sessions had
MCP activity (issue #496).

Add an mcp section to the JSON export and an mcp.csv to the CSV export,
sourced from session.mcpBreakdown (server -> calls, with share). Mirrors the
existing tools section.

The underlying parse fix (Codex mcp_tool_call_end attribution) landed in
#513; this makes that data visible in exports. Validated on real local data:
the JSON export now reports mcp: [{Server: node_repl, Calls: 5, ...}].

Fixes #496
2026-06-18 23:13:48 +02:00
Resham Joshi
80e3de3bab
fix(codex): attribute MCP calls emitted as event_msg/mcp_tool_call_end (#513)
Recent Codex sessions report completed MCP tool calls as an event_msg with
type mcp_tool_call_end instead of a function_call response_item. The parser
only built its tool list from function_call and patch_apply_end events, so
these MCP calls were never attributed: token usage was still counted, but the
MCP tool itself was missing from recent lookback windows (today/week/month)
while older history still showed it.

Add a handler that reads invocation.server and invocation.tool from the
event and rebuilds the canonical mcp__<server>__<tool> name the classifier
recognizes. Bump the Codex result cache to v4 so sessions cached under v3
re-parse and pick up the previously dropped MCP calls.

Validated on real local data: 5 mcp_tool_call_end events that were dropped
before are now attributed as mcp__node_repl__js, with no change to the total
call count.

Fixes #478
2026-06-18 22:32:40 +02:00
Resham Joshi
9e997ddb15
fix(cursor): scan the requested window instead of a blind ROWID cap (#482) (#512)
Some checks are pending
CI / semgrep (push) Waiting to run
Large Cursor DBs were scanned as "the most-recent 250k bubbles by ROWID",
which dropped in-range older sessions from long-range reports and warned even
when the requested window fit comfortably. The bubble timestamp lives in the
JSON value (no index), so the date filter forces a full decode per row, which
is why a scan bound exists.

Replace the blind cap with a range-aware paged scan: for DBs over the budget,
page ROWID-descending, keep only rows within the window (createdAt > timeFloor),
and stop once a full page falls past the window floor. The hard budget remains
as a backstop for genuinely enormous in-range scans, and the "older sessions
may be missing" warning now fires only when that budget is actually hit.

Effect: short ranges decode far fewer rows and no longer warn; long ranges
return the full window when it fits the budget; truncation keeps the newest
in-range bubbles and warns only then. Small DBs are unchanged (un-paged query).
Budget is overridable via CODEBURN_CURSOR_MAX_BUBBLES for tests.
2026-06-18 18:45:38 +02:00
Resham Joshi
a3da2ded2a
feat(codex): compute Codex credit usage (#408, #495) (#510)
* feat(codex): compute Codex credit usage (#408, #495)

Codex/ChatGPT subscription users consume credits, a unit separate from API
dollars: usage is billed as credits-per-million-tokens at per-model rates that
differ from the API USD pricing CodeBurn uses for cost. So the reported dollar
cost does not match what credits actually consume.

Add a credit engine sourced from the official Codex credit rates
(developers.openai.com/codex/pricing): GPT-5.5 125/12.5/750, GPT-5.4
62.5/6.25/375, GPT-5.4 mini 18.75/1.875/113 credits per 1M input/cached/output
tokens. Surface per-model credit usage in `codeburn models` JSON output
(credits field; null for non-Codex or unknown models). models-report already
folds reasoning into output and keeps non-cached input + cached-read separately,
which is exactly what the credit rates expect, so the figure is exact.

Engine + computation are unit-tested. UI display surfaces (the models table,
the TUI dashboard, the menubar "credits" view) are intentionally left for a
follow-up so the display choice can be decided.

* feat(menubar): opt-in Codex credits display metric (#408, #495)

Surface Codex credit usage in the menubar as a selectable metric, without
changing the default. Cost ($) stays the default in both the menubar and the
CLI; credits only appear when explicitly chosen.

- TS: buildMenubarPayloadForRange computes the period's Codex credits (via the
  tested aggregateModels, so reasoning/cached are handled) and exposes
  current.codexCredits in the menubar JSON.
- Swift: new DisplayMetric.credits, a "Credits (Codex)" option in the metric
  picker, decodes codexCredits, and renders it in the menu-bar title. Default
  metric remains .cost.
2026-06-18 17:03:46 +02:00
Resham Joshi
b481f81fc4
test(cli-proxy-path): raise timeout for spawn-based tests to fix load flake (#504)
Each test spawns 'tsx src/cli.ts' several times, re-transpiling the CLI on
every spawn. Under full-suite parallel load these spawns contend for CPU and
the slowest test could exceed the 5s default timeout, even though it runs in
~1.7s in isolation and the spawnSync calls already allow 30s each. Set the
file testTimeout to 30s so the wrapper matches the per-spawn cap. Full suite
is green across repeated runs.
2026-06-18 12:57:44 +02:00
Resham Joshi
a9c0273a42
test(usage-aggregator): build payload against an empty HOME to fix timeout flake (#503)
buildMenubarPayloadForRange('today') parsed the developer's real on-disk
session data under a fixed 5s timeout, so on a heavy-usage day the test
timed out locally (it stayed green on CI, which has no real data). Point
HOME and the config dirs at an empty temp dir so the payload is built from
an empty dataset: deterministic and fast (~0.3s) while still asserting the
payload shape and the optimize:false short-circuit.
2026-06-18 12:50:39 +02:00
Wurzer, Wilhelm
89b365c269 feat(kiro): add Kiro CLI session discovery and parsing
The Kiro provider previously only detected sessions from the Kiro IDE
(VS Code-based) stored in globalStorage. This adds support for Kiro CLI
(`kiro-cli chat`) sessions stored in ~/.kiro/sessions/cli/.

CLI sessions use a different format:
- .jsonl files with Prompt/AssistantMessage/ToolResults entries
- Companion .json files with session metadata, model info, and
  per-turn metering usage (credits)

Changes:
- Add CLI session discovery (scans ~/.kiro/sessions/cli/ for .jsonl)
- Add CLI JSONL parser that extracts turns, tools, and cost from
  metering_usage credits
- Add CLI tool name mappings (read, write, shell, grep, glob)
- Make CLI sessions dir configurable via third param to
  createKiroProvider for testability
- Add unit tests for CLI session discovery and parsing
2026-06-18 12:42:58 +02:00
Resham Joshi
c5bf09921b
fix(cli): validate --provider and make non-TTY report deterministic (#501)
Two CLI polish fixes found during a full command sweep:

- Validate --provider against the known provider set (report, status, today,
  month, export, optimize, compare, models). An unknown provider previously
  produced a silently empty report; it now exits 1 with a clear message
  listing valid values, matching how --period and --format already behave.
  Provider names are exposed via a lazy allProviderNames() helper so importing
  the providers module never depends on every provider object being defined.

- Make the non-interactive report/today/month render deterministic: yield a
  tick so ink flushes the one-shot frame to stdout before unmounting, instead
  of unmounting synchronously which could race the flush and drop the output.

Adds CLI provider-validation tests (rejection, valid name, all sentinel, and
a drift guard that allProviderNames covers every loadable provider).
2026-06-18 12:39:22 +02:00
barry
a2947a48be Add JSON output for optimize and yield
Dashboard integrations need machine-readable optimize findings and yield ratios without parsing terminal output. This threads the existing analysis results into conservative JSON serializers while preserving text output as the default.

Constraint: Issue #419 asks for dashboard-friendly JSON for optimize and yield

Rejected: Build a separate analysis path | would risk drift from terminal output

Confidence: high

Scope-risk: narrow

Tested: npm test

Tested: npm run build

Tested: npm run dev -- optimize -p today --format json

Tested: npm run dev -- yield -p today --format json

Not-tested: Real downstream dashboard integration
2026-06-18 12:13:17 +02:00
Resham Joshi
49d1ddc376
Merge pull request #499 from getagentseal/reduce-status-parsing-patched
fix(menubar): reduce repeated status parsing (#486) + clock-skew guard
2026-06-18 12:08:51 +02:00
AgentSeal
7f44eeb1ba fix(daily-cache): purge cached today/future entries on hydration
Keeps the perf win from PR #486 (yesterday stays cached, no re-parse every
run) but restores a narrow safety guard: drop any cached entry dated today or
later before computing the gap range. The cache only ever stores complete past
days, so a >= today entry can only come from the clock moving backward or a
stale older cache; without this it would be served frozen instead of being
recomputed live. Yesterday and earlier are untouched, so this does not
re-parse already-cached days. Adds a regression test.
2026-06-18 12:07:35 +02:00
Resham Joshi
7b484c1644
Merge pull request #498 from getagentseal/copilot-otel-patched
feat(copilot): OTel cache-token parsing (#477) + maintainer review fixes
2026-06-18 11:57:27 +02:00
steelp02
d68a214c76
fix(copilot): Implement durable sources for OTel DB parsing.
Signed-off-by: steelp02 <pieter.steel@pfizer.com>
2026-06-17 21:42:40 +02:00
Vaibhav Arora
0ac09d8909 fix(menubar): reduce repeated status parsing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-13 00:07:04 +05:30
Stephan Leicht Vogt
04f3fc1060
fix(menubar): support installer HTTP proxies (#475)
Some checks failed
CI / semgrep (push) Has been cancelled
Route the menubar installer's GitHub downloads through an undici ProxyAgent when HTTP(S)_PROXY is set, honoring NO_PROXY for bypass. Falls back to direct fetch when no proxy is configured. Closes #473.
2026-06-11 14:13:10 +02:00
steelp02
7d067e82b2
feat(providers): [copilot.ts]Add OTel cache token parsing including tests and regression checks.
Signed-off-by: steelp02 <pieter.steel@pfizer.com>
2026-06-10 22:58:12 +02:00
iamtoruk
f1bf7a197b feat(report): Claude-scoped agent-type breakdown
Some checks are pending
CI / semgrep (push) Waiting to run
Surfaces real subagent-transcript spend grouped by agentType
(workflow-subagent / Explore / general-purpose / …), read from each agent's
sibling .meta.json (cached on CachedFile; session cache bumped 3→4). This makes
ultra/workflow usage visible — the existing Task-input-based "subagents" section
never sees workflow agents. Shown in `report --format json` (claudeAgentTypes)
and a "Claude Agent Types" dashboard panel that renders only when Claude agent
transcripts exist, so it never appears for the other providers.
2026-06-10 11:45:28 +02:00
iamtoruk
aa07d5c939 fix(parser): count workflow/ultracode subagent usage (#470)
collectJsonlFiles only read agent transcripts directly under `subagents/`, but
the workflow feature nests them at `subagents/workflows/<wf>/agent-*.jsonl`, so
their tokens were dropped — undercounting whenever workflow/ultracode was on.
Walk the `subagents/` subtree recursively. Verified on real data: a workflow-
using project recovered ~16% of its cost, with no change to other projects.
2026-06-10 11:45:28 +02:00
iamtoruk
e7c0e21846 fix(vercel-gateway): route network sources through aggregation
The synthetic source path has no on-disk file, so fingerprintFile returned
null and parseProviderSources dropped the source before parsing — the provider
always reported $0 even with a key set. Add a `network` provider flag; such
sources skip the fingerprint gate, re-fetch each run with a synthetic
fingerprint, and keep the gateway's reported cost (instead of recomputing from
tokens, which would be $0 for any model codeburn can't price). Adds an
end-to-end test through parseAllSessions.
2026-06-10 00:09:31 +02:00
Gaurav Sisodia
a2e18d79e7
fix(cursor): period-aligned lookback; add Vercel AI Gateway provider (#432)
Opt-in Vercel AI Gateway provider (AI_GATEWAY_API_KEY/VERCEL_OIDC_TOKEN), inert without a key. Cursor lookback now period-aligned with a 6-month floor. Gateway fetch hardened on merge with an 8s timeout and try/catch fallback.
2026-06-09 23:01:43 +02:00
KirDE
35a8518518
feat(antigravity-ide): added support for antigravity IDE (#418) 2026-06-09 22:12:01 +02:00
Tiago Santos
cf35854b09
feat: add devin provider (#444)
* feat: add devin provider

* feat: add devin to gnome extension and improve dev scripts

* fix: fix local installer

* chore: cleanup unecessary changes and address pr comments
2026-06-09 21:58:31 +02:00
Resham Joshi
e83160f415
feat(pricing): proxy-aware cost attribution for subscription-backed Claude (#417) (#459)
Claude Code routed through a GitHub-Copilot-backed proxy (ANTHROPIC_BASE_URL
-> claude-code-over-github-copilot / claudegate) costs ~$0 marginal but was
priced at full Anthropic API rates, producing a misleading cost figure. The
JSONL records only the model name and no endpoint, so proxying cannot be
auto-detected; the user declares it.

Add a `proxyPaths` config (managed via a new `codeburn proxy-path` subcommand)
listing project directories served through a subscription proxy. Sessions whose
canonical path is under one keep their full API-rate totalCostUSD (the billable
would-be figure is never destroyed) and additionally report totalProxiedCostUSD,
so the JSON report overview exposes cost / proxiedCost / netCost
(netCost = cost - proxiedCost). With no proxyPaths configured the new fields are
0 and every existing consumer is unchanged.

Design: "full cost, flagged" was chosen over zeroing cost so a misconfigured or
since-changed path can never silently erase real Anthropic spend. Attribution is
project-level (one canonical path per project), computed in a single helper
(summarizeProject) that all ProjectSummary builders route through, including the
cross-provider merge in parseAllSessions (re-derived from the merged total so a
repo used with both Claude and Codex stays correct). The in-memory session-cache
key folds in a proxy-config hash so toggling proxyPaths in a long-lived process
cannot serve stale attribution. Path matching is segment-boundary anchored
(/foo does not match /foobar), trailing-slash and backslash tolerant, leading-
slash agnostic (so a non-Claude provider's slash-stripped path matches the same
way Claude's absolute path does), and case-folded only on case-insensitive
filesystems (macOS/Windows, not Linux). The proxy-path CLI sanitizes a
hand-edited config.json (non-array / non-string entries) rather than crashing.

Tested: isProxiedPath matching matrix (boundary, case, Windows, empty, root,
multi-path, leading-slash form); config-hash distinctness/order-independence;
end-to-end attribution through parseAllSessions incl. the critical negative
cases (real spend must not be zeroed); cross-provider Claude+Codex merge;
Codex-only project under a proxy path; date-range-filtered attribution;
cache-staleness after a config change; and the proxy-path CLI add/list/remove,
malformed-config robustness, and the report --format json overview.

Scope note: proxiedCost/netCost currently surface in `report --format json`
only; wiring them into the TUI dashboard and menubar payload is a follow-up.
2026-06-09 21:30:57 +02:00
Resham Joshi
ad251cfa3d
chore(pricing): drop manual Fable/Mythos patch; fable now gap-filled from models.dev/OpenRouter; keep Fable 5 name (#464) 2026-06-09 21:22:38 +02:00
Resham Joshi
a385f65dee
feat(pricing): automatic gap-fill from models.dev and OpenRouter (#457)
Keep model pricing automatic instead of hand-coding new models. The bundler
now layers three sources in priority order: LiteLLM (broad list prices),
hand-curated MANUAL_ENTRIES overrides, then a separate last-resort fallback
file gap-filled from models.dev first-party makers (official direct prices)
and OpenRouter (resale backstop). New models such as MiniMax-M3 ($0.6/$2.4)
now price correctly with no per-model code.

The fallback is written to its own pricing-fallback.json and consulted only
case-insensitively as the final step in getModelCosts, so a reseller variant
name can never shadow a canonical or aliased match.

Fixes surfaced while building and verifying this:
- Alias precedence: LiteLLM ships snowflake/claude-4-opus ($5), which the
  bundler strips to a bare claude-4-opus key that shadowed the curated alias
  to claude-opus-4 ($15 official). An explicit alias for a bare name now wins
  over a coincidental stripped reseller key; the prefixed gateway price is
  still returned for the fully-qualified id.
- Zero-stub guard: LiteLLM [0,0] price stubs (e.g. GigaChat-2-Max) are
  excluded from the case-insensitive index so a case-mismatched query stays
  null and keeps firing the unknown-model warning instead of silently
  reporting $0.
- Negative-sentinel guard: OpenRouter returns -1 for variable/BYOK-priced
  models. The bundler now rejects any non-positive rate pair (and strips the
  sentinel from cache fields) so a negative per-token cost can never ship and
  subtract from spend totals.

Bundler hardening: bareKey strips @pin and date suffixes to match the runtime
canonical form, seen-set dedupes on both full and bare key shapes, and it logs
MANUAL_ENTRIES now covered upstream plus models.dev allowlist drift. Extracted
buildCosts so the cache-cost heuristics live in one place. Added a data-hygiene
test that fails CI if a rebundle reintroduces negative, free, or unreachable
fallback entries.
2026-06-09 21:17:23 +02:00
Resham Joshi
c36f3afa76
chore(pricing): temp Fable 5 + Mythos 5 launch pricing ($10/$50 per M) + names until LiteLLM indexes them (#463) 2026-06-09 20:51:51 +02:00
Resham Joshi
8e460096e3
fix(codex): content-address fork dedupe key to stop undercounting divergent events (#458)
Some checks failed
CI / semgrep (push) Has been cancelled
Forked Codex sessions copy the parent's entire token_count history
(re-timestamped), so those replays are keyed into the parent's namespace
(forkedFromId) and deduped to avoid double-counting the parent's spend. But the
key used cumulativeTotal alone, which is too coarse: a genuine post-divergence
fork event whose running total coincidentally equals some parent total collided
with it and was dropped, undercounting real spend.

Add the cumulative token breakdown (input, cached, output, reasoning) to the
dedupe key. A fork replays those cumulative figures verbatim, so a true replay
still collides and parent and fork are not double-counted, while genuinely
different work that happens to reach the same cumulative total stays distinct.

The breakdown must come from the CUMULATIVE totals, not the per-event deltas:
the deltas are computed against a running `prev` that the fork advances
differently once the 5s replay cutoff skips some events, so a delta-based key
would spuriously diverge on a replay and double-count it (in the total-only
fallback branch).

This is the correct fix for issue #413. The reported "undercount" is mostly
replayed parent history being correctly credited to the parent, not lost; the
issue's suggested change (key on the fork's own session id) would instead
re-double-count the entire replayed history. Three regression tests pin the
invariants: a replay past the 5s cutoff counts once, a divergent fork event
sharing a parent's cumulative total is kept, and a total-only fork whose replay
straddles the cutoff does not overcount.
2026-06-07 07:29:42 +02:00
Resham Joshi
0edc8644aa
test(copilot): add JetBrains coverage; fix Windows path inference (#433 follow-up) (#456)
Some checks are pending
CI / semgrep (push) Waiting to run
Follow-up to #433. Adds tests for the JetBrains format: discovery of a jb
chat.jsonl, parsing into a call with inferred model/tools/user message, the
isJetBrainsFormat routing guard (legacy user.message files must not route to
the JB parser), and the id-less dedup fallback.

Also fixes inferJBProjectFromContent: it split homedir() on the platform
separator but the recorded tool path on a fixed '/', so project inference
always fell back to the raw session id on Windows. Split both on either
separator.
2026-06-06 23:32:56 +02:00
AgentSeal
5a41f39944 Merge PR #423 (local-model savings) onto main, re-homing payload savings into usage-aggregator
Resolves conflicts from the post-PR refactor that moved buildPeriodData,
hydrateCache, and the menubar payload builder out of main.ts into
usage-aggregator.ts. The PR's savings additions to those functions are
re-homed there; config.ts keeps both new fields; parser.ts keeps both imports;
redact.ts session details carry savingsUSD.
2026-06-06 22:14:13 +02:00
Resham Joshi
efa8593cc5
fix(parser): cache parse failures so broken files aren't re-read every run (#441 follow-up) (#453)
Some checks are pending
CI / semgrep (push) Waiting to run
Follow-up to #450. When a session file throws during parse it was excluded but
left uncached, so every refresh (~4x/min in the menubar) re-read and re-parsed
it, and only the first failing file per provider was ever surfaced.

- Add a negative-result marker: a failed file is cached as { fingerprint,
  turns: [], failed: true }. reconcileFile treats it as 'unchanged' at the same
  fingerprint, so it's skipped (no re-read) until the file changes. Empty turns
  => contributes no usage.
- Warn per offending file (with its path), capped at 5 per provider per run,
  instead of once-per-provider — so a systemic break surfaces more than one file
  without flooding. Cached markers keep it quiet across refreshes.

Tests: marker round-trips through save/load; reconcile stays 'unchanged' at the
same fingerprint and re-parses when the file changes.
2026-06-06 21:10:10 +02:00
Resham Joshi
e8009c4559
fix(parser): tolerate string message content; isolate per-file parse failures (#441) (#450)
Some checks are pending
CI / semgrep (push) Waiting to run
Some agents (Pi, and others for injected turns) write a message's `content`
as a string instead of an array of blocks. Parsers did `(content ?? []).filter`,
which throws on a string — and because the daily-cache backfill swallowed parse
errors, one bad session silently wiped the entire trend/history.

- Add normalizeContentBlocks(): string -> one text block, array -> as-is (by
  reference; drops null/undefined elements so the same crash can't happen one
  level down), else -> []. Applied across pi/codex/droid/cursor-agent and the
  Claude path in parser.ts.
- Isolate per-file parse failures in parseProviderSources: skip the offending
  file (warn once per provider) instead of re-throwing and aborting the whole
  backfill. The stale cache entry is already cleared, so the file is excluded.
- Surface backfill failures in hydrateCache via stderr instead of silently
  returning an empty cache.

Likely fixes #425 (previous-day always 0) for the throwing-file cause.
Tests: content-utils unit tests + a Pi string-content regression test.
2026-06-06 04:01:12 +02:00
Resham Joshi
f57ad64ce7
fix(network): add timeouts to critical-path fetches (#445) (#448)
The pricing fetch (loadPricing -> fetchAndCachePricing) runs on every CLI
invocation, and the macOS menubar shells out to the CLI and blocks on its
exit. fetch() had no timeout, so a half-open network after wake-from-sleep
made it hang forever once the 24h pricing cache expired — wedging the
menubar on its loading spinner until relaunch.

Add a shared fetchWithTimeout helper (8s default, AbortSignal.timeout) and
apply it to the two daily-critical-path fetches: pricing (models.ts) and
the currency rate (currency.ts). On timeout the existing catch falls back
to the bundled price snapshot / cached or USD rate.

Reproduced on main (stale cache + black-holed host -> hangs indefinitely);
with the timeout the same scenario aborts in 8s and renders via fallback.
2026-06-06 03:25:36 +02:00
Resham Joshi
77340e52b8
fix(models-report): stop double-counting cache reads (#447)
cacheReadInputTokens (Anthropic) and cachedInputTokens (OpenAI) name the
same tokens. ~11 providers populate both with the same value, so summing
them doubled the cache-read token figure in the models report. Take the
max instead. Cost is unaffected (calculateCost never used the sum).
2026-06-06 03:14:51 +02:00
Thomas Kosiewski
e0051fc403
feat(providers): add coder/mux as a datasource (#438)
* feat(providers): add coder/mux as a datasource

Reads coder/mux session data from ~/.mux/sessions/<workspaceId>/chat.jsonl and normalizes per-assistant-message token usage into ParsedProviderCall. Discovery resolves project names from config.json; the token decomposition matches mux's own inclusive input/output accounting, and cost is recomputed via LiteLLM. Includes unit tests and a provider doc.

Change-Id: Ie6ce9d41254d8bf05ff0965b443328dfa7b598de
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Thomas Kosiewski <tk@coder.com>

* fix(providers): discover mux sub-agent transcripts

discoverSessions only globbed sessions/<id>/chat.jsonl and skipped each
spawned sub-agent's transcript at
sessions/<id>/subagent-transcripts/<childTaskId>/chat.jsonl. Against a real
~/.mux (629 workspaces) those nested files are 5,889 sessions and ~51% of all
assistant messages, so sub-agent spend was silently dropped: total mux usage
went from $17,113 to $21,564 (+26%) once counted.

Walk the subagent-transcripts dir per workspace and attribute each child
session to the parent's project. Dedup is unaffected: the parser keys off the
<childTaskId> dir name, which is disjoint from every workspace id, so each call
is still counted once. Cross-checked parsed per-model token totals against
mux's sibling session-usage.json.

Also corrects the provider doc, which wrongly claimed sub-agents get their own
top-level sessions/<id>/chat.jsonl, and documents the Google reasoning>output
decomposition edge case.

Change-Id: I1d43f26eec7c9c6c523e5ea541e2ff8d0c3aa07e
Signed-off-by: Thomas Kosiewski <tk@coder.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 03:04:24 +02:00
Resham Joshi
3cdd13881f
feat(menubar): configure CLAUDE_CONFIG_DIRS via Settings (#434) (#436)
Adds a "Config Directories" section under the Claude settings tab so users
can aggregate usage across multiple Claude config directories (work /
personal accounts) from the GUI. The menubar is an accessory app that
doesn't inherit the user's shell environment, so CLAUDE_CONFIG_DIRS was
previously unreachable from the app.

Rather than injecting the value as an env var into every spawned subprocess
(which would force arbitrary user paths through the shell/AppleScript
allowlist that deliberately excludes shell metacharacters), the list is
persisted to the shared ~/.config/codeburn/config.json. The CLI reads it
regardless of how it's launched, so both the menubar's data refresh and
terminal-launched `report`/`optimize` honor it consistently.

CLI: getClaudeConfigDirs() now reads a claudeConfigDirs array from config
as a fallback below the CLAUDE_CONFIG_DIRS / CLAUDE_CONFIG_DIR env vars
(env still wins for per-shell overrides), above the ~/.claude default.

Menubar: CLIClaudeConfig mirrors CLICurrencyConfig's flock-guarded write;
the Settings UI offers an add/remove list with a folder picker and forces
a refresh on edit.
2026-06-06 02:30:46 +02:00
Resham Joshi
a6601efc60
Merge pull request #430 from PorunC/feat/add-cny-currency
Add CNY currency support
2026-06-03 23:25:32 +02:00
AgentSeal
692bc09729 Merge feat/codeburn-mcp: MCP server for AI agent usage queries
Adds stdio-based MCP server (codeburn mcp) exposing get_usage and
get_savings tools. Includes pseudonymized project names with per-install
salt, session detail redaction, structured output schemas, and inflight
request coalescing.
2026-06-03 22:48:36 +02:00
Misaka
906c5338e4 Add CNY currency support 2026-06-03 10:45:39 +08:00
AgentSeal
f748d3463b fix(test): kilo-code tests fail on machines with KiloCode installed
Some checks are pending
CI / semgrep (push) Waiting to run
discoverSessions always checks the SQLite path at ~/.local/share/kilo
regardless of overrideDir, so the test found real sessions on the host.
Filter to override-dir sessions and avoid hardcoded /tmp paths.
2026-06-03 01:03:39 +02:00
AgentSeal
679f7ba5a6 fix(mcp): harden redaction, error responses, and pre-warm race
- Add per-install random salt to pseudonym hash to prevent rainbow table
  reversal of common project names
- Redact session details (dates, models) when project names are hashed
  to prevent re-identification via cost fingerprinting
- Return structuredContent in error responses to satisfy strict MCP
  clients that validate against declared outputSchema
- Remove pre-warm fire-and-forget that raced with the inflight map
- Fix empty markdown table producing malformed cells
- Add tests for session detail redaction and cross-field consistency
2026-06-03 00:56:30 +02:00
iamtoruk
1e54967d97 feat(mcp): get_usage + get_savings tools with annotations, schemas, coalescing 2026-06-02 02:16:10 -07:00
iamtoruk
296085dff1 feat(mcp): markdown table renderers for usage and savings 2026-06-02 02:13:51 -07:00