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
+235
View File
@@ -0,0 +1,235 @@
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
namespace FinalToken.Core;
/// <summary>Shared app/CLI host (D6). Caller holds StoreLock. SnapshotChanged, PopupRequested,
/// ActivationRequested run on worker threads, never the caller's UI synchronization context.
/// UI hosts must marshal events. History query results are safe copies.</summary>
public sealed class RefreshEngine : IAsyncDisposable
{
private readonly SemaphoreSlim refreshGate = new(1, 1);
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
private readonly string directory;
private readonly TimeProvider clock;
private readonly string? appPath;
private readonly IncrementalScanner scanner;
private readonly LimitProbe probe;
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
private readonly PopupDecider popups = new();
private readonly Dictionary<Provider, DateTimeOffset> lastProbe = [];
private readonly Dictionary<Provider, (ProviderStatus Status, string? Reason)> statuses = [];
private readonly HashSet<Provider> pendingProbe = [];
private readonly List<FileSystemWatcher> watchers = [];
private CancellationTokenSource? lifetime = new();
private Task? loop;
private Snapshot? current;
private Settings settings;
private long changedTicks;
private DateTimeOffset lastRefresh = DateTimeOffset.MinValue;
private string? activation;
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
string? claudeDirectory = null, string? codexDirectory = null,
Func<Provider, string?, CliDiscoveryResult>? cliDiscovery = null, string? appPath = null)
{
directory = dataDirectory ?? DataPaths.DataDirectory;
Directory.CreateDirectory(directory);
clock = timeProvider ?? TimeProvider.System;
Diagnostics = new(clock);
settings = SettingsFile.Load(directory, Diagnostics);
History = new(directory, Diagnostics, clock);
ClaudeDirectory = claudeDirectory ?? DataPaths.ClaudeDirectory;
CodexDirectory = codexDirectory ?? DataPaths.CodexDirectory;
scanner = new(History, Diagnostics, ClaudeDirectory, CodexDirectory);
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
this.appPath = appPath ?? current?.AppPath;
activation = ActivationFile.ReadRequest(directory);
}
public string DataDirectory => directory;
public string ClaudeDirectory { get; }
public string CodexDirectory { get; }
public Snapshot? CurrentSnapshot => Volatile.Read(ref current);
public Settings Settings => Volatile.Read(ref settings);
public HistoryStore History { get; }
public DiagnosticLog Diagnostics { get; }
public IReadOnlyList<Diagnostic> RecentDiagnostics => Diagnostics.Recent;
public event Action<Snapshot>? SnapshotChanged;
public event Action<PopupEvent>? PopupRequested;
public event Action? ActivationRequested;
public Task UpdateSettingsAsync(Settings value, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
await refreshGate.WaitAsync(cancellationToken);
try
{
await SettingsFile.SaveAsync(directory, value, cancellationToken);
Volatile.Write(ref settings, value);
}
finally { refreshGate.Release(); }
}, cancellationToken);
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await lifecycleGate.WaitAsync(cancellationToken);
try
{
if (loop is not null) return;
lifetime ??= new();
foreach (var path in new[] { Path.Combine(ClaudeDirectory, "projects"), Path.Combine(CodexDirectory, "sessions"), Path.Combine(CodexDirectory, "archived_sessions") })
{
if (!Directory.Exists(path)) continue;
var watcher = new FileSystemWatcher(path, "*.jsonl") { IncludeSubdirectories = true };
watcher.Changed += (_, _) => NotifySourceChanged();
watcher.Created += (_, _) => NotifySourceChanged();
watcher.Deleted += (_, _) => NotifySourceChanged();
watcher.Renamed += (_, _) => NotifySourceChanged();
watcher.Error += (_, _) => { Diagnostics.Add(null, "watcher", "File watcher failed; periodic scans continue."); NotifySourceChanged(); };
watcher.EnableRaisingEvents = true;
watchers.Add(watcher);
}
loop = Task.Run(() => RunLoopAsync(lifetime.Token), CancellationToken.None);
}
finally { lifecycleGate.Release(); }
}
public async Task StopAsync()
{
await lifecycleGate.WaitAsync();
try
{
foreach (var watcher in watchers) watcher.Dispose();
watchers.Clear();
if (lifetime is not null) await lifetime.CancelAsync();
if (loop is not null)
try { await loop; } catch (OperationCanceledException) { }
// Also wait for any manually requested refresh, which shares the lifetime token.
await refreshGate.WaitAsync();
refreshGate.Release();
lifetime?.Dispose();
lifetime = null;
loop = null;
}
finally { lifecycleGate.Release(); }
}
public void NotifySourceChanged() => Interlocked.Exchange(ref changedTicks, clock.GetUtcNow().UtcTicks);
public Task<Snapshot> RefreshNowAsync(bool noProbe = false, CancellationToken cancellationToken = default)
{
var shutdown = lifetime?.Token ?? CancellationToken.None;
return Task.Run(async () =>
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, shutdown);
return await RefreshAsync(noProbe, linked.Token);
}, cancellationToken);
}
/// <summary>One scheduler tick, also usable with a fake TimeProvider. Changes debounce for two seconds.</summary>
public Task TickAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var request = ActivationFile.ReadRequest(directory);
if (request is not null && request != activation) { activation = request; Dispatch(ActivationRequested); }
var now = clock.GetUtcNow();
var changes = Interlocked.Read(ref changedTicks);
if (now - lastRefresh >= Settings.RefreshInterval || changes > 0 && now.UtcTicks - changes >= TimeSpan.FromSeconds(2).Ticks)
{
Interlocked.CompareExchange(ref changedTicks, 0, changes);
await RefreshAsync(false, cancellationToken);
}
}, cancellationToken);
private async Task RunLoopAsync(CancellationToken token)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), clock);
do
{
try { await TickAsync(token); }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
// D6: isolate a failed tick, including a malformed stored partition, and retry.
catch (Exception)
{ Diagnostics.Add(null, "refresh-failed", "Refresh failed; the scheduler will retry."); }
} while (await timer.WaitForNextTickAsync(token));
}
private async Task<Snapshot> RefreshAsync(bool noProbe, CancellationToken token)
{
await refreshGate.WaitAsync(token);
try
{
var config = Settings;
var scan = await scanner.ScanAsync(token, config.Claude.Enabled, config.Codex.Enabled);
if (scan.ClaudeAdded > 0) pendingProbe.Add(Provider.Claude);
if (scan.CodexAdded > 0) pendingProbe.Add(Provider.Codex);
var now = clock.GetUtcNow();
List<ProviderSnapshot> providers = [];
List<PopupEvent> alerts = [];
foreach (var provider in new[] { Provider.Claude, Provider.Codex })
{
var providerSettings = config.For(provider);
if (!providerSettings.Enabled) statuses[provider] = (ProviderStatus.Disabled, "Disabled in settings.");
else
{
var cli = discover(provider, providerSettings.CliPath);
if (cli.Command is null) statuses[provider] = (ProviderStatus.Unavailable, cli.Reason);
else
{
if (!statuses.ContainsKey(provider) || statuses[provider].Status == ProviderStatus.Disabled)
statuses[provider] = (ProviderStatus.Available, null);
var previousProbe = lastProbe.GetValueOrDefault(provider, DateTimeOffset.MinValue);
var since = now - previousProbe;
if (!noProbe && since >= TimeSpan.FromMinutes(1) && (since >= config.ProbeInterval || pendingProbe.Contains(provider)))
{
lastProbe[provider] = now;
pendingProbe.Remove(provider);
var result = await probe.RunAsync(provider, cli.Command, now, token);
if (result.Success)
{
History.AddLimits(result.Windows);
statuses[provider] = (ProviderStatus.Available, null);
}
else
{
if (provider == Provider.Codex && scan.CodexFallback.Count > 0)
statuses[provider] = (ProviderStatus.Available, "Probe failed; using rollout limits.");
else statuses[provider] = (ProviderStatus.Unavailable, result.Reason);
}
}
}
}
var windows = History.LatestLimits(provider);
// Session totals follow an explicitly short limit window, never a week mislabeled primary.
var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5));
var totals = History.Totals(provider, now, session);
var state = statuses[provider];
var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray();
providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week));
foreach (var window in snapshots)
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
alerts.Add(alert);
}
var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval,
Providers = providers, AppPath = appPath };
await History.SaveAsync(token);
await SnapshotFile.WriteAsync(directory, snapshot, token);
Volatile.Write(ref current, snapshot);
lastRefresh = clock.GetUtcNow();
Dispatch(SnapshotChanged, snapshot);
foreach (var alert in alerts) Dispatch(PopupRequested, alert);
return snapshot;
}
finally { refreshGate.Release(); }
}
private void Dispatch<T>(Action<T>? handlers, T value)
{
if (handlers is null) return;
foreach (var handler in handlers.GetInvocationList().Cast<Action<T>>())
try { handler(value); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
}
private void Dispatch(Action? handlers)
{
if (handlers is null) return;
foreach (var handler in handlers.GetInvocationList().Cast<Action>())
try { handler(); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
}
public async ValueTask DisposeAsync() => await StopAsync();
}