Core implements the CLI-only collectors for Claude and Codex (D2 to D4), the history store (D5), the refresh engine (D6), pace and popup decisions (D7, D8), the snapshot contract (D9) and the Stream Deck installer contract (D11). finaltoken status runs one refresh and prints the snapshot. The app and plugin projects are placeholders so the solution file is complete before they are built in parallel. Refs #1
34 lines
2.1 KiB
C#
34 lines
2.1 KiB
C#
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));
|
|
}
|
|
}
|