Files
FinalToken/src/FinalToken.Core/Collectors/IncrementalScanner.cs
T
schmidt.florian f8afd11679 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
2026-10-14 22:11:19 +02:00

137 lines
7.3 KiB
C#

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