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:
2026-10-14 22:11:19 +02:00
parent 6d67f157a5
commit f8afd11679
106 changed files with 6583 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
# Agent review
Every PR needs a passing review from a fresh agent session before it merges. The review sets the
`agent-review` commit status on the PR's head commit. A push after the review moves the head, so
the PR needs a new review.
## Starting a review (author)
After the last push, start a reviewer that has none of the work's context: a new agent session, or
a subagent whose whole prompt is `Review PR #<N> of FinalFactory/FinalToken following
docs/agents/review.md`. Use a capable model at high effort. The PR body, the issue and the earlier
reviews on the PR explain the change; the reviewer gets no other briefing.
## Reviewing (reviewer)
1. Record the head commit you review:
`tools/gitea.sh GET /repos/FinalFactory/FinalToken/pulls/<N> | jq -r .head.sha`.
2. Read the PR, its linked issue, the root `AGENTS.md`, the `AGENTS.md` of every touched project,
the [requirements](../requirements.md) and the [recorded decisions](../decisions.md) the change
touches, and the earlier agent reviews on the PR.
3. Read the whole diff: `git fetch origin && git diff origin/master...<sha>`. On a re-review it is
context; step 5 says what can block.
4. Check out the head in a separate worktree and run the checks in
[AGENTS.md](../../AGENTS.md#building-and-testing) that the change affects, always including
`python -B tools/docs/check_docs.py`.
5. If the PR already has a failed agent review, this is a re-review. Check that each blocking
finding of the last failed review is fixed or answered. Then review only the author's commits
since the commit that review covered (named in its first line), leaving out what came in from
`master`: `git log -p --no-merges ^<old sha> ^origin/master <sha>`. Only these two can block.
Anything else you notice is a note, even a bug; the author decides whether to fix it in this
PR. A full pass in every round finds new problems each time, and the loop never ends.
6. Look for:
- **Spec**: it does what the issue asks and stays inside its scope.
- **Decisions**: it matches the recorded decisions, or the PR changes their text and carries
the `type/decision` label.
- **Correctness**: bugs, edge cases, error handling, concurrency, resource cleanup.
- **Rules**: the rules in `AGENTS.md` and in the touched projects' `AGENTS.md`.
- **Tests**: new behaviour has tests.
- **Docs**: docs and `AGENTS.md` files match the new behaviour, commands and decisions.
7. Decide the verdict. `fail` only for a blocking finding: a bug, missing behaviour the issue asks
for, code that breaks a recorded decision or a rule from step 6, missing tests for new
behaviour, or a failing check. A check or tool that misses some cases does not break the rule
it guards: name the gap as a note. Everything else is a note and the review passes.
8. Write the review to a file in this format, then post it with
`tools/agent-review.sh <N> <sha> <pass|fail> <file>`:
```markdown
## Blocking
1. `path:line`: what is wrong, why it matters, and the fix.
## Notes
- `path:line`: the suggestion.
## Checked
What you read and ran, on which commit.
```
The reviewer reports and leaves the code to the author.
## After a failed review (author)
Fix each blocking finding, or answer it in a PR comment when it is wrong. Push, then start a new
fresh review.
After the second failed review, stop. Comment on the issue with the open findings, add the
`status/needs-decision` label and leave it to a developer: merge anyway, allow more rounds, split
the PR or close it.
+239
View File
@@ -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.
+14
View File
@@ -0,0 +1,14 @@
# Requirements
Set by schmidt.florian on 2026-10-14 ([#1](https://git.finalfactory.de/FinalFactory/FinalToken/issues/1)).
Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken meets them.
- **R1** NativeAOT on the newest .NET. Cross-platform: at least Windows 11 and CachyOS.
- **R2** No sign-in to an AI provider inside the app and no API key or OAuth token. Data comes
through the providers' command-line tools.
- **R3** Supported providers: at least Codex and Claude.
- **R4** Opening the app shows a comprehensive stats panel, history included.
- **R5** Small, non-intrusive popups remind the user when usage runs ahead of or behind the pace
of a limit.
- **R6** A Stream Deck plugin shows selected stats on its buttons.
- **R7** The app installs or updates the Stream Deck plugin automatically, as the user chooses.