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,7 +1,17 @@
import { createSignal } from "solid-js"
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
import { USAGE_DAYS_KV } from "./format"
import { resolveGreenptKey, type CredentialEnv } from "./credential"
import {
addCreditsSpent,
applyMessages,
parseUsageDays,
pruneUsage,
serializeUsage,
type UsageDays,
type UsageMessage,
} from "./usage"
/** Default GreenPT API base URL. */
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
@@ -9,6 +19,12 @@ export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
/** Default refresh interval, in seconds. The probe is free but should stay gentle. */
export const DEFAULT_REFRESH_SECONDS = 300
/** Default retention window for usage buckets, in days. */
export const DEFAULT_USAGE_WINDOW_DAYS = 90
/** Default number of recent sessions reconciled at startup. */
export const DEFAULT_USAGE_BACKFILL = 10
export type BalanceOptions = {
apiKey?: string
baseUrl?: string
@@ -16,6 +32,9 @@ export type BalanceOptions = {
order?: number
showWhenUnavailable?: boolean
unit?: string
trackUsage?: boolean
usageWindowDays?: number
usageBackfill?: number
}
export type BalanceState =
@@ -29,7 +48,9 @@ export type BalanceState =
export type BalanceStore = {
state: () => BalanceState
now: () => number
usageDays: () => UsageDays
refresh: () => Promise<void>
resetUsage: () => void
dispose: () => void
}
@@ -45,7 +66,13 @@ const TICK_MS = 30_000
* timer, and on demand via `refresh()`. Errors are retried with an
* exponential backoff so a transient outage does not hammer the API.
*
* @param api TUI plugin API (used for the auth store path and events).
* Usage tracking (opt-out via `trackUsage: false`) keeps per-day buckets:
* real credit spend from balance deltas, and per-model token/cost totals
* reconciled from local OpenCode assistant messages. Buckets are persisted
* in the plugin KV store and pruned to `usageWindowDays`.
*
* @param api TUI plugin API (used for the auth store path, events, KV and
* session messages).
* @param options Plugin options.
* @param env Environment mapping, injectable for tests.
* @param fetchImpl Fetch implementation, injectable for tests.
@@ -59,9 +86,13 @@ export function createBalanceStore(
): BalanceStore {
const [state, setState] = createSignal<BalanceState>({ status: "loading" })
const [now, setNow] = createSignal(Date.now())
const [usageDays, setUsageDays] = createSignal<UsageDays>(readUsageDays(api.kv))
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
const trackUsage = options.trackUsage !== false
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let tickTimer: ReturnType<typeof setTimeout> | undefined
@@ -70,11 +101,116 @@ export function createBalanceStore(
let inFlight = false
let disposed = false
let retriedState = false
let lastCredits: number | undefined
let kvLoaded = false
const trackedSessions = new Set<string>()
const controller = new AbortController()
const unsubscribeIdle = api.event.on("session.idle", () => void refresh())
const unsubscribeIdle = api.event.on("session.idle", (event) => {
trackSession(event.properties.sessionID)
reconcileSessions()
void refresh()
})
const unsubscribeStatus = api.event.on("session.status", (event) => {
trackSession(event.properties.sessionID)
})
const unsubscribeConnected = api.event.on("server.connected", () => void refresh())
function readUsageDays(kv: TuiPluginApi["kv"]): UsageDays {
try {
const raw = kv.get(USAGE_DAYS_KV)
if (raw === undefined) return {}
return parseUsageDays(raw)
} catch {
return {}
}
}
function writeUsageDays(kv: TuiPluginApi["kv"], days: UsageDays): void {
try {
kv.set(USAGE_DAYS_KV, serializeUsage(days))
} catch {
// KV persistence is optional; in-memory buckets remain usable.
}
}
function trackSession(sessionID: string): void {
if (sessionID) trackedSessions.add(sessionID)
}
/** Apply usage mutations through a fresh top-level record for reactivity. */
function mutateUsage(mutate: (days: UsageDays) => void): void {
if (!trackUsage) return
const days: UsageDays = { ...usageDays() }
mutate(days)
pruneUsage(days, usageWindowDays, Date.now())
setUsageDays(days)
writeUsageDays(api.kv, days)
}
/**
* Reconcile per-model usage from the messages of every tracked session.
* Idempotent: messages are de-duplicated by id in `usage.ts`.
*/
function reconcileSessions(): void {
if (!trackUsage || trackedSessions.size === 0) return
for (const sessionID of trackedSessions) {
let messages: ReadonlyArray<UsageMessage> | undefined
try {
messages = api.state.session.messages(sessionID)
} catch {
continue
}
if (!messages?.length) continue
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>))
}
}
/** Best-effort startup backfill from recently updated sessions. */
async function backfillUsage(): Promise<void> {
if (!trackUsage || usageBackfillLimit <= 0) return
const client = api.client as
| {
session?: {
list?: (parameters?: { limit?: number }) => Promise<unknown>
messages?: (parameters: { sessionID: string }) => Promise<unknown>
}
}
| undefined
if (!client?.session?.list || !client.session.messages) return
try {
const listed = (await client.session.list({ limit: usageBackfillLimit })) as {
data?: unknown
}
if (!Array.isArray(listed?.data)) return
for (const session of listed.data) {
if (disposed) return
const sessionID = (session as { id?: unknown })?.id
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
try {
const result = (await client.session.messages({ sessionID })) as { data?: unknown }
if (!Array.isArray(result?.data)) continue
const messages = result.data
.map((row) => (row as { info?: unknown })?.info)
.filter((info) => info !== undefined && info !== null)
mutateUsage((days) => applyMessages(days, messages))
} catch {
// One unreadable session must not abort the whole backfill.
}
}
} catch {
// Backfill is optional; live tracking continues regardless.
}
}
/** Re-read persisted buckets once the KV store becomes ready. */
function reloadUsageWhenReady(): void {
if (!trackUsage || kvLoaded || api.kv.ready !== true) return
kvLoaded = true
setUsageDays(readUsageDays(api.kv))
}
function scheduleNext() {
if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer)
@@ -97,6 +233,7 @@ export function createBalanceStore(
async function refresh(): Promise<void> {
if (disposed || inFlight) return
inFlight = true
reloadUsageWhenReady()
try {
const credential = resolveGreenptKey(options, api.state.path.state, env)
if (!credential.ok) {
@@ -119,6 +256,14 @@ export function createBalanceStore(
if ("credits" in result) {
backoff = BACKOFF_BASE_MS
const credits = result.credits
if (trackUsage && Number.isFinite(credits)) {
if (lastCredits !== undefined && credits < lastCredits) {
const spent = lastCredits - credits
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
}
lastCredits = credits
}
setState({ status: "ready", data: result, fetchedAt: Date.now() })
} else {
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS)
@@ -128,9 +273,18 @@ export function createBalanceStore(
inFlight = false
}
if (disposed) return
reconcileSessions()
scheduleNext()
}
/** Clear every persisted and in-memory usage bucket. */
function resetUsage(): void {
lastCredits = undefined
mutateUsage((days) => {
for (const date of Object.keys(days)) delete days[date]
})
}
tickTimer = setTimeout(tick, TICK_MS)
function dispose() {
@@ -140,8 +294,11 @@ export function createBalanceStore(
if (tickTimer) clearTimeout(tickTimer)
if (stateRetryTimer) clearTimeout(stateRetryTimer)
unsubscribeIdle()
unsubscribeStatus()
unsubscribeConnected()
}
return { state, now, refresh, dispose }
void backfillUsage()
return { state, now, usageDays, refresh, resetUsage, dispose }
}