opencode-codebuddy-quota 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,150 @@
1
+ import { apiHeaders } from "./headers"
2
+ import type { SiteAuth } from "./login"
3
+
4
+ export interface UpstreamReading {
5
+ remaining: number
6
+ used: number
7
+ total: number
8
+ cycleStart: string | null
9
+ cycleEnd: string | null
10
+ resetAt: string | null
11
+ fetchedAt: string
12
+ }
13
+
14
+ export interface FetchUpstreamOptions {
15
+ auth: SiteAuth
16
+ signal?: AbortSignal
17
+ fetchImpl?: typeof fetch
18
+ now?: () => number
19
+ }
20
+
21
+ const num = (v: unknown): number => {
22
+ const n = typeof v === "string" ? Number(v) : v
23
+ return typeof n === "number" && Number.isFinite(n) ? n : 0
24
+ }
25
+
26
+ /**
27
+ * Personal (non-enterprise) accounts cannot use get-enterprise-user-usage: the
28
+ * gateway rejects a personal JWT with 400/403. Their quota lives in resource
29
+ * packages returned by get-user-resource. Sum every package's cycle figures
30
+ * (the user chose "sum all packages"), but take the cycle boundaries from the
31
+ * main plan; fall back to the earliest cycle end when no main plan is present.
32
+ */
33
+ async function fetchUserResource(
34
+ auth: SiteAuth,
35
+ opts: FetchUpstreamOptions,
36
+ ): Promise<UpstreamReading> {
37
+ const doFetch = opts.fetchImpl ?? fetch
38
+ // Resource endpoint is on the intl endpoint host for personal accounts.
39
+ const url = `${auth.endpoint}/v2/billing/meter/get-user-resource`
40
+ const response = await doFetch(url, {
41
+ method: "POST",
42
+ headers: { ...apiHeaders(auth), "Content-Type": "application/json" },
43
+ body: "{}",
44
+ signal: opts.signal,
45
+ })
46
+ if (!response.ok) throw new Error(`upstream HTTP ${response.status}`)
47
+ const payload = (await response.json()) as {
48
+ code?: number
49
+ msg?: string
50
+ data?: { Response?: { Data?: { Accounts?: Array<Record<string, unknown>> } } }
51
+ }
52
+ if (payload?.code !== 0) throw new Error(`upstream code ${payload?.code}: ${payload?.msg || "unknown"}`)
53
+ const accounts = payload.data?.Response?.Data?.Accounts ?? []
54
+ if (!Array.isArray(accounts) || accounts.length === 0) {
55
+ throw new Error("upstream payload has no resource packages")
56
+ }
57
+ let remaining = 0
58
+ let total = 0
59
+ const ends: string[] = []
60
+ // The cycle boundaries (progress bar + reset time) follow the main plan, not
61
+ // whichever bonus package happens to expire first. A main plan is the base
62
+ // subscription: its name says "Plan"/"Subscription", or its CapacityType is 4
63
+ // (observed on the free monthly plan). Bonus packs are CapacityType 1.
64
+ let main: Record<string, unknown> | null = null
65
+ for (const a of accounts) {
66
+ const rem = num(a.CycleCapacityRemainPrecise ?? a.CapacityRemainPrecise)
67
+ const size = num(a.CycleCapacitySizePrecise ?? a.CapacitySizePrecise)
68
+ remaining += rem
69
+ total += size
70
+ if (typeof a.CycleEndTime === "string") ends.push(a.CycleEndTime)
71
+ if (
72
+ !main &&
73
+ (/plan|subscription|主套餐|基础套餐/i.test(String(a.PackageName ?? "")) ||
74
+ num(a.CapacityType) === 4)
75
+ ) {
76
+ main = a
77
+ }
78
+ }
79
+ if (!Number.isFinite(total) || total <= 0) throw new Error("upstream payload is missing capacity figures")
80
+ // Sort by parsed time, not lexical order (formats may include T/ms/timezone).
81
+ const sorted = ends
82
+ .map((s) => ({ s, t: new Date(s).getTime() }))
83
+ .filter((e) => Number.isFinite(e.t))
84
+ .sort((a, b) => a.t - b.t)
85
+ const earliest = sorted[0]?.s ?? null
86
+ const mainEnd = main && typeof main.CycleEndTime === "string" ? main.CycleEndTime : null
87
+ const reset = mainEnd ?? earliest
88
+ // Keep the start from the same source as the end. If the main plan has no end
89
+ // (so reset falls back to the earliest bonus package), a main-only start would
90
+ // pair boundaries from different packages and skew the time ratio.
91
+ const cycleStart =
92
+ mainEnd !== null && main && typeof main.CycleStartTime === "string" ? main.CycleStartTime : null
93
+ const at = opts.now ? opts.now() : Date.now()
94
+ return {
95
+ remaining: Math.max(0, remaining),
96
+ used: Math.max(0, total - remaining),
97
+ total,
98
+ cycleStart,
99
+ cycleEnd: reset,
100
+ resetAt: reset,
101
+ fetchedAt: new Date(at).toISOString(),
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Fetch the site's cycle usage with its JWT. Enterprise accounts (with an
107
+ * enterpriseId claim) use get-enterprise-user-usage; personal accounts fall
108
+ * back to get-user-resource. For the enterprise endpoint the host is
109
+ * `usageHost`, while `x-domain` stays the endpoint host from `apiHeaders`
110
+ * (never the realm domain — that triggers 12403).
111
+ */
112
+ export async function fetchUpstream(opts: FetchUpstreamOptions): Promise<UpstreamReading> {
113
+ if (!opts.auth.enterpriseId) return fetchUserResource(opts.auth, opts)
114
+
115
+ const doFetch = opts.fetchImpl ?? fetch
116
+ const url = `${opts.auth.usageHost}/v2/billing/meter/get-enterprise-user-usage`
117
+ const response = await doFetch(url, {
118
+ method: "POST",
119
+ headers: { ...apiHeaders(opts.auth), "Content-Type": "application/json" },
120
+ body: "{}",
121
+ signal: opts.signal,
122
+ })
123
+
124
+ if (!response.ok) throw new Error(`upstream HTTP ${response.status}`)
125
+
126
+ const payload = (await response.json()) as {
127
+ code?: number
128
+ msg?: string
129
+ data?: Record<string, unknown>
130
+ }
131
+ if (payload?.code !== 0) throw new Error(`upstream code ${payload?.code}: ${payload?.msg || "unknown"}`)
132
+
133
+ const data = payload.data ?? {}
134
+ const used = Number(data.credit)
135
+ const total = Number(data.limitNum)
136
+ if (!Number.isFinite(used) || !Number.isFinite(total)) {
137
+ throw new Error("upstream payload is missing credit/limitNum")
138
+ }
139
+
140
+ const at = opts.now ? opts.now() : Date.now()
141
+ return {
142
+ remaining: Math.max(0, total - used),
143
+ used,
144
+ total,
145
+ cycleStart: typeof data.cycleStartTime === "string" ? data.cycleStartTime : null,
146
+ cycleEnd: typeof data.cycleEndTime === "string" ? data.cycleEndTime : null,
147
+ resetAt: typeof data.cycleResetTime === "string" ? data.cycleResetTime : null,
148
+ fetchedAt: new Date(at).toISOString(),
149
+ }
150
+ }
@@ -0,0 +1,67 @@
1
+ import type { SiteInfo } from "../shared"
2
+ import type { Reading } from "./quota-source"
3
+
4
+ /** The object the RPC returns; the fields mirror `rpc.ts`'s output schema. */
5
+ export interface WireReading {
6
+ ok: boolean
7
+ stale: boolean
8
+ /** Served from the 30-second cache: the numbers are real but not from this call. */
9
+ cached: boolean
10
+ /** How old the numbers are, in whole seconds. */
11
+ ageSeconds: number | null
12
+ remaining: number | null
13
+ used: number | null
14
+ total: number | null
15
+ cycleStart: string | null
16
+ cycleEnd: string | null
17
+ resetAt: string | null
18
+ fetchedAt: string | null
19
+ error: string | null
20
+ site: "cn" | "intl"
21
+ sites: SiteInfo[]
22
+ }
23
+
24
+ /**
25
+ * `ok` answers "do we have numbers", `stale` answers "did the latest attempt
26
+ * fail". A reading with numbers but a failed refresh is `ok: true, stale: true`
27
+ * — the GUI shows the old figure marked stale. Only a source that never
28
+ * succeeded says `ok: false`, which the GUI treats as unavailable rather than
29
+ * as a stale number.
30
+ */
31
+ export function toWireReading(
32
+ reading: Reading,
33
+ info: { site: "cn" | "intl"; sites: SiteInfo[] },
34
+ ): WireReading {
35
+ const numbers = {
36
+ remaining: reading.remaining,
37
+ used: reading.used,
38
+ total: reading.total,
39
+ cycleStart: reading.cycleStart,
40
+ cycleEnd: reading.cycleEnd,
41
+ resetAt: reading.resetAt,
42
+ fetchedAt: reading.fetchedAt,
43
+ error: reading.error,
44
+ }
45
+ if (reading.fetchedAt === null) {
46
+ return {
47
+ ok: false,
48
+ stale: true,
49
+ cached: false,
50
+ ageSeconds: null,
51
+ ...numbers,
52
+ remaining: null,
53
+ used: null,
54
+ total: null,
55
+ cycleStart: null,
56
+ cycleEnd: null,
57
+ resetAt: null,
58
+ fetchedAt: null,
59
+ site: info.site,
60
+ sites: info.sites,
61
+ }
62
+ }
63
+ return {
64
+ ok: true, stale: reading.stale, cached: reading.cached, ageSeconds: reading.ageSeconds,
65
+ ...numbers, site: info.site, sites: info.sites,
66
+ }
67
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,20 @@
1
+ /** The two CodeBuddy sites. Pure type shared by server and GUI bundles. */
2
+ export type Site = "cn" | "intl"
3
+
4
+ /** A brief account identity sent to the GUI. Never carries a token. */
5
+ export interface AccountBrief {
6
+ id: string
7
+ label: string
8
+ }
9
+
10
+ /**
11
+ * Per-site availability and account list for the quota dialog. `accounts` and
12
+ * `activeId` are always 0/1 this term; the shape leaves room for future
13
+ * multi-account switching without changing the RPC contract.
14
+ */
15
+ export interface SiteInfo {
16
+ site: Site
17
+ available: boolean
18
+ accounts: AccountBrief[]
19
+ activeId: string | null
20
+ }