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
@@ -0,0 +1,61 @@
using System.Globalization;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace FinalToken.Core.Collectors;
public static partial class ClaudeUsageParser
{
[GeneratedRegex(@"^Current (?<label>session|week \([^)]+\)): (?<used>\d+(?:\.\d+)?)% used\s*[·•]\s*resets (?<date>[A-Za-z]{3} \d{1,2}), (?<clock>\d{1,2}(?::\d{2})?[ap]m) \((?<zone>[^)]+)\)$", RegexOptions.CultureInvariant)]
private static partial Regex UsageLine();
public static IReadOnlyList<LimitWindow> ParseEnvelope(string json, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
{
try
{
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
if (root.Field("is_error").ValueKind != JsonValueKind.False || root.Field("num_turns").Integer() != 0 ||
root.Text("local_command") != "usage" || root.Text("result") is not { } text)
{ diagnostics.Add(Provider.Claude, "claude-envelope", "Usage command did not return a successful local result."); return []; }
return ParseText(text, sampleTime, diagnostics);
}
catch (JsonException) { diagnostics.Add(Provider.Claude, "claude-envelope", "Malformed usage response."); return []; }
}
public static IReadOnlyList<LimitWindow> ParseText(string text, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
{
List<LimitWindow> windows = [];
foreach (var raw in text.Split('\n'))
{
var line = raw.Trim();
if (line.StartsWith("What's contributing to your limits usage?", StringComparison.Ordinal)) break;
if (!line.StartsWith("Current ", StringComparison.Ordinal)) continue;
var match = UsageLine().Match(line);
if (!match.Success)
{ diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; }
try
{
var used = double.Parse(match.Groups["used"].Value, CultureInfo.InvariantCulture);
if (used is < 0 or > 100) throw new FormatException();
var label = match.Groups["label"].Value;
var length = label == "session" ? TimeSpan.FromHours(5) : TimeSpan.FromDays(7);
var zone = TimeZoneInfo.FindSystemTimeZoneById(match.Groups["zone"].Value);
var local = TimeZoneInfo.ConvertTime(sampleTime, zone);
DateTimeOffset? reset = null;
foreach (var year in new[] { local.Year, local.Year + 1 })
{
var date = DateTime.ParseExact($"{year} {match.Groups["date"].Value}, {match.Groups["clock"].Value}",
["yyyy MMM d, h:mmtt", "yyyy MMM d, htt"], CultureInfo.InvariantCulture, DateTimeStyles.None);
if (zone.IsInvalidTime(date) || zone.IsAmbiguousTime(date)) continue;
var candidate = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(date, zone));
if (candidate > sampleTime && candidate - sampleTime <= length) { reset = candidate; break; }
}
if (reset is null) throw new FormatException();
windows.Add(new(Provider.Claude, label.ToLowerInvariant(), "Current " + label, used, reset, length, sampleTime, "usage"));
}
catch (Exception e) when (e is FormatException or TimeZoneNotFoundException or InvalidTimeZoneException or ArgumentException)
{ diagnostics.Add(Provider.Claude, "claude-reset-parse", "Unknown or invalid usage reset skipped."); }
}
return windows;
}
}
@@ -0,0 +1,136 @@
using System.Security.Cryptography;
using System.Text;
namespace FinalToken.Core.Collectors;
public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> CodexFallback,
int ClaudeAdded = 0, int CodexAdded = 0);
/// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only.
/// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary>
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
string claudeDirectory, string codexDirectory)
{
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
bool claudeEnabled = true, bool codexEnabled = true)
{
var added = 0;
var claudeFiles = claudeEnabled ? FindFiles(Path.Combine(claudeDirectory, "projects"), "*.jsonl", Provider.Claude) : [];
foreach (var path in claudeFiles)
added += await ScanFileAsync(path, Provider.Claude, [], cancellationToken);
var claudeAdded = added;
var codexFiles = !codexEnabled ? [] : FindFiles(Path.Combine(codexDirectory, "sessions"), "rollout-*.jsonl", Provider.Codex)
.Concat(FindFiles(Path.Combine(codexDirectory, "archived_sessions"), "rollout-*.jsonl", Provider.Codex))
.OrderBy(File.GetLastWriteTimeUtc).ToArray();
// D4 fallback belongs to the newest rollout, even when it had no appended bytes this time.
var latest = codexFiles.LastOrDefault();
List<LimitWindow> fallback = [];
foreach (var path in codexFiles)
{
List<LimitWindow> limits = [];
added += await ScanFileAsync(path, Provider.Codex, limits, cancellationToken);
if (path == latest && limits.Count > 0) fallback = limits;
}
if (latest is not null && fallback.Count == 0) fallback = history.Cursor(latest).LatestLimits;
return new(added, fallback, claudeAdded, added - claudeAdded);
}
private IReadOnlyList<string> FindFiles(string directory, string pattern, Provider provider)
{
try { return Directory.Exists(directory) ? Directory.GetFiles(directory, pattern, SearchOption.AllDirectories) : []; }
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{ diagnostics.Add(provider, "scan-directory", "Source directory cannot be enumerated."); return []; }
}
private async Task<int> ScanFileAsync(string path, Provider provider, List<LimitWindow> latestLimits, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
var info = new FileInfo(path);
var cursor = history.Cursor(path);
var length = info.Length;
var lastWrite = info.LastWriteTimeUtc.Ticks;
var creation = info.CreationTimeUtc.Ticks;
if (cursor.ObservedLength == length && cursor.LastWriteTicks == lastWrite && cursor.CreationTicks == creation)
return 0;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
if (stream.Length < cursor.Offset || cursor.CreationTicks != creation ||
cursor.PrefixHash != Fingerprint(stream, 0, cursor.PrefixLength) ||
cursor.TailHash != Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset)))
{
cursor.Offset = 0;
cursor.SessionId = Path.GetFileNameWithoutExtension(path);
cursor.Model = null;
cursor.Project = null;
cursor.LatestLimits = [];
}
var added = 0;
stream.Position = cursor.Offset;
var readBuffer = new byte[65536];
using var line = new MemoryStream();
var consumed = cursor.Offset;
int read;
while ((read = await stream.ReadAsync(readBuffer, cancellationToken)) > 0)
{
var start = 0;
while (start < read)
{
var newline = readBuffer.AsSpan(start, read - start).IndexOf((byte)'\n');
var segmentLength = newline < 0 ? read - start : newline;
line.Write(readBuffer.AsSpan(start, segmentLength));
consumed += segmentLength;
start += segmentLength;
if (newline < 0) break;
consumed++;
start++;
cancellationToken.ThrowIfCancellationRequested();
// Source entries can contain large tool results. An output-capture bound
// belongs to child processes, not to valid transcript records (D3).
{
try
{
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
if (text.Length > 0 && provider == Provider.Claude)
{
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++;
}
else if (text.Length > 0)
{
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++;
if (entry.Limits.Count > 0)
{
latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
cursor.LatestLimits = entry.Limits.ToList();
}
history.AddLimits(entry.Limits);
}
}
catch (DecoderFallbackException) { diagnostics.Add(provider, "scan-encoding", "Invalid UTF-8 source line skipped."); }
}
cursor.Offset = consumed;
line.SetLength(0);
}
}
cursor.CreationTicks = creation;
cursor.PrefixLength = (int)Math.Min(256, cursor.Offset);
cursor.PrefixHash = Fingerprint(stream, 0, cursor.PrefixLength);
cursor.TailHash = Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset));
cursor.ObservedLength = length;
cursor.LastWriteTicks = lastWrite;
history.CursorChanged(path);
return added;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{ diagnostics.Add(provider, "scan-file", "Source file cannot be read."); return 0; }
}
private static string Fingerprint(FileStream stream, long offset, int length)
{
if (length == 0) return "";
stream.Position = offset;
var bytes = new byte[length];
var count = stream.ReadAtLeast(bytes, length, false);
return Convert.ToHexString(SHA256.HashData(bytes.AsSpan(0, count)));
}
}
@@ -0,0 +1,33 @@
using System.Globalization;
using System.Text.Json;
namespace FinalToken.Core.Collectors;
internal static class JsonFields
{
public static JsonElement Field(this JsonElement element, string name) =>
element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) ? value : default;
public static string? Text(this JsonElement element) => element.ValueKind == JsonValueKind.String ? element.GetString() : null;
public static string? Text(this JsonElement element, string name) => element.Field(name).Text();
public static long? Integer(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetInt64(out var value) ? value : null;
public static double? Number(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetDouble(out var value) && double.IsFinite(value) ? value : null;
public static DateTimeOffset? Timestamp(this JsonElement element) => element.Text() is { } text &&
DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time.ToUniversalTime() : null;
public static long Count(this JsonElement element, string name, bool required = false)
{
var field = element.Field(name);
if (!required && field.ValueKind == JsonValueKind.Undefined) return 0;
if (field.Integer() is not { } count || count is < 0 or > 1_000_000_000_000_000) throw new FormatException();
return count;
}
public static TokenCounts Counts(JsonElement usage, bool claude)
{
var input = usage.Count("input_tokens", true);
var output = usage.Count("output_tokens", true);
var read = usage.Count(claude ? "cache_read_input_tokens" : "cached_input_tokens");
var write = usage.Count(claude ? "cache_creation_input_tokens" : "cache_write_input_tokens");
var reasoning = claude ? 0 : usage.Count("reasoning_output_tokens");
return new(input, read, write, output, reasoning,
claude ? checked(input + output + read + write) : usage.Count("total_tokens", true));
}
}
@@ -0,0 +1,34 @@
using FinalToken.Core.Processes;
namespace FinalToken.Core.Collectors;
public sealed record ProbeResult(bool Success, IReadOnlyList<LimitWindow> Windows, string? Reason);
public sealed class LimitProbe(IProcessRunner runner, DiagnosticLog diagnostics, string dataDirectory)
{
public async Task<ProbeResult> RunAsync(Provider provider, CliCommand command, DateTimeOffset sampleTime, CancellationToken cancellationToken)
{
try
{
var result = await runner.RunAsync(new(command, provider == Provider.Claude
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : ["app-server"],
dataDirectory, TimeSpan.FromSeconds(60), provider == Provider.Codex), cancellationToken);
if (result.TimedOut || result.ExitCode != 0 || result.OutputTruncated)
{
var reason = result.TimedOut ? "Limit probe timed out." : "Limit probe failed or exceeded its output bound.";
diagnostics.Add(provider, result.TimedOut ? "probe-timeout" : "probe-failed", reason);
return new(false, [], reason);
}
var windows = provider == Provider.Claude ? ClaudeUsageParser.ParseEnvelope(result.Output, sampleTime, diagnostics)
: CodexLimitsParser.ParseResponse(result.Output, sampleTime, diagnostics);
if (windows.Count > 0) return new(true, windows, null);
diagnostics.Add(provider, "probe-no-limits", "No usable limit windows returned; CLI may be logged out.");
return new(false, [], "No usable limits returned; CLI may be logged out.");
}
catch (Exception) when (cancellationToken.IsCancellationRequested)
{ throw new OperationCanceledException(cancellationToken); }
// D2: a provider's process/protocol failure must not interrupt the other provider.
// Exception messages can contain child output; expose only fixed metadata.
catch (Exception)
{ diagnostics.Add(provider, "probe-failed", "CLI probe could not complete."); return new(false, [], "CLI probe could not complete."); }
}
}
@@ -0,0 +1,88 @@
using System.Text.Json;
namespace FinalToken.Core.Collectors;
public sealed record RolloutEntry(UsageEvent? CumulativeUsage, IReadOnlyList<LimitWindow> Limits);
public static class RolloutParser
{
public static RolloutEntry Parse(string line, ScanCursor cursor, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
{
try
{
using var document = JsonDocument.Parse(line);
var root = document.RootElement;
var payload = root.Field("payload");
switch (root.Text("type"))
{
case "session_meta":
cursor.SessionId = payload.Text("id") ?? cursor.SessionId;
cursor.Project = payload.Text("cwd") ?? cursor.Project;
return new(null, []);
case "turn_context":
cursor.Model = payload.Text("model");
cursor.Project = payload.Text("cwd") ?? cursor.Project;
return new(null, []);
case "event_msg" when payload.Text("type") == "token_count":
if (root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
var limits = CodexLimitsParser.Parse(payload.Field("rate_limits"), time, "rollout", diagnostics);
if (payload.Field("info").ValueKind == JsonValueKind.Null) return new(null, limits);
var counts = JsonFields.Counts(payload.Field("info").Field("total_token_usage"), false);
return new(new(Provider.Codex, time, cursor.Model, cursor.Project, counts,
$"codex:{cursor.SessionId}:{counts.Total}"), limits);
default: return new(null, []);
}
}
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
{ diagnostics.Add(Provider.Codex, "rollout-parse", "Malformed token count entry skipped."); return new(null, []); }
}
}
public static class CodexLimitsParser
{
public static IReadOnlyList<LimitWindow> Parse(JsonElement value, DateTimeOffset sampleTime, string source, DiagnosticLog diagnostics)
{
if (value.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) return [];
List<LimitWindow> windows = [];
var camel = source == "app-server";
var id = value.Text(camel ? "limitId" : "limit_id") ?? "codex";
foreach (var name in new[] { "primary", "secondary" })
{
var window = value.Field(name);
if (window.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) continue;
var used = window.Field(camel ? "usedPercent" : "used_percent").Number();
var minutesField = window.Field(camel ? "windowDurationMins" : "window_minutes");
var resetField = window.Field(camel ? "resetsAt" : "resets_at");
var minutes = minutesField.Integer();
var reset = resetField.Integer();
try
{
if (used is not (>= 0 and <= 100) || minutes is <= 0 or > 525600 ||
(minutesField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && minutes is null) ||
(resetField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && reset is null)) throw new FormatException();
var length = minutes is { } m ? TimeSpan.FromMinutes(m) : (TimeSpan?)null;
var resetsAt = reset is { } r ? DateTimeOffset.FromUnixTimeSeconds(r) : (DateTimeOffset?)null;
windows.Add(new(Provider.Codex, id + ":" + name,
length <= TimeSpan.FromHours(5) ? "Session" : length >= TimeSpan.FromDays(7) ? "Week" : name,
used.Value, resetsAt, length, sampleTime, source));
}
catch (Exception e) when (e is FormatException or ArgumentOutOfRangeException)
{ diagnostics.Add(Provider.Codex, "codex-limit-parse", "Malformed limit window skipped."); }
}
return windows;
}
public static IReadOnlyList<LimitWindow> ParseResponse(string line, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
{
try
{
using var document = JsonDocument.Parse(line);
var result = document.RootElement.Field("result");
var buckets = result.Field("rateLimitsByLimitId");
if (buckets.ValueKind == JsonValueKind.Object)
return buckets.EnumerateObject().SelectMany(b => Parse(b.Value, sampleTime, "app-server", diagnostics)).ToArray();
return Parse(result.Field("rateLimits"), sampleTime, "app-server", diagnostics);
}
catch (JsonException) { diagnostics.Add(Provider.Codex, "codex-rpc-parse", "Malformed rate limit response."); return []; }
}
}
@@ -0,0 +1,28 @@
using System.Text.Json;
namespace FinalToken.Core.Collectors;
public static class TranscriptParser
{
public static UsageEvent? Parse(string line, DiagnosticLog diagnostics)
{
try
{
using var document = JsonDocument.Parse(line);
var root = document.RootElement;
if (root.Text("type") != "assistant") return null;
var message = root.Field("message");
if (message.Text("model") == "<synthetic>") return null;
if (message.Field("usage").ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null;
var counts = JsonFields.Counts(message.Field("usage"), true);
if (root.Text("requestId") is not { Length: > 0 } && counts == new TokenCounts()) return null;
if (message.Text("id") is not { Length: > 0 } id || root.Text("requestId") is not { Length: > 0 } request ||
root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
// Length prefixes avoid collisions between ids that contain separators (D3).
return new(Provider.Claude, time, message.Text("model"), root.Text("cwd"),
counts, $"claude:{id.Length}:{id}{request.Length}:{request}");
}
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
{ diagnostics.Add(Provider.Claude, "transcript-parse", "Malformed assistant usage entry skipped."); return null; }
}
}