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.
This commit is contained in:
168
src/store.ts
168
src/store.ts
@@ -1,14 +1,11 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
|
||||
import type { Context } from "@opencode/plugin/tui/plugin"
|
||||
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"
|
||||
@@ -16,6 +13,9 @@ import {
|
||||
/** 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
|
||||
|
||||
@@ -29,7 +29,6 @@ export type BalanceOptions = {
|
||||
apiKey?: string
|
||||
baseUrl?: string
|
||||
refreshInterval?: number
|
||||
order?: number
|
||||
showWhenUnavailable?: boolean
|
||||
unit?: string
|
||||
trackUsage?: boolean
|
||||
@@ -48,17 +47,42 @@ export type BalanceState =
|
||||
export type BalanceStore = {
|
||||
state: () => BalanceState
|
||||
now: () => number
|
||||
usageDays: () => UsageDays
|
||||
usageDays: UsageDays
|
||||
refresh: () => Promise<void>
|
||||
resetUsage: () => void
|
||||
resetUsage: () => Promise<void>
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
const BACKOFF_BASE_MS = 60_000
|
||||
const BACKOFF_MAX_MS = 10 * 60_000
|
||||
const STATE_RETRY_MS = 5_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.
|
||||
*
|
||||
@@ -68,25 +92,23 @@ const TICK_MS = 30_000
|
||||
*
|
||||
* 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`.
|
||||
* reconciled from local OpenCode assistant messages. Buckets live in the
|
||||
* plugin durable storage and are pruned to `usageWindowDays`.
|
||||
*
|
||||
* @param api TUI plugin API (used for the auth store path, events, KV and
|
||||
* session messages).
|
||||
* @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(
|
||||
api: TuiPluginApi,
|
||||
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 [usageDays, setUsageDays] = createSignal<UsageDays>(readUsageDays(api.kv))
|
||||
|
||||
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
|
||||
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
|
||||
@@ -94,107 +116,82 @@ export function createBalanceStore(
|
||||
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 stateRetryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let backoff = BACKOFF_BASE_MS
|
||||
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", (event) => {
|
||||
trackSession(event.properties.sessionID)
|
||||
reconcileSessions()
|
||||
const unsubscribeIdle = context.data.on("session.idle", (event) => {
|
||||
trackSession(event.data.sessionID)
|
||||
void reconcileSessions()
|
||||
void refresh()
|
||||
})
|
||||
const unsubscribeStatus = api.event.on("session.status", (event) => {
|
||||
trackSession(event.properties.sessionID)
|
||||
const unsubscribeStatus = context.data.on("session.status", (event) => {
|
||||
trackSession(event.data.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.
|
||||
}
|
||||
}
|
||||
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
|
||||
|
||||
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)
|
||||
/** 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(): void {
|
||||
if (!trackUsage || trackedSessions.size === 0) return
|
||||
function reconcileSessions(): Promise<void> {
|
||||
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
|
||||
const updates: Promise<void>[] = []
|
||||
for (const sessionID of trackedSessions) {
|
||||
let messages: ReadonlyArray<UsageMessage> | undefined
|
||||
let messages: ReadonlyArray<unknown> | undefined
|
||||
try {
|
||||
messages = api.state.session.messages(sessionID)
|
||||
messages = context.data.session.message.list(sessionID)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (!messages?.length) continue
|
||||
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>))
|
||||
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
|
||||
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) {
|
||||
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 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))
|
||||
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.
|
||||
}
|
||||
@@ -204,13 +201,6 @@ export function createBalanceStore(
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -233,15 +223,10 @@ 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)
|
||||
const credential = resolveGreenptKey(options, undefined, env)
|
||||
if (!credential.ok) {
|
||||
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
|
||||
if (api.state.path.state === undefined && !retriedState) {
|
||||
retriedState = true
|
||||
stateRetryTimer = setTimeout(() => void refresh(), STATE_RETRY_MS)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -260,7 +245,7 @@ export function createBalanceStore(
|
||||
if (trackUsage && Number.isFinite(credits)) {
|
||||
if (lastCredits !== undefined && credits < lastCredits) {
|
||||
const spent = lastCredits - credits
|
||||
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
||||
await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
||||
}
|
||||
lastCredits = credits
|
||||
}
|
||||
@@ -273,14 +258,14 @@ export function createBalanceStore(
|
||||
inFlight = false
|
||||
}
|
||||
if (disposed) return
|
||||
reconcileSessions()
|
||||
await reconcileSessions()
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
/** Clear every persisted and in-memory usage bucket. */
|
||||
function resetUsage(): void {
|
||||
async function resetUsage(): Promise<void> {
|
||||
lastCredits = undefined
|
||||
mutateUsage((days) => {
|
||||
await mutateUsage((days) => {
|
||||
for (const date of Object.keys(days)) delete days[date]
|
||||
})
|
||||
}
|
||||
@@ -292,7 +277,6 @@ export function createBalanceStore(
|
||||
controller.abort()
|
||||
if (refreshTimer) clearTimeout(refreshTimer)
|
||||
if (tickTimer) clearTimeout(tickTimer)
|
||||
if (stateRetryTimer) clearTimeout(stateRetryTimer)
|
||||
unsubscribeIdle()
|
||||
unsubscribeStatus()
|
||||
unsubscribeConnected()
|
||||
|
||||
Reference in New Issue
Block a user