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
+10
View File
@@ -0,0 +1,10 @@
# App
Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model
properties use CommunityToolkit.Mvvm source generators. Custom charts use DrawingContext.
Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI;
Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots.
history queries run on worker threads and discard superseded results. Keep all writes atomic (D5).
Daily charts use local calendar boundaries; never assume a day lasts 24 hours.
Stream Deck policy and the real installer come through IPluginInstaller (D11).
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+114
View File
@@ -0,0 +1,114 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Styling;
using FinalToken.Core;
using System.Globalization;
namespace FinalToken.App;
public sealed class UsageChart : Control
{
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")];
public static IBrush SeriesColour(int index) => Palette[index % Palette.Length];
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary>
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
{
if (!double.IsFinite(maximum) || maximum <= 0) return [0];
if (percent) return [0, 25, 50, 75, 100];
var target = Math.Max(1, maximum / 4);
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target)));
var fraction = target / magnitude;
var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude;
var intervals = (int)Math.Ceiling(maximum / step);
return Enumerable.Range(0, intervals + 1).Select(i => i * step).ToArray();
}
public IReadOnlyList<ChartValue> Values { get; init; } = [];
public bool Percent { get; init; }
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
private readonly List<(Rect Rect, string Text)> hits = [];
public UsageChart()
{
Height = 180;
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text);
PointerExited += (_, _) => ToolTip.SetTip(this, null);
}
public override void Render(DrawingContext context)
{
base.Render(context);
hits.Clear();
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray;
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent);
var max = Math.Max(1, ticks[^1]);
foreach (var tick in ticks)
{
var y = plot.Bottom - plot.Height * tick / max;
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y));
var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}";
Text(context, label, new(0, y - 8), ink);
}
if (groups.Length == 0) { Text(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
var series = Values.Select(v => v.Series).Distinct().ToArray();
if (Percent)
{
ChartValue? previous = null;
var minTime = groups[0].Key;
var timeSpan = Math.Max(1, (groups[^1].Key - minTime).TotalSeconds);
Point Position(ChartValue v, double value) => new(plot.Left + (v.Time - minTime).TotalSeconds / timeSpan * plot.Width, plot.Bottom - Math.Clamp(value, 0, 100) / 100 * plot.Height);
foreach (var value in Values.OrderBy(v => v.Time))
{
var point = Position(value, value.Value);
if (previous is { } p && !value.BreakBefore)
{
context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point);
if (p.Expected is { } pe && value.Expected is { } expected)
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
}
context.DrawEllipse(Palette[0], null, point, 3, 3);
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}"));
previous = value;
}
}
else
{
var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
var width = plot.Width * Interval.TotalSeconds / duration;
for (var i = 0; i < groups.Length; i++)
{
var bottom = plot.Bottom;
foreach (var value in groups[i])
{
var height = value.Value / max * plot.Height;
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens"));
bottom -= height;
}
}
}
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink);
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
ToolTip.SetShowDelay(this, 0);
}
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, 11, brush), point);
}
public sealed class PaceBar(WindowSnapshot window) : Control
{
public static IBrush Colour(PaceState state) => Brush.Parse(state switch
{ PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" });
public override void Render(DrawingContext context)
{
base.Render(context);
context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4);
context.DrawRectangle(Colour(window.Pace.State), null, new Rect(0, 0, Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1), Bounds.Height), 4, 4);
if (window.Pace.ElapsedFraction is { } elapsed)
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height));
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%");
}
}
+187
View File
@@ -0,0 +1,187 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
namespace FinalToken.App;
public sealed class DesktopApp : Application
{
private readonly PanelViewModel model = new();
private IClassicDesktopStyleApplicationLifetime? desktop;
private PanelWindow? panel;
private PopupStack? popups;
private TrayIcon? tray;
private DispatcherTimer? ageTimer;
private SettingsWindow? settingsWindow;
private Task settingsSave = Task.CompletedTask;
private PopupWindow? pluginAsk;
private RefreshEngine? engine;
private readonly SemaphoreSlim pluginGate = new(1, 1);
private int historyRequest;
private bool quitting;
private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
public override void Initialize() => Styles.Add(new FluentTheme());
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
{
desktop = lifetime; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
engine = Program.Engine;
if (Program.StartupError is { } error)
{
var window = new Window { Title = "FinalToken — history error", Width = 560, Height = 240,
Content = Ui.Card(Ui.Stack(Ui.Text("History cannot be loaded", 22), Ui.Text(error), Ui.Button("Quit", () => desktop.Shutdown(1)))) };
desktop.MainWindow = window; window.Show();
window.Closed += (_, _) => desktop.Shutdown(1);
}
else
{
panel = new PanelWindow(model, () => Run(Refresh), OpenSettings, () => Run(Quit), () => Run(LoadHistory));
desktop.MainWindow = panel; popups = new(OpenPanel);
panel.Closing += (_, e) => { if (!quitting && engine?.Settings.CloseToTray != false) { e.Cancel = true; panel.Hide(); } else if (!quitting) { e.Cancel = true; Run(Quit); } };
CreateTray(); panel.Show();
if (engine is not null)
{
engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
ageTimer.Start();
Run(Start);
}
}
desktop.ShutdownRequested += (_, e) => { if (!quitting && engine is not null) { e.Cancel = true; Run(Quit); } };
}
base.OnFrameworkInitializationCompleted();
}
private async Task Start()
{
await engine!.StartAsync();
if (engine.Settings.StartWithOs) await OsStartup.ApplyAsync(true);
await CheckPlugin();
}
private void CreateTray()
{
var menu = new NativeMenu();
foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
{ var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32));
using (var context = bitmap.CreateDrawingContext())
{ context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
tray.Clicked += (_, _) => OpenPanel();
TrayIcon.SetIcons(this, [tray]);
}
private void OpenPanel()
{
if (panel is null || quitting) return;
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
}
private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync();
private async Task LoadHistory()
{
if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
var request = ++historyRequest; var range = model.Range; var filter = model.ProviderFilter;
var history = await Task.Run(() => PanelViewModel.QueryHistory(engine.History, snapshot, range, filter, DateTimeOffset.UtcNow));
if (request == historyRequest && !quitting) model.History = history;
}
private void OpenSettings()
{
if (engine is null) return;
if (settingsWindow is not null) { settingsWindow.Activate(); return; }
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value));
settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show();
}
private async Task SaveSettings(Settings value)
{
if (engine is null || quitting) return;
var previous = engine.Settings;
await OsStartup.ApplyAsync(value.StartWithOs);
if (quitting) { await OsStartup.ApplyAsync(previous.StartWithOs); return; }
try { await engine.UpdateSettingsAsync(value); }
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return;
await CheckPlugin();
if (!quitting) await engine.RefreshNowAsync();
}
private async Task CheckPlugin()
{
if (engine is null || quitting) return;
await pluginGate.WaitAsync();
try
{
if (quitting) return;
pluginAsk?.Close(); pluginAsk = null;
pluginStatus = await PluginInstaller.GetStatusAsync();
var action = InstallPolicy.Decide(engine.Settings.StreamDeckInstallMode, pluginStatus, engine.Settings.DismissedPluginVersion);
if (action == InstallAction.Install) await InstallPlugin();
else if (action == InstallAction.Ask)
{
var version = pluginStatus.ShippedVersion;
pluginAsk = new PopupWindow("Stream Deck plugin", $"Version {version} is ready.", OpenPanel,
pluginStatus.State == PluginInstallState.Outdated ? "Update" : "Install", () => Run(() => AcceptPlugin(version)),
() => Run(() => DismissPlugin(version)));
popups!.Show(pluginAsk);
}
}
finally { pluginGate.Release(); }
}
private async Task DismissPlugin(string? version)
{
await pluginGate.WaitAsync();
try { if (!quitting && engine is not null) await engine.UpdateSettingsAsync(engine.Settings with { DismissedPluginVersion = version }); }
finally { pluginGate.Release(); }
}
private async Task AcceptPlugin(string? version)
{
await pluginGate.WaitAsync();
try
{
if (quitting || engine?.Settings.StreamDeckInstallMode == InstallMode.Off) return;
var current = await PluginInstaller.GetStatusAsync();
if (current.ShippedVersion == version && current.State is PluginInstallState.NotInstalled or PluginInstallState.Outdated)
await InstallPlugin();
}
finally { pluginGate.Release(); }
}
private async Task InstallPlugin()
{
try { await PluginInstaller.InstallOrUpdateAsync(); pluginStatus = await PluginInstaller.GetStatusAsync(); if (!quitting) popups!.Show(new PopupWindow("Stream Deck", pluginStatus.State == PluginInstallState.UpToDate ? "Plugin installed successfully." : $"Plugin status: {pluginStatus.State}", OpenPanel)); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException)
{ if (!quitting) popups!.Show(new PopupWindow("Stream Deck", "Install failed: " + e.Message, OpenPanel)); }
}
private async Task Quit()
{
if (quitting) return; quitting = true;
ageTimer?.Stop(); tray?.Dispose(); popups?.Dispose(); settingsWindow?.Close();
var stopping = engine?.StopAsync() ?? Task.CompletedTask;
await pluginGate.WaitAsync(); pluginGate.Release();
try { await settingsSave; }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or OperationCanceledException)
{ engine?.Diagnostics.Add(null, "settings-shutdown", "Settings could not finish applying before shutdown."); }
await stopping;
desktop?.Shutdown();
}
private async void Run(Func<Task> work)
{
try { await work(); }
catch (OperationCanceledException) { }
catch (Exception)
{
engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed.");
model.Message = "Operation failed. See diagnostics.";
}
}
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<AssemblyName>FinalToken</AssemblyName>
<PublishAot>true</PublishAot>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" />
<PackageReference Include="CommunityToolkit.Mvvm" />
</ItemGroup>
</Project>
+35
View File
@@ -0,0 +1,35 @@
using System.Runtime.Versioning;
using FinalToken.Core;
using Microsoft.Win32;
namespace FinalToken.App;
public static class OsStartup
{
public static string LinuxAutostartPath(string? configHome, string userHome)
=> Path.Combine(string.IsNullOrEmpty(configHome) ? Path.Combine(userHome, ".config") : configHome, "autostart", "finaltoken.desktop");
public static async Task ApplyAsync(bool enabled, string? executable = null)
{
executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable.");
if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; }
if (!OperatingSystem.IsLinux()) return;
var path = LinuxAutostartPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"),
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
if (!enabled) { if (File.Exists(path)) File.Delete(path); return; }
await AtomicFile.WriteAsync(path, DesktopEntry(executable));
}
public static string DesktopEntry(string executable)
{
if (executable.IndexOfAny(['\r', '\n', '\0']) >= 0) throw new ArgumentException("Executable path contains invalid characters.", nameof(executable));
var quoted = executable.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)
.Replace("`", "\\`", StringComparison.Ordinal).Replace("$", "\\$", StringComparison.Ordinal).Replace("%", "%%", StringComparison.Ordinal);
var escaped = quoted.Replace("\\", "\\\\", StringComparison.Ordinal);
return $"[Desktop Entry]\nType=Application\nName=FinalToken\nExec=\"{escaped}\"\nTerminal=false\nX-GNOME-Autostart-enabled=true\n";
}
[SupportedOSPlatform("windows")]
private static void ApplyWindows(bool enabled, string executable)
{
using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (enabled) key.SetValue("FinalToken", "\"" + executable + "\""); else key.DeleteValue("FinalToken", false);
}
}
+88
View File
@@ -0,0 +1,88 @@
using CommunityToolkit.Mvvm.ComponentModel;
using FinalToken.Core;
namespace FinalToken.App;
public enum HistoryRange { Hours24, Days7, Days30, Days90, All }
public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false);
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share);
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values);
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects);
public partial class PanelViewModel : ObservableObject
{
[ObservableProperty] private Snapshot? snapshot;
[ObservableProperty] private HistoryRange range = HistoryRange.Days7;
[ObservableProperty] private Provider? providerFilter;
[ObservableProperty] private HistoryView history = new([], [], [], [], []);
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
[ObservableProperty] private string message = "Reading local CLI data…";
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
{
HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7),
HistoryRange.Days30 => now.AddDays(-30), HistoryRange.Days90 => now.AddDays(-90),
_ => DateTimeOffset.MinValue
};
// D5: queries return copies; the caller runs this on a worker thread.
public static HistoryView QueryHistory(HistoryStore store, Snapshot snapshot, HistoryRange range, Provider? filter, DateTimeOffset now)
{
var from = RangeStart(range, now);
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day);
var limits = providers.SelectMany(p => p.Windows.Select(w =>
{
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent,
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray());
})).ToArray();
return new(hourly, daily, limits, Breakdown(true), Breakdown(false));
IReadOnlyList<ChartValue> Series(SeriesInterval interval) => providers.SelectMany(p =>
store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
{
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time);
return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
}
IReadOnlyList<BreakdownRow> Breakdown(bool models)
{
var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
.GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key,
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray();
var total = rows.Sum(r => (double)r.Counts.Total);
return rows.Select(r => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray();
}
}
}
public static class Display
{
public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString("g");
private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval)
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
{
clock ??= TimeProvider.System;
var local = TimeZoneInfo.ConvertTime(projection, clock.LocalTimeZone);
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
culture ?? System.Globalization.CultureInfo.CurrentCulture);
}
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min";
public static string Tokens(TokenCounts? counts) => counts is { } c
? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}"
: "Unavailable — no known session window";
public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() };
}
+130
View File
@@ -0,0 +1,130 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public static class Ui
{
public static TextBlock Text(string text, double size = 13) => new() { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 10 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content) => new() { Child = content, Padding = new Thickness(18), CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1), BorderBrush = Brush.Parse("#558795A5") };
public static Button Button(string text, Action action)
{
var button = new Button { Content = text };
button.Click += (_, _) => action();
return button;
}
}
public sealed class PanelWindow : Window
{
private readonly PanelViewModel model;
private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) };
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload)
{
this.model = model;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
header.Children.Add(Ui.Text("FinalToken", 28));
header.Children.Add(Ui.Button("Refresh now", refresh));
header.Children.Add(Ui.Button("Settings", settings));
header.Children.Add(Ui.Button("Quit", quit));
var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 };
range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); };
var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 };
providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); };
var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
filters.Children.Add(range); filters.Children.Add(providers);
var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) };
var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0);
DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top);
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
model.PropertyChanged += (_, _) => RenderModel();
RenderModel();
}
public void RenderModel()
{
body.Children.Clear();
body.Children.Add(Ui.Text(model.Message));
if (model.Snapshot is { } snapshot)
{
foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter))
{
var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}"));
foreach (var window in provider.Windows)
{
var w = window.Window; var pace = window.Pace;
var title = Ui.Text($"{w.Label} {w.UsedPercent:0.##}% {Display.State(pace.State)} {(pace.Delta is { } d ? $"{d:+0.0;-0.0;0} points" : "")}", 15);
title.Foreground = PaceBar.Colour(pace.State);
card.Children.Add(title);
card.Children.Add(new PaceBar(window) { Height = 14 });
card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
(pace.Projection is { } projection ? $" Reaches 100%: {Display.Projection(projection)}" : "")));
}
card.Children.Add(Ui.Text("Tokens · provider totals", 15));
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session)));
card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week)));
card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11));
body.Children.Add(Ui.Card(card));
}
}
var h = model.History;
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly })));
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) })));
foreach (var limit in h.Limits)
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true })));
body.Children.Add(Breakdown("By model", h.Models));
body.Children.Add(Breakdown("By project", h.Projects));
var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19));
foreach (var d in model.Diagnostics) diagnostics.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary}"));
if (model.Diagnostics.Count == 0) diagnostics.Children.Add(Ui.Text("No recent problems."));
body.Children.Add(Ui.Card(diagnostics));
}
private static Control Legend(IReadOnlyList<ChartValue> values)
{
var legend = new WrapPanel { Orientation = Orientation.Horizontal };
var index = 0;
foreach (var series in values.Select(v => v.Series).Distinct())
{
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++);
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
}
return legend;
}
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows)
{
var table = Ui.Stack(Ui.Text(title, 19));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 };
var headers = new[] { "Name", "Total", "Share", "Input", "Cache read", "Cache write", "Output", "Reasoning" };
AddRow(headers, 0);
var index = 1;
foreach (var row in rows)
{
var c = row.Counts;
AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"),
c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++);
}
table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range."));
return Ui.Card(table);
void AddRow(string[] values, int row)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
for (var column = 0; column < values.Length; column++)
{
var text = Ui.Text(values[column], 11); text.Margin = new Thickness(0, 4, 8, 4);
Grid.SetRow(text, row); Grid.SetColumn(text, column); grid.Children.Add(text);
}
}
}
}
+71
View File
@@ -0,0 +1,71 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.Styling;
using Avalonia.VisualTree;
using FinalToken.Core;
namespace FinalToken.App;
public sealed class PopupWindow : Window
{
public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null)
{
Width = 380; Height = install is null ? 145 : 180;
RequestedThemeVariant = ThemeVariant.Dark;
WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
if (install is not null)
{
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
actions.Children.Add(Ui.Button(installLabel ?? "Install", () => { install(); Close(); }));
actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
body.Children.Add(actions);
}
var card = Ui.Card(body); card.Background = Brush.Parse("#202C40");
body.Resources["TextControlForeground"] = Brushes.WhiteSmoke;
foreach (var text in body.Children.OfType<TextBlock>()) text.Foreground = Brushes.WhiteSmoke;
((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
Content = card;
PointerPressed += (_, e) =>
{
var source = e.Source as Control;
if (source is not Button && source?.FindAncestorOfType<Button>() is null)
{ open(); Close(); e.Handled = true; }
};
}
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
(alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State));
}
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
{
private readonly List<PopupWindow> windows = [];
public void Pace(PopupEvent alert) => Show(PopupWindow.Pace(alert, open));
public void Show(PopupWindow window)
{
windows.Add(window);
window.Closed += (_, _) => { windows.Remove(window); Position(); };
window.Show(); Position();
// D8: timer callbacks are off the UI thread; closing always marshals back.
var timer = (clock ?? TimeProvider.System).CreateTimer(_ => Dispatcher.UIThread.Post(window.Close),
null, TimeSpan.FromSeconds(8), Timeout.InfiniteTimeSpan);
window.Closed += (_, _) => timer.Dispose();
}
private void Position()
{
var bottom = 0;
foreach (var window in windows)
{
var screen = window.Screens.Primary;
if (screen is null) continue;
var area = screen.WorkingArea; var scale = screen.Scaling;
bottom += (int)(window.Height * scale) + 12;
window.Position = new PixelPoint(area.Right - (int)(window.Width * scale) - 16, area.Bottom - bottom - 4);
}
}
public void Dispose() { foreach (var window in windows.ToArray()) window.Close(); }
}
+37
View File
@@ -0,0 +1,37 @@
using Avalonia;
using FinalToken.Core;
namespace FinalToken.App;
public static class Program
{
internal static RefreshEngine? Engine { get; private set; }
internal static string? StartupError { get; private set; }
[STAThread]
public static int Main(string[] args)
{
StoreLock? storeLock = null;
try
{
var directory = DataPaths.DataDirectory;
storeLock = StoreLock.TryAcquire(directory);
if (storeLock is null)
{
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0;
}
try { Engine = new RefreshEngine(directory, appPath: Environment.ProcessPath); }
catch (InvalidDataException e) { StartupError = e.Message; }
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
return StartupError is null ? 0 : 1;
}
finally
{
Engine?.DisposeAsync().AsTask().GetAwaiter().GetResult();
storeLock?.Dispose();
}
}
// D8: Avalonia 12.1.4's platform detection selects X11 on Linux (XWayland).
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
.With(new X11PlatformOptions()).LogToTrace();
}
+58
View File
@@ -0,0 +1,58 @@
using Avalonia;
using Avalonia.Controls;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
namespace FinalToken.App;
public sealed class SettingsWindow : Window
{
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save)
{
Title = "FinalToken settings"; Width = 620; Height = 800;
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24);
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind);
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray);
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex);
body.Children.Add(Ui.Text("Stream Deck", 19));
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}"));
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode };
body.Children.Add(mode);
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed);
var error = Ui.Text(""); body.Children.Add(error);
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
button.Click += async (_, _) =>
{
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true,
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(),
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() };
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
button.IsEnabled = false;
try { await save(value); Close(); }
catch (OperationCanceledException) { error.Text = "Settings save was cancelled."; button.IsEnabled = true; }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
};
body.Children.Add(button); Content = new ScrollViewer { Content = body };
NumericUpDown Number(string label, decimal value, decimal min, decimal max)
{ body.Children.Add(Ui.Text(label)); var c = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; body.Children.Add(c); return c; }
CheckBox Check(string label, bool value)
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; }
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config)
{
body.Children.Add(Ui.Text(name, 19));
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled);
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind);
body.Children.Add(Ui.Text("CLI path (empty uses PATH)"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; body.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, PopupsEnabled = popups.IsChecked == true, PopupAhead = pa.IsChecked == true,
PopupBehind = pb.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
}
}
}
+55
View File
@@ -0,0 +1,55 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Avalonia.Controls;
namespace FinalToken.App;
[SupportedOSPlatform("windows")]
internal static partial class WindowsActivation
{
public static void Activate(Window window)
{
if (window.TryGetPlatformHandle() is not { } platform) return;
var handle = platform.Handle;
if (SetForegroundWindow(handle) != 0) return;
var foreground = GetForegroundWindow();
if (foreground == 0) return;
var foregroundThread = GetWindowThreadProcessId(foreground, out _);
var ownThread = GetCurrentThreadId();
if (foregroundThread == ownThread || AttachThreadInput(ownThread, foregroundThread, 1) == 0) return;
try { SetForegroundWindow(handle); }
finally { AttachThreadInput(ownThread, foregroundThread, 0); }
}
// D8: a launcher transfers its foreground permission before the running app activates.
public static void AllowRunningInstance()
{
using var current = Process.GetCurrentProcess();
foreach (var candidate in Process.GetProcessesByName(current.ProcessName))
{
using (candidate)
{
try
{
if (candidate.Id != current.Id && candidate.SessionId == current.SessionId &&
string.Equals(candidate.MainModule?.FileName, Environment.ProcessPath, StringComparison.OrdinalIgnoreCase))
AllowSetForegroundWindow(candidate.Id);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException) { }
}
}
}
[LibraryImport("user32.dll")]
private static partial int AllowSetForegroundWindow(int processId);
[LibraryImport("user32.dll")]
private static partial int SetForegroundWindow(nint window);
[LibraryImport("user32.dll")]
private static partial nint GetForegroundWindow();
[LibraryImport("user32.dll")]
private static partial uint GetWindowThreadProcessId(nint window, out uint processId);
[LibraryImport("kernel32.dll")]
private static partial uint GetCurrentThreadId();
[LibraryImport("user32.dll")]
private static partial int AttachThreadInput(uint first, uint second, int attach);
}
+6
View File
@@ -0,0 +1,6 @@
# CLI
NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2.
Assembly/executable name is `finaltoken-cli` on every platform, beside the `FinalToken` app.
A busy store is read-only. Keep argument parsing in CliApplication for tests.
Pass no app path to RefreshEngine; preserve the desktop path from an existing snapshot.
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+52
View File
@@ -0,0 +1,52 @@
using System.Globalization;
using System.Text.Json;
using FinalToken.Core;
namespace FinalToken.Cli;
public static class CliApplication
{
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error,
string? dataDirectory = null, Func<string, RefreshEngine>? engineFactory = null, CancellationToken cancellationToken = default)
{
if (args.Length == 0 || args[0] != "status" || args.Skip(1).Any(a => a is not ("--json" or "--no-probe")) ||
args.Skip(1).Distinct().Count() != args.Length - 1)
{ await error.WriteLineAsync("Usage: finaltoken-cli status [--json] [--no-probe]"); return 2; }
try
{
var directory = dataDirectory ?? DataPaths.DataDirectory;
using var storeLock = StoreLock.TryAcquire(directory);
Snapshot snapshot;
if (storeLock is null)
{
await error.WriteLineAsync("Store is in use; reading the existing snapshot without refreshing.");
var result = SnapshotFile.Read(directory);
if (result.Snapshot is not { } existing) { await error.WriteLineAsync(result.Error); return 1; }
if (result.IsStale) await error.WriteLineAsync("Snapshot is stale.");
snapshot = existing;
}
else
{
await using var engine = engineFactory?.Invoke(directory) ?? new RefreshEngine(directory);
snapshot = await engine.RefreshNowAsync(args.Contains("--no-probe"), cancellationToken);
foreach (var diagnostic in engine.RecentDiagnostics)
await error.WriteLineAsync($"{diagnostic.Code} (x{diagnostic.Count}, last {diagnostic.Time:O}): {diagnostic.Summary}");
}
if (args.Contains("--json")) await output.WriteLineAsync(JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot));
else
{
await output.WriteLineAsync($"FinalToken {snapshot.MadeAt:O}");
foreach (var provider in snapshot.Providers)
{
await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}");
await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}");
foreach (var window in provider.Windows)
await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}"));
}
}
return 0;
}
catch (Exception)
{ await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; }
}
}
+8
View File
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AssemblyName>finaltoken-cli</AssemblyName>
<PublishAot>true</PublishAot>
</PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
</Project>
+3
View File
@@ -0,0 +1,3 @@
using FinalToken.Cli;
return await CliApplication.RunAsync(args, Console.Out, Console.Error);
+64
View File
@@ -0,0 +1,64 @@
# Core
UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract.
Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock.
Persisted defaults use settable properties: source-generated init-only property factories can
overwrite initializers for missing JSON members. Treat settings as values; update them with `with`.
Events from RefreshEngine run on a worker thread; UI hosts must marshal them.
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
## Host contract
- Acquire `StoreLock.TryAcquire(dataDirectory)` before creating a writing engine. A busy app calls
`ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`.
- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
The desktop host passes `appPath: Environment.ProcessPath`. Other hosts omit it to keep the
previous snapshot's desktop path. A missing path stays null in readers and writers (D9).
- Probes return a failed `ProbeResult` for process or protocol failures; shutdown cancellation
propagates. The background engine records other tick failures and retries without faulting its loop.
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the
reset and length of a known short limit. Hourly storage includes whole boundary hours (D5).
Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`.
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
- `StreamDeck/` contains `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and platform deployment.
No shipped production dependency is needed in Core. Source parsers use temporary memory for one
complete line; memory usage therefore scales with the largest transcript entry.
## Store persistence and scaling
- Refresh changes append as one durable, newline-terminated transaction to
`history.journal.jsonl`. Ignore a torn final line on load; reject a corrupt complete line.
Before another append, truncate the torn tail. Hosts still hold `StoreLock` (D5).
- At 8 MiB, compact committed changes into UTC monthly `history/yyyy-MM.json` files, then
atomically replace `history.state.json`, then reset the journal. Absolute bucket upserts,
exact sample sets and checkpoint sequences make interrupted compaction replay idempotent.
Ordinary idle saves write nothing. `CompactAsync` is an explicit maintenance operation.
- Keep three monthly partitions in memory. Bucket updates use keyed lookup. Journal overlays
are bounded by compaction; scanner/session metadata remains one entry per observed source or
session. Queries load only overlapping months and preserve their existing public signatures.
- Claude imports and response keys have a 60-day horizon, twice the default 30-day cleanup.
Keys expire daily; entries older than the horizon are ignored even after a key expires.
Codex replay protection uses the last session timestamp and cumulative counts, with no
per-event dedupe keys. A later counter reset still permits subsequent increases.
- Store changed percent/reset samples and at most one unchanged sample per window per hour.
Late observations from archived files use neighbouring timestamps so they keep real changes
without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have
a per-window time index for ordered lookup.
Successful unchanged probes refresh the in-memory sample age without writing history before
that hourly point. The latest window set remains separate from the history samples.
- A scanner compares length, last-write time and creation time before opening a source file.
Unchanged files stay closed; changed files retain prefix/tail replacement checks. A replacement
that preserves all those metadata fields cannot be distinguished from an unchanged file.
- Readers of replaced files use `FileShare.ReadWrite | FileShare.Delete`. Atomic replacements
use `File.Replace` for existing targets and retry Windows sharing failures for at most 500 ms.
- Diagnostics fold by provider/code; `Count` is additive and `Time` is the latest occurrence.
Synthetic Claude entries are silent. No message text appears in a diagnostic or journal.
- ProcessRunner redirects all three handles, closes non-interactive stdin and sets explicit
UTF-8 encodings. A WinExe's default console encoding corrupts UTF-8 provider JSON (D3, D6).
`tests/FinalToken.ProcessHost` reproduces the missing-console case without a provider login.
- Claude usage prose is silent. Diagnose only malformed `Current ...` lines before the
contributing section, where parsing stops. No legacy development-store migration is supported.
+81
View File
@@ -0,0 +1,81 @@
using System.Text;
namespace FinalToken.Core;
public static class AtomicFile
{
// D5: same-directory rename; a reader sees either complete version.
public static Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default)
=> WriteAsync(path, contents, cancellationToken, TimeProvider.System);
public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken, TimeProvider timeProvider)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None,
4096, FileOptions.Asynchronous | FileOptions.WriteThrough))
{
await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
stream.Flush(true);
}
cancellationToken.ThrowIfCancellationRequested();
for (var attempt = 0; ; attempt++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
if (File.Exists(path)) File.Replace(temporary, path, null);
else File.Move(temporary, path);
break;
}
catch (Exception e) when (OperatingSystem.IsWindows() &&
e is IOException or UnauthorizedAccessException && (e.HResult & 0xffff) is 5 or 32 or 33)
{
// Windows can report ACCESS_DENIED for an open destination as well as SHARING_VIOLATION.
if (attempt == 10) throw new IOException("Atomic replacement remained blocked after 500 ms.", e);
await Task.Delay(TimeSpan.FromMilliseconds(50), timeProvider, cancellationToken).ConfigureAwait(false);
}
}
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
}
/// <summary>The host must hold this for the entire lifetime of a writing HistoryStore/RefreshEngine (D5).</summary>
public sealed class StoreLock : IDisposable
{
private readonly FileStream stream;
private StoreLock(FileStream stream) => this.stream = stream;
public static StoreLock? TryAcquire(string directory)
{
Directory.CreateDirectory(directory);
try { return new(new FileStream(Path.Combine(directory, "store.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); }
catch (IOException) { return null; }
}
public void Dispose() => stream.Dispose();
}
public static class ActivationFile
{
public static Task RequestAsync(string directory, CancellationToken cancellationToken = default) =>
AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken);
public static string? ReadRequest(string directory)
{
try { return SharedFile.ReadAllText(Path.Combine(directory, "activate.request")); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; }
}
}
internal static class SharedFile
{
public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan);
public static string ReadAllText(string path)
{
using var stream = OpenRead(path);
using var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+26
View File
@@ -0,0 +1,26 @@
namespace FinalToken.Core;
/// <summary>Local calendar boundaries, including 23/25-hour days. Midnight overlaps choose
/// the earlier instant; midnight gaps start at the first valid local minute.</summary>
public static class CalendarDays
{
/// <summary>Start of a specified local calendar date; midnight gaps and overlaps follow the same policy as Start(instant).</summary>
public static DateTimeOffset Start(DateTime date, TimeZoneInfo? zone = null)
=> AtStart(DateTime.SpecifyKind(date.Date, DateTimeKind.Unspecified), zone ?? TimeZoneInfo.Local);
public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null)
{
zone ??= TimeZoneInfo.Local;
return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date, zone);
}
public static DateTimeOffset NextStart(DateTimeOffset instant, TimeZoneInfo? zone = null)
{
zone ??= TimeZoneInfo.Local;
return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date.AddDays(1), zone);
}
private static DateTimeOffset AtStart(DateTime date, TimeZoneInfo zone)
{
while (zone.IsInvalidTime(date)) date = date.AddMinutes(1);
var offset = zone.IsAmbiguousTime(date) ? zone.GetAmbiguousTimeOffsets(date).Max() : zone.GetUtcOffset(date);
return new(date, offset);
}
}
@@ -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; }
}
}
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk" />
+132
View File
@@ -0,0 +1,132 @@
using System.Text.Json;
using System.Text;
namespace FinalToken.Core;
internal readonly record struct BucketKey(Provider Provider, DateTimeOffset Hour, string? Model, string? Project)
{
public static BucketKey For(TokenBucket bucket) => new(bucket.Provider, bucket.Hour, bucket.Model, bucket.Project);
}
public sealed class HistoryPartition
{
public int V { get; set; } = 1;
public List<TokenBucket> Buckets { get; set; } = [];
public List<LimitWindow> Limits { get; set; } = [];
}
public sealed class HistoryState
{
public int V { get; set; } = 1;
public long Sequence { get; set; }
public Dictionary<string, DateTimeOffset> ClaudeKeys { get; set; } = [];
public Dictionary<string, TokenCounts> CodexTotals { get; set; } = [];
public Dictionary<string, DateTimeOffset> CodexTimes { get; set; } = [];
public Dictionary<string, ScanCursor> Cursors { get; set; } = [];
public Dictionary<Provider, List<LimitWindow>> LatestWindows { get; set; } = [];
public Dictionary<string, LimitWindow> LastSamples { get; set; } = [];
}
public sealed class HistoryTransaction
{
public int V { get; set; } = 1;
public long Sequence { get; set; }
public List<TokenBucket> Buckets { get; set; } = [];
public List<LimitWindow> Limits { get; set; } = [];
public Dictionary<string, DateTimeOffset> ClaudeKeys { get; set; } = [];
public List<string> ExpiredClaudeKeys { get; set; } = [];
public Dictionary<string, TokenCounts> CodexTotals { get; set; } = [];
public Dictionary<string, DateTimeOffset> CodexTimes { get; set; } = [];
public Dictionary<string, ScanCursor> Cursors { get; set; } = [];
public Dictionary<Provider, List<LimitWindow>> LatestWindows { get; set; } = [];
public Dictionary<string, LimitWindow> LastSamples { get; set; } = [];
}
internal sealed class PartitionIndex
{
private readonly Dictionary<(Provider, string), SortedSet<LimitWindow>> windowSamples = [];
private static readonly IComparer<LimitWindow> SampleTimeComparer = Comparer<LimitWindow>.Create((a, b) => a.SampleTime.CompareTo(b.SampleTime));
public Dictionary<BucketKey, TokenBucket> Buckets { get; } = [];
public HashSet<LimitWindow> Limits { get; } = [];
public void Apply(HistoryPartition partition)
{
foreach (var bucket in partition.Buckets) Buckets[BucketKey.For(bucket)] = bucket;
foreach (var sample in partition.Limits) AddLimit(sample);
}
public void Apply(PartitionIndex other)
{
foreach (var (key, bucket) in other.Buckets) Buckets[key] = bucket;
foreach (var sample in other.Limits) AddLimit(sample);
}
public bool AddLimit(LimitWindow sample)
{
if (!Limits.Add(sample)) return false;
var key = (sample.Provider, sample.Id);
if (!windowSamples.TryGetValue(key, out var samples)) windowSamples[key] = samples = new(SampleTimeComparer);
samples.Add(sample);
return true;
}
public LimitWindow? PreviousLimit(LimitWindow sample)
{
if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == 0) return null;
return samples.GetViewBetween(sample with { SampleTime = DateTimeOffset.MinValue },
sample with { SampleTime = new(sample.SampleTime.UtcTicks - 1, TimeSpan.Zero) }).Max;
}
public LimitWindow? NextLimit(LimitWindow sample)
{
if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == DateTimeOffset.MaxValue.UtcTicks) return null;
return samples.GetViewBetween(sample with { SampleTime = new(sample.SampleTime.UtcTicks + 1, TimeSpan.Zero) },
sample with { SampleTime = DateTimeOffset.MaxValue }).Min;
}
public HistoryPartition Export() => new() { Buckets = Buckets.Values.ToList(), Limits = Limits.ToList() };
}
internal static class HistoryJournal
{
/// <summary>Only newline-terminated records commit. Returns the byte position of the last complete record.
/// A corrupt completed record is an error; a torn final line is deliberately ignored.</summary>
public static long Read(string path, Action<HistoryTransaction> apply)
{
if (!File.Exists(path)) return 0;
using var stream = SharedFile.OpenRead(path);
using var line = new MemoryStream();
var buffer = new byte[65536];
long position = 0, committed = 0;
int count;
while ((count = stream.Read(buffer)) > 0)
{
var start = 0;
while (start < count)
{
var newline = buffer.AsSpan(start, count - start).IndexOf((byte)'\n');
var length = newline < 0 ? count - start : newline;
line.Write(buffer.AsSpan(start, length));
position += length;
start += length;
if (newline < 0) break;
var transaction = JsonSerializer.Deserialize(line.GetBuffer().AsSpan(0, (int)line.Length), CoreJsonContext.Default.HistoryTransaction)
?? throw new JsonException();
if (transaction.V != 1 || transaction.Sequence <= 0) throw new JsonException();
apply(transaction);
committed = ++position;
start++;
line.SetLength(0);
}
}
return committed;
}
public static long Append(string path, long committed, HistoryTransaction transaction, CancellationToken token)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
token.ThrowIfCancellationRequested();
var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(transaction, CoreJsonContext.Default.HistoryTransaction) + "\n");
using var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read,
65536, FileOptions.WriteThrough);
// Repair a torn previous append before adding another record.
if (stream.Length != committed) stream.SetLength(committed);
stream.Position = committed;
stream.Write(bytes);
stream.Flush(true);
return stream.Position;
}
}
+372
View File
@@ -0,0 +1,372 @@
using System.Globalization;
using System.Text.Json;
namespace FinalToken.Core;
public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts);
public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts);
public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
public enum SeriesInterval { Hour, Day }
public sealed class ScanCursor
{
public long Offset { get; set; }
public long CreationTicks { get; set; }
public string PrefixHash { get; set; } = "";
public int PrefixLength { get; set; }
public string TailHash { get; set; } = "";
public string? SessionId { get; set; }
public string? Model { get; set; }
public string? Project { get; set; }
public List<LimitWindow> LatestLimits { get; set; } = [];
public long ObservedLength { get; set; } = -1;
public long LastWriteTicks { get; set; }
}
/// <summary>UTC hourly storage; queries use [from,to), including whole boundary hours (D5).
/// Data partitions load on demand with a three-month cache; journal replay is bounded by compaction.
/// Claude imports and dedupe keys have a 60-day horizon, longer than the CLI's default 30-day cleanup.
/// Scanner/session metadata scales with the local source files, not with their token events.</summary>
public sealed class HistoryStore
{
public const int ClaudeRetentionDays = 60;
private const long CompactBytes = 8 * 1024 * 1024;
private readonly Lock gate = new();
private readonly string directory;
private readonly TimeProvider clock;
private readonly HistoryState state;
private readonly Dictionary<string, PartitionIndex> overlays = [];
private readonly Dictionary<string, PartitionIndex> pendingPartitions = [];
private readonly Dictionary<string, PartitionIndex> cache = [];
private readonly LinkedList<string> cacheOrder = [];
private readonly HashSet<string> months = [];
private HistoryTransaction pending = new();
private long journalBytes;
private DateTimeOffset prunedDay = DateTimeOffset.MinValue;
private string JournalPath => Path.Combine(directory, "history.journal.jsonl");
private string StatePath => Path.Combine(directory, "history.state.json");
private string PartitionPath(string month) => Path.Combine(directory, "history", month + ".json");
public HistoryStore(string directory, DiagnosticLog diagnostics) : this(directory, diagnostics, TimeProvider.System) { }
public HistoryStore(string directory, DiagnosticLog diagnostics, TimeProvider timeProvider)
{
this.directory = directory;
clock = timeProvider;
try
{
state = File.Exists(StatePath) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(StatePath),
CoreJsonContext.Default.HistoryState) ?? throw new JsonException() : new();
ValidateState(state);
if (Directory.Exists(Path.Combine(directory, "history")))
foreach (var path in Directory.GetFiles(Path.Combine(directory, "history"), "*.json"))
{
var month = Path.GetFileNameWithoutExtension(path);
if (!DateTime.TryParseExact(month, "yyyy-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
throw new JsonException();
months.Add(month);
}
journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction);
PruneKeys();
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
{
diagnostics.Add(null, "history-invalid", "History cannot be loaded; refusing to overwrite it.");
throw new InvalidDataException("History cannot be loaded; restore or move the invalid history file.", e);
}
}
internal ScanCursor Cursor(string path)
{
lock (gate)
{
if (!state.Cursors.TryGetValue(path, out var cursor)) state.Cursors[path] = cursor = new();
return cursor;
}
}
internal void CursorChanged(string path)
{
lock (gate) pending.Cursors[path] = CloneCursor(state.Cursors[path]);
}
private static ScanCursor CloneCursor(ScanCursor c) => new()
{
Offset = c.Offset, CreationTicks = c.CreationTicks, PrefixHash = c.PrefixHash,
PrefixLength = c.PrefixLength, TailHash = c.TailHash, SessionId = c.SessionId,
Model = c.Model, Project = c.Project, LatestLimits = c.LatestLimits.ToList(),
ObservedLength = c.ObservedLength, LastWriteTicks = c.LastWriteTicks
};
public bool Add(UsageEvent usage)
{
lock (gate)
{
PruneKeys();
if (usage.Provider == Provider.Claude && usage.Time < clock.GetUtcNow().AddDays(-ClaudeRetentionDays)) return false;
if (state.ClaudeKeys.ContainsKey(usage.DedupeKey)) return false;
AddBucket(usage);
state.ClaudeKeys[usage.DedupeKey] = usage.Time;
pending.ClaudeKeys[usage.DedupeKey] = usage.Time;
return true;
}
}
internal bool AddCodex(string session, UsageEvent cumulative)
{
lock (gate)
{
var previous = state.CodexTotals.GetValueOrDefault(session);
var previousTime = state.CodexTimes.GetValueOrDefault(session, DateTimeOffset.MinValue);
// Archive copies and rescans replay earlier totals. A later counter reset is retained,
// so its subsequent increases still count, without keeping a key for every token event.
if (cumulative.Time < previousTime || cumulative.Time == previousTime && cumulative.Counts.Total <= previous.Total) return false;
var delta = cumulative.Counts.IncreaseFrom(previous);
if (delta.Total > 0) AddBucket(cumulative with { Counts = delta });
state.CodexTotals[session] = pending.CodexTotals[session] = cumulative.Counts;
state.CodexTimes[session] = pending.CodexTimes[session] = cumulative.Time;
return delta.Total > 0;
}
}
private void PruneKeys()
{
var now = clock.GetUtcNow();
var day = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
if (day == prunedDay) return;
prunedDay = day;
var cutoff = now.AddDays(-ClaudeRetentionDays);
foreach (var key in state.ClaudeKeys.Where(k => k.Value < cutoff).Select(k => k.Key).ToArray())
{
state.ClaudeKeys.Remove(key);
pending.ClaudeKeys.Remove(key);
pending.ExpiredClaudeKeys.Add(key);
}
}
private void AddBucket(UsageEvent usage)
{
var bucket = new TokenBucket(usage.Provider, FloorHour(usage.Time), usage.Model, usage.Project, usage.Counts);
var key = BucketKey.For(bucket);
var month = Month(bucket.Hour);
var partition = GetPartition(month);
if (partition.Buckets.TryGetValue(key, out var previous)) bucket = bucket with { Counts = previous.Counts + usage.Counts };
partition.Buckets[key] = bucket;
PendingPartition(month).Buckets[key] = bucket;
}
public void AddLimits(IEnumerable<LimitWindow> windows)
{
lock (gate)
{
var batch = windows.ToArray();
HashSet<Provider> changedSets = [];
foreach (var group in batch.GroupBy(w => w.Provider))
{
var newest = group.Max(w => w.SampleTime);
if (!state.LatestWindows.TryGetValue(group.Key, out var old) || old.Count == 0 || newest >= old.Max(w => w.SampleTime))
{
var next = group.Where(w => w.SampleTime == newest).GroupBy(w => w.Id).Select(g => g.Last()).ToList();
if (old is null || !old.Select(WindowValue).SequenceEqual(next.Select(WindowValue))) changedSets.Add(group.Key);
state.LatestWindows[group.Key] = next;
}
}
foreach (var window in batch)
{
var key = WindowKey(window);
var previous = state.LastSamples.GetValueOrDefault(key);
var month = Month(window.SampleTime);
var partition = GetPartition(month);
if (partition.Limits.Contains(window)) continue;
var chronologicalPrevious = previous;
LimitWindow? chronologicalNext = null;
if (previous is not null && window.SampleTime < previous.SampleTime)
{
chronologicalPrevious = partition.PreviousLimit(window);
if (chronologicalPrevious is null)
foreach (var earlier in months.Where(m => string.CompareOrdinal(m, month) < 0).OrderDescending())
if (GetPartition(earlier).PreviousLimit(window) is { } found) { chronologicalPrevious = found; break; }
chronologicalNext = partition.NextLimit(window);
if (chronologicalNext is null)
foreach (var later in months.Where(m => string.CompareOrdinal(m, month) > 0).Order())
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
}
if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent &&
window.ResetsAt == chronologicalPrevious.ResetsAt &&
window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue;
if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent &&
window.ResetsAt == chronologicalNext.ResetsAt &&
chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue;
if (previous is null || window.SampleTime >= previous.SampleTime)
state.LastSamples[key] = pending.LastSamples[key] = window;
changedSets.Add(window.Provider);
if (partition.AddLimit(window)) PendingPartition(month).Limits.Add(window);
}
foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider];
}
}
private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) =>
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
{
lock (gate) return state.LatestWindows.GetValueOrDefault(provider, []).OrderBy(w => w.Length).ToArray();
}
public IReadOnlyList<LimitWindow> LimitSamples(Provider provider, string windowId, DateTimeOffset from, DateTimeOffset to)
{
lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits)
.Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to)
.OrderBy(w => w.SampleTime).ToArray();
}
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
TimeZoneInfo? zone)
{
lock (gate)
{
Dictionary<DateTimeOffset, TokenCounts> points = [];
foreach (var bucket in Range(provider, from, to))
{
var key = interval == SeriesInterval.Hour ? bucket.Hour : CalendarDays.Start(bucket.Hour, zone);
points[key] = points.GetValueOrDefault(key) + bucket.Counts;
}
return points.OrderBy(p => p.Key).Select(p => new TokenPoint(p.Key, p.Value)).ToArray();
}
}
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true);
public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false);
private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model)
{
lock (gate) return Range(provider, from, to).GroupBy(b => model ? b.Model : b.Project)
.Select(g => new TokenBreakdown(g.Key, Sum(g.Select(b => b.Counts)))).OrderByDescending(b => b.Counts.Total).ToArray();
}
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now,
LimitWindow? session, TimeZoneInfo? zone = null)
{
zone ??= TimeZoneInfo.Local;
var local = TimeZoneInfo.ConvertTime(now, zone);
var today = local.Date;
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
var todayUtc = CalendarDays.Start(today, zone);
var weekUtc = CalendarDays.Start(week, zone);
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
}
private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values)
.Where(b => b.Provider == provider && b.Hour >= FloorHour(from) && b.Hour < to);
private string[] SelectMonths(DateTimeOffset from, DateTimeOffset to) => to <= from ? [] :
months.Where(m => string.CompareOrdinal(m, Month(from)) >= 0 && string.CompareOrdinal(m, Month(to)) <= 0).Order().ToArray();
private static string Month(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM", CultureInfo.InvariantCulture);
private static string WindowKey(LimitWindow window) => ((int)window.Provider).ToString(CultureInfo.InvariantCulture) + ":" + window.Id;
private static DateTimeOffset FloorHour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
private static TokenCounts Sum(IEnumerable<TokenCounts> values) => values.Aggregate(new TokenCounts(), (a, b) => a + b);
private PartitionIndex PendingPartition(string month)
{
months.Add(month);
if (!pendingPartitions.TryGetValue(month, out var partition)) pendingPartitions[month] = partition = new();
return partition;
}
private PartitionIndex GetPartition(string month)
{
if (!cache.TryGetValue(month, out var partition))
{
partition = new();
var path = PartitionPath(month);
if (File.Exists(path))
{
var data = JsonSerializer.Deserialize(SharedFile.ReadAllText(path), CoreJsonContext.Default.HistoryPartition) ?? throw new JsonException();
if (data.V != 1 || data.Buckets is null || data.Limits is null) throw new JsonException();
partition.Apply(data);
}
if (overlays.TryGetValue(month, out var overlay)) partition.Apply(overlay);
if (pendingPartitions.TryGetValue(month, out var changes)) partition.Apply(changes);
cache[month] = partition;
while (cache.Count > 3)
{
var first = cacheOrder.First!.Value;
cacheOrder.RemoveFirst();
cache.Remove(first);
}
}
cacheOrder.Remove(month);
cacheOrder.AddLast(month);
return partition;
}
public Task SaveAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => Save(false, cancellationToken), cancellationToken);
/// <summary>Explicit bounded-journal maintenance; ordinary idle SaveAsync does no I/O.</summary>
public Task CompactAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => Save(true, cancellationToken), cancellationToken);
private void Save(bool compact, CancellationToken token)
{
lock (gate)
{
PruneKeys();
pending.Buckets = pendingPartitions.Values.SelectMany(p => p.Buckets.Values).ToList();
pending.Limits = pendingPartitions.Values.SelectMany(p => p.Limits).ToList();
var changed = pending.Buckets.Count + pending.Limits.Count + pending.ClaudeKeys.Count +
pending.ExpiredClaudeKeys.Count + pending.CodexTotals.Count + pending.Cursors.Count +
pending.LatestWindows.Count + pending.LastSamples.Count > 0;
if (changed)
{
pending.Sequence = state.Sequence + 1;
journalBytes = HistoryJournal.Append(JournalPath, journalBytes, pending, token);
foreach (var (month, changes) in pendingPartitions)
{
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
overlay.Apply(changes);
}
state.Sequence = pending.Sequence;
pending = new();
pendingPartitions.Clear();
}
if ((changed && journalBytes >= CompactBytes || compact) && journalBytes > 0)
{
foreach (var month in overlays.Keys.ToArray())
{
token.ThrowIfCancellationRequested();
AtomicFile.WriteAsync(PartitionPath(month), JsonSerializer.Serialize(GetPartition(month).Export(),
CoreJsonContext.Default.HistoryPartition), token).GetAwaiter().GetResult();
}
// Checkpoint last. If interrupted, absolute bucket upserts and exact sample sets replay idempotently.
AtomicFile.WriteAsync(StatePath, JsonSerializer.Serialize(state, CoreJsonContext.Default.HistoryState), token).GetAwaiter().GetResult();
AtomicFile.WriteAsync(JournalPath, "", token).GetAwaiter().GetResult();
journalBytes = 0;
overlays.Clear();
}
}
}
private void ApplyTransaction(HistoryTransaction transaction)
{
if (transaction.Sequence <= state.Sequence) return;
if (transaction.Sequence != state.Sequence + 1 || transaction.Buckets is null || transaction.Limits is null ||
transaction.ClaudeKeys is null || transaction.ExpiredClaudeKeys is null || transaction.CodexTotals is null ||
transaction.CodexTimes is null || transaction.Cursors is null || transaction.LatestWindows is null || transaction.LastSamples is null)
throw new JsonException();
foreach (var key in transaction.ExpiredClaudeKeys) state.ClaudeKeys.Remove(key);
foreach (var (key, value) in transaction.ClaudeKeys) state.ClaudeKeys[key] = value;
foreach (var (key, value) in transaction.CodexTotals) state.CodexTotals[key] = value;
foreach (var (key, value) in transaction.CodexTimes) state.CodexTimes[key] = value;
foreach (var (key, value) in transaction.Cursors) state.Cursors[key] = value;
foreach (var (key, value) in transaction.LatestWindows) state.LatestWindows[key] = value;
foreach (var (key, value) in transaction.LastSamples) state.LastSamples[key] = value;
foreach (var bucket in transaction.Buckets)
{
var month = Month(bucket.Hour);
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
overlay.Buckets[BucketKey.For(bucket)] = bucket;
months.Add(month);
}
foreach (var sample in transaction.Limits)
{
var month = Month(sample.SampleTime);
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
overlay.Limits.Add(sample);
months.Add(month);
}
state.Sequence = transaction.Sequence;
}
private static void ValidateState(HistoryState value)
{
if (value.V != 1 || value.Sequence < 0 || value.ClaudeKeys is null || value.CodexTotals is null || value.CodexTimes is null ||
value.Cursors is null || value.LatestWindows is null || value.LastSamples is null) throw new JsonException();
}
}
+61
View File
@@ -0,0 +1,61 @@
using System.Text.Json.Serialization;
namespace FinalToken.Core;
[JsonConverter(typeof(JsonStringEnumConverter<Provider>))]
public enum Provider { Claude, Codex }
[JsonConverter(typeof(JsonStringEnumConverter<ProviderStatus>))]
public enum ProviderStatus { Available, Unavailable, Disabled }
[JsonConverter(typeof(JsonStringEnumConverter<PaceState>))]
public enum PaceState { Unknown, OnTrack, Ahead, Behind }
[JsonConverter(typeof(JsonStringEnumConverter<InstallMode>))]
public enum InstallMode { Off, Ask, Automatic }
/// <summary>Cache read is a subset of input for Codex, but separate for Claude.
/// Reasoning is a subset of output. Total is provider-reported or computed by its parser.</summary>
public readonly record struct TokenCounts(long Input = 0, long CacheRead = 0, long CacheWrite = 0,
long Output = 0, long ReasoningOutput = 0, long Total = 0)
{
public static TokenCounts operator +(TokenCounts a, TokenCounts b) => new(
checked(a.Input + b.Input), checked(a.CacheRead + b.CacheRead), checked(a.CacheWrite + b.CacheWrite),
checked(a.Output + b.Output), checked(a.ReasoningOutput + b.ReasoningOutput), checked(a.Total + b.Total));
public TokenCounts IncreaseFrom(TokenCounts previous) => new(
Math.Max(0, Input - previous.Input), Math.Max(0, CacheRead - previous.CacheRead),
Math.Max(0, CacheWrite - previous.CacheWrite), Math.Max(0, Output - previous.Output),
Math.Max(0, ReasoningOutput - previous.ReasoningOutput), Math.Max(0, Total - previous.Total));
}
public sealed record UsageEvent(Provider Provider, DateTimeOffset Time, string? Model, string? Project,
TokenCounts Counts, string DedupeKey);
public sealed record LimitWindow(Provider Provider, string Id, string Label, double UsedPercent,
DateTimeOffset? ResetsAt, TimeSpan? Length, DateTimeOffset SampleTime, string Source);
public sealed record PaceResult(PaceState State, double? ElapsedFraction = null, double? Delta = null,
DateTimeOffset? Projection = null);
public sealed record PopupEvent(Provider Provider, string WindowId, string Label, PaceState State,
double Delta, DateTimeOffset? Projection);
public sealed record Diagnostic(DateTimeOffset Time, Provider? Provider, string Code, string Summary)
{
public long Count { get; init; } = 1;
}
/// <summary>Bounded metadata-only diagnostics. Never pass parser input or process output here (D2).</summary>
public sealed class DiagnosticLog(TimeProvider? timeProvider = null, int capacity = 100)
{
private readonly Lock gate = new();
private readonly List<Diagnostic> entries = [];
public void Add(Provider? provider, string code, string summary)
{
lock (gate)
{
var time = (timeProvider ?? TimeProvider.System).GetUtcNow();
var index = entries.FindIndex(d => d.Provider == provider && d.Code == code);
if (index >= 0) entries[index] = entries[index] with { Time = time, Count = entries[index].Count + 1 };
else
{
entries.Add(new(time, provider, code, summary));
if (entries.Count > Math.Max(1, capacity)) entries.RemoveAt(0);
}
}
}
public IReadOnlyList<Diagnostic> Recent { get { lock (gate) return entries.ToArray(); } }
}
+49
View File
@@ -0,0 +1,49 @@
namespace FinalToken.Core;
public static class Pace
{
// D7. A reset in the past clamps elapsed to one; it never has a future projection.
public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10)
{
if (window.Length is not { Ticks: > 0 } length || window.ResetsAt is not { } reset ||
!double.IsFinite(window.UsedPercent) || window.UsedPercent is < 0 or > 100 ||
!double.IsFinite(threshold) || threshold <= 0)
return new(PaceState.Unknown);
var elapsed = Math.Clamp(1 - (reset - now).TotalSeconds / length.TotalSeconds, 0, 1);
var delta = window.UsedPercent - 100 * elapsed;
var state = delta >= threshold ? PaceState.Ahead :
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
DateTimeOffset? projection = null;
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0)
{
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
}
return new(state, elapsed, delta, projection);
}
}
/// <summary>D8: retains an alert until it clears its threshold by two points.
/// Observe is deterministic and has no side effects beyond its own state.</summary>
public sealed class PopupDecider
{
private readonly Dictionary<(Provider, string), PaceState> states = [];
public PopupEvent? Observe(LimitWindow window, PaceResult pace, Settings settings)
{
var key = (window.Provider, window.Id);
var previous = states.GetValueOrDefault(key, PaceState.Unknown);
var next = pace.State;
if (pace.Delta is { } delta && pace.State != PaceState.Unknown)
{
if (previous == PaceState.Ahead && delta > settings.PaceThreshold - 2) next = PaceState.Ahead;
if (previous == PaceState.Behind && delta < -settings.PaceThreshold + 2 && pace.ElapsedFraction >= 0.5)
next = PaceState.Behind;
}
states[key] = next;
if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) ||
!settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled ||
(next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead :
!settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null;
return new(window.Provider, window.Id, window.Label, next, pace.Delta!.Value, pace.Projection);
}
}
@@ -0,0 +1,86 @@
namespace FinalToken.Core.Processes;
public sealed record CliCommand(string FileName, IReadOnlyList<string> PrefixArguments);
public sealed record CliDiscoveryResult(CliCommand? Command, string? Reason);
public static class CliDiscovery
{
public static CliDiscoveryResult Find(Provider provider, string? overridePath = null,
string? searchPath = null, bool? windows = null)
{
try { return FindCore(provider, overridePath, searchPath, windows); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{ return new(null, "CLI path is invalid or cannot be inspected."); }
}
private static CliDiscoveryResult FindCore(Provider provider, string? overridePath,
string? searchPath, bool? windows)
{
var isWindows = windows ?? OperatingSystem.IsWindows();
var name = provider == Provider.Claude ? "claude" : "codex";
if (!string.IsNullOrWhiteSpace(overridePath)) return Resolve(Path.GetFullPath(overridePath), provider, isWindows, searchPath);
foreach (var directory in (searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(isWindows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries))
{
foreach (var suffix in isWindows ? new[] { ".exe", ".cmd", ".ps1", "" } : new[] { "" })
{
var candidate = Path.Combine(directory.Trim('"'), name + suffix);
if (File.Exists(candidate))
{
var resolved = Resolve(candidate, provider, isWindows, searchPath);
if (resolved.Command is not null) return resolved;
}
}
}
return new(null, $"{name} CLI was not found.");
}
private static CliDiscoveryResult Resolve(string path, Provider provider, bool windows, string? searchPath)
{
if (!File.Exists(path)) return new(null, "Configured CLI does not exist.");
var directory = Path.GetDirectoryName(path)!;
if (windows && Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) return new(new(path, []), null);
if (provider == Provider.Claude && windows)
{
var package = Path.Combine(directory, "node_modules", "@anthropic-ai", "claude-code");
// Current npm installs copy the platform binary here; older releases use cli.js.
var binary = Path.Combine(package, "bin", "claude.exe");
if (File.Exists(binary)) return new(new(binary, []), null);
var script = Path.Combine(package, "cli.js");
if (File.Exists(script) && FindNode(directory, searchPath, true) is { } node) return new(new(node, [script]), null);
}
if (provider == Provider.Codex)
{
var package = Path.Combine(directory, "node_modules", "@openai", "codex");
// Unix npm bin symlinks point into the package; resolve before looking for vendor/node.
var target = File.ResolveLinkTarget(path, true)?.FullName;
if (target is not null && Path.GetFileName(target) == "codex.js") package = Path.GetDirectoryName(Path.GetDirectoryName(target))!;
foreach (var vendorRoot in new[] { Path.Combine(package, "node_modules", "@openai", "codex-win32-x64", "vendor"), Path.Combine(package, "vendor") })
{
var binary = Path.Combine(vendorRoot, windows ? "x86_64-pc-windows-msvc" : "x86_64-unknown-linux-musl", "bin", windows ? "codex.exe" : "codex");
if (File.Exists(binary)) return new(new(binary, []), null);
}
var script = Path.Combine(package, "bin", "codex.js");
if (File.Exists(script) && FindNode(directory, searchPath, windows) is { } node) return new(new(node, [script]), null);
}
if (!windows)
{
using var file = File.OpenRead(path);
var bytes = new byte[128];
var count = file.Read(bytes);
var first = System.Text.Encoding.UTF8.GetString(bytes, 0, count).Split('\n')[0];
if (!first.StartsWith("#!", StringComparison.Ordinal)) return new(new(path, []), null);
if ((first == "#!/usr/bin/env node" || first == "#!/usr/bin/node") && FindNode(directory, searchPath, false) is { } node)
return new(new(node, [path]), null);
}
return new(null, "CLI wrapper has no supported native binary or Node runtime.");
}
private static string? FindNode(string directory, string? searchPath, bool windows)
{
foreach (var candidateDirectory in new[] { directory }.Concat((searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(windows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries)))
{
var path = Path.Combine(candidateDirectory.Trim('"'), windows ? "node.exe" : "node");
if (File.Exists(path)) return path;
}
return null;
}
}
@@ -0,0 +1,115 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
namespace FinalToken.Core.Processes;
public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory,
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024);
public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false);
public interface IProcessRunner
{
Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken);
}
/// <summary>No shell; bounded capture; cancellation/timeout kills and waits for the whole child tree (D6).</summary>
public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessRunner
{
public async Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
{
using var timeout = new CancellationTokenSource(request.Timeout, timeProvider ?? TimeProvider.System);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
var token = linked.Token;
using var process = new Process { StartInfo = new()
{
FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory,
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardInput = true,
// CLI JSON is UTF-8. A GUI host has no console code page; using its default
// encoding corrupts Unicode delimiters in Claude's local /usage result (D3).
StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false),
StandardInputEncoding = new UTF8Encoding(false)
} };
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
process.Start();
// D6: a WinExe host can have no standard input handle. Give every child a valid
// pipe; non-interactive probes get EOF, while app-server keeps its RPC input open.
if (!request.CodexRpc) process.StandardInput.Close();
var stderr = CaptureAsync(process.StandardError, request.OutputLimit, token);
Task<(string Output, bool Truncated)>? stdout = null;
try
{
if (request.CodexRpc)
{
await process.StandardInput.WriteLineAsync("{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"finaltoken\",\"version\":\"1.0.0\"},\"capabilities\":{\"experimentalApi\":false,\"explicitGatewayOauth\":true}}}".AsMemory(), token);
await ReadResponseAsync(process.StandardOutput, 1, request.OutputLimit, token);
await process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token);
await process.StandardInput.WriteLineAsync("{\"id\":2,\"method\":\"account/rateLimits/read\",\"params\":null}".AsMemory(), token);
var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token);
Kill(process);
await process.WaitForExitAsync(CancellationToken.None);
await stderr;
return new(0, output);
}
stdout = CaptureAsync(process.StandardOutput, request.OutputLimit, token);
await process.WaitForExitAsync(token);
var captured = await stdout;
await stderr;
return new(process.ExitCode, captured.Output, false, captured.Truncated);
}
catch (OperationCanceledException) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{ return new(-1, "", true); }
finally
{
Kill(process);
await process.WaitForExitAsync(CancellationToken.None);
// Observe capture cancellation/failure; process output is never logged.
try { await stderr; } catch (OperationCanceledException) { }
if (stdout is not null)
try { await stdout; } catch (OperationCanceledException) { }
}
}
private static void Kill(Process process)
{
try { if (!process.HasExited) process.Kill(true); }
catch (InvalidOperationException) { }
}
private static async Task<(string Output, bool Truncated)> CaptureAsync(StreamReader reader, int limit, CancellationToken token)
{
var output = new StringBuilder();
var buffer = new char[4096];
var truncated = false;
int read;
while ((read = await reader.ReadAsync(buffer, token)) > 0)
{
var keep = Math.Min(read, Math.Max(0, limit - output.Length));
output.Append(buffer, 0, keep);
truncated |= keep < read;
}
return (output.ToString(), truncated);
}
private static async Task<string> ReadResponseAsync(StreamReader reader, int id, int limit, CancellationToken token)
{
// Bound each line and total traffic, including unrelated notifications.
var line = new StringBuilder();
var one = new char[1];
var total = 0;
while (await reader.ReadAsync(one, token) > 0)
{
if (++total > limit) throw new InvalidDataException("RPC output exceeded its bound.");
if (one[0] != '\n') { line.Append(one[0]); continue; }
try
{
using var document = JsonDocument.Parse(line.ToString());
if (document.RootElement.TryGetProperty("id", out var value) && value.TryGetInt32(out var responseId) && responseId == id)
{
if (document.RootElement.TryGetProperty("error", out _)) throw new InvalidDataException("RPC request failed.");
return line.ToString();
}
}
catch (JsonException) { }
line.Clear();
}
throw new InvalidDataException("RPC response was not returned.");
}
}
+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();
}
+66
View File
@@ -0,0 +1,66 @@
using System.Text.Json;
namespace FinalToken.Core;
public sealed record ProviderSettings
{
// Setters let source-generated JSON construct defaults before assigning present properties.
public bool Enabled { get; set; } = true;
public bool PopupsEnabled { get; set; } = true;
public bool PopupAhead { get; set; } = true;
public bool PopupBehind { get; set; } = true;
public string? CliPath { get; set; }
}
public sealed record Settings
{
// Preserve initializers when an older file lacks newly added properties (D5).
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromSeconds(60);
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
public double PaceThreshold { get; set; } = 10;
public bool PopupAhead { get; set; } = true;
public bool PopupBehind { get; set; } = true;
public InstallMode StreamDeckInstallMode { get; set; } = InstallMode.Ask;
public string? DismissedPluginVersion { get; set; }
public bool StartWithOs { get; set; }
public bool CloseToTray { get; set; } = true;
public ProviderSettings Claude { get; set; } = new();
public ProviderSettings Codex { get; set; } = new();
public ProviderSettings For(Provider provider) => provider == Provider.Claude ? Claude : Codex;
[System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) &&
ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) &&
double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is not null && Codex is not null &&
Enum.IsDefined(StreamDeckInstallMode);
}
public static class DataPaths
{
public static string DataDirectory => Environment.GetEnvironmentVariable("FINALTOKEN_DATA_DIR") is { Length: > 0 } path
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FinalToken");
public static string ClaudeDirectory => Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR") is { Length: > 0 } path
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude");
public static string CodexDirectory => Environment.GetEnvironmentVariable("CODEX_HOME") is { Length: > 0 } path
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
}
public static class SettingsFile
{
public static Settings Load(string directory, DiagnosticLog diagnostics)
{
try
{
var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
if (value is { IsValid: true }) return value;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults.");
return new();
}
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
{
if (!settings.IsValid) throw new ArgumentException("Invalid settings.", nameof(settings));
return AtomicFile.WriteAsync(Path.Combine(directory, "settings.json"),
JsonSerializer.Serialize(settings, CoreJsonContext.Default.Settings), cancellationToken);
}
}
+49
View File
@@ -0,0 +1,49 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace FinalToken.Core;
public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
{
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
}
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week);
public sealed record Snapshot
{
// Keep this initializer for omitted properties in source-generated JSON (D9).
public int V { get; set; } = 1;
public required DateTimeOffset MadeAt { get; init; }
public required TimeSpan RefreshInterval { get; init; }
public string? AppPath { get; init; }
public required IReadOnlyList<ProviderSnapshot> Providers { get; init; }
}
public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error);
public static class SnapshotFile
{
public static Task WriteAsync(string directory, Snapshot snapshot, CancellationToken cancellationToken = default) =>
AtomicFile.WriteAsync(Path.Combine(directory, "snapshot.json"),
JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot), cancellationToken);
public static SnapshotReadResult Read(string directory, DateTimeOffset? now = null)
{
try
{
var snapshot = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "snapshot.json")), CoreJsonContext.Default.Snapshot);
if (snapshot is null || snapshot.V != 1 || snapshot.RefreshInterval <= TimeSpan.Zero || snapshot.Providers is null)
return new(null, true, "Snapshot schema is invalid or unsupported.");
var age = (now ?? DateTimeOffset.UtcNow) - snapshot.MadeAt;
return new(snapshot, age.TotalSeconds > snapshot.RefreshInterval.TotalSeconds * 3, null);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
{ return new(null, true, "Snapshot is missing or invalid."); }
}
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
[JsonSerializable(typeof(Snapshot))]
[JsonSerializable(typeof(Settings))]
[JsonSerializable(typeof(HistoryState))]
[JsonSerializable(typeof(HistoryPartition))]
[JsonSerializable(typeof(HistoryTransaction))]
public partial class CoreJsonContext : JsonSerializerContext;
@@ -0,0 +1,21 @@
namespace FinalToken.Core.StreamDeck;
public enum PluginInstallState { NoHostFound, NotInstalled, Outdated, UpToDate, NoShippedPlugin }
public sealed record PluginInstallStatus(PluginInstallState State, string? ShippedVersion = null, string? InstalledVersion = null);
public interface IPluginInstaller
{
Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default);
Task InstallOrUpdateAsync(CancellationToken cancellationToken = default);
}
public enum InstallAction { Nothing, Ask, Install }
public static class InstallPolicy
{
public static InstallAction Decide(InstallMode mode, PluginInstallStatus status, string? dismissedVersion) =>
status.State is not (PluginInstallState.NotInstalled or PluginInstallState.Outdated) || status.ShippedVersion is null
? InstallAction.Nothing : mode switch
{
InstallMode.Automatic => InstallAction.Install,
InstallMode.Ask when status.ShippedVersion != dismissedVersion => InstallAction.Ask,
_ => InstallAction.Nothing
};
}
@@ -0,0 +1,202 @@
using System.Diagnostics;
using System.Text.Json;
namespace FinalToken.Core.StreamDeck;
public sealed record PluginHost(string PluginDirectory, string Executable, string ProcessName, IReadOnlyList<string>? Arguments = null, bool Flatpak = false);
public interface IHostProcesses
{
Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct);
Task StopAsync(PluginHost host, CancellationToken ct);
Task StartAsync(PluginHost host, CancellationToken ct);
}
public enum InstallOutcome { Installed, Updated, AlreadyCurrent, NoHost, NoShippedPlugin, RolledBack, Failed, HostStopped, HostRestarted, HostRestartFailed }
/// <summary>D11: stage beside the destination, stop only a running host, swap and restore on failure.</summary>
public sealed class PluginInstaller(string shippedDirectory, PluginHost? host, IHostProcesses? processes = null) : IPluginInstaller
{
public const string FolderName = "de.finalfactory.finaltoken.sdPlugin";
private readonly IHostProcesses processes = processes ?? new HostProcesses();
private readonly SemaphoreSlim gate = new(1, 1);
public event Action<InstallOutcome>? Outcome;
public static PluginInstaller CreateDefault(string? appDirectory = null) => new(
Path.Combine(appDirectory ?? AppContext.BaseDirectory, "streamdeck", FolderName), HostDiscovery.Find());
public Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default) => Task.Run(() => Status(), cancellationToken);
private PluginInstallStatus Status()
{
if (host is null) return new(PluginInstallState.NoHostFound);
var shipped = ReadVersion(shippedDirectory);
if (shipped is null) return new(PluginInstallState.NoShippedPlugin);
var installedPath = Path.Combine(host.PluginDirectory, FolderName);
var installed = ReadVersion(installedPath);
return new(installed is null ? PluginInstallState.NotInstalled : installed >= shipped ? PluginInstallState.UpToDate : PluginInstallState.Outdated,
shipped.ToString(), installed?.ToString());
}
public async Task InstallOrUpdateAsync(CancellationToken cancellationToken = default)
{
await gate.WaitAsync(cancellationToken);
try { await Task.Run(() => Install(cancellationToken), cancellationToken); }
finally { gate.Release(); }
}
private async Task Install(CancellationToken ct)
{
var status = Status();
if (status.State == PluginInstallState.NoHostFound) { Report(InstallOutcome.NoHost); return; }
if (status.State == PluginInstallState.NoShippedPlugin) { Report(InstallOutcome.NoShippedPlugin); throw new InvalidOperationException("Shipped plugin is missing or invalid."); }
if (status.State == PluginInstallState.UpToDate) { Report(InstallOutcome.AlreadyCurrent); return; }
var target = Path.Combine(host!.PluginDirectory, FolderName);
var suffix = Guid.NewGuid().ToString("N");
var staged = target + ".stage-" + suffix;
var backup = target + ".backup-" + suffix;
var movedOld = false;
var movedNew = false;
var restart = false;
try
{
Directory.CreateDirectory(host.PluginDirectory);
Copy(shippedDirectory, staged, ct);
if (ReadVersion(staged)?.ToString() != status.ShippedVersion) throw new IOException("Staged plugin version changed.");
restart = await processes.IsRunningAsync(host, ct);
if (restart) { await processes.StopAsync(host, ct); Report(InstallOutcome.HostStopped); }
ct.ThrowIfCancellationRequested();
if (Directory.Exists(target)) { Directory.Move(target, backup); movedOld = true; }
Directory.Move(staged, target); movedNew = true;
if (restart) { await processes.StartAsync(host, CancellationToken.None); restart = false; Report(InstallOutcome.HostRestarted); }
Report(movedOld ? InstallOutcome.Updated : InstallOutcome.Installed);
}
catch
{
try
{
if (movedNew) Directory.Delete(target, true);
if (movedOld) Directory.Move(backup, target);
Report(movedOld || movedNew ? InstallOutcome.RolledBack : InstallOutcome.Failed);
}
catch { Report(InstallOutcome.Failed); throw; }
throw;
}
finally
{
if (restart)
{
try { await processes.StartAsync(host, CancellationToken.None); Report(InstallOutcome.HostRestarted); }
catch { Report(InstallOutcome.HostRestartFailed); }
}
DeleteTemporary(staged);
// A backup left by a failed rollback must survive for recovery.
if (Directory.Exists(target) && ReadVersion(target)?.ToString() == status.ShippedVersion) DeleteTemporary(backup);
}
}
private void Report(InstallOutcome outcome) => Outcome?.Invoke(outcome);
private static void DeleteTemporary(string path)
{
try { if (Directory.Exists(path)) Directory.Delete(path, true); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
}
private static void Copy(string source, string destination, CancellationToken ct)
{
if ((File.GetAttributes(source) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported.");
Directory.CreateDirectory(destination);
foreach (var file in Directory.EnumerateFiles(source))
{
ct.ThrowIfCancellationRequested();
if ((File.GetAttributes(file) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported.");
var copied = Path.Combine(destination, Path.GetFileName(file));
File.Copy(file, copied);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(copied, File.GetUnixFileMode(file));
}
foreach (var directory in Directory.EnumerateDirectories(source)) Copy(directory, Path.Combine(destination, Path.GetFileName(directory)), ct);
}
public static Version? ReadVersion(string directory)
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(directory, "manifest.json")));
return doc.RootElement.TryGetProperty("Version", out var version) && version.ValueKind == JsonValueKind.String && Version.TryParse(version.GetString(), out var parsed) ? parsed : null;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) { return null; }
}
}
public static class HostDiscovery
{
public const string FlatpakId = "me.amankhanna.opendeck";
public static PluginHost? Find()
{
if (OperatingSystem.IsWindows())
{
var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Elgato", "StreamDeck", "StreamDeck.exe");
// A running installation can be outside Program Files.
foreach (var process in Process.GetProcessesByName("StreamDeck"))
{
using (process)
{
try { executable = process.MainModule?.FileName ?? executable; }
catch (Exception e) when (e is System.ComponentModel.Win32Exception or InvalidOperationException) { }
}
}
return File.Exists(executable) ? new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Elgato", "StreamDeck", "Plugins"), executable, "StreamDeck") : null;
}
if (!OperatingSystem.IsLinux()) return null;
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var config = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(home, ".config");
var native = FindExecutable("opendeck");
if (native is not null) return new(Path.Combine(config, "opendeck", "plugins"), native, "opendeck");
var flatpak = FindExecutable("flatpak");
var installed = Directory.Exists(Path.Combine(home, ".local", "share", "flatpak", "app", FlatpakId)) ||
Directory.Exists(Path.Combine(Path.DirectorySeparatorChar.ToString(), "var", "lib", "flatpak", "app", FlatpakId));
return flatpak is not null && installed ? new(Path.Combine(home, ".var", "app", FlatpakId, "config", "opendeck", "plugins"), flatpak, "opendeck", ["run", FlatpakId], true) : null;
}
private static string? FindExecutable(string name) => (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)
.Where(Path.IsPathFullyQualified).Select(p => Path.Combine(p, name)).FirstOrDefault(File.Exists);
}
public sealed class HostProcesses : IHostProcesses
{
private static Process[] Matching(PluginHost host) => Process.GetProcessesByName(host.ProcessName);
public Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var processes = Matching(host);
foreach (var process in processes) process.Dispose();
return Task.FromResult(processes.Length > 0);
}
public async Task StopAsync(PluginHost host, CancellationToken ct)
{
if (host.Flatpak)
{
using var kill = Process.Start(new ProcessStartInfo(host.Executable) { UseShellExecute = false, ArgumentList = { "kill", HostDiscovery.FlatpakId } })
?? throw new IOException("Could not stop OpenDeck.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
try { await kill.WaitForExitAsync(timeout.Token); }
catch { if (!kill.HasExited) kill.Kill(true); throw; }
if (kill.ExitCode != 0) throw new IOException("OpenDeck stop failed.");
}
foreach (var process in Matching(host))
{
using (process)
{
if (process.HasExited) continue;
process.CloseMainWindow();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException)
{
if (!process.HasExited) process.Kill(true);
await process.WaitForExitAsync(CancellationToken.None);
ct.ThrowIfCancellationRequested();
}
}
}
}
public Task StartAsync(PluginHost host, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var start = new ProcessStartInfo(host.Executable) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(host.Executable)! };
foreach (var argument in host.Arguments ?? []) start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new IOException("Could not start Stream Deck host.");
return Task.CompletedTask;
}
}
+8
View File
@@ -0,0 +1,8 @@
# Stream Deck
D10 native SDK-v2 plugin. Read snapshots using SnapshotFile (D9); use Core DTOs.
Keep file IO off the socket owner loop. Never reconnect after the host closes the socket.
Protocol DTOs use PluginJsonContext. Assets and the local inspector live in plugin/.
Directory.Build.props is the release version source. tools/publish.py stamps the published manifest;
the repository manifest is an asset template, not the shipped version.
Core/StreamDeck owns D11 deployment with injectable host process control.
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<PublishAot>true</PublishAot>
</PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
<ItemGroup><Content Include="plugin/**/*" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" /></ItemGroup>
</Project>
+77
View File
@@ -0,0 +1,77 @@
using System.Net.WebSockets;
using System.Threading.Channels;
using FinalToken.Core;
using FinalToken.StreamDeck;
var registration = Registration.Parse(args);
if (registration is null) return 2;
using var stop = new CancellationTokenSource();
try
{
using var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri($"ws://127.0.0.1:{registration.Port}"), stop.Token);
var transport = new PluginSocket(socket);
var session = new PluginSession(transport, PluginSession.LaunchAppAsync);
await session.RegisterAsync(registration, stop.Token);
await RollingLog.WriteAsync("registered");
// D9: file IO runs on a separate worker; all state and WebSocket sends have one owner.
var updates = Channel.CreateBounded<SnapshotReadResult>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest });
var poll = Task.Run(async () =>
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); }
while (await timer.WaitForNextTickAsync(stop.Token));
});
var incoming = session.ReceiveAsync(stop.Token);
var update = updates.Reader.ReadAsync(stop.Token).AsTask();
try
{
while (true)
{
var ready = await Task.WhenAny(incoming, update);
if (ready == incoming)
{
var json = await incoming;
if (json is null) break;
await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token);
incoming = session.ReceiveAsync(stop.Token);
}
else
{
await session.UpdateAsync(await update, DateTimeOffset.UtcNow, stop.Token);
update = updates.Reader.ReadAsync(stop.Token).AsTask();
}
}
}
finally
{
await stop.CancelAsync();
try { await poll; } catch (OperationCanceledException) { }
try { await incoming; } catch (Exception e) when (e is OperationCanceledException or WebSocketException) { }
}
if (socket.State == WebSocketState.CloseReceived)
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
await RollingLog.WriteAsync(session.ConnectionEndCode);
return 0;
}
catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException)
{
await stop.CancelAsync();
await RollingLog.WriteAsync("connection-ended");
return 0;
}
internal static class RollingLog
{
public static async Task WriteAsync(string code)
{
try
{
var path = Path.Combine(DataPaths.DataDirectory, "streamdeck.log");
var previous = File.Exists(path) ? await File.ReadAllTextAsync(path) : "";
var lines = previous.Split('\n', StringSplitOptions.RemoveEmptyEntries).TakeLast(199);
await AtomicFile.WriteAsync(path, string.Join('\n', lines) + $"\n{DateTimeOffset.UtcNow:O} {code}\n");
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
}
}
+150
View File
@@ -0,0 +1,150 @@
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using FinalToken.Core;
namespace FinalToken.StreamDeck;
public sealed record Registration(int Port, string Uuid, string Event)
{
public static Registration? Parse(string[] args)
{
var values = new Dictionary<string, string>();
for (var i = 0; i + 1 < args.Length; i += 2) values[args[i]] = args[i + 1];
return values.TryGetValue("-port", out var port) && int.TryParse(port, out var number) && number is > 0 and <= 65535 &&
values.TryGetValue("-pluginUUID", out var uuid) && uuid.Length > 0 &&
values.TryGetValue("-registerEvent", out var evt) && evt == "registerPlugin" && values.ContainsKey("-info") ? new(number, uuid, evt) : null;
}
}
public sealed record Command(string Event, string? Context = null, string? Uuid = null, string? Action = null, JsonElement? Payload = null);
public sealed record ImagePayload(string Image, int Target = 0);
public sealed record TitlePayload(string Title, int Target = 0);
public sealed record InspectorPayload(StatSettings Settings, WindowOption[] Windows);
public sealed record WindowOption(string Id, string Label);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(Command))]
[JsonSerializable(typeof(ImagePayload))]
[JsonSerializable(typeof(TitlePayload))]
[JsonSerializable(typeof(StatSettings))]
[JsonSerializable(typeof(InspectorPayload))]
public partial class PluginJsonContext : JsonSerializerContext;
public interface IPluginSocket
{
Task SendAsync(string json, CancellationToken cancellationToken);
Task<string?> ReceiveAsync(CancellationToken cancellationToken);
}
public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket
{
public async Task SendAsync(string json, CancellationToken cancellationToken) =>
await socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, cancellationToken);
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
{
var buffer = new byte[8192];
using var message = new MemoryStream();
while (true)
{
var result = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Text || message.Length + result.Count > 1_048_576)
throw new InvalidDataException("Invalid host frame.");
message.Write(buffer, 0, result.Count);
if (result.EndOfMessage) return Encoding.UTF8.GetString(message.ToArray());
}
}
}
public sealed class PluginSession(IPluginSocket socket, Func<string?, Task<bool>> launch)
{
public string ConnectionEndCode { get; private set; } = "host-closed";
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
{
try { return await socket.ReceiveAsync(cancellationToken); }
catch (InvalidDataException) { ConnectionEndCode = "connection-ended"; return null; }
}
public const string Action = "de.finalfactory.finaltoken.stat";
private readonly Dictionary<string, StatSettings> keys = [];
private readonly Dictionary<string, string> images = [];
private SnapshotReadResult read = new(null, true, null);
public Task RegisterAsync(Registration registration, CancellationToken ct = default) => Send(new(registration.Event, Uuid: registration.Uuid), ct);
public async Task UpdateAsync(SnapshotReadResult snapshot, DateTimeOffset now, CancellationToken ct = default)
{
read = StatRenderer.Validate(snapshot);
foreach (var (context, settings) in keys) await Draw(context, settings, now, ct);
}
public async Task HandleAsync(string json, DateTimeOffset now, CancellationToken ct = default)
{
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("event", out var evt) || evt.ValueKind != JsonValueKind.String) return;
if (evt.GetString() == "systemDidWakeUp") { images.Clear(); await UpdateAsync(read, now, ct); return; }
if (!root.TryGetProperty("context", out var ctx) || ctx.ValueKind != JsonValueKind.String || ctx.GetString() is not { Length: > 0 } context) return;
if (root.TryGetProperty("action", out var action) && action.GetString() != Action) return;
root.TryGetProperty("payload", out var payload);
switch (evt.GetString())
{
case "willDisappear": keys.Remove(context); images.Remove(context); break;
case "willAppear":
case "didReceiveSettings":
var settings = ReadSettings(payload);
if (settings is null) return;
keys[context] = settings;
await Draw(context, settings, now, ct);
break;
case "keyDown":
if (!await launch(read.Snapshot?.AppPath)) await Send(new("showAlert", context), ct);
break;
case "sendToPlugin":
if (payload.ValueKind == JsonValueKind.Object && payload.TryGetProperty("settings", out _))
{
var updated = ReadSettings(payload);
if (updated is null) return;
keys[context] = updated;
await Send(new("setSettings", context, Payload: JsonSerializer.SerializeToElement(updated, PluginJsonContext.Default.StatSettings)), ct);
await Draw(context, updated, now, ct);
}
await Inspector(context, ct);
break;
case "propertyInspectorDidAppear": await Inspector(context, ct); break;
}
}
catch (Exception e) when (e is JsonException or InvalidOperationException or ArgumentException) { }
}
private static StatSettings? ReadSettings(JsonElement payload)
{
if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty("settings", out var element)) return new();
var settings = element.Deserialize(PluginJsonContext.Default.StatSettings);
return settings is { IsValid: true } ? settings : null;
}
private Task Inspector(string context, CancellationToken ct)
{
var settings = keys.GetValueOrDefault(context) ?? new();
var windows = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider)?.Windows
.Select(w => new WindowOption(w.Window.Id, w.Window.Label)).ToArray() ?? [];
return Send(new("sendToPropertyInspector", context, Action: Action,
Payload: JsonSerializer.SerializeToElement(new InspectorPayload(settings, windows), PluginJsonContext.Default.InspectorPayload)), ct);
}
private async Task Draw(string context, StatSettings settings, DateTimeOffset now, CancellationToken ct)
{
var svg = StatRenderer.Render(read, settings, now);
if (images.GetValueOrDefault(context) == svg) return;
await Send(new("setTitle", context, Payload: JsonSerializer.SerializeToElement(new TitlePayload(""), PluginJsonContext.Default.TitlePayload)), ct);
await Send(new("setImage", context, Payload: JsonSerializer.SerializeToElement(new ImagePayload("data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(svg))), PluginJsonContext.Default.ImagePayload)), ct);
images[context] = svg;
}
private Task Send(Command command, CancellationToken ct) => socket.SendAsync(JsonSerializer.Serialize(command, PluginJsonContext.Default.Command), ct);
public static Task<bool> LaunchAppAsync(string? path) => Task.Run(() =>
{
try
{
if (path is null || !Path.IsPathFullyQualified(path) || !File.Exists(path)) return false;
using var process = Process.Start(new ProcessStartInfo(path) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(path)! });
return process is not null;
}
catch (Exception e) when (e is IOException or System.ComponentModel.Win32Exception or InvalidOperationException) { return false; }
});
}
+35
View File
@@ -0,0 +1,35 @@
# Stream Deck plugin
D10 uses a native SDK-v2 WebSocket connection. There is one owner for key state and socket sends;
a separate worker polls the D9 Core reader every two seconds. Closing the connection exits.
Only changed SVGs are sent. The bounded log is `streamdeck.log` in FinalToken's data directory.
Protocol sources checked on 2026-10-14:
- [Elgato Plugin WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/plugin/)
— registration arguments, key/settings/wake events and drawing commands.
- [Elgato Property Inspector WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/ui/)
— inspector registration and messages.
- [Elgato Manifest](https://docs.elgato.com/streamdeck/sdk/references/manifest/)
— native entry points, SDK version, actions and resources.
- [OpenDeck README](https://github.com/aberja/opendeck)
— native plugins and host installation.
- [OpenDeck manifest parser](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/manifest.rs)
— `CodePathLin`.
- [OpenDeck plugin lifecycle](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/mod.rs)
and [shared paths](https://github.com/aberja/opendeck/blob/main/src-tauri/src/shared.rs)
— `app_config_dir()/plugins`; Tauri identifier `opendeck`.
- [OpenDeck installation script](https://github.com/aberja/opendeck/blob/main/install_opendeck.sh)
— executable `opendeck`, Flatpak ID `me.amankhanna.opendeck`.
The D11 installer discovers Windows Stream Deck, Linux native OpenDeck and Flatpak OpenDeck.
Linux locations are `$XDG_CONFIG_HOME/opendeck/plugins` (default `~/.config/opendeck/plugins`)
and `~/.var/app/me.amankhanna.opendeck/config/opendeck/plugins`.
Deployment stages in a sibling folder, swaps with a backup and rolls back on failure.
`PluginInstaller.CreateDefault()` is the app entry point; `Outcome` reports installation steps.
The interface and install policy remain compatible with the original Core contract.
`python -B tools/publish.py win-x64` builds the app, CLI and plugin into one folder and ZIP.
The CLI is named `finaltoken-cli` on every platform (`finaltoken-cli.exe` on Windows),
beside the desktop app. Publish a Linux RID on Linux;
the .NET NativeAOT toolchain does not support cross-OS compilation.
+69
View File
@@ -0,0 +1,69 @@
using System.Globalization;
using System.Security;
using FinalToken.Core;
namespace FinalToken.StreamDeck;
public enum Metric { SessionPercent, WeekPercent, PaceDelta, TimeToReset, TokensToday, TokensWeek }
public sealed record StatSettings(string Provider = "Claude", string Metric = "SessionPercent", string Window = "")
{
public bool IsValid => Enum.TryParse<Core.Provider>(Provider, out var p) && Enum.IsDefined(p) &&
Enum.TryParse<StreamDeck.Metric>(Metric, out var m) && Enum.IsDefined(m) && Window is not null;
}
public static class StatRenderer
{
public static WindowSnapshot? SelectWindow(ProviderSnapshot provider, StatSettings settings)
{
if (settings.Window.Length > 0) return provider.Windows.FirstOrDefault(w => w.Window.Id == settings.Window);
if (settings.Metric is "PaceDelta" or "TimeToReset")
return provider.Windows.FirstOrDefault(w => w.Window.Length is { } length && length < TimeSpan.FromDays(1)) ?? provider.Windows.FirstOrDefault();
var week = settings.Metric is "WeekPercent";
return provider.Windows.FirstOrDefault(w => week ? w.Window.Length >= TimeSpan.FromDays(1) :
w.Window.Length is { } length && length < TimeSpan.FromDays(1));
}
public static string Render(SnapshotReadResult read, StatSettings settings, DateTimeOffset now)
{
read = Validate(read);
var provider = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider);
var offline = read.IsStale || provider is null;
var window = provider is null ? null : SelectWindow(provider, settings);
var metric = Enum.TryParse<Metric>(settings.Metric, out var parsed) ? parsed : Metric.SessionPercent;
var state = offline ? PaceState.Unknown : window?.Pace.State ?? PaceState.Unknown;
var color = state switch { PaceState.Ahead => "#ef6461", PaceState.Behind => "#69a7ff", PaceState.OnTrack => "#58d6a0", _ => "#a0a7b4" };
var label = metric switch { Metric.SessionPercent => "SESSION", Metric.WeekPercent => "WEEK", Metric.PaceDelta => "PACE", Metric.TimeToReset => "RESET", Metric.TokensToday => "TODAY", _ => "WEEK TOKENS" };
var value = offline ? "offline" : metric switch
{
Metric.TokensToday => Compact(provider!.Today.Total),
Metric.TokensWeek => Compact(provider!.Week.Total),
Metric.PaceDelta => window?.Pace.Delta is { } delta ? delta.ToString("+0;-0;0", CultureInfo.InvariantCulture) + "pp" : "—",
Metric.TimeToReset => window?.Window.ResetsAt is { } reset ? Duration(reset - now) : "—",
_ => window is null ? "—" : window.Window.UsedPercent.ToString("0", CultureInfo.InvariantCulture) + "%"
};
var bar = "";
if (!offline && window is not null && metric is Metric.SessionPercent or Metric.WeekPercent)
{
var width = Math.Clamp(window.Window.UsedPercent, 0, 100) * .6;
bar = FormattableString.Invariant($"<rect x='6' y='59' width='60' height='5' rx='2' fill='#343b48'/><rect x='6' y='59' width='{width:0.##}' height='5' rx='2' fill='{color}'/>");
if (window.Pace.ElapsedFraction is { } e)
bar += FormattableString.Invariant($"<path d='M{6 + Math.Clamp(e, 0, 1) * 60:0.##} 56v11' stroke='white' stroke-width='2'/>");
}
return $"<svg xmlns='http://www.w3.org/2000/svg' width='72' height='72' viewBox='0 0 72 72'><rect width='72' height='72' rx='8' fill='#151a23'/><text x='36' y='13' text-anchor='middle' font-family='Arial,sans-serif' font-size='9' fill='#c4cbd6'>{SecurityElement.Escape(settings.Provider)}</text><text x='36' y='25' text-anchor='middle' font-family='Arial,sans-serif' font-size='8' fill='#c4cbd6'>{label}</text><text x='36' y='48' text-anchor='middle' font-family='Arial,sans-serif' font-weight='bold' font-size='{(value.Length > 6 ? 14 : 20)}' fill='{color}'>{value}</text>{bar}</svg>";
}
// The reader rejects unsupported schemas; nested data is still an external trust boundary (D9).
public static SnapshotReadResult Validate(SnapshotReadResult read)
{
if (read.Snapshot is not { } snapshot) return new(null, true, read.Error);
if (snapshot.Providers is null || snapshot.Providers.Any(p => p is null || !Enum.IsDefined(p.Provider) || p.Windows is null ||
p.Windows.Any(w => w is null || w.Window is null || w.Pace is null || w.Window.Id is null || w.Window.Label is null ||
!double.IsFinite(w.Window.UsedPercent) || w.Window.UsedPercent is < 0 or > 100 ||
w.Pace.ElapsedFraction is { } e && !double.IsFinite(e) || w.Pace.Delta is { } d && !double.IsFinite(d))))
return new(null, true, "Invalid snapshot content.");
return read;
}
private static string Compact(long value) => value >= 1_000_000 ? (value / 1_000_000d).ToString("0.#", CultureInfo.InvariantCulture) + "M" :
value >= 1_000 ? (value / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k" : value.ToString(CultureInfo.InvariantCulture);
private static string Duration(TimeSpan time) => time <= TimeSpan.Zero ? "0m" : time.TotalDays >= 1 ? $"{(int)time.TotalDays}d {time.Hours}h" :
time.TotalHours >= 1 ? $"{(int)time.TotalHours}h {time.Minutes}m" : $"{Math.Ceiling(time.TotalMinutes):0}m";
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72"><rect width="72" height="72" rx="12" fill="#151a23"/><path d="M18 18h38v8H27v9h24v8H27v13h-9z" fill="#58d6a0"/></svg>

After

Width:  |  Height:  |  Size: 201 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72"><rect width="72" height="72" rx="8" fill="#151a23"/><text x="36" y="29" text-anchor="middle" font-family="Arial" font-size="10" fill="#c4cbd6">FinalToken</text><text x="36" y="49" text-anchor="middle" font-family="Arial" font-size="16" fill="#a0a7b4">offline</text></svg>

After

Width:  |  Height:  |  Size: 335 B

@@ -0,0 +1,5 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="style.css"><title>FinalToken Stat</title></head>
<body><label>Provider<select id="provider"><option>Claude</option><option>Codex</option></select></label>
<label>Metric<select id="metric"><option value="SessionPercent">Session percent</option><option value="WeekPercent">Week percent</option><option value="PaceDelta">Pace delta</option><option value="TimeToReset">Time to reset</option><option value="TokensToday">Tokens today</option><option value="TokensWeek">Tokens this week</option></select></label>
<label>Window<select id="window"><option value="">Automatic</option></select></label><p>Press the key to open FinalToken. Keep FinalToken running to refresh stats.</p><script src="inspector.js"></script></body></html>
@@ -0,0 +1,27 @@
'use strict';
let connection, context;
const provider = document.getElementById('provider'), metric = document.getElementById('metric'), windowSelect = document.getElementById('window');
function apply(settings) {
provider.value = settings.provider || 'Claude'; metric.value = settings.metric || 'SessionPercent';
if (!Array.from(windowSelect.options).some(o => o.value === settings.window) && settings.window) windowSelect.add(new Option(settings.window, settings.window));
windowSelect.value = settings.window || '';
}
function send(payload) { if (connection && connection.readyState === WebSocket.OPEN) connection.send(JSON.stringify({event:'sendToPlugin',action:'de.finalfactory.finaltoken.stat',context,payload})); }
window.connectElgatoStreamDeckSocket = (port, uuid, event, info, actionInfo) => {
const action = JSON.parse(actionInfo); context = action.context; apply(action.payload.settings || {});
connection = new WebSocket(`ws://127.0.0.1:${port}`);
connection.onopen = () => { connection.send(JSON.stringify({event,uuid})); send({request:'windows'}); };
connection.onmessage = message => {
const data = JSON.parse(message.data);
if (data.event === 'didReceiveSettings') apply(data.payload.settings);
if (data.event === 'sendToPropertyInspector') {
windowSelect.replaceChildren(new Option('Automatic', ''));
for (const item of data.payload.windows || []) windowSelect.add(new Option(item.label, item.id));
apply(data.payload.settings);
}
};
};
for (const element of [provider,metric,windowSelect]) element.addEventListener('change', () => {
if (element === provider) windowSelect.value = '';
send({settings:{provider:provider.value,metric:metric.value,window:windowSelect.value}});
});
@@ -0,0 +1 @@
:root{color-scheme:dark}body{margin:16px 12px;background:#2d2d2d;color:#d8d8d8;font:12px Arial,sans-serif}label{display:grid;grid-template-columns:72px 1fr;align-items:center;gap:8px;margin-bottom:12px}select{min-width:0;background:#3d3d3d;color:#eee;border:1px solid #555;border-radius:3px;padding:6px}select:focus{outline:1px solid #2ea8ff}p{line-height:1.5;color:#aaa}
@@ -0,0 +1,24 @@
{
"UUID": "de.finalfactory.finaltoken",
"Name": "FinalToken",
"Author": "Final Factory",
"Description": "Claude and Codex usage from FinalToken.",
"Version": "1.0.0.1",
"SDKVersion": 2,
"CodePathWin": "FinalToken.StreamDeck.exe",
"CodePathLin": "FinalToken.StreamDeck",
"Icon": "images/icon",
"Category": "FinalToken",
"CategoryIcon": "images/icon",
"PropertyInspectorPath": "inspector/index.html",
"Software": { "MinimumVersion": "7.0" },
"OS": [ { "Platform": "windows", "MinimumVersion": "10" }, { "Platform": "linux", "MinimumVersion": "0" } ],
"Actions": [ {
"UUID": "de.finalfactory.finaltoken.stat",
"Name": "Stat",
"Tooltip": "Show usage. Press to open FinalToken.",
"Icon": "images/icon",
"SupportedInMultiActions": false,
"States": [ { "Image": "images/key", "ShowTitle": false } ]
} ]
}