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:
@@ -0,0 +1,8 @@
|
||||
# Process probe host
|
||||
Windows GUI-subsystem regression helper for D6. It deliberately has no console or standard
|
||||
handles, then runs Core's ProcessRunner. Child modes check handles and synthetic UTF-8 JSON. The optional
|
||||
live Claude mode keeps provider output in memory and writes only diagnostic metadata.
|
||||
No provider text or real transcript fixtures belong here. JSON uses source generation.
|
||||
Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`.
|
||||
Portable `--rpc-*` modes provide synthetic app-server exchanges, errors, EOF and malformed output.
|
||||
The `app-server` mode returns an RPC error for published-CLI checks; it never contacts a provider.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.Collectors;
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.ProcessHost;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server"))
|
||||
return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode);
|
||||
if (!OperatingSystem.IsWindows()) return 0;
|
||||
if (args is ["--handles"])
|
||||
return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17;
|
||||
if (args is ["--utf8"])
|
||||
{
|
||||
await Console.OpenStandardOutput().WriteAsync(System.Text.Encoding.UTF8.GetBytes("{\"marker\":\"· •\"}"));
|
||||
return 0;
|
||||
}
|
||||
if (args.Length < 2) return 2;
|
||||
Native.FreeConsole();
|
||||
foreach (var id in new[] { -10, -11, -12 }) Native.SetStdHandle(id, 0);
|
||||
var report = new ProbeReport { HostHasConsole = Native.GetConsoleWindow() != 0,
|
||||
HostInputValid = Native.GetFileType(Native.GetStdHandle(-10)) != 0, OutputCodePage = Console.OutputEncoding.CodePage };
|
||||
var live = args[0] == "--claude";
|
||||
var utf8 = args[0] == "--utf8-probe";
|
||||
var cli = live ? CliDiscovery.Find(Provider.Claude).Command : new CliCommand(Environment.ProcessPath!, []);
|
||||
if (cli is null) return 3;
|
||||
var result = await new ProcessRunner().RunAsync(new(cli, live
|
||||
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : utf8 ? ["--utf8"] : ["--handles"],
|
||||
Path.GetDirectoryName(Path.GetFullPath(args[1]))!, TimeSpan.FromSeconds(60)), CancellationToken.None);
|
||||
report = report with { ExitCode = result.ExitCode, TimedOut = result.TimedOut,
|
||||
Utf8Matched = utf8 && result.Output == "{\"marker\":\"· •\"}" };
|
||||
if (live)
|
||||
{
|
||||
var diagnostics = new DiagnosticLog();
|
||||
var windows = ClaudeUsageParser.ParseEnvelope(result.Output, DateTimeOffset.UtcNow, diagnostics);
|
||||
report = report with { WindowCount = windows.Count, DiagnosticCodes = diagnostics.Recent.Select(d => d.Code).ToArray() };
|
||||
}
|
||||
await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport));
|
||||
return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode;
|
||||
}
|
||||
private static async Task<int> RpcAsync(string mode)
|
||||
{
|
||||
Console.InputEncoding = System.Text.Encoding.UTF8;
|
||||
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
|
||||
if (mode == "--rpc-eof") return 0;
|
||||
var initialize = await Console.In.ReadLineAsync();
|
||||
using var first = JsonDocument.Parse(initialize ?? "null");
|
||||
if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20;
|
||||
if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; }
|
||||
await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}");
|
||||
using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||
using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||
if (initialized.RootElement.GetProperty("method").GetString() != "initialized" ||
|
||||
request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21;
|
||||
await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}");
|
||||
var response = mode switch
|
||||
{
|
||||
"--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}",
|
||||
"--rpc-garbage" => "not JSON",
|
||||
"--rpc-shape" => "[]",
|
||||
"--rpc-bound" => new string('x', 1024 * 1024 + 1),
|
||||
_ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}"
|
||||
};
|
||||
await Console.Out.WriteLineAsync(response);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record ProbeReport
|
||||
{
|
||||
public bool HostHasConsole { get; init; }
|
||||
public bool HostInputValid { get; init; }
|
||||
public int ExitCode { get; init; }
|
||||
public bool TimedOut { get; init; }
|
||||
public int WindowCount { get; init; }
|
||||
public int OutputCodePage { get; init; }
|
||||
public bool Utf8Matched { get; init; }
|
||||
public string[] DiagnosticCodes { get; init; } = [];
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(ProbeReport))]
|
||||
internal partial class ProbeJsonContext : JsonSerializerContext;
|
||||
|
||||
internal static partial class Native
|
||||
{
|
||||
[LibraryImport("kernel32.dll")]
|
||||
internal static partial nint GetStdHandle(int id);
|
||||
[LibraryImport("kernel32.dll")]
|
||||
internal static partial uint GetFileType(nint handle);
|
||||
[LibraryImport("kernel32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool SetStdHandle(int id, nint handle);
|
||||
[LibraryImport("kernel32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool FreeConsole();
|
||||
[LibraryImport("kernel32.dll")]
|
||||
internal static partial nint GetConsoleWindow();
|
||||
}
|
||||
Reference in New Issue
Block a user