opencode-codebuddy-quota 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -0,0 +1,198 @@
1
+ import type { Site, SiteInfo } from "../shared"
2
+
3
+ export type QuotaStatus = "ok" | "cached" | "stale" | "error"
4
+
5
+ export interface Quota {
6
+ status: QuotaStatus
7
+ site: Site
8
+ sites: SiteInfo[]
9
+ remaining: number | null
10
+ used: number | null
11
+ total: number | null
12
+ usedPct: number | null
13
+ timePct: number | null
14
+ diff: number | null
15
+ cycleStart: string | null
16
+ cycleEnd: string | null
17
+ resetAt: string | null
18
+ fetchedAt: string | null
19
+ /** Age of the numbers in whole seconds, as the server counted it. */
20
+ ageSeconds: number | null
21
+ error: string | null
22
+ }
23
+
24
+ export interface NormalizeContext {
25
+ now: number
26
+ fallback?: Quota | null
27
+ }
28
+
29
+ const round2 = (n: number) => Math.round(n * 100) / 100
30
+
31
+ function num(value: unknown): number | null {
32
+ const n = typeof value === "string" ? Number(value) : value
33
+ return typeof n === "number" && Number.isFinite(n) ? n : null
34
+ }
35
+
36
+ /**
37
+ * "2026-10-28 00:00:00" is the upstream's local-time format. `new Date(str)` treats it
38
+ * as UTC in some engines, which would shift timePct by the UTC offset, so parse the
39
+ * parts by hand into local time.
40
+ */
41
+ export function parseLocalTime(value: unknown): number | null {
42
+ if (typeof value !== "string") return null
43
+ const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(value.trim())
44
+ if (!m) return null
45
+ const [, y, mo, d, h, mi, s] = m.map(Number)
46
+ const t = new Date(y, mo - 1, d, h, mi, s).getTime()
47
+ return Number.isFinite(t) ? t : null
48
+ }
49
+
50
+ const DEFAULT_SITES: SiteInfo[] = [
51
+ { site: "cn", available: false, accounts: [], activeId: null },
52
+ { site: "intl", available: false, accounts: [], activeId: null },
53
+ ]
54
+
55
+ function empty(status: QuotaStatus, error: string | null): Quota {
56
+ return {
57
+ status,
58
+ site: "cn",
59
+ sites: DEFAULT_SITES,
60
+ remaining: null,
61
+ used: null,
62
+ total: null,
63
+ usedPct: null,
64
+ timePct: null,
65
+ diff: null,
66
+ cycleStart: null,
67
+ cycleEnd: null,
68
+ resetAt: null,
69
+ fetchedAt: null,
70
+ ageSeconds: null,
71
+ error,
72
+ }
73
+ }
74
+
75
+ function timeProgress(
76
+ startMs: number | null,
77
+ endMs: number | null,
78
+ atMs: number | null,
79
+ ): number | null {
80
+ if (startMs === null || endMs === null || atMs === null) return null
81
+ if (endMs <= startMs) return null
82
+ // A fetched time outside the cycle (clock skew, a stale cached reading carried
83
+ // across a reset) would otherwise render -87% or 110%, desyncing formatPct and
84
+ // paceColor from the already-clamped progress bar.
85
+ const pct = ((atMs - startMs) / (endMs - startMs)) * 100
86
+ return round2(Math.min(100, Math.max(0, pct)))
87
+ }
88
+
89
+ export function normalizeQuota(payload: unknown, ctx: NormalizeContext): Quota {
90
+ /**
91
+ * `keepFallback` separates two different failures:
92
+ * - the server said `ok: false` — it is unavailable, and a previous reading
93
+ * must not be dressed up as merely stale, so the fallback is dropped;
94
+ * - the answer arrived but is unusable — the numbers are bad, not the line,
95
+ * so the last good reading still describes the quota.
96
+ */
97
+ const unusable = (error: string, keepFallback: boolean): Quota =>
98
+ keepFallback && ctx.fallback ? { ...ctx.fallback, status: "stale", error } : empty("error", error)
99
+
100
+ if (typeof payload !== "object" || payload === null) {
101
+ return unusable(
102
+ typeof payload === "string"
103
+ ? `unexpected response: ${payload.slice(0, 80)}`
104
+ : "empty response",
105
+ true,
106
+ )
107
+ }
108
+
109
+ const data = payload as Record<string, unknown>
110
+ const error = typeof data.error === "string" ? data.error : null
111
+
112
+ if (data.ok !== true) return unusable(error ?? "quota service reported no reading", false)
113
+
114
+ const total = num(data.total)
115
+ const used = num(data.used)
116
+ const remaining = num(data.remaining)
117
+ if (total === null || total <= 0 || used === null || remaining === null) {
118
+ return unusable(error ?? "payload is missing a usable total/used/remaining", true)
119
+ }
120
+
121
+ const cycleStart = typeof data.cycleStart === "string" ? data.cycleStart : null
122
+ const cycleEnd = typeof data.cycleEnd === "string" ? data.cycleEnd : null
123
+ const resetAt = typeof data.resetAt === "string" ? data.resetAt : null
124
+ const fetchedAt = typeof data.fetchedAt === "string" ? data.fetchedAt : null
125
+
126
+ const usedPct = round2((used / total) * 100)
127
+ // Date.parse answers NaN for an unparseable string, and `NaN ?? x` is NaN, so
128
+ // guard with isFinite rather than relying on a nullish fallback. An unknown
129
+ // fetch time cannot anchor the time progress: falling back to "now" would make
130
+ // the pace drift with every render, so report no progress instead.
131
+ const parsedAt = fetchedAt ? Date.parse(fetchedAt) : NaN
132
+ const atMs = Number.isFinite(parsedAt) ? parsedAt : null
133
+ // The cycle ends when the next one starts, not on its last second, so progress
134
+ // reaches 100% exactly when the allowance resets. Using `cycleEnd` (23:59:59)
135
+ // would read as "period over" a second before the credits come back.
136
+ const timePct = timeProgress(
137
+ parseLocalTime(cycleStart),
138
+ parseLocalTime(resetAt) ?? parseLocalTime(cycleEnd),
139
+ atMs,
140
+ )
141
+ // Time progress minus spend progress: positive means the credits are being
142
+ // used more slowly than the cycle is passing, which is the healthy direction.
143
+ const diff =
144
+ usedPct !== null && timePct !== null && Number.isFinite(timePct) ? round2(timePct - usedPct) : null
145
+
146
+ const status: QuotaStatus =
147
+ data.stale === true ? "stale" : data.cached === true ? "cached" : "ok"
148
+ const ageSeconds = num(data.ageSeconds)
149
+ const site: Site = data.site === "intl" ? "intl" : "cn"
150
+ const sites: SiteInfo[] = Array.isArray(data.sites)
151
+ ? (data.sites as SiteInfo[]).filter(
152
+ (s) => s && (s.site === "cn" || s.site === "intl") && Array.isArray(s.accounts),
153
+ )
154
+ : DEFAULT_SITES
155
+
156
+ return {
157
+ status,
158
+ site,
159
+ sites,
160
+ remaining,
161
+ used,
162
+ total,
163
+ usedPct,
164
+ timePct,
165
+ diff,
166
+ cycleStart,
167
+ cycleEnd,
168
+ resetAt,
169
+ fetchedAt,
170
+ ageSeconds: ageSeconds === null ? null : Math.round(ageSeconds),
171
+ error: error ?? null,
172
+ }
173
+ }
174
+
175
+ /** The number inside the capsule: remaining share as a whole 0..100, no percent sign. */
176
+ export function remainingPercent(q: Quota): number | null {
177
+ if (q.total === null || q.total <= 0) return null
178
+ // Derive from used rather than trusting `remaining`: the upstream clamps remaining
179
+ // to >= 0, so an overrun would otherwise read as a healthy 89%.
180
+ const used = q.used
181
+ if (used === null) {
182
+ if (q.remaining === null) return null
183
+ return Math.min(100, Math.max(0, Math.round((q.remaining / q.total) * 100)))
184
+ }
185
+ const pct = Math.round(((q.total - used) / q.total) * 100)
186
+ return Math.min(100, Math.max(0, pct))
187
+ }
188
+
189
+ /**
190
+ * The remaining share at full precision, for every label that is not the capsule.
191
+ * The capsule rounds it to a whole number; the tooltip and the dialog must agree
192
+ * with each other, so both read this one function.
193
+ */
194
+ export function remainingShare(q: Quota): number | null {
195
+ if (q.usedPct === null || q.used === null || q.total === null) return null
196
+ const pct = 100 - q.usedPct
197
+ return Math.max(0, Math.round(pct * 100) / 100)
198
+ }
@@ -0,0 +1,181 @@
1
+ import type { Site } from "../shared"
2
+ import { normalizeQuota, type Quota } from "./quota"
3
+
4
+ /** The shape `ctx.client.rpc(CodebuddyQuota)` satisfies; kept loose so tests can fake it. */
5
+ export interface QuotaClient {
6
+ read(input: { site?: Site }): Promise<unknown>
7
+ login?(input: { site: Site }): Promise<unknown>
8
+ }
9
+
10
+ export interface QuotaStore {
11
+ read(): Quota
12
+ subscribe(listener: (q: Quota) => void): () => void
13
+ refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
14
+ login(site: Site): Promise<boolean>
15
+ start(): () => void
16
+ }
17
+
18
+ /** Background safety net only; the capsule refreshes on hover and the dialog on open. */
19
+ const REFRESH_MS = 30 * 60_000
20
+ /** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
21
+ export const HOVER_MIN_AGE_MS = 60_000
22
+ const STALE_AFTER_RESUME_MS = 2 * 60_000
23
+
24
+ const idle = (status: "error", error: string | null): Quota => ({
25
+ status,
26
+ site: "cn",
27
+ sites: [
28
+ { site: "cn", available: false, accounts: [], activeId: null },
29
+ { site: "intl", available: false, accounts: [], activeId: null },
30
+ ],
31
+ remaining: null,
32
+ used: null,
33
+ total: null,
34
+ usedPct: null,
35
+ timePct: null,
36
+ diff: null,
37
+ cycleStart: null,
38
+ cycleEnd: null,
39
+ resetAt: null,
40
+ fetchedAt: null,
41
+ ageSeconds: null,
42
+ error,
43
+ })
44
+
45
+ /**
46
+ * One read of the quota over the plugin RPC.
47
+ *
48
+ * Both a rejection (`RPC is unavailable`, the server restarting) and an explicit
49
+ * `ok: false` mean "no answer", but they keep the previous numbers differently:
50
+ * a rejection keeps them and marks them stale, because the quota itself is
51
+ * probably fine; `ok: false` is the server saying it has nothing, so the old
52
+ * numbers are dropped rather than dressed up as merely stale.
53
+ */
54
+ export async function readQuota(opts: {
55
+ client: QuotaClient
56
+ fallback?: Quota | null
57
+ now?: number
58
+ site?: Site
59
+ }): Promise<Quota> {
60
+ const now = opts.now ?? Date.now()
61
+ let body: unknown
62
+ try {
63
+ body = await opts.client.read(opts.site ? { site: opts.site } : {})
64
+ } catch (error) {
65
+ const message = String((error as Error)?.message ?? error)
66
+ return opts.fallback
67
+ ? { ...opts.fallback, status: "stale", error: message }
68
+ : idle("error", message)
69
+ }
70
+ // An explicit "unavailable" must never be dressed up as a stale number, so
71
+ // the fallback is deliberately not offered here.
72
+ return normalizeQuota(body, { now })
73
+ }
74
+
75
+ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
76
+ let current: Quota = normalizeQuota(null, { now: Date.now() })
77
+ let lastAttempt = 0
78
+ let inflight: Promise<void> | null = null
79
+ let pendingSite: Site | null = null
80
+ let started = false
81
+ const listeners = new Set<(q: Quota) => void>()
82
+
83
+ const emit = (next: Quota) => {
84
+ current = next
85
+ for (const listener of listeners) listener(next)
86
+ }
87
+
88
+ /**
89
+ * `force` skips every GUI-side age check (the dialog's refresh button); the
90
+ * server's own 30-second cache still applies behind it.
91
+ * `maxAgeMs` refreshes only when the last attempt is older than that, which is
92
+ * how hover keeps working without spamming on every pointer move.
93
+ */
94
+ const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
95
+ // One request at a time: without this, a forced refresh racing a hover refresh
96
+ // can land out of order and let the older reading win.
97
+ if (inflight) {
98
+ // Compare against the IN-FLIGHT site, not current.site (which is the last
99
+ // emitted one and is frozen while a read runs). Last explicit request wins.
100
+ if (options.site) pendingSite = options.site
101
+ return inflight
102
+ }
103
+ const now = Date.now()
104
+ const maxAge = options.force ? 0 : (options.maxAgeMs ?? REFRESH_MS)
105
+ if (now - lastAttempt < maxAge) return
106
+ lastAttempt = now
107
+
108
+ inflight = (async () => {
109
+ try {
110
+ // Only a reading that actually carried data is worth falling back to.
111
+ const usable = current.remaining !== null ? current : null
112
+ let next: Quota
113
+ try {
114
+ // Read the client per request: it changes when the server restarts.
115
+ next = await readQuota({ client: client(), fallback: usable, site: options.site })
116
+ } catch (error) {
117
+ // `client()` itself can throw when the server client is unavailable,
118
+ // which is the same situation as a rejected RPC call.
119
+ const message = String((error as Error)?.message ?? error)
120
+ next = usable ? { ...usable, status: "stale", error: message } : idle("error", message)
121
+ }
122
+ emit(next)
123
+ } finally {
124
+ inflight = null
125
+ const queued = pendingSite
126
+ pendingSite = null
127
+ // Re-run only if the last request was for a different site than the one
128
+ // that just completed; otherwise it is already served.
129
+ if (queued && queued !== current.site) void refresh({ force: true, site: queued })
130
+ }
131
+ })()
132
+
133
+ return inflight
134
+ }
135
+
136
+ const start = () => {
137
+ if (started) return () => {}
138
+ started = true
139
+ const hasDocument = typeof globalThis.document !== "undefined"
140
+ const tick = () => {
141
+ // A hidden window must not poll; on return, refresh only if the data aged.
142
+ if (hasDocument && globalThis.document.hidden) return
143
+ void refresh()
144
+ }
145
+ const onVisible = () => {
146
+ if (globalThis.document.hidden) return
147
+ if (Date.now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
148
+ }
149
+ const timer = setInterval(tick, REFRESH_MS)
150
+ if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
151
+ // The one place the capsule gets its first number without any interaction.
152
+ void refresh({ force: true })
153
+ return () => {
154
+ clearInterval(timer)
155
+ if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
156
+ started = false
157
+ }
158
+ }
159
+
160
+ return {
161
+ read: () => current,
162
+ subscribe(listener) {
163
+ listeners.add(listener)
164
+ return () => listeners.delete(listener)
165
+ },
166
+ refresh,
167
+ async login(site) {
168
+ try {
169
+ const loginFn = client().login
170
+ if (!loginFn) return false
171
+ const result = (await loginFn({ site })) as { ok?: boolean } | null
172
+ const ok = result?.ok === true
173
+ if (ok) await refresh({ force: true, site })
174
+ return ok
175
+ } catch {
176
+ return false
177
+ }
178
+ },
179
+ start,
180
+ }
181
+ }
package/src/gui.tsx ADDED
@@ -0,0 +1,111 @@
1
+ import { Plugin, Slot, Style } from "@opencode/plugin/gui"
2
+ import { createSignal, onCleanup } from "solid-js"
3
+ import { CodebuddyQuota } from "../rpc"
4
+ import { Battery } from "./gui/battery"
5
+ import { QuotaDialog } from "./gui/dialog"
6
+ import { formatPct, paceColor } from "./gui/pace"
7
+ import { remainingPercent, remainingShare, type Quota } from "./gui/quota"
8
+ import { createQuotaStore, HOVER_MIN_AGE_MS } from "./gui/store"
9
+ import dialogCss from "./gui/dialog.css?inline"
10
+
11
+ export default Plugin.define({
12
+ setup(ctx) {
13
+ // Scoped dialog styles. currentColor/color-mix follow the active OpenCode
14
+ // theme, so the dialog stays in step with light/dark and custom themes.
15
+ ctx.add(Style, dialogCss)
16
+
17
+ // The client is read per request, not captured here: it changes when the
18
+ // OpenCode server restarts, and a captured one would keep failing.
19
+ const store = createQuotaStore(() => ctx.client.rpc(CodebuddyQuota))
20
+ const [quota, setQuota] = createSignal<Quota>(store.read())
21
+ onCleanup(store.subscribe(setQuota))
22
+ onCleanup(store.start())
23
+
24
+ const openDetails = () => {
25
+ // Refreshing here as well as on the dialog's mount would fire two requests
26
+ // for one click, so the dialog owns that refresh.
27
+ ctx.dialogs.open((dialog) => {
28
+ // The subscription lives in its own component so its owner is the dialog's
29
+ // render, not whatever scope `dialogs.open` happens to run in.
30
+ const Live = () => {
31
+ const [live, setLive] = createSignal<Quota>(store.read())
32
+ onCleanup(store.subscribe(setLive))
33
+ return (
34
+ <QuotaDialog
35
+ quota={live()}
36
+ ui={ctx.ui}
37
+ onRefresh={(site) => store.refresh({ force: true, site })}
38
+ onLogin={(site) => store.login(site)}
39
+ close={dialog.close}
40
+ />
41
+ )
42
+ }
43
+ return <Live />
44
+ })
45
+ }
46
+
47
+ // Hover is the main way this refreshes: the background timer is only a safety
48
+ // net, so pointing at the capsule pulls a reading that is older than a minute.
49
+ const onHover = () => {
50
+ void store.refresh({ maxAgeMs: HOVER_MIN_AGE_MS, site: store.read().site })
51
+ }
52
+ const SITE_LABEL = { cn: "国内站", intl: "国际站" } as const
53
+ // Any site needing login shows an amber dot outside the capsule. Read the
54
+ // quota signal, not store.read(): the latter is a plain variable that Solid
55
+ // never tracks, so the dot froze on the first "needs login" verdict.
56
+ const needsLogin = () => quota().sites.some((s) => !s.available)
57
+
58
+ // The capsule lives on the session header row — the only surface the
59
+ // side-tabs layout leaves a plugin. See the design notes for why.
60
+ //
61
+ // Every value is read inside the JSX, not in the render body: a signal read
62
+ // outside a tracked expression is evaluated once and then frozen, which is
63
+ // why the capsule used to stay on "--" while the dialog showed live numbers.
64
+ ctx.add(Slot, {
65
+ at: "session.header",
66
+ order: 50,
67
+ render: () => (
68
+ <button
69
+ type="button"
70
+ title={
71
+ remainingShare(quota()) === null
72
+ ? `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:暂不可用(点击查看/登录)`
73
+ : `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:剩余 ${formatPct(remainingShare(quota()))}`
74
+ }
75
+ onMouseEnter={onHover}
76
+ onFocus={onHover}
77
+ onClick={openDetails}
78
+ style={{
79
+ position: "relative",
80
+ background: "transparent",
81
+ border: "none",
82
+ padding: "2px 6px 2px 0",
83
+ "margin-left": "auto",
84
+ cursor: "pointer",
85
+ "line-height": "0",
86
+ }}
87
+ >
88
+ <Battery
89
+ value={remainingPercent(quota())}
90
+ color={paceColor(quota())}
91
+ dim={quota().status === "stale"}
92
+ />
93
+ {needsLogin() && (
94
+ <span
95
+ style={{
96
+ position: "absolute",
97
+ top: "0",
98
+ right: "0",
99
+ width: "9px",
100
+ height: "9px",
101
+ "border-radius": "50%",
102
+ background: "#ffb84d",
103
+ border: "1.5px solid transparent",
104
+ }}
105
+ />
106
+ )}
107
+ </button>
108
+ ),
109
+ })
110
+ },
111
+ })