new: [opencode-greenpt-usage] track API key consumption per day and model

Show real credit spend and a per-model breakdown under the balance:

- ``src/usage.ts`` (new, pure): idempotent day buckets keyed by message
  id, day/month totals, retention pruning, validated KV serialization.
- Real spend = delta of ``x-credits-remaining`` between two free probes
  (top-ups are not counted as spend), covering every client of the key.
- Per-model detail = reconciliation of local GreenPT assistant messages
  (tokens + estimated cost, marked ``~``), re-run on every refresh and
  on ``session.idle``; last 10 sessions backfilled at startup.
- Buckets persisted in the plugin KV store (90-day window) with new
  options ``trackUsage``, ``usageWindowDays``, ``usageBackfill`` and a
  ``greenpt.usage.reset`` command.
This commit is contained in:
Stéphan Sainléger
2026-10-19 11:36:45 +02:00
parent 5c11754e2d
commit 9c84473266
10 changed files with 871 additions and 10 deletions

View File

@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
import { formatBalanceError, formatCredits, readFoldOpen } from "../src/format"
import { formatBalanceError, formatCredits, formatTokens, readFoldOpen } from "../src/format"
describe("formatCredits", () => {
it("formats with two decimals", () => {
@@ -15,6 +15,32 @@ describe("formatCredits", () => {
})
})
describe("formatTokens", () => {
it("formats small counts as integers", () => {
expect(formatTokens(842)).toBe("842")
expect(formatTokens(0)).toBe("0")
})
it("formats thousands with one decimal below 100k", () => {
expect(formatTokens(12_400)).toBe("12.4k")
expect(formatTokens(999)).toBe("999")
})
it("rounds thousands above 100k", () => {
expect(formatTokens(234_500)).toBe("235k")
})
it("formats millions", () => {
expect(formatTokens(3_200_000)).toBe("3.2M")
expect(formatTokens(45_000_000)).toBe("45.0M")
})
it("handles non-finite and negative input", () => {
expect(formatTokens(Number.NaN)).toBe("0")
expect(formatTokens(-5)).toBe("0")
})
})
describe("formatBalanceError", () => {
it("renders each error kind", () => {
expect(formatBalanceError({ kind: "unauthorized" })).toContain("invalid")