Files
opencode-greenpt-usage/src/store.ts
Stéphan Sainléger 5129f295da new: [opencode-greenpt-usage] port plugin to OpenCode v2
Rewrite the TUI plugin against the OpenCode v2 plugin API
(``@opencode/plugin`` + ``@opencode/plugin/tui``):

- ``src/index.ts``: minimal server-side ``Plugin.define`` entry.
- ``src/tui.tsx``: CLI plugin registered as ``./tui``, appending the
  widget to the ``sidebar.content`` slot through ``context.ui.slot``
  and exposing the refresh/reset commands via ``context.keymap.layer``.
- ``src/store.ts``: durable plugin storage (``context.storage.store``)
  replaces the KV store; ``session.idle``/``session.status`` events and
  the ``client.session`` API drive reconciliation and backfill.
- ``src/widget.tsx``: v2 semantic theme tokens
  (``theme.text.base``/``text.muted``/``text.feedback``).
- Tests updated to a structural fake of the v2 context.

The free ``HEAD /v1/chat/completions`` balance probe and the credential
resolution order are unchanged. The ``order`` option is gone: v2 slot
placement is additive.
2026-10-19 17:00:48 +02:00

289 lines
9.2 KiB
TypeScript

import { createSignal } from "solid-js"
import type { Context } from "@opencode/plugin/tui/plugin"
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
import { resolveGreenptKey, type CredentialEnv } from "./credential"
import {
addCreditsSpent,
applyMessages,
pruneUsage,
type UsageDays,
type UsageMessage,
} from "./usage"
/** Default GreenPT API base URL. */
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
/** Storage key for the usage day buckets (durable plugin storage). */
export const USAGE_DAYS_KEY = "greenpt.usage.days"
/** 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
refreshInterval?: number
showWhenUnavailable?: boolean
unit?: string
trackUsage?: boolean
usageWindowDays?: number
usageBackfill?: number
}
export type BalanceState =
| { status: "loading" }
| { status: "ready"; data: Balance; fetchedAt: number }
| {
status: "error"
error: BalanceError | { kind: "no-credential"; reason: "missing" }
}
export type BalanceStore = {
state: () => BalanceState
now: () => number
usageDays: UsageDays
refresh: () => Promise<void>
resetUsage: () => Promise<void>
dispose: () => void
}
const BACKOFF_BASE_MS = 60_000
const BACKOFF_MAX_MS = 10 * 60_000
const TICK_MS = 30_000
/** Structural view of a v2 assistant message used for accounting. */
function toUsageMessages(messages: ReadonlyArray<unknown>): ReadonlyArray<UsageMessage> {
const out: UsageMessage[] = []
for (const message of messages) {
const m = message as {
type?: unknown
id?: unknown
model?: { providerID?: unknown; id?: unknown }
cost?: unknown
time?: { created?: unknown }
tokens?: UsageMessage["tokens"]
}
if (m?.type !== "assistant" || typeof m.id !== "string") continue
out.push({
id: m.id,
role: "assistant",
providerID: m.model?.providerID,
modelID: m.model?.id,
cost: m.cost,
time: { created: m.time?.created },
tokens: m.tokens,
})
}
return out
}
/**
* Create the reactive store backing the sidebar widget.
*
* Refreshes on creation, on `session.idle`, on `server.connected`, on a
* timer, and on demand via `refresh()`. Errors are retried with an
* exponential backoff so a transient outage does not hammer the API.
*
* 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 live in the
* plugin durable storage and are pruned to `usageWindowDays`.
*
* @param context OpenCode v2 TUI plugin context.
* @param options Plugin options.
* @param env Environment mapping, injectable for tests.
* @param fetchImpl Fetch implementation, injectable for tests.
* @returns The store.
*/
export function createBalanceStore(
context: Context,
options: BalanceOptions = {},
env: CredentialEnv = process.env as CredentialEnv,
fetchImpl: FetchLike = nativeFetch,
): BalanceStore {
const [state, setState] = createSignal<BalanceState>({ status: "loading" })
const [now, setNow] = createSignal(Date.now())
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 usageDays: UsageDays = {}
let updateUsage: (mutation: (draft: UsageDays) => void) => Promise<void> = () =>
Promise.resolve()
if (trackUsage) {
const stored = context.storage.store(USAGE_DAYS_KEY, { initial: {} as UsageDays })
usageDays = stored[0]
updateUsage = stored[1]
}
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let tickTimer: ReturnType<typeof setTimeout> | undefined
let backoff = BACKOFF_BASE_MS
let inFlight = false
let disposed = false
let lastCredits: number | undefined
const trackedSessions = new Set<string>()
const controller = new AbortController()
const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.data.sessionID)
void reconcileSessions()
void refresh()
})
const unsubscribeStatus = context.data.on("session.status", (event) => {
trackSession(event.data.sessionID)
})
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
function trackSession(sessionID: string): void {
if (sessionID) trackedSessions.add(sessionID)
}
/** Apply usage mutations through the durable storage draft. */
function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> {
if (!trackUsage) return Promise.resolve()
return updateUsage((draft) => {
mutate(draft)
pruneUsage(draft, usageWindowDays, Date.now())
})
}
/**
* Reconcile per-model usage from the messages of every tracked session.
* Idempotent: messages are de-duplicated by id in `usage.ts`.
*/
function reconcileSessions(): Promise<void> {
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
const updates: Promise<void>[] = []
for (const sessionID of trackedSessions) {
let messages: ReadonlyArray<unknown> | undefined
try {
messages = context.data.session.message.list(sessionID)
} catch {
continue
}
if (!messages?.length) continue
updates.push(mutateUsage((days) => applyMessages(days, toUsageMessages(messages ?? []))))
}
return Promise.all(updates).then(() => undefined)
}
/** Best-effort startup backfill from recently updated sessions. */
async function backfillUsage(): Promise<void> {
if (!trackUsage || usageBackfillLimit <= 0) return
try {
const listed = await context.client.session.list({
limit: usageBackfillLimit,
})
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 messages = await context.client.session.context({ sessionID })
await mutateUsage((days) => applyMessages(days, toUsageMessages(messages)))
} catch {
// One unreadable session must not abort the whole backfill.
}
}
} catch {
// Backfill is optional; live tracking continues regardless.
}
}
function scheduleNext() {
if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer)
refreshTimer = undefined
const intervalMs = interval * 1000
if (intervalMs <= 0) return
const delay = state().status === "error" ? backoff : intervalMs
refreshTimer = setTimeout(() => {
refreshTimer = undefined
void refresh()
}, delay)
}
function tick() {
if (disposed) return
setNow(Date.now())
tickTimer = setTimeout(tick, TICK_MS)
}
async function refresh(): Promise<void> {
if (disposed || inFlight) return
inFlight = true
try {
const credential = resolveGreenptKey(options, undefined, env)
if (!credential.ok) {
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
return
}
let result
try {
result = await fetchBalance(baseUrl, credential.key, controller.signal, fetchImpl)
} catch {
if (disposed) return
result = { kind: "network", cause: undefined } as BalanceError
}
if (disposed) return
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
await 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)
setState({ status: "error", error: result })
}
} finally {
inFlight = false
}
if (disposed) return
await reconcileSessions()
scheduleNext()
}
/** Clear every persisted and in-memory usage bucket. */
async function resetUsage(): Promise<void> {
lastCredits = undefined
await mutateUsage((days) => {
for (const date of Object.keys(days)) delete days[date]
})
}
tickTimer = setTimeout(tick, TICK_MS)
function dispose() {
disposed = true
controller.abort()
if (refreshTimer) clearTimeout(refreshTimer)
if (tickTimer) clearTimeout(tickTimer)
unsubscribeIdle()
unsubscribeStatus()
unsubscribeConnected()
}
void backfillUsage()
return { state, now, usageDays, refresh, resetUsage, dispose }
}