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,87 @@
1
+ import type { Site } from "../shared"
2
+ import { createLoginGate, type LoginGate } from "./login-gate"
3
+ import { getAuthState, openBrowser, pollToken, type SiteAuth } from "./login"
4
+ import { resolveSite } from "./site-select"
5
+ import { siteInfo } from "./site-state"
6
+ import type { TokenStore } from "./token-store"
7
+ import type { QuotaSource, Reading } from "./quota-source"
8
+ import { toWireReading, type WireReading } from "./wire"
9
+
10
+ /** The `read`/`login` handlers the plugin registers over RPC. */
11
+ export interface RpcHandlers {
12
+ read(input: unknown, context: { signal: AbortSignal }): Promise<WireReading>
13
+ login(input: unknown): Promise<{ ok: boolean; error: string | null }>
14
+ }
15
+
16
+ export interface HandlerDeps {
17
+ store: TokenStore
18
+ source: QuotaSource
19
+ log: (message: string) => void
20
+ /** Injectable login step returning the new credential; defaults to browser flow. */
21
+ performLogin?: (site: Site) => Promise<SiteAuth>
22
+ /** Injectable gate; defaults to per-site single-flight. */
23
+ loginGate?: LoginGate
24
+ /**
25
+ * Best-effort hook run after a successful login so the freshly added account
26
+ * can re-import its provider models. A failure here never fails the login.
27
+ */
28
+ afterLogin?: (site: Site) => Promise<void>
29
+ }
30
+
31
+ /**
32
+ * Build the RPC handlers. Kept free of Plugin/Context so the wiring —
33
+ * site selection persistence, post-refresh cache snapshot, login single-flight —
34
+ * can be asserted without starting a real proxy or touching the disk.
35
+ */
36
+ export function makeRpcHandlers(deps: HandlerDeps): RpcHandlers {
37
+ const gate = deps.loginGate ?? createLoginGate()
38
+ // Returns the new credential; the handler archives it on success so the
39
+ // write is part of the tested assembly, not hidden in the login step.
40
+ const performLogin =
41
+ deps.performLogin ??
42
+ (async (site) => {
43
+ const { state, authUrl } = await getAuthState(site)
44
+ openBrowser(authUrl)
45
+ return pollToken(site, state)
46
+ })
47
+
48
+ return {
49
+ async read(input, context) {
50
+ const requested = (input as { site?: Site } | undefined)?.site
51
+ const site = resolveSite(deps.store, requested, (m) => deps.log(m))
52
+ const reading: Reading = await deps.source.read(site, context.signal)
53
+ // Read the cache AFTER the refresh so a rotated token cannot leave a
54
+ // stale "needs login" tag next to freshly returned numbers.
55
+ const state = deps.store.all()
56
+ return toWireReading(reading, { site, sites: siteInfo(state, (s) => deps.store.refreshFailed(s)).sites })
57
+ },
58
+ async login(input) {
59
+ const site = (input as { site: Site }).site
60
+ return gate.run(site, async () => {
61
+ try {
62
+ const auth = await performLogin(site)
63
+ deps.store.archive(auth)
64
+ // A read before login likely armed the 30s failure cooldown. Clear it
65
+ // so the GUI's post-login refresh retries upstream with the new token
66
+ // immediately instead of replaying the old "needs login" verdict.
67
+ deps.source.clearFailure(site)
68
+ deps.log(`${site} login complete`)
69
+ // Re-import this account's models: a login after startup is the moment
70
+ // a previously missing site becomes importable. Fire-and-forget — the
71
+ // registry/catalog fetch can take tens of seconds, and a best-effort
72
+ // re-import must neither block the login response nor fail it.
73
+ if (deps.afterLogin) {
74
+ void deps.afterLogin(site).catch((error) => {
75
+ deps.log(`${site} post-login model re-import failed: ${String((error as Error)?.message ?? error)}`)
76
+ })
77
+ }
78
+ return { ok: true, error: null }
79
+ } catch (error) {
80
+ const message = String((error as Error)?.message ?? error)
81
+ deps.log(`${site} login failed: ${message}`)
82
+ return { ok: false, error: message }
83
+ }
84
+ })
85
+ },
86
+ }
87
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * AbortSignal.any is not guaranteed in every runtime OpenCode embeds, so keep a
3
+ * small compatible implementation shared by the server and the catalog fetch.
4
+ */
5
+ export function anySignal(signals: AbortSignal[]): AbortSignal {
6
+ for (const signal of signals) {
7
+ if (signal.aborted) return AbortSignal.abort(signal.reason)
8
+ }
9
+ const controller = new AbortController()
10
+ const listeners = signals.map((signal) => {
11
+ const handler = () => controller.abort(signal.reason)
12
+ signal.addEventListener("abort", handler, { once: true })
13
+ return { signal, handler }
14
+ })
15
+ // When one signal wins, detach from the others so a long-lived parent does
16
+ // not accumulate listeners across many requests.
17
+ controller.signal.addEventListener("abort", () => {
18
+ for (const { signal, handler } of listeners) signal.removeEventListener("abort", handler)
19
+ }, { once: true })
20
+ return controller.signal
21
+ }
22
+
23
+ /**
24
+ * AbortSignal.timeout is also not guaranteed in every embedded runtime. Prefer
25
+ * the native implementation; fall back to a timer-driven AbortController.
26
+ */
27
+ export function timeoutSignal(ms: number): AbortSignal {
28
+ if (typeof AbortSignal.timeout === "function") return AbortSignal.timeout(ms)
29
+ const controller = new AbortController()
30
+ const timer = setTimeout(() => controller.abort(), ms)
31
+ // On Node the timer would otherwise hold the process open until it fires.
32
+ // Browsers return a numeric id with no unref — optional call is safe there.
33
+ timer.unref?.()
34
+ controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true })
35
+ return controller.signal
36
+ }
@@ -0,0 +1,24 @@
1
+ import type { Site } from "../shared"
2
+ import type { TokenStore } from "./token-store"
3
+ import { currentSite } from "./site-state"
4
+
5
+ /**
6
+ * Decide which site a `read` should use. An explicit requested site becomes the
7
+ * persisted selection, so a tag switch survives restart. A failed persist must
8
+ * not fail the read — the caller still gets numbers for the requested site.
9
+ */
10
+ export function resolveSite(
11
+ store: Pick<TokenStore, "all" | "select">,
12
+ requested: Site | undefined,
13
+ onError?: (message: string) => void,
14
+ ): Site {
15
+ if (requested === "cn" || requested === "intl") {
16
+ try {
17
+ store.select(requested)
18
+ } catch (error) {
19
+ onError?.(`could not persist selected site: ${String((error as Error)?.message ?? error)}`)
20
+ }
21
+ return requested
22
+ }
23
+ return currentSite(store.all())
24
+ }
@@ -0,0 +1,58 @@
1
+ import type { AccountBrief, Site, SiteInfo } from "../shared"
2
+ import { activeAccount, type TokenCache } from "./token-store"
3
+
4
+ /** A site is available if it has a usable session and refresh has not just failed. */
5
+ const siteAvailable = (
6
+ cache: TokenCache,
7
+ site: Site,
8
+ refreshFailed?: (site: Site) => boolean,
9
+ ): boolean => {
10
+ const auth = activeAccount(cache, site)
11
+ if (!auth) return false
12
+ const now = Date.now()
13
+ // Usable if the access token is still valid, or the refresh token has not expired.
14
+ if (!(now < auth.expiresAt || now < auth.refreshExpiresAt)) return false
15
+ // A recent refresh failure means "needs login" — surface the login button
16
+ // instead of looping on a session that keeps failing to refresh.
17
+ if (refreshFailed?.(site)) return false
18
+ return true
19
+ }
20
+
21
+ export function availableSites(
22
+ cache: TokenCache,
23
+ refreshFailed?: (site: Site) => boolean,
24
+ ): Site[] {
25
+ const sites: Site[] = ["cn", "intl"]
26
+ return sites.filter((s) => siteAvailable(cache, s, refreshFailed))
27
+ }
28
+
29
+ export function currentSite(
30
+ cache: TokenCache,
31
+ refreshFailed?: (site: Site) => boolean,
32
+ ): Site {
33
+ const available = availableSites(cache, refreshFailed)
34
+ if (available.includes(cache.selected)) return cache.selected
35
+ if (available.length === 1) return available[0]
36
+ return cache.selected
37
+ }
38
+
39
+ /** SiteInfo for the GUI: availability + account briefs (never tokens). */
40
+ export function siteInfo(
41
+ cache: TokenCache,
42
+ refreshFailed?: (site: Site) => boolean,
43
+ ): { sites: SiteInfo[]; selected: Site } {
44
+ const sites: SiteInfo[] = (["cn", "intl"] as Site[]).map((site) => {
45
+ const account = activeAccount(cache, site)
46
+ const accounts: AccountBrief[] = cache.accounts[site].map((a) => ({
47
+ id: a.id,
48
+ label: a.uid,
49
+ }))
50
+ return {
51
+ site,
52
+ available: siteAvailable(cache, site, refreshFailed),
53
+ accounts,
54
+ activeId: account?.id ?? null,
55
+ }
56
+ })
57
+ return { sites, selected: currentSite(cache, refreshFailed) }
58
+ }
@@ -0,0 +1,166 @@
1
+ export interface CollectedToolCall {
2
+ index: number
3
+ id: string
4
+ name: string
5
+ arguments: string
6
+ }
7
+
8
+ export interface CollectedCompletion {
9
+ id: string
10
+ model: string
11
+ created: number
12
+ content: string
13
+ reasoning: string
14
+ toolCalls: CollectedToolCall[]
15
+ finishReason: string | null
16
+ usage: Record<string, unknown> | null
17
+ }
18
+
19
+ /**
20
+ * Fold an SSE chat-completion stream into one object. Events are reassembled
21
+ * before parsing: a `data:` line may arrive split across network chunks, and a
22
+ * per-line parser would silently drop half a tool-call's arguments.
23
+ */
24
+ export function collectSse(text: string): CollectedCompletion {
25
+ let id = ""
26
+ let model = ""
27
+ let created = 0
28
+ let content = ""
29
+ let reasoning = ""
30
+ let finishReason: string | null = null
31
+ let usage: Record<string, unknown> | null = null
32
+ const toolCalls = new Map<number, CollectedToolCall>()
33
+
34
+ for (const event of text.split("\n\n")) {
35
+ const dataLines: string[] = []
36
+ for (const line of event.split("\n")) {
37
+ if (!line.startsWith("data:")) continue
38
+ let payload = line.slice("data:".length)
39
+ // SSE allows exactly one optional space after the colon.
40
+ if (payload.startsWith(" ")) payload = payload.slice(1)
41
+ dataLines.push(payload)
42
+ }
43
+ if (dataLines.length === 0) continue
44
+
45
+ // Multiple data lines belong to one event and are joined with a newline;
46
+ // a lone [DONE] line is only a termination marker.
47
+ const payload = dataLines.join("\n").trim()
48
+ if (!payload || payload === "[DONE]") continue
49
+
50
+ let parsed: unknown
51
+ try {
52
+ parsed = JSON.parse(payload)
53
+ } catch {
54
+ // Keep-alive comments and malformed frames must not abort collection.
55
+ continue
56
+ }
57
+ if (!parsed || typeof parsed !== "object") continue
58
+ const chunk = parsed as Record<string, unknown>
59
+
60
+ if (typeof chunk.id === "string") id = chunk.id
61
+ if (typeof chunk.model === "string") model = chunk.model
62
+ if (typeof chunk.created === "number") created = chunk.created
63
+ // usage and finish_reason commonly arrive only in a late frame, so keep
64
+ // overwriting with each non-empty value rather than trusting the first.
65
+ if (chunk.usage && typeof chunk.usage === "object") {
66
+ usage = chunk.usage as Record<string, unknown>
67
+ }
68
+
69
+ const choices = Array.isArray(chunk.choices) ? chunk.choices : []
70
+ for (const choice of choices) {
71
+ if (!choice || typeof choice !== "object") continue
72
+ const c = choice as Record<string, unknown>
73
+ if (typeof c.finish_reason === "string" && c.finish_reason !== "") {
74
+ finishReason = c.finish_reason
75
+ }
76
+ const delta = c.delta
77
+ if (!delta || typeof delta !== "object") continue
78
+ const d = delta as Record<string, unknown>
79
+ if (typeof d.content === "string") content += d.content
80
+ if (typeof d.reasoning_content === "string") reasoning += d.reasoning_content
81
+
82
+ if (Array.isArray(d.tool_calls)) {
83
+ for (const part of d.tool_calls) {
84
+ if (!part || typeof part !== "object") continue
85
+ const tc = part as Record<string, unknown>
86
+ const index = typeof tc.index === "number" ? tc.index : 0
87
+ const collected = toolCalls.get(index) ?? { index, id: "", name: "", arguments: "" }
88
+ // Fragments arrive across frames; appending preserves the full value.
89
+ if (typeof tc.id === "string") collected.id += tc.id
90
+ const fn = tc.function
91
+ if (fn && typeof fn === "object") {
92
+ const f = fn as Record<string, unknown>
93
+ if (typeof f.name === "string") collected.name += f.name
94
+ if (typeof f.arguments === "string") collected.arguments += f.arguments
95
+ }
96
+ toolCalls.set(index, collected)
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ return {
103
+ id,
104
+ model,
105
+ created,
106
+ content,
107
+ reasoning,
108
+ toolCalls: [...toolCalls.values()].sort((a, b) => a.index - b.index),
109
+ finishReason,
110
+ usage,
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Read an SSE body chunk by chunk instead of buffering it with `text()`.
116
+ *
117
+ * A non-streaming client that disconnects mid-completion would otherwise still
118
+ * have the whole answer generated and billed to its quota, so `signal` is
119
+ * checked before every chunk and the body is cancelled on abort. The decoder
120
+ * streams so a multi-byte character split across two chunks is not mangled.
121
+ * `onAbort` is invoked before the cancellation so the caller can close the
122
+ * client response (a cancel alone can leave the reader's loop unresolved).
123
+ */
124
+ export async function collectSseFromStream(
125
+ body: ReadableStream<Uint8Array>,
126
+ opts: { signal?: AbortSignal; onAbort?: () => void } = {},
127
+ ): Promise<string> {
128
+ const reader = body.getReader()
129
+ const decoder = new TextDecoder()
130
+ let text = ""
131
+ for (;;) {
132
+ if (opts.signal?.aborted) {
133
+ opts.onAbort?.()
134
+ await reader.cancel().catch(() => {})
135
+ return text
136
+ }
137
+ const { done, value } = await reader.read()
138
+ if (done) break
139
+ if (value) text += decoder.decode(value, { stream: true })
140
+ }
141
+ return text + decoder.decode()
142
+ }
143
+
144
+ /** Render the collected stream as a single OpenAI `chat.completion` object. */
145
+ export function toChatCompletion(collected: CollectedCompletion): Record<string, unknown> {
146
+ const message: Record<string, unknown> = {
147
+ role: "assistant",
148
+ content: collected.content,
149
+ reasoning_content: collected.reasoning,
150
+ }
151
+ if (collected.toolCalls.length > 0) {
152
+ message.tool_calls = collected.toolCalls.map((tc) => ({
153
+ id: tc.id,
154
+ type: "function",
155
+ function: { name: tc.name, arguments: tc.arguments },
156
+ }))
157
+ }
158
+ return {
159
+ id: collected.id,
160
+ object: "chat.completion",
161
+ created: collected.created,
162
+ model: collected.model,
163
+ choices: [{ index: 0, message, finish_reason: collected.finishReason }],
164
+ usage: collected.usage,
165
+ }
166
+ }
@@ -0,0 +1,263 @@
1
+ import { chmodSync, readFileSync, writeFileSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import type { Site } from "../shared"
5
+ import { refreshHeaders } from "./headers"
6
+ import type { SiteAuth } from "./login"
7
+
8
+ /** Two-site cache. `accounts`/`activeId` reserve room for future multi-account. */
9
+ export interface TokenCache {
10
+ accounts: Record<Site, SiteAuth[]>
11
+ activeId: Record<Site, string | null>
12
+ selected: Site
13
+ }
14
+
15
+ export const CACHE_FILENAME = "codebuddy-quota-auth.json"
16
+
17
+ export function cachePath(dir?: string): string {
18
+ const base = dir ?? join(homedir(), ".config", "opencode")
19
+ return join(base, CACHE_FILENAME)
20
+ }
21
+
22
+ const emptyCache = (): TokenCache => ({
23
+ accounts: { cn: [], intl: [] },
24
+ activeId: { cn: null, intl: null },
25
+ selected: "cn",
26
+ })
27
+
28
+ type ReadFile = () => string
29
+ type WriteFile = (path: string, data: string) => void
30
+
31
+ const defaultRead = (path: string): ReadFile => () => readFileSync(path, "utf8")
32
+ const defaultWrite = (_path: string): WriteFile => (p, data) => {
33
+ writeFileSync(p, data, { mode: 0o600 })
34
+ // `mode` only applies on create; tighten an existing (e.g. 0644) file too.
35
+ try { chmodSync(p, 0o600) } catch { /* no-op on platforms without POSIX modes */ }
36
+ }
37
+
38
+ const isSite = (v: unknown): v is Site => v === "cn" || v === "intl"
39
+
40
+ /** Guard against a hand-corrupted cache entry with missing/ill-typed fields. */
41
+ const isSiteAuth = (v: unknown): v is SiteAuth => {
42
+ if (typeof v !== "object" || v === null) return false
43
+ const a = v as Record<string, unknown>
44
+ return (
45
+ typeof a.id === "string" &&
46
+ typeof a.accessToken === "string" &&
47
+ typeof a.refreshToken === "string" &&
48
+ typeof a.expiresAt === "number" &&
49
+ typeof a.refreshExpiresAt === "number" &&
50
+ typeof a.uid === "string" &&
51
+ typeof a.endpoint === "string" &&
52
+ typeof a.usageHost === "string" &&
53
+ (a.enterpriseId === null || typeof a.enterpriseId === "string")
54
+ )
55
+ }
56
+ const filterAuths = (v: unknown): SiteAuth[] =>
57
+ Array.isArray(v) ? (v as unknown[]).filter(isSiteAuth) : []
58
+
59
+ /** Read the cache, migrating the old flat `{ cn, intl, selected }` format. */
60
+ export function readCache(readFile?: ReadFile): TokenCache {
61
+ const raw = readFile ? readFile() : (() => {
62
+ try {
63
+ return defaultRead(cachePath())()
64
+ } catch {
65
+ return ""
66
+ }
67
+ })()
68
+ if (!raw) return emptyCache()
69
+ let parsed: Record<string, unknown>
70
+ try {
71
+ parsed = JSON.parse(raw) as Record<string, unknown>
72
+ } catch {
73
+ return emptyCache()
74
+ }
75
+
76
+ // New format: { accounts, activeId, selected }
77
+ if (parsed.accounts && typeof parsed.accounts === "object") {
78
+ const accounts = parsed.accounts as Record<string, unknown>
79
+ const active = (parsed.activeId ?? {}) as Record<string, unknown>
80
+ const cn = filterAuths(accounts.cn)
81
+ const intl = filterAuths(accounts.intl)
82
+ const selectSite = isSite(parsed.selected) ? parsed.selected : "cn"
83
+ const pick = (listed: unknown, accounts: SiteAuth[]): string | null => {
84
+ const id = typeof listed === "string" ? listed : (accounts[0]?.id ?? null)
85
+ return id && accounts.some((a) => a.id === id) ? id : (accounts[0]?.id ?? null)
86
+ }
87
+ return {
88
+ accounts: { cn, intl },
89
+ activeId: { cn: pick(active.cn, cn), intl: pick(active.intl, intl) },
90
+ selected: selectSite,
91
+ }
92
+ }
93
+
94
+ // Old format: { cn: SiteAuth|null, intl: SiteAuth|null, selected }
95
+ const cn = isSiteAuth(parsed.cn) ? parsed.cn : null
96
+ const intl = isSiteAuth(parsed.intl) ? parsed.intl : null
97
+ const accounts: Record<Site, SiteAuth[]> = {
98
+ cn: cn ? [cn] : [],
99
+ intl: intl ? [intl] : [],
100
+ }
101
+ return {
102
+ accounts,
103
+ activeId: { cn: cn?.id ?? null, intl: intl?.id ?? null },
104
+ selected: isSite(parsed.selected) ? parsed.selected : "cn",
105
+ }
106
+ }
107
+
108
+ export function writeCache(cache: TokenCache, writeFile?: WriteFile, dir?: string): void {
109
+ const path = cachePath(dir)
110
+ const target = writeFile ?? defaultWrite(path)
111
+ target(path, JSON.stringify(cache, null, 2))
112
+ }
113
+
114
+ /** The currently active account for a site; callers never handle 1 vs N. */
115
+ export function activeAccount(cache: TokenCache, site: Site): SiteAuth | null {
116
+ const id = cache.activeId[site]
117
+ if (!id) return null
118
+ return cache.accounts[site].find((a) => a.id === id) ?? null
119
+ }
120
+
121
+ /** Store/replace an account for its site and make it active there. */
122
+ export function archive(cache: TokenCache, incoming: SiteAuth): TokenCache {
123
+ const site: Site = incoming.id.startsWith("intl:") ? "intl" : "cn"
124
+ const list = cache.accounts[site].filter((a) => a.id !== incoming.id)
125
+ list.push(incoming)
126
+ return {
127
+ ...cache,
128
+ accounts: { ...cache.accounts, [site]: list },
129
+ activeId: { ...cache.activeId, [site]: incoming.id },
130
+ }
131
+ }
132
+
133
+ export function needsRefresh(auth: SiteAuth, now: number): boolean {
134
+ return now >= auth.expiresAt - 5 * 60_000
135
+ }
136
+
137
+ interface RefreshDeps {
138
+ fetchImpl?: typeof fetch
139
+ now?: () => number
140
+ }
141
+
142
+ /** Refresh via the proprietary REST endpoint; token pair rotates. */
143
+ export async function refreshSite(
144
+ auth: SiteAuth,
145
+ deps: RefreshDeps = {},
146
+ ): Promise<SiteAuth> {
147
+ const doFetch = deps.fetchImpl ?? fetch
148
+ const now = deps.now ?? Date.now
149
+ const url = `${auth.endpoint}/v2/plugin/auth/token/refresh`
150
+ const res = await doFetch(url, {
151
+ method: "POST",
152
+ headers: refreshHeaders(auth),
153
+ body: "{}",
154
+ })
155
+ const json = (await res.json()) as {
156
+ code?: number
157
+ msg?: string
158
+ data?: {
159
+ accessToken?: string
160
+ refreshToken?: string
161
+ expiresIn?: number
162
+ refreshExpiresIn?: number
163
+ }
164
+ }
165
+ if (json.code !== 0 || !json.data?.accessToken || !json.data?.refreshToken) {
166
+ throw new Error(`refresh failed: code=${json.code ?? "?"} msg=${json.msg ?? "?"}`)
167
+ }
168
+ const t = now()
169
+ return {
170
+ ...auth,
171
+ accessToken: json.data.accessToken,
172
+ refreshToken: json.data.refreshToken,
173
+ expiresAt: t + (json.data.expiresIn ?? 0) * 1000,
174
+ refreshExpiresAt: t + (json.data.refreshExpiresIn ?? 0) * 1000,
175
+ }
176
+ }
177
+
178
+ export interface TokenStore {
179
+ get(site: Site): SiteAuth | null
180
+ activeAccount(site: Site): SiteAuth | null
181
+ ensureFresh(site: Site): Promise<SiteAuth>
182
+ archive(auth: SiteAuth): void
183
+ select(site: Site): void
184
+ all(): TokenCache
185
+ /** True when the last refresh for this site failed (in-memory only). */
186
+ refreshFailed(site: Site): boolean
187
+ }
188
+
189
+ interface StoreDeps extends RefreshDeps {
190
+ fetchImpl?: typeof fetch
191
+ now?: () => number
192
+ persist?: (cache: TokenCache) => void
193
+ load?: () => TokenCache
194
+ }
195
+
196
+ /** In-memory store backed by the cache file; per-site single-flight refresh. */
197
+ export function createTokenStore(deps: StoreDeps = {}): TokenStore {
198
+ let cache = deps.load ? deps.load() : readCache()
199
+ const persist = deps.persist ?? ((c: TokenCache) => writeCache(c))
200
+ const inFlight: Partial<Record<Site, Promise<SiteAuth>>> = {}
201
+ const refreshErrors: Record<Site, boolean> = { cn: false, intl: false }
202
+ const lastRefreshAt: Partial<Record<Site, number>> = {}
203
+ const nowOf = deps.now ?? Date.now
204
+
205
+ const save = () => persist(cache)
206
+
207
+ return {
208
+ get: (site) => activeAccount(cache, site),
209
+ activeAccount: (site) => activeAccount(cache, site),
210
+ all: () => cache,
211
+ archive: (auth) => {
212
+ cache = archive(cache, auth)
213
+ // A freshly stored credential (login or a successful refresh) makes any
214
+ // prior refresh failure stale. Clear it so the site reads as available
215
+ // again and the amber "needs login" dot disappears.
216
+ const site: Site = auth.id.startsWith("intl:") ? "intl" : "cn"
217
+ refreshErrors[site] = false
218
+ delete lastRefreshAt[site]
219
+ save()
220
+ },
221
+ select: (site) => {
222
+ if (cache.selected !== site) {
223
+ cache = { ...cache, selected: site }
224
+ save()
225
+ }
226
+ },
227
+ refreshFailed: (site) => refreshErrors[site],
228
+ ensureFresh: (site) => {
229
+ const current = activeAccount(cache, site)
230
+ if (!current) return Promise.reject(new Error(`no account for ${site}`))
231
+ if (!needsRefresh(current, nowOf())) return Promise.resolve(current)
232
+ // Cooldown: a short-TTL token that is already inside the 5-minute window
233
+ // must not be refreshed again on every request right after a refresh —
234
+ // but never hand back a token that has actually expired.
235
+ if (
236
+ lastRefreshAt[site] !== undefined &&
237
+ nowOf() - lastRefreshAt[site]! < 60_000 &&
238
+ nowOf() < current.expiresAt
239
+ ) {
240
+ return Promise.resolve(current)
241
+ }
242
+ const existing = inFlight[site]
243
+ if (existing) return existing
244
+ const task = refreshSite(current, deps)
245
+ .then((next) => {
246
+ cache = archive(cache, next)
247
+ refreshErrors[site] = false
248
+ lastRefreshAt[site] = nowOf()
249
+ save()
250
+ return next
251
+ })
252
+ .catch((error) => {
253
+ refreshErrors[site] = true
254
+ throw error
255
+ })
256
+ .finally(() => {
257
+ delete inFlight[site]
258
+ })
259
+ inFlight[site] = task
260
+ return task
261
+ },
262
+ }
263
+ }