opencode-codebuddy-quota 0.1.3 → 0.1.5

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,62 @@
1
+ const JSON_MEDIA_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/i
2
+
3
+ /** Exact media-type comparison: `application/jsonp` must not pass for JSON. */
4
+ export function isJsonContentType(value: string | null): boolean {
5
+ if (!value) return false
6
+ const mediaType = value.split(";", 1)[0].trim()
7
+ return JSON_MEDIA_TYPE.test(mediaType)
8
+ }
9
+
10
+ /**
11
+ * OpenCode (through the AI SDK) only surfaces `error.message` from an OpenAI-shaped
12
+ * error body; anything else degrades to the HTTP status phrase ("Too Many Requests").
13
+ * Map the status the same way the SDK classifies it so clients keep their retry policy.
14
+ */
15
+ function errorTypeForStatus(status: number): string {
16
+ if (status === 401 || status === 403) return "authentication_error"
17
+ if (status === 402) return "insufficient_quota"
18
+ if (status === 429) return "rate_limit_exceeded"
19
+ if (status >= 500) return "api_error"
20
+ return "invalid_request_error"
21
+ }
22
+
23
+ function isRecord(value: unknown): value is Record<string, unknown> {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value)
25
+ }
26
+
27
+ /**
28
+ * Rewrite CodeBuddy's `{ code, msg }` envelope into the OpenAI error shape so the
29
+ * upstream reason reaches the client instead of being replaced by the status text.
30
+ *
31
+ * Returns `null` when the body must be passed through verbatim: non-JSON content,
32
+ * unparseable text, an already OpenAI-shaped error, or a missing/blank `msg`.
33
+ * The status never decides *whether* to rewrite; it only picks `error.type`.
34
+ * Callers must keep it as-is.
35
+ */
36
+ export function normalizeUpstreamError(status: number, contentType: string | null, body: string): string | null {
37
+ if (!isJsonContentType(contentType)) return null
38
+
39
+ let parsed: unknown
40
+ try {
41
+ parsed = JSON.parse(body)
42
+ } catch {
43
+ return null
44
+ }
45
+ if (!isRecord(parsed)) return null
46
+
47
+ const existing = parsed.error
48
+ if (isRecord(existing) && typeof existing.message === "string") return null
49
+
50
+ const rawMessage = parsed.msg
51
+ if (typeof rawMessage !== "string") return null
52
+ if (rawMessage.trim() === "") return null
53
+
54
+ // Keep the upstream code and request id: they are what upstream support asks for,
55
+ // and the SDK ignores unknown keys so they cost nothing on the client side.
56
+ // OpenAI defines `code` as a string, so a numeric upstream code is stringified.
57
+ const error: Record<string, unknown> = { message: rawMessage, type: errorTypeForStatus(status) }
58
+ if (typeof parsed.code === "number" || typeof parsed.code === "string") error.code = String(parsed.code)
59
+ if (typeof parsed.requestId === "string") error.request_id = parsed.requestId
60
+
61
+ return JSON.stringify({ error })
62
+ }
@@ -10,7 +10,7 @@ import type { ModelMapping } from "./config"
10
10
  * which is exactly why the mapping names the provider rather than inferring it.
11
11
  */
12
12
 
13
- /** models.dev v3 sometimes declares cache.write as per-duration tiers, e.g. {"5m":3,"1h":6}. */
13
+ /** models.dev sometimes declares cache.write as per-duration tiers, e.g. {"5m":3,"1h":6}. */
14
14
  export type CacheWritePrice = number | Record<string, number>
15
15
 
16
16
  export interface ModelsDevCost {
@@ -35,7 +35,7 @@ export interface ModelsDevEntry {
35
35
  }
36
36
  }
37
37
 
38
- /** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:v3:catalog`. */
38
+ /** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:v4:catalog`. */
39
39
  export type ModelsDevCatalog = Record<string, { models?: Record<string, ModelsDevEntry> }>
40
40
 
