new: [opencode-greenpt-usage] add GreenPT credit balance plugin
Show the remaining GreenPT API credit balance in the OpenCode TUI sidebar. The key is resolved from the ``apiKey`` option, the ``GREENPT_API_KEY`` environment variable, or the active OpenCode ``auth.json`` (provider ``greenpt``); the section is hidden when no key is present, so the plugin stays portable across machines and profiles. The balance is read from the ``x-credits-remaining`` header returned by a free ``HEAD /v1/chat/completions`` probe (HTTP 400 before any credit is consumed), which avoids a billable call per refresh. Tests cover the credential resolution, the header parsing and the live API. Distribute via git clone; there is no npm publish.
This commit is contained in:
147
src/store.ts
Normal file
147
src/store.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
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 { resolveGreenptKey, type CredentialEnv } from "./credential"
|
||||
|
||||
/** Default GreenPT API base URL. */
|
||||
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
|
||||
|
||||
export type BalanceOptions = {
|
||||
apiKey?: string
|
||||
baseUrl?: string
|
||||
refreshInterval?: number
|
||||
order?: number
|
||||
showWhenUnavailable?: boolean
|
||||
unit?: string
|
||||
}
|
||||
|
||||
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
|
||||
refresh: () => 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
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param api TUI plugin API (used for the auth store path and events).
|
||||
* @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,
|
||||
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
|
||||
|
||||
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
|
||||
const controller = new AbortController()
|
||||
|
||||
const unsubscribeIdle = api.event.on("session.idle", () => void refresh())
|
||||
const unsubscribeConnected = api.event.on("server.connected", () => void refresh())
|
||||
|
||||
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, api.state.path.state, 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
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
tickTimer = setTimeout(tick, TICK_MS)
|
||||
|
||||
function dispose() {
|
||||
disposed = true
|
||||
controller.abort()
|
||||
if (refreshTimer) clearTimeout(refreshTimer)
|
||||
if (tickTimer) clearTimeout(tickTimer)
|
||||
if (stateRetryTimer) clearTimeout(stateRetryTimer)
|
||||
unsubscribeIdle()
|
||||
unsubscribeConnected()
|
||||
}
|
||||
|
||||
return { state, now, refresh, dispose }
|
||||
}
|
||||
Reference in New Issue
Block a user