feat: add FinalToken v1 for Claude and Codex usage (#2)
FinalToken v1: a NativeAOT tray app for Windows 11 and CachyOS that tracks Claude Code and Codex usage and limits through their CLIs only, with no provider sign-in and no tokens (R1-R7, D1-D11). - Core: incremental collectors for Claude transcripts and Codex rollouts, limit probes through `claude -p /usage` and `codex app-server`, a journaled history store, the refresh engine, pace and popup decisions, and the snapshot.json contract. - App (Avalonia): stats panel with limit bars, pace, projections, token totals, charts, limit history and breakdowns; tray, settings, non-activating pace popups, single-instance activation, start with the OS, and the Off/Ask/Automatic Stream Deck plugin install. - Stream Deck plugin (SDK v2, NativeAOT) for Elgato and OpenDeck. - finaltoken-cli, tools/publish.py, the documentation check and the agent review workflow. Closes #1
This commit was merged in pull request #2.
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
# Recorded decisions
|
||||
|
||||
These bind. Each says what was decided, why, and what it gives up. A decision changes only through
|
||||
a PR that edits its text here and carries the `type/decision` label. Code, commits and PRs cite
|
||||
the IDs instead of restating the text. The requirements (R1 to R7) are in
|
||||
[requirements.md](requirements.md).
|
||||
|
||||
## D1 — .NET 10, C# 14 and NativeAOT for win-x64 and linux-x64
|
||||
|
||||
**Decision.** Every shipped executable (the app, the CLI and the Stream Deck plugin) targets
|
||||
`net10.0` with C# 14 and publishes NativeAOT for `win-x64` and `linux-x64`. `global.json` asks
|
||||
for SDK 10.0.100 or newer within 10.0 (`rollForward: latestFeature`), so the SDK from CachyOS's
|
||||
package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers.
|
||||
JSON goes through System.Text.Json source generation only. Nothing uses reflection-driven
|
||||
serialization, binding or loading, or runtime code generation.
|
||||
|
||||
**Why.** R1. .NET 10 is the newest stable release on 2026-10-14; .NET 11 is not released yet.
|
||||
|
||||
**Gives up.** .NET 11 preview features, and libraries that need reflection at run time.
|
||||
|
||||
## D2 — The CLIs are the only interface to a provider
|
||||
|
||||
**Decision.** FinalToken never reads, stores, logs or sends a credential (OAuth token, API key,
|
||||
cookie). It never opens a provider login and never calls a provider's HTTP API itself. It reads
|
||||
the files the CLIs write and runs the installed `claude` and `codex` executables as child
|
||||
processes, which use their own login. It never opens credential files such as
|
||||
`~/.claude/.credentials.json` or `~/.codex/auth.json`, or the OS keychain. Only counts, model
|
||||
names, timestamps and project paths leave a parser; message text is never kept. A missing or
|
||||
logged-out CLI makes its provider show "unavailable" with the reason, and the other provider keeps
|
||||
working.
|
||||
|
||||
**Why.** R2, R3.
|
||||
|
||||
**Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed.
|
||||
|
||||
## D3 — Claude data sources
|
||||
|
||||
**Decision.**
|
||||
|
||||
- **Tokens.** The transcripts `<config>/projects/**/*.jsonl`, where `<config>` is
|
||||
`CLAUDE_CONFIG_DIR` or `~/.claude`. Each assistant entry gives `message.usage` (input, output,
|
||||
cache creation and cache read tokens), `message.model`, `timestamp` and `cwd` (the project).
|
||||
One API response can appear on several lines, and a resumed session copies earlier ones, so a
|
||||
response counts once, keyed on `message.id` and `requestId`.
|
||||
- **Limits.** `claude -p "/usage" --output-format json --no-session-persistence`, run with
|
||||
FinalToken's data directory as the working directory. Claude Code answers it locally
|
||||
(`num_turns` 0, cost 0) and `--no-session-persistence` keeps it out of the transcripts. The
|
||||
`result` text holds lines such as
|
||||
`Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)` and
|
||||
`Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)`. Each becomes a
|
||||
limit window: the session window is 5 h, a week window 7 d. Only lines that start with
|
||||
`Current ` are limit lines; other prose is ignored and parsing stops at the "What's
|
||||
contributing to your limits usage?" section. A limit line that does not parse is reported as a
|
||||
diagnostic and skipped; the parser never guesses a value.
|
||||
|
||||
**Why.** Claude Code has no machine-readable limit command, and `/usage` is the CLI's own view.
|
||||
Claude Code deletes transcripts after `cleanupPeriodDays` (30 days by default), so history
|
||||
comes from FinalToken's own store ([D5](#d5--own-history-store)), not from re-reading
|
||||
transcripts.
|
||||
|
||||
**Gives up.** Reset times are known only to the minute, and a Claude Code release can change the
|
||||
text. Fixtures pin the known formats so a change fails visibly.
|
||||
|
||||
## D4 — Codex data sources
|
||||
|
||||
**Decision.**
|
||||
|
||||
- **Tokens.** The rollouts `<home>/sessions/**/rollout-*.jsonl` and
|
||||
`<home>/archived_sessions/**/rollout-*.jsonl`, where `<home>` is `CODEX_HOME` or `~/.codex`.
|
||||
`event_msg` entries of type `token_count` carry `info.total_token_usage` (input, cached input,
|
||||
output and reasoning output tokens). A session's usage is the increase of that total between
|
||||
consecutive events, so a repeated event adds nothing. The model comes from the latest
|
||||
`turn_context` entry before the event.
|
||||
- **Limits.** `codex app-server` over stdio JSON-RPC: `initialize`, then
|
||||
`account/rateLimits/read`. The fallback is the latest `rate_limits` object in the newest
|
||||
rollout: `primary` and `secondary` windows with `used_percent`, `window_minutes` and
|
||||
`resets_at` in Unix seconds.
|
||||
|
||||
**Why.** R2, R3. The app server is the CLI's machine interface, and the rollouts are written on
|
||||
every turn.
|
||||
|
||||
**Gives up.** The app server is marked experimental; the rollout fallback keeps limits working
|
||||
when it changes.
|
||||
|
||||
## D5 — Own history store
|
||||
|
||||
**Decision.** FinalToken keeps its own history in its data directory, which is
|
||||
`Environment.SpecialFolder.LocalApplicationData/FinalToken` (`%LOCALAPPDATA%\FinalToken` on
|
||||
Windows, `~/.local/share/FinalToken` on Linux). It holds hourly token buckets per provider, model
|
||||
and project, and limit samples (time, provider, window, used percent, reset). A sample is kept
|
||||
when it differs from the window's previous one, and otherwise at most once an hour. Hours are
|
||||
stored in UTC; day series, today and the week follow the local calendar day, including days of 23
|
||||
and 25 hours at daylight-saving changes. All files are JSON or JSON lines through
|
||||
System.Text.Json source generation. There is no database dependency.
|
||||
|
||||
- **Writing.** Each refresh that found something new appends one newline-terminated transaction
|
||||
to a journal. A torn last line is ignored on load and cut off before the next append. When the
|
||||
journal reaches 8 MiB, it is compacted into one file per month and a state checkpoint, each
|
||||
written atomically (a temporary file in the same directory, then a replace), and the journal
|
||||
starts empty. Transactions hold absolute values, so replaying them after an interrupted
|
||||
compaction gives the same result. A refresh that found nothing new writes no history.
|
||||
- **Reading.** Files that are replaced atomically (`snapshot.json`, settings, the month files,
|
||||
the checkpoint, the activation request) are opened with read, write and delete sharing, and the
|
||||
replace retries briefly, so a reader never makes a write fail on Windows.
|
||||
- **Scanning.** For each source file the store remembers its length, its last write time and how
|
||||
far it read. An unchanged file is not opened; otherwise only appended bytes are read. A file
|
||||
that shrank or was replaced is read again from the start.
|
||||
- **Counting once.** A response counts once across restarts, rescans and resumed sessions. Claude
|
||||
responses are keyed on `message.id` and `requestId` (D3). Their keys are kept for 60 days,
|
||||
twice Claude Code's default cleanup period, and Claude entries older than that are ignored.
|
||||
Codex sessions keep their last cumulative total and its time (D4), so a replayed or archived
|
||||
copy adds nothing.
|
||||
- **One writer.** One process writes the store at a time, guarded by an exclusive lock file in
|
||||
the data directory. While another process holds it, the CLI only reads the current
|
||||
`snapshot.json` and says so. `FINALTOKEN_DATA_DIR` overrides the data directory, for tests and
|
||||
parallel checks.
|
||||
|
||||
**Why.** R4 needs history longer than the CLIs keep theirs ([D3](#d3--claude-data-sources)). A
|
||||
file store has no native dependency to ship with NativeAOT. Rewriting all history on every
|
||||
refresh wrote about 27 GB a day on the developer's machine; the journal makes writes follow new
|
||||
data.
|
||||
|
||||
**Gives up.** Ad-hoc queries, token history finer than an hour, limit samples finer than an hour
|
||||
while the value does not change, and Claude history older than 60 days on a fresh install.
|
||||
|
||||
## D6 — Refresh
|
||||
|
||||
**Decision.** Token scans run when a watched source directory changes (debounced by 2 s) and at
|
||||
least every 60 s. Limit probes ([D3](#d3--claude-data-sources), [D4](#d4--codex-data-sources))
|
||||
run every 5 min by default (configurable from 1 to 60 min), and also after new tokens arrive,
|
||||
but at most once a minute per provider. Probes run one at a time per provider with a 60 s
|
||||
timeout; a probe that times out has its process tree killed and counts as failed. A failed probe
|
||||
keeps the last good sample and marks it with its age. Shutting down cancels the running work
|
||||
and waits for it. Every child process gets its own standard input, output and error pipes, decoded
|
||||
as UTF-8, because a GUI host has no console and no console code page; stdin is closed at once
|
||||
unless the probe is the Codex RPC.
|
||||
|
||||
**Why.** Limits change only when tokens are spent, and a probe starts a CLI process, so probing
|
||||
follows token activity instead of a tight timer.
|
||||
|
||||
**Gives up.** Limit changes caused by other devices or the web show up only at the next timed
|
||||
probe.
|
||||
|
||||
## D7 — Pace
|
||||
|
||||
**Decision.** For a limit window with used percent `u`, length `W` and reset time `r`, at time `t`:
|
||||
|
||||
- elapsed fraction `e = 1 − (r − t) / W`, clamped to 0..1
|
||||
- expected use `100·e`, pace delta `d = u − 100·e` in percentage points
|
||||
- **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track**
|
||||
otherwise. The threshold defaults to 10 points and is a setting.
|
||||
- when ahead, the projected time of reaching 100 % at the average rate so far,
|
||||
`t + (100 − u) · e·W / u`, shown only if it comes before `r`.
|
||||
|
||||
A window without a known length or reset has no pace; FinalToken never guesses one.
|
||||
|
||||
**Why.** R5. A straight line from the window's start to its reset is a pace the user can check
|
||||
by hand.
|
||||
|
||||
**Gives up.** Weekday and working-hour patterns.
|
||||
|
||||
## D8 — Desktop app
|
||||
|
||||
**Decision.**
|
||||
|
||||
- **Toolkit.** Avalonia, the newest stable release that supports NativeAOT (checked on nuget.org
|
||||
when the app is built), with the Fluent theme, compiled bindings only and CommunityToolkit.Mvvm
|
||||
source generators. Charts are small custom controls drawn with Avalonia's `DrawingContext`;
|
||||
there is no chart library.
|
||||
- **Lifecycle.** One instance per user, guarded by the store's lock file
|
||||
([D5](#d5--own-history-store)). Starting it again writes an activation request file to the data
|
||||
directory and exits; the running instance watches for it and brings its window to the front.
|
||||
The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app
|
||||
running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an
|
||||
opt-in setting.
|
||||
- **Popups (R5).** A small borderless, topmost window that does not take focus, at the
|
||||
bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click
|
||||
opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to
|
||||
ahead or behind, at most once per window and state until the state changes again, with
|
||||
hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per
|
||||
provider and per state.
|
||||
- **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma
|
||||
Wayland session, because Wayland clients cannot place their own windows.
|
||||
|
||||
**Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A
|
||||
chart library would add reflection and size for three chart types.
|
||||
|
||||
**Gives up.** Native OS notification styling, and a native Wayland window.
|
||||
|
||||
## D9 — The snapshot file is the app's only output to other processes
|
||||
|
||||
**Decision.** After each refresh the app writes `snapshot.json` atomically to its data directory
|
||||
([D5](#d5--own-history-store)). It carries a schema version `v` (1 to begin with), the time it
|
||||
was made, the refresh interval, the path of the app's executable and, per provider, its status
|
||||
and reason, its limit windows (used percent, reset, length, pace state, delta and projection)
|
||||
and its token totals for today, the current session window and the current week. The DTOs and
|
||||
their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the
|
||||
Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a
|
||||
snapshot older than three refresh intervals as stale. The app gives the engine its own path; a
|
||||
CLI refresh keeps the path already in the snapshot, and a snapshot without one has none, so a
|
||||
reader never mistakes its own path for the app's.
|
||||
|
||||
**Why.** R6 needs the stats outside the app. A file has no network surface, and it survives a
|
||||
restart of either side.
|
||||
|
||||
**Gives up.** Updates faster than the reader's poll interval.
|
||||
|
||||
## D10 — Stream Deck plugin
|
||||
|
||||
**Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder
|
||||
`de.finalfactory.finaltoken.sdPlugin`, its manifest SDK version 2. The plugin executable is C#
|
||||
NativeAOT: `CodePathWin` for Elgato Stream Deck on Windows, and `CodePathLin` for OpenDeck on
|
||||
Linux, since Elgato's software does not run there. It speaks the Stream Deck WebSocket protocol
|
||||
itself through `System.Net.WebSockets`, without an SDK package. It reads `snapshot.json`
|
||||
([D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes)) and draws each key as
|
||||
an SVG image through `setImage`. One action, "Stat", has a property inspector (HTML in the
|
||||
plugin folder) that picks the provider and the metric: session percent, week percent, pace
|
||||
delta, time to reset, tokens today or tokens this week. The key's colour follows the pace state.
|
||||
A key press opens the app's stats panel. A missing or stale snapshot shows "offline".
|
||||
|
||||
**Why.** R6 and R1 with one language and one snapshot contract.
|
||||
|
||||
**Gives up.** The helpers of Elgato's Node SDK, and marketplace distribution.
|
||||
|
||||
## D11 — Plugin install and update
|
||||
|
||||
**Decision.** A setting has three values: Off, Ask (the default) and Automatic. The app ships the
|
||||
built plugin folder at `<app directory>/streamdeck/de.finalfactory.finaltoken.sdPlugin`. On start
|
||||
it compares the shipped manifest's `Version` with the installed plugin's. The install targets are
|
||||
`%APPDATA%\Elgato\StreamDeck\Plugins\` on Windows and OpenDeck's plugin directory on Linux,
|
||||
native or Flatpak. Ask shows a popup with Install (or Update) and Not now; Automatic installs
|
||||
without asking. An install replaces the plugin folder. When the Stream Deck software is running,
|
||||
the app stops it first and starts it again afterwards. Nothing is installed while the setting is
|
||||
Off, or in Ask mode before the user presses Install. When no Stream Deck software is found, the
|
||||
setting says so and nothing happens.
|
||||
|
||||
**Why.** R7.
|
||||
|
||||
**Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks.
|
||||
Reference in New Issue
Block a user