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
+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;
}
}