41
41
  export interface ModelCost {
@@ -101,7 +101,7 @@ function toCost(entry: ModelsDevEntry): ModelCost | null {
101
101
  return {
102
102
  input,
103
103
  output,
104
- // Most catalog entries omit cache.write; some v3 entries declare it as a
104
+ // Most catalog entries omit cache.write; some declare it as a
105
105
  // per-duration tier object. Neither is a usable scalar, so fall back to zero.
106
106
  cache: {
107
107
  read: finitePrice(text?.input?.cache?.read),
@@ -1,9 +1,11 @@
1
1
  import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
2
2
  import type { Site } from "../shared"
3
3
  import { createLocalEmbedder, isLocalModel, routeEmbedding, type LocalEmbedding } from "./embedding-local"
4
+ import type { RateLimitStore } from "./rate-limit-store"
4
5
  import { apiHeaders, channelHeaders } from "./headers"
5
6
  import { SITE_ENDPOINTS } from "./login"
6
7
  import type { ModelsListResponse } from "./models-endpoint"
8
+ import { isJsonContentType, normalizeUpstreamError } from "./openai-error"
7
9
  import { collectSse, collectSseFromStream, toChatCompletion } from "./stream-collect"
8
10
  import type { TokenStore } from "./token-store"
9
11
 
@@ -114,6 +116,26 @@ export interface ProxyResponse {
114
116
  end(chunk?: string | Uint8Array): void
115
117
  }
116
118
 
119
+ /**
120
+ * Pull a human-readable upstream message from a 429 body. `normalized` is the
121
+ * rewritten OpenAI error (null when the body was already OpenAI-shaped or bad);
122
+ * fall back through the raw text so the notice always carries a string.
123
+ */
124
+ function extractErrorMessage(normalized: string | null, text: string): string {
125
+ if (normalized) {
126
+ try {
127
+ const m = (JSON.parse(normalized) as { error?: { message?: unknown } }).error?.message
128
+ if (typeof m === "string" && m !== "") return m
129
+ } catch { /* fall through */ }
130
+ }
131
+ try {
132
+ const parsed = JSON.parse(text) as { error?: { message?: unknown }; msg?: unknown }
133
+ if (typeof parsed?.error?.message === "string" && parsed.error.message !== "") return parsed.error.message
134
+ if (typeof parsed?.msg === "string" && parsed.msg !== "") return parsed.msg
135
+ } catch { /* fall through */ }
136
+ return text || "HTTP 429"
137
+ }
138
+
117
139
  export interface HandleRequestDeps {
118
140
  store: TokenStore
119
141
  fetchImpl?: typeof fetch
@@ -135,6 +157,8 @@ export interface HandleRequestDeps {
135
157
  embeddingTimeoutMs?: number
136
158
  /** Configured backend for embeddings; absent keeps the legacy body-prefix routing. */
137
159
  embeddingMode?: "cloud" | "local"
160
+ /** Optional best-effort recorder of model-level 429 limits. */
161
+ rateLimitStore?: RateLimitStore
138
162
  }
139
163
 
140
164
  /** Emit OpenAI's error envelope, not a stack trace or a gateway-specific body. */
@@ -319,6 +343,12 @@ export async function handleRequest(
319
343
  const readBody = deps.readBody ?? (() => Promise.resolve(""))
320
344
  // Read once: `readBody` is an injectable seam and need not be replayable.
321
345
  const raw = await readBody(req)
346
+ // The model id identifies the rate-limit bucket; absent on non-chat/malformed bodies.
347
+ let chatModel: string | undefined
348
+ try {
349
+ const parsed = JSON.parse(raw) as { model?: unknown }
350
+ if (typeof parsed?.model === "string" && parsed.model !== "") chatModel = parsed.model
351
+ } catch { /* not a JSON chat body */ }
322
352
  const isEmbeddings = pathAfterV2 === EMBEDDINGS_PATH
323
353
  // A local-mode embedding (configured, or a legacy `Xenova/*` body id) runs
324
354
  // in-process, so it must return before the upstream fetch and before any auth
@@ -438,7 +468,14 @@ export async function handleRequest(
438
468
  }
439
469
 
440
470
  // Plain OpenAI clients expect a single JSON object. Upstream errors are never
441
- // aggregated — they pass through unchanged so error bodies stay intact.
471
+ // aggregated; a chat error that is a JSON envelope gets normalized below so
472
+ // clients can read the real reason instead of the HTTP status phrase.
473
+ // A successful chat request clears any prior limit for this (site, model) —
474
+ // covers both the streaming and aggregate paths, and never runs for a 429.
475
+ if (isChat && upstream.ok && chatModel) {
476
+ try { deps.rateLimitStore?.clear(site, chatModel) } catch { /* best-effort */ }
477
+ }
478
+
442
479
  const isAggregate = !wantsStream && upstream.ok && isChat
443
480
  if (isAggregate) {
444
481
  // Aggregate through a reader rather than `text()`: a client that walks away
@@ -473,6 +510,57 @@ export async function handleRequest(
473
510
  )
474
511
  }
475
512
 
513
+ // 429 chat errors: record the model-level limit (best-effort) and rewrite the
514
+ // body so the client sees the upstream reason. `text()` is read exactly once —
515
+ // both the recorder and the response rewrite reuse it.
516
+ if (isChat && upstream.status === 429) {
517
+ const text = await upstream.text()
518
+ if (deps.signal?.aborted) return
519
+ const ct = upstream.headers.get("content-type")
520
+ const normalized = isJsonContentType(ct) ? normalizeUpstreamError(429, ct, text) : null
521
+ if (chatModel) {
522
+ try {
523
+ deps.rateLimitStore?.record(site, chatModel, {
524
+ message: extractErrorMessage(normalized, text),
525
+ retryAfter: upstream.headers.get("retry-after"),
526
+ at: Date.now(),
527
+ })
528
+ } catch { /* rate-limit notice is best-effort */ }
529
+ }
530
+ copyHeaders(upstream.headers, res)
531
+ if (normalized !== null) {
532
+ res.setHeader("Content-Type", "application/json; charset=utf-8")
533
+ res.status(429)
534
+ res.end(normalized)
535
+ return
536
+ }
537
+ res.status(429)
538
+ res.end(text)
539
+ return
540
+ }
541
+
542
+ // Side effect only for chat errors: the AI SDK derives `error.message` from an
543
+ // OpenAI-shaped body and falls back to the status phrase otherwise, which hides
544
+ // the upstream reason ("Too Many Requests"). Keep the status so the client's
545
+ // classification and backoff stay unchanged; only the body is rewritten.
546
+ if (isChat && !upstream.ok && isJsonContentType(upstream.headers.get("content-type"))) {
547
+ const text = await upstream.text()
548
+ if (deps.signal?.aborted) return
549
+ const normalized = normalizeUpstreamError(upstream.status, upstream.headers.get("content-type"), text)
550
+ // Copy first so retry-after and other hints survive, then override the type:
551
+ // headers must be set before status(), which is where Node emits the head.
552
+ copyHeaders(upstream.headers, res)
553
+ if (normalized !== null) {
554
+ res.setHeader("Content-Type", "application/json; charset=utf-8")
555
+ res.status(upstream.status)
556
+ res.end(normalized)
557
+ return
558
+ }
559
+ res.status(upstream.status)
560
+ res.end(text)
561
+ return
562
+ }
563
+
476
564
  copyHeaders(upstream.headers, res)
477
565
  res.status(upstream.status)
478
566
 
@@ -524,6 +612,7 @@ export function createProxy(deps: {
524
612
  createLocalEmbedder?: (modelId?: string) => LocalEmbedding
525
613
  embeddingTimeoutMs?: number
526
614
  embeddingMode?: "cloud" | "local"
615
+ rateLimitStore?: RateLimitStore
527
616
  listenOptions?: ListenOptions
528
617
  }): ProxyServer {
529
618
  const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
@@ -578,6 +667,7 @@ export function createProxy(deps: {
578
667
  createLocalEmbedder: deps.createLocalEmbedder,
579
668
  embeddingTimeoutMs: deps.embeddingTimeoutMs,
580
669
  embeddingMode: deps.embeddingMode,
670
+ rateLimitStore: deps.rateLimitStore,
581
671
  },
582
672
  ).catch(() => {
583
673
  if (controller.signal.aborted) return
@@ -0,0 +1,102 @@
1
+ import { join } from "node:path"
2
+ import { readFileSync, writeFileSync } from "node:fs"
3
+ import type { RateLimitInfo, Site } from "../shared"
4
+ import { configDir } from "./config"
5
+
6
+ /** The full record kept on disk; the GUI only receives the 4-field RateLimitInfo. */
7
+ export type StoredRateLimitInfo = RateLimitInfo & { retryAfter: string | null; at: number }
8
+
9
+ export interface RateLimitStore {
10
+ record(site: Site, model: string, input: { message: string; retryAfter: string | null; at: number }): void
11
+ list(site: Site): StoredRateLimitInfo[]
12
+ clear(site: Site, model: string): void
13
+ }
14
+
15
+ export interface RateLimitStoreDeps {
16
+ path?: string
17
+ readFile?: (path: string) => string
18
+ writeFile?: (path: string, content: string) => void
19
+ now?: () => number
20
+ }
21
+
22
+ const SECONDS = /(\d+)\s*(秒|s|sec|seconds)/i
23
+ const MINUTES = /(\d+)\s*(分|分钟|m|min|minutes)/i
24
+
25
+ /**
26
+ * Resolve the moment a 429 lifts: retry-after first (integer seconds or an HTTP
27
+ * date), then a relative-time phrase in the upstream message, else null (the
28
+ * notice stays until a successful request clears it).
29
+ */
30
+ export function parseUnlockAt(retryAfter: string | null, message: string, now: number): number | null {
31
+ if (retryAfter) {
32
+ if (/^\d+$/.test(retryAfter.trim())) {
33
+ return now + Number(retryAfter.trim()) * 1000
34
+ }
35
+ const parsed = Date.parse(retryAfter)
36
+ if (Number.isFinite(parsed)) return parsed
37
+ }
38
+ const min = MINUTES.exec(message)
39
+ if (min) return now + Number(min[1]) * 60_000
40
+ const sec = SECONDS.exec(message)
41
+ if (sec) return now + Number(sec[1]) * 1000
42
+ return null
43
+ }
44
+
45
+ export function createRateLimitStore(deps: RateLimitStoreDeps = {}): RateLimitStore {
46
+ const path = deps.path ?? join(configDir(), "codebuddy-quota-ratelimit.json")
47
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
48
+ const write = deps.writeFile ?? ((p: string, s: string) => writeFileSync(p, s, "utf8"))
49
+ const now = deps.now ?? Date.now
50
+
51
+ const load = (): StoredRateLimitInfo[] => {
52
+ try {
53
+ const parsed = JSON.parse(read(path)) as { entries?: unknown }
54
+ if (!Array.isArray(parsed.entries)) return []
55
+ return parsed.entries.filter(
56
+ (e): e is StoredRateLimitInfo =>
57
+ !!e &&
58
+ typeof e === "object" &&
59
+ (e as StoredRateLimitInfo).site !== undefined &&
60
+ typeof (e as StoredRateLimitInfo).model === "string" &&
61
+ typeof (e as StoredRateLimitInfo).message === "string",
62
+ )
63
+ } catch {
64
+ return []
65
+ }
66
+ }
67
+
68
+ const save = (entries: StoredRateLimitInfo[]) => {
69
+ try {
70
+ write(path, JSON.stringify({ entries }, null, 2))
71
+ } catch {
72
+ // A rate-limit notice is best-effort; a failed write must not affect the proxy.
73
+ }
74
+ }
75
+
76
+ const matches = (e: StoredRateLimitInfo, site: Site, model: string) =>
77
+ e.site === site && e.model === model
78
+
79
+ return {
80
+ record(site, model, input) {
81
+ const entries = load().filter((e) => !matches(e, site, model))
82
+ entries.push({
83
+ site,
84
+ model,
85
+ message: input.message,
86
+ retryAfter: input.retryAfter,
87
+ at: input.at,
88
+ unlockAt: parseUnlockAt(input.retryAfter, input.message, now()),
89
+ })
90
+ save(entries)
91
+ },
92
+ list(site) {
93
+ return load()
94
+ .filter((e) => e.site === site)
95
+ .filter((e) => e.unlockAt === null || e.unlockAt > now())
96
+ .sort((a, b) => (a.unlockAt ?? Infinity) - (b.unlockAt ?? Infinity))
97
+ },
98
+ clear(site, model) {
99
+ save(load().filter((e) => !matches(e, site, model)))
100
+ },
101
+ }
102
+ }
@@ -1,9 +1,10 @@
1
- import type { Site } from "../shared"
1
+ import type { RateLimitInfo, Site } from "../shared"
2
2
  import { createLoginGate, type LoginGate } from "./login-gate"
3
3
  import { getAuthState, openBrowser, pollToken, type SiteAuth } from "./login"
4
4
  import { resolveSite } from "./site-select"
5
5
  import { siteInfo } from "./site-state"
6
6
  import type { TokenStore } from "./token-store"
7
+ import type { RateLimitStore } from "./rate-limit-store"
7
8
  import type { QuotaSource, Reading } from "./quota-source"
8
9
  import { toWireReading, type WireReading } from "./wire"
9
10
 
@@ -11,6 +12,7 @@ import { toWireReading, type WireReading } from "./wire"
11
12
  export interface RpcHandlers {
12
13
  read(input: unknown, context: { signal: AbortSignal }): Promise<WireReading>
13
14
  login(input: unknown): Promise<{ ok: boolean; error: string | null }>
15
+ config(): Promise<{ refreshMinutes: number }>
14
16
  }
15
17
 
16
18
  export interface HandlerDeps {
@@ -26,6 +28,10 @@ export interface HandlerDeps {
26
28
  * can re-import its provider models. A failure here never fails the login.
27
29
  */
28
30
  afterLogin?: (site: Site) => Promise<void>
31
+ /** Background refresh interval in minutes; optional so existing callers need not set it. */
32
+ refreshMinutes?: number
33
+ /** Best-effort source of model-level rate limits; absent yields an empty list. */
34
+ rateLimitStore?: RateLimitStore
29
35
  }
30
36
 
31
37
  /**
@@ -53,7 +59,15 @@ export function makeRpcHandlers(deps: HandlerDeps): RpcHandlers {
53
59
  // Read the cache AFTER the refresh so a rotated token cannot leave a
54
60
  // stale "needs login" tag next to freshly returned numbers.
55
61
  const state = deps.store.all()
56
- return toWireReading(reading, { site, sites: siteInfo(state, (s) => deps.store.refreshFailed(s)).sites })
62
+ // Project to the 4-field wire shape so `additionalProperties:false` in the
63
+ // RPC schema stays satisfied (the store also keeps retryAfter/at internally).
64
+ const rateLimits: RateLimitInfo[] = (deps.rateLimitStore?.list(site) ?? []).map(
65
+ ({ site: s, model, message, unlockAt }) => ({ site: s, model, message, unlockAt }),
66
+ )
67
+ return toWireReading(reading, { site, sites: siteInfo(state, (s) => deps.store.refreshFailed(s)).sites }, rateLimits)
68
+ },
69
+ async config() {
70
+ return { refreshMinutes: deps.refreshMinutes ?? 10 }
57
71
  },
58
72
  async login(input) {
59
73
  const site = (input as { site: Site }).site
@@ -0,0 +1,17 @@
1
+ import type { GatewaySetup } from "./gateway-setup"
2
+
3
+ /**
4
+ * Register the RPC handlers before acquiring the gateway. The GUI fires its
5
+ * first quota read the moment it mounts, so a handler that is only registered
6
+ * after the gateway bind leaves a window where that read gets a 400 and the
7
+ * battery shows a stale hatch. Registering first closes that window; the
8
+ * gateway's register callback merely reuses the same registration.
9
+ */
10
+ export async function registerThenGateway<T>(deps: {
11
+ register(): Promise<T>
12
+ setupGateway(deps: { register(): Promise<T> }): Promise<GatewaySetup>
13
+ }): Promise<{ registration: T; gw: GatewaySetup }> {
14
+ const registration = await deps.register()
15
+ const gw = await deps.setupGateway({ register: async () => registration })
16
+ return { registration, gw }
17
+ }
@@ -1,4 +1,4 @@
1
- import type { SiteInfo } from "../shared"
1
+ import type { RateLimitInfo, SiteInfo } from "../shared"
2
2
  import type { Reading } from "./quota-source"
3
3
 
4
4
  /** The object the RPC returns; the fields mirror `rpc.ts`'s output schema. */
@@ -19,6 +19,8 @@ export interface WireReading {
19
19
  error: string | null
20
20
  site: "cn" | "intl"
21
21
  sites: SiteInfo[]
22
+ /** Active model-level limits for the requested site; empty when none. */
23
+ rateLimits: RateLimitInfo[]
22
24
  }
23
25
 
24
26
  /**
@@ -31,6 +33,7 @@ export interface WireReading {
31
33
  export function toWireReading(
32
34
  reading: Reading,
33
35
  info: { site: "cn" | "intl"; sites: SiteInfo[] },
36
+ rateLimits: RateLimitInfo[] = [],
34
37
  ): WireReading {
35
38
  const numbers = {
36
39
  remaining: reading.remaining,
@@ -58,10 +61,11 @@ export function toWireReading(
58
61
  fetchedAt: null,
59
62
  site: info.site,
60
63
  sites: info.sites,
64
+ rateLimits,
61
65
  }
62
66
  }
63
67
  return {
64
68
  ok: true, stale: reading.stale, cached: reading.cached, ageSeconds: reading.ageSeconds,
65
- ...numbers, site: info.site, sites: info.sites,
69
+ ...numbers, site: info.site, sites: info.sites, rateLimits,
66
70
  }
67
71
  }
package/src/shared.ts CHANGED
@@ -21,3 +21,12 @@ export interface SiteInfo {
21
21
  accounts: AccountBrief[]
22
22
  activeId: string | null
23
23
  }
24
+
25
+ /** A rate-limit notice sent to the GUI: one per (site, model). */
26
+ export interface RateLimitInfo {
27
+ site: Site
28
+ model: string
29
+ message: string
30
+ /** Epoch ms when the limit lifts, or null when unknown (cleared on success). */
31
+ unlockAt: number | null
32
+ }