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,564 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
2
+ import type { Site } from "../shared"
3
+ import { createLocalEmbedder, isLocalModel, routeEmbedding, type LocalEmbedding } from "./embedding-local"
4
+ import { apiHeaders, channelHeaders } from "./headers"
5
+ import { SITE_ENDPOINTS } from "./login"
6
+ import type { ModelsListResponse } from "./models-endpoint"
7
+ import { collectSse, collectSseFromStream, toChatCompletion } from "./stream-collect"
8
+ import type { TokenStore } from "./token-store"
9
+
10
+ /**
11
+ * Exact wire body of `GET /health`. Cross-task contract: a later probe parses
12
+ * `status === "ok" && service === "codebuddy-quota"`, so both the keys and the
13
+ * spelling are part of the API. Export it instead of duplicating the literal.
14
+ */
15
+ export const HEALTH_BODY = '{"status":"ok","service":"codebuddy-quota"}'
16
+
17
+ export function routeSite(url: string): Site | null {
18
+ if (url.startsWith("/cn/v2/")) return "cn"
19
+ if (url.startsWith("/intl/v2/")) return "intl"
20
+ return null
21
+ }
22
+
23
+ export function upstreamUrl(site: Site, pathAfterV2: string): string {
24
+ return `${SITE_ENDPOINTS[site].endpoint}/v2/${pathAfterV2}`
25
+ }
26
+
27
+ /**
28
+ * The path after `/v2/` with any query string stripped.
29
+ *
30
+ * Every route decision in `handleRequest` (embeddings, models, Accept
31
+ * injection, aggregation) must key off this one helper: keying some branches off
32
+ * the raw `req.url` made `?foo=1` silently skip aggregation, and a `startsWith`
33
+ * test accepted nonsense like `chat/completionsXYZ`.
34
+ */
35
+ export function pathOf(url: string): string {
36
+ const after = url.split("/v2/")[1] ?? ""
37
+ const query = after.indexOf("?")
38
+ return query === -1 ? after : after.slice(0, query)
39
+ }
40
+
41
+ /** Local, quota-free routes; each is matched exactly, never by prefix. */
42
+ const EMBEDDINGS_PATH = "embeddings"
43
+ const MODELS_PATH = "models"
44
+ const CHAT_PATH = "chat/completions"
45
+
46
+ /**
47
+ * Input limits for the in-process embedder. transformers.js runs on the same
48
+ * event loop as every proxied chat stream, so one oversized embeddings call
49
+ * would stall unrelated conversations. bge-m3 truncates at 8192 tokens, so
50
+ * 20000 characters is already past everything the model reads, and 64 inputs
51
+ * keeps one batch's compute bounded while matching the batch sizes clients use.
52
+ */
53
+ const MAX_EMBEDDING_INPUTS = 64
54
+ const MAX_EMBEDDING_CHARS = 20_000
55
+
56
+ /**
57
+ * Budget for a warm local `embed` call. A cold build (~600 MB download) is not
58
+ * timed on purpose: a fixed limit would turn a slow first download into a
59
+ * spurious 502. This only bounds compute on an already-built pipeline.
60
+ */
61
+ const EMBEDDING_TIMEOUT_MS = 30_000
62
+
63
+ /**
64
+ * `routeEmbedding` only accepts ids with the local `Xenova/` prefix. When the
65
+ * configured mode is local, the request body's `model` is an arbitrary
66
+ * identifier and must not decide routing, so the router gets this fixed
67
+ * internal id and the caller's id is restored on the response instead.
68
+ */
69
+ const INTERNAL_LOCAL_MODEL = "Xenova/bge-m3"
70
+
71
+ /** Reject with `reason` after `ms`, clearing the timer when `task` settles. */
72
+ function withTimeout<T>(task: Promise<T>, ms: number, reason: string): Promise<T> {
73
+ return new Promise<T>((resolve, reject) => {
74
+ const timer = setTimeout(() => reject(new Error(reason)), ms)
75
+ timer.unref?.()
76
+ task.then(
77
+ (value) => { clearTimeout(timer); resolve(value) },
78
+ (error: unknown) => { clearTimeout(timer); reject(error) },
79
+ )
80
+ })
81
+ }
82
+
83
+ /** The bits of an HTTP request the handler needs. */
84
+ export interface ProxyRequest {
85
+ url: string
86
+ method?: string
87
+ headers?: Record<string, string | string[] | undefined>
88
+ }
89
+
90
+ /** The bits of an HTTP response the handler writes to. */
91
+ export interface ProxyResponse {
92
+ status(code: number): void
93
+ setHeader(name: string, value: string): void
94
+ write(chunk: string | Uint8Array): void
95
+ end(chunk?: string | Uint8Array): void
96
+ }
97
+
98
+ export interface HandleRequestDeps {
99
+ store: TokenStore
100
+ fetchImpl?: typeof fetch
101
+ /** Reads the inbound body; injectable so the handler is testable without a socket. */
102
+ readBody?: (req: ProxyRequest) => Promise<string>
103
+ /** Aborts when the client disconnects, so we stop the upstream SSE stream. */
104
+ signal?: AbortSignal
105
+ /** Optional logger; errors are logged here, never echoed to the client body. */
106
+ log?: (message: string) => void
107
+ /** Local source for GET /v2/models; unwired in tests that don't exercise it. */
108
+ models?: (site: Site) => Promise<ModelsListResponse>
109
+ /** In-process embedder for `Xenova/*` model ids; defaults to the lazy ONNX one. */
110
+ local?: LocalEmbedding
111
+ /** Configured local model id for the lazy fallback; undefined keeps the shipped default. */
112
+ localEmbeddingModel?: string
113
+ /** Factory seam so tests can observe the id without triggering a real download. */
114
+ createLocalEmbedder?: (modelId?: string) => LocalEmbedding
115
+ /** Budget for one warm local `embed` call; injectable so a test need not wait 30s. */
116
+ embeddingTimeoutMs?: number
117
+ /** Configured backend for embeddings; absent keeps the legacy body-prefix routing. */
118
+ embeddingMode?: "cloud" | "local"
119
+ }
120
+
121
+ /** Emit OpenAI's error envelope, not a stack trace or a gateway-specific body. */
122
+ function sendModelsError(res: ProxyResponse, status: number, type: string, code: string, message: string): void {
123
+ res.setHeader("Content-Type", "application/json")
124
+ res.status(status)
125
+ res.end(JSON.stringify({ error: { message, type, code } }))
126
+ }
127
+
128
+ /** Pull the model id and input out of an embeddings body, or null when unusable. */
129
+ function parseEmbeddingBody(
130
+ raw: string,
131
+ ): { model: string; input: string | string[] } | null {
132
+ try {
133
+ const parsed = JSON.parse(raw) as { model?: unknown; input?: unknown } | null
134
+ const model = parsed?.model
135
+ const input = parsed?.input
136
+ if (typeof model !== "string" || model === "") return null
137
+ if (typeof input === "string") return { model, input }
138
+ // OpenAI also allows token arrays (and arrays of them); transformers.js only
139
+ // takes text. A batch is all-strings or nothing: a mixed array like
140
+ // `["a", ["b"]]` would otherwise reach the extractor and be read as
141
+ // vocabulary ids, producing a silent garbage vector.
142
+ if (Array.isArray(input) && input.every((part) => typeof part === "string")) {
143
+ return { model, input }
144
+ }
145
+ return null
146
+ } catch {
147
+ return null
148
+ }
149
+ }
150
+
151
+ /**
152
+ * True when the body names a local `Xenova/*` model but its `input` is not a
153
+ * plain string or a plain array of strings.
154
+ *
155
+ * `parseEmbeddingBody` returns null for those shapes — it cannot tell why — so
156
+ * the model id is read separately here. Without this, `Xenova/bge-m3` with a
157
+ * token array would fall through to the cloud path and be forwarded, which the
158
+ * caller has every reason not to expect.
159
+ */
160
+ function rawModelIsLocalButUnsupported(raw: string): boolean {
161
+ try {
162
+ const parsed = JSON.parse(raw) as { model?: unknown } | null
163
+ return typeof parsed?.model === "string" && isLocalModel(parsed.model)
164
+ } catch {
165
+ return false
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Name the reason an input set cannot be answered within the local budget, or
171
+ * null when it is acceptable.
172
+ */
173
+ function oversizeEmbeddingReason(input: string | string[]): string | null {
174
+ const parts = Array.isArray(input) ? input : [input]
175
+ if (parts.length === 0) return "input must not be empty"
176
+ if (parts.length > MAX_EMBEDDING_INPUTS) {
177
+ return `input must contain at most ${MAX_EMBEDDING_INPUTS} strings`
178
+ }
179
+ if (parts.some((part) => part.length > MAX_EMBEDDING_CHARS)) {
180
+ return `each input must be at most ${MAX_EMBEDDING_CHARS} characters`
181
+ }
182
+ return null
183
+ }
184
+
185
+ /** Official identity the intl gateway requires as the first system message. */
186
+ const SYSTEM_PROMPT = "You are CodeBuddy Code."
187
+
188
+ /** Extract plain text from a message content (string or multimodal text parts). */
189
+ function identityText(content: unknown): string | null {
190
+ if (typeof content === "string") return content
191
+ if (Array.isArray(content)) {
192
+ return content
193
+ .filter((part) => part && typeof part === "object" && (part as { type?: unknown }).type === "text")
194
+ .map((part) => String((part as { text?: unknown }).text ?? ""))
195
+ .join("\n")
196
+ }
197
+ return null
198
+ }
199
+
200
+ /**
201
+ * Force `stream:true`, and for intl prepend the official system prompt the
202
+ * gateway's channel verification checks for. A caller-supplied leading system
203
+ * message is kept as-is; only the identity prompt is prepended when missing.
204
+ */
205
+ function prepareBody(body: string, site: Site, pathAfterV2: string): string {
206
+ // /embeddings has no stream concept; injecting it makes the gateway answer
207
+ // 10001 "Unmarshal embedding params failed".
208
+ if (pathAfterV2 === EMBEDDINGS_PATH) return body
209
+ try {
210
+ const parsed = JSON.parse(body) as Record<string, unknown>
211
+ parsed.stream = true
212
+ if (site === "intl" && Array.isArray(parsed.messages) && parsed.messages.length > 0) {
213
+ const messages = parsed.messages as Array<{ role?: unknown; content?: unknown }>
214
+ // The gate requires the identity specifically as a *system* message; a
215
+ // developer-role copy does not satisfy it (verified against the gateway).
216
+ // Normalise content (string or multimodal text parts) and compare exactly:
217
+ // a loose substring would mistake an unrelated message mentioning the
218
+ // name for the identity, while a bare `===` would miss trailing whitespace
219
+ // and inject a duplicate. The identity may sit at any position — only
220
+ // duplicates are avoided (verified against the gateway).
221
+ const hasIdentity = messages.some(
222
+ (m) => m?.role === "system" && identityText(m?.content)?.trim() === SYSTEM_PROMPT,
223
+ )
224
+ if (!hasIdentity) parsed.messages = [{ role: "system", content: SYSTEM_PROMPT }, ...messages]
225
+ }
226
+ return JSON.stringify(parsed)
227
+ } catch {
228
+ return body
229
+ }
230
+ }
231
+
232
+ const copyHeaders = (from: Headers, to: ProxyResponse): void => {
233
+ for (const [key, value] of from.entries()) {
234
+ // Hop-by-hop / framing / content-encoding headers are unsafe to forward:
235
+ // undici already decompressed the body, so a forwarded gzip header would
236
+ // make strict clients try to gunzip plain text.
237
+ if (
238
+ key === "content-length" ||
239
+ key === "transfer-encoding" ||
240
+ key === "connection" ||
241
+ key === "content-encoding" ||
242
+ key === "keep-alive" ||
243
+ key === "upgrade" ||
244
+ key === "trailer"
245
+ ) continue
246
+ to.setHeader(key, value)
247
+ }
248
+ }
249
+
250
+ export async function handleRequest(
251
+ req: ProxyRequest,
252
+ res: ProxyResponse,
253
+ deps: HandleRequestDeps,
254
+ ): Promise<void> {
255
+ // Identify this listener before routing, auth, or the body read: the probe
256
+ // must be answered even with no account configured. Exact match only — a
257
+ // lookalike path must keep its existing 404 behaviour.
258
+ if ((req.method === "GET" || req.method === undefined) && req.url === "/health") {
259
+ res.setHeader("Content-Type", "application/json")
260
+ res.status(200)
261
+ res.end(HEALTH_BODY)
262
+ return
263
+ }
264
+
265
+ const site = routeSite(req.url ?? "")
266
+ if (!site) {
267
+ res.status(404)
268
+ res.end("not found")
269
+ return
270
+ }
271
+
272
+ // The cloud has no /v2/models route; serve the list locally so OpenAI clients
273
+ // can discover exactly the models the provider actually imported. This must
274
+ // return before any upstream fetch.
275
+ const pathAfterV2 = pathOf(req.url ?? "")
276
+ if (req.method === "GET" && pathAfterV2 === MODELS_PATH) {
277
+ if (!deps.models) {
278
+ sendModelsError(res, 501, "not_implemented", "not_implemented", "models endpoint is not available")
279
+ return
280
+ }
281
+ // No account means there is no catalog to build the list from.
282
+ if (!deps.store.get(site)) {
283
+ sendModelsError(res, 503, "service_unavailable", "no_account", `no account for ${site}`)
284
+ return
285
+ }
286
+ let list: ModelsListResponse
287
+ try {
288
+ list = await deps.models(site)
289
+ } catch (error) {
290
+ deps.log?.(`models endpoint error: ${String((error as Error)?.message ?? error)}`)
291
+ sendModelsError(res, 502, "bad_gateway", "catalog_failed", "failed to load the model catalog")
292
+ return
293
+ }
294
+ res.setHeader("Content-Type", "application/json")
295
+ res.status(200)
296
+ res.end(JSON.stringify(list))
297
+ return
298
+ }
299
+
300
+ const readBody = deps.readBody ?? (() => Promise.resolve(""))
301
+ // Read once: `readBody` is an injectable seam and need not be replayable.
302
+ const raw = await readBody(req)
303
+ const isEmbeddings = pathAfterV2 === EMBEDDINGS_PATH
304
+ // A local-mode embedding (configured, or a legacy `Xenova/*` body id) runs
305
+ // in-process, so it must return before the upstream fetch and before any auth
306
+ // is required: it costs no quota, so a logged-out gateway can still serve it.
307
+ // Cloud mode — including a body that names `Xenova/*` — keeps the pass-through
308
+ // behaviour below. An unusable local body must fail here, not silently go
309
+ // upstream.
310
+ if (isEmbeddings) {
311
+ const requested = parseEmbeddingBody(raw)
312
+ // An injected mode is authoritative; only callers that inject nothing keep
313
+ // the legacy body-prefix rule. The body's `model` is an identifier, never a
314
+ // routing signal once configuration has decided.
315
+ const isLocal =
316
+ deps.embeddingMode === "local" ||
317
+ (deps.embeddingMode === undefined && rawModelIsLocalButUnsupported(raw))
318
+ // A body we cannot parse as a text-input request is not a local request at
319
+ // all: `Xenova/*` with token arrays, a mixed array, or a model-less body.
320
+ // Answering 400 here beats forwarding a request the caller believes is local.
321
+ if (isLocal && requested === null) {
322
+ sendModelsError(
323
+ res, 400, "invalid_request_error", "invalid_input",
324
+ "input must be a string or an array of strings",
325
+ )
326
+ return
327
+ }
328
+ if (isLocal && requested) {
329
+ const { model, input } = requested
330
+ const oversize = oversizeEmbeddingReason(input)
331
+ if (oversize) {
332
+ sendModelsError(res, 400, "invalid_request_error", "invalid_input", oversize)
333
+ return
334
+ }
335
+ const local =
336
+ deps.local ??
337
+ (deps.createLocalEmbedder ?? createLocalEmbedder)(deps.localEmbeddingModel)
338
+ const budget = deps.embeddingTimeoutMs ?? EMBEDDING_TIMEOUT_MS
339
+ // Configured-local mode bypasses the body id when choosing the backend,
340
+ // but `routeEmbedding` still needs a local-prefixed id to pass its guard.
341
+ // The legacy path passes the body id through unchanged.
342
+ const routeModel = deps.embeddingMode === "local" ? INTERNAL_LOCAL_MODEL : model
343
+ let result: Awaited<ReturnType<typeof routeEmbedding>>
344
+ try {
345
+ result = await withTimeout(
346
+ routeEmbedding(routeModel, input, { local }),
347
+ budget,
348
+ `local embedding exceeded ${budget} ms`,
349
+ )
350
+ } catch (error) {
351
+ deps.log?.(`local embedding error: ${String((error as Error)?.message ?? error)}`)
352
+ sendModelsError(res, 502, "bad_gateway", "embedding_failed", "failed to compute the embedding locally")
353
+ return
354
+ }
355
+ // Defensive: `routeEmbedding` returns null only for a non-local model,
356
+ // which `isLocalModel` already excluded, but keeping the guard means a
357
+ // future non-nullable record type cannot silently forward an empty body.
358
+ if (result) {
359
+ if (result.data.some((row) => row.embedding.length !== local.dimension)) {
360
+ deps.log?.(`local embedding returned an incomplete vector (expected ${local.dimension} values)`)
361
+ sendModelsError(res, 502, "bad_gateway", "embedding_failed", "failed to compute the embedding locally")
362
+ return
363
+ }
364
+ // Echo the caller's id: in configured-local mode the body model is only
365
+ // an identifier, and the router saw the fixed internal id above. On the
366
+ // legacy path this is a no-op (the values are identical).
367
+ result.model = model
368
+ res.setHeader("Content-Type", "application/json")
369
+ res.status(200)
370
+ res.end(JSON.stringify(result))
371
+ return
372
+ }
373
+ }
374
+ }
375
+
376
+ // A cloud embeddings call needs an account just like a chat call, but
377
+ // `ensureFresh` rejects when none exists. Left uncaught that rejection became
378
+ // an opaque empty 500 from `createProxy`'s last-resort catch, while the local
379
+ // branch above answered 200 — two meanings for "logged out" on one endpoint.
380
+ // Emit the models branch's envelope instead so it stays uncaught for real bugs.
381
+ if (!deps.store.get(site)) {
382
+ sendModelsError(res, 503, "service_unavailable", "no_account", `no account for ${site}`)
383
+ return
384
+ }
385
+ const auth = await deps.store.ensureFresh(site)
386
+ const url = upstreamUrl(site, pathAfterV2)
387
+ // A plain OpenAI client omits `stream` (or sends false) and expects one JSON
388
+ // object. Only an explicit `stream: false` triggers aggregation; a missing
389
+ // field stays on the existing streaming path. A malformed body is streaming.
390
+ let wantsStream = true
391
+ try {
392
+ const parsed = JSON.parse(raw) as Record<string, unknown> | null
393
+ wantsStream = parsed?.stream !== false
394
+ } catch {
395
+ // Malformed bodies fall through to the original streaming behaviour.
396
+ }
397
+ const body = prepareBody(raw, site, pathAfterV2)
398
+ const doFetch = deps.fetchImpl ?? fetch
399
+ const isChat = pathAfterV2 === CHAT_PATH
400
+
401
+ let upstream: Response
402
+ try {
403
+ upstream = await doFetch(url, {
404
+ method: "POST",
405
+ headers: {
406
+ ...(isChat ? apiHeaders(auth, { accept: "text/event-stream" }) : apiHeaders(auth)),
407
+ // Only intl is channel-gated; keep CN's existing header set untouched.
408
+ ...(site === "intl" ? channelHeaders() : {}),
409
+ "Content-Type": "application/json",
410
+ },
411
+ body,
412
+ signal: deps.signal,
413
+ })
414
+ } catch (err) {
415
+ deps.log?.(`proxy upstream error: ${String((err as Error)?.message ?? err)}`)
416
+ res.status(502)
417
+ res.end() // never echo internal error detail (host/path) to the caller
418
+ return
419
+ }
420
+
421
+ // Plain OpenAI clients expect a single JSON object. Upstream errors are never
422
+ // aggregated — they pass through unchanged so error bodies stay intact.
423
+ const isAggregate = !wantsStream && upstream.ok && isChat
424
+ if (isAggregate) {
425
+ // Aggregate through a reader rather than `text()`: a client that walks away
426
+ // must not still pay for the whole completion. Abort ends the response so
427
+ // `createProxy`'s catch sees a closed socket, not an unhandled rejection.
428
+ const body = upstream.body
429
+ let text: string
430
+ if (body) {
431
+ text = await collectSseFromStream(body, {
432
+ signal: deps.signal,
433
+ onAbort: () => { res.end() },
434
+ })
435
+ } else {
436
+ text = await upstream.text()
437
+ }
438
+ if (deps.signal?.aborted) return
439
+ const result = toChatCompletion(collectSse(text))
440
+ res.setHeader("Content-Type", "application/json")
441
+ res.status(upstream.status)
442
+ res.end(JSON.stringify(result))
443
+ return
444
+ }
445
+
446
+ copyHeaders(upstream.headers, res)
447
+ res.status(upstream.status)
448
+
449
+ const reader = upstream.body?.getReader()
450
+ if (!reader) {
451
+ const text = await upstream.text()
452
+ res.end(text)
453
+ return
454
+ }
455
+ for (;;) {
456
+ const { done, value } = await reader.read()
457
+ if (done) break
458
+ res.write(value)
459
+ }
460
+ res.end()
461
+ }
462
+
463
+ export interface ProxyServer {
464
+ start(port: number): Promise<void>
465
+ close(): Promise<void>
466
+ }
467
+
468
+ /**
469
+ * Bind options for the listener. `reuseAddr` + `exclusive: false` let a bind
470
+ * succeed on Windows when an orphaned socket still holds the fixed port; an
471
+ * injected object overrides these defaults field by field.
472
+ */
473
+ export interface ListenOptions {
474
+ reuseAddr?: boolean
475
+ exclusive?: boolean
476
+ }
477
+
478
+ const DEFAULT_LISTEN_OPTIONS: Required<ListenOptions> = { reuseAddr: true, exclusive: false }
479
+
480
+ export function createProxy(deps: {
481
+ store: TokenStore
482
+ fetchImpl?: typeof fetch
483
+ log?: (message: string) => void
484
+ models?: (site: Site) => Promise<ModelsListResponse>
485
+ local?: LocalEmbedding
486
+ localEmbeddingModel?: string
487
+ createLocalEmbedder?: (modelId?: string) => LocalEmbedding
488
+ embeddingTimeoutMs?: number
489
+ embeddingMode?: "cloud" | "local"
490
+ listenOptions?: ListenOptions
491
+ }): ProxyServer {
492
+ const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
493
+ const headers: Record<string, string> = {}
494
+ for (const [k, v] of Object.entries(incoming.headers)) {
495
+ if (typeof v === "string") headers[k] = v
496
+ else if (Array.isArray(v)) headers[k] = v.join(", ")
497
+ }
498
+ const controller = new AbortController()
499
+ // A client that disconnects (Esc / tab close) must stop the upstream stream,
500
+ // otherwise the full SSE answer is generated and billed to the user's quota.
501
+ outgoing.on("close", () => controller.abort())
502
+ incoming.on("aborted", () => controller.abort())
503
+ const chunks: Buffer[] = []
504
+ let size = 0
505
+ const MAX_BODY = 8 * 1024 * 1024
506
+ let tooLarge = false
507
+ incoming.on("data", (c: Buffer) => {
508
+ size += c.length
509
+ if (size > MAX_BODY) {
510
+ tooLarge = true
511
+ controller.abort()
512
+ return
513
+ }
514
+ chunks.push(c)
515
+ })
516
+ incoming.on("end", () => {
517
+ if (tooLarge || controller.signal.aborted) {
518
+ if (!outgoing.headersSent) outgoing.writeHead(413)
519
+ outgoing.end()
520
+ return
521
+ }
522
+ const text = Buffer.concat(chunks).toString("utf8")
523
+ const response: ProxyResponse = {
524
+ status: (code) => outgoing.writeHead(code),
525
+ setHeader: (name, value) => outgoing.setHeader(name, value),
526
+ write: (chunk) => { outgoing.write(chunk) },
527
+ end: (chunk) => { outgoing.end(chunk) },
528
+ }
529
+ void handleRequest(
530
+ { url: incoming.url ?? "", method: incoming.method, headers },
531
+ response,
532
+ {
533
+ store: deps.store,
534
+ fetchImpl: deps.fetchImpl,
535
+ readBody: async () => text,
536
+ signal: controller.signal,
537
+ log: deps.log,
538
+ models: deps.models,
539
+ local: deps.local,
540
+ localEmbeddingModel: deps.localEmbeddingModel,
541
+ createLocalEmbedder: deps.createLocalEmbedder,
542
+ embeddingTimeoutMs: deps.embeddingTimeoutMs,
543
+ embeddingMode: deps.embeddingMode,
544
+ },
545
+ ).catch(() => {
546
+ if (controller.signal.aborted) return
547
+ if (!outgoing.headersSent) outgoing.writeHead(500)
548
+ outgoing.end()
549
+ })
550
+ })
551
+ })
552
+ return {
553
+ start: (port) =>
554
+ new Promise<void>((resolve, reject) => {
555
+ server.once("error", reject)
556
+ const options = { ...DEFAULT_LISTEN_OPTIONS, ...deps.listenOptions }
557
+ server.listen({ port, host: "127.0.0.1", ...options }, () => resolve())
558
+ }),
559
+ close: () =>
560
+ new Promise<void>((resolve, reject) => {
561
+ server.close((err) => (err ? reject(err) : resolve()))
562
+ }),
563
+ }
564
+ }
@@ -0,0 +1,129 @@
1
+ import type { Site } from "../shared"
2
+ import type { UpstreamReading } from "./upstream"
3
+
4
+ /**
5
+ * A reading plus the freshness verdict. `fetchedAt` is null only when nothing
6
+ * has ever been read successfully — every numeric field is null then.
7
+ */
8
+ export interface Reading {
9
+ remaining: number | null
10
+ used: number | null
11
+ total: number | null
12
+ cycleStart: string | null
13
+ cycleEnd: string | null
14
+ resetAt: string | null
15
+ fetchedAt: string | null
16
+ stale: boolean
17
+ error: string | null
18
+ /** This answer was served from the cache; the upstream was not called. */
19
+ cached: boolean
20
+ /** How old the numbers are, in whole seconds. Null when there are no numbers. */
21
+ ageSeconds: number | null
22
+ }
23
+
24
+ export interface QuotaSource {
25
+ read(site: Site, signal?: AbortSignal): Promise<Reading>
26
+ /**
27
+ * Called after a fresh login. Drops the failure cooldown *and* the cached
28
+ * reading, so the next read re-fetches with the new token instead of serving
29
+ * the old account's numbers from the 30-second cache.
30
+ */
31
+ clearFailure(site: Site): void
32
+ }
33
+
34
+ export interface QuotaSourceDeps {
35
+ /** Site-based fetch callback; the server wraps it over store.ensureFresh + fetchUpstream. */
36
+ readForSite: (site: Site, signal?: AbortSignal) => Promise<UpstreamReading>
37
+ now?: () => number
38
+ minRefreshMs?: number
39
+ }
40
+
41
+ export const MIN_REFRESH_MS = 30_000
42
+
43
+ const EMPTY: Reading = {
44
+ remaining: null, used: null, total: null,
45
+ cycleStart: null, cycleEnd: null, resetAt: null,
46
+ fetchedAt: null, stale: false, error: null, cached: false, ageSeconds: null,
47
+ }
48
+
49
+ interface SiteState {
50
+ cached: { reading: UpstreamReading; at: number } | null
51
+ failedAt: number | null
52
+ lastError: string | null
53
+ inflight: Promise<Reading> | null
54
+ /** Bumped on clearFailure so a read that began with an old token cannot write
55
+ * its late result back into the cache after a new login. */
56
+ epoch: number
57
+ }
58
+
59
+ const newState = (): SiteState => ({ cached: null, failedAt: null, lastError: null, inflight: null, epoch: 0 })
60
+
61
+ /** Per-site cache: one broken site cannot starve the other. */
62
+ export function createQuotaSource(deps: QuotaSourceDeps): QuotaSource {
63
+ const now = deps.now ?? Date.now
64
+ const minRefreshMs = deps.minRefreshMs ?? MIN_REFRESH_MS
65
+ const states: Record<Site, SiteState> = { cn: newState(), intl: newState() }
66
+
67
+ const ageOf = (at: number) => Math.max(0, Math.round((now() - at) / 1000))
68
+ const fresh = (r: UpstreamReading): Reading => ({ ...r, stale: false, error: null, cached: false, ageSeconds: 0 })
69
+ const fromCache = (e: { reading: UpstreamReading; at: number }): Reading => ({
70
+ ...e.reading, stale: false, error: null, cached: true, ageSeconds: ageOf(e.at),
71
+ })
72
+ const fallback = (state: SiteState, error: string): Reading =>
73
+ state.cached
74
+ ? { ...state.cached.reading, stale: true, error, cached: false, ageSeconds: ageOf(state.cached.at) }
75
+ : { ...EMPTY, stale: true, error }
76
+
77
+ const load = async (site: Site, state: SiteState, signal?: AbortSignal): Promise<Reading> => {
78
+ const epoch = state.epoch
79
+ try {
80
+ const reading = await deps.readForSite(site, signal)
81
+ // A clearFailure (new login) may have happened while this request was in
82
+ // flight. Its result belongs to the old token — return it to this caller
83
+ // but never cache it, so the next read fetches with the new token.
84
+ if (state.epoch !== epoch) return fresh(reading)
85
+ state.cached = { reading, at: now() }
86
+ state.failedAt = null
87
+ state.lastError = null
88
+ return fresh(reading)
89
+ } catch (error) {
90
+ const message = String((error as Error)?.message ?? error)
91
+ if (state.epoch !== epoch) return fallback(state, message)
92
+ state.failedAt = now()
93
+ state.lastError = message
94
+ return fallback(state, message)
95
+ }
96
+ }
97
+
98
+ return {
99
+ clearFailure(site) {
100
+ const state = states[site]
101
+ state.epoch += 1
102
+ state.failedAt = null
103
+ state.lastError = null
104
+ state.cached = null
105
+ // Release the single-flight slot so the next read starts a fresh request
106
+ // with the new token instead of awaiting the stale in-flight one.
107
+ state.inflight = null
108
+ },
109
+ async read(site, signal) {
110
+ const state = states[site]
111
+ if (signal?.aborted) return fallback(state, String(signal.reason ?? "aborted"))
112
+ if (state.cached && now() - state.cached.at < minRefreshMs) return fromCache(state.cached)
113
+ if (state.failedAt !== null && now() - state.failedAt < minRefreshMs) {
114
+ return fallback(state, state.lastError ?? "upstream unavailable")
115
+ }
116
+ if (!state.inflight) {
117
+ // Identity check: a clearFailure may have released the slot and a newer
118
+ // request taken it while this one was still in flight. Only the current
119
+ // owner may clear it — otherwise a late old request would drop the new
120
+ // one's slot and cause a redundant upstream call.
121
+ const pending = load(site, state, signal).finally(() => {
122
+ if (state.inflight === pending) state.inflight = null
123
+ })
124
+ state.inflight = pending
125
+ }
126
+ return state.inflight
127
+ },
128
+ }
129
+ }