opencode-codebuddy-quota 0.1.0 → 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.
- package/config.default.json +41 -38
- package/package.json +2 -1
- package/rpc.ts +92 -92
- package/server.ts +132 -17
- package/src/gui/battery.tsx +81 -81
- package/src/gui/pace.ts +76 -76
- package/src/gui/quota.ts +198 -198
- package/src/gui/store.ts +181 -181
- package/src/gui.tsx +111 -111
- package/src/server/catalog.ts +264 -264
- package/src/server/config-writer.ts +621 -621
- package/src/server/config.ts +215 -195
- package/src/server/embedding-local.ts +166 -0
- package/src/server/embedding-mode.ts +14 -0
- package/src/server/gateway-owner.ts +243 -0
- package/src/server/gateway-setup.ts +51 -0
- package/src/server/logger.ts +26 -26
- package/src/server/model-cache.ts +136 -0
- package/src/server/model-info.ts +109 -109
- package/src/server/model-prewarm.ts +123 -0
- package/src/server/models-dev.ts +77 -77
- package/src/server/models-endpoint.ts +74 -0
- package/src/server/package-spec.ts +42 -42
- package/src/server/package-version.ts +51 -51
- package/src/server/pricing.ts +169 -169
- package/src/server/proxy.ts +335 -7
- package/src/server/stream-collect.ts +166 -0
- package/src/server/wire.ts +67 -67
package/src/server/proxy.ts
CHANGED
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
|
2
2
|
import type { Site } from "../shared"
|
|
3
|
+
import { createLocalEmbedder, isLocalModel, routeEmbedding, type LocalEmbedding } from "./embedding-local"
|
|
3
4
|
import { apiHeaders, channelHeaders } from "./headers"
|
|
4
5
|
import { SITE_ENDPOINTS } from "./login"
|
|
6
|
+
import type { ModelsListResponse } from "./models-endpoint"
|
|
7
|
+
import { collectSse, collectSseFromStream, toChatCompletion } from "./stream-collect"
|
|
5
8
|
import type { TokenStore } from "./token-store"
|
|
6
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
|
+
|
|
7
17
|
export function routeSite(url: string): Site | null {
|
|
8
18
|
if (url.startsWith("/cn/v2/")) return "cn"
|
|
9
19
|
if (url.startsWith("/intl/v2/")) return "intl"
|
|
@@ -14,6 +24,62 @@ export function upstreamUrl(site: Site, pathAfterV2: string): string {
|
|
|
14
24
|
return `${SITE_ENDPOINTS[site].endpoint}/v2/${pathAfterV2}`
|
|
15
25
|
}
|
|
16
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
|
+
|
|
17
83
|
/** The bits of an HTTP request the handler needs. */
|
|
18
84
|
export interface ProxyRequest {
|
|
19
85
|
url: string
|
|
@@ -38,6 +104,82 @@ export interface HandleRequestDeps {
|
|
|
38
104
|
signal?: AbortSignal
|
|
39
105
|
/** Optional logger; errors are logged here, never echoed to the client body. */
|
|
40
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
|
|
41
183
|
}
|
|
42
184
|
|
|
43
185
|
/** Official identity the intl gateway requires as the first system message. */
|
|
@@ -60,7 +202,10 @@ function identityText(content: unknown): string | null {
|
|
|
60
202
|
* gateway's channel verification checks for. A caller-supplied leading system
|
|
61
203
|
* message is kept as-is; only the identity prompt is prepended when missing.
|
|
62
204
|
*/
|
|
63
|
-
function prepareBody(body: string, site: Site): string {
|
|
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
|
|
64
209
|
try {
|
|
65
210
|
const parsed = JSON.parse(body) as Record<string, unknown>
|
|
66
211
|
parsed.stream = true
|
|
@@ -107,26 +252,158 @@ export async function handleRequest(
|
|
|
107
252
|
res: ProxyResponse,
|
|
108
253
|
deps: HandleRequestDeps,
|
|
109
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
|
+
|
|
110
265
|
const site = routeSite(req.url ?? "")
|
|
111
266
|
if (!site) {
|
|
112
267
|
res.status(404)
|
|
113
268
|
res.end("not found")
|
|
114
269
|
return
|
|
115
270
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
+
|
|
119
300
|
const readBody = deps.readBody ?? (() => Promise.resolve(""))
|
|
301
|
+
// Read once: `readBody` is an injectable seam and need not be replayable.
|
|
120
302
|
const raw = await readBody(req)
|
|
121
|
-
const
|
|
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)
|
|
122
398
|
const doFetch = deps.fetchImpl ?? fetch
|
|
399
|
+
const isChat = pathAfterV2 === CHAT_PATH
|
|
123
400
|
|
|
124
401
|
let upstream: Response
|
|
125
402
|
try {
|
|
126
403
|
upstream = await doFetch(url, {
|
|
127
404
|
method: "POST",
|
|
128
405
|
headers: {
|
|
129
|
-
...apiHeaders(auth, { accept: "text/event-stream" }),
|
|
406
|
+
...(isChat ? apiHeaders(auth, { accept: "text/event-stream" }) : apiHeaders(auth)),
|
|
130
407
|
// Only intl is channel-gated; keep CN's existing header set untouched.
|
|
131
408
|
...(site === "intl" ? channelHeaders() : {}),
|
|
132
409
|
"Content-Type": "application/json",
|
|
@@ -141,6 +418,31 @@ export async function handleRequest(
|
|
|
141
418
|
return
|
|
142
419
|
}
|
|
143
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
|
+
|
|
144
446
|
copyHeaders(upstream.headers, res)
|
|
145
447
|
res.status(upstream.status)
|
|
146
448
|
|
|
@@ -163,10 +465,29 @@ export interface ProxyServer {
|
|
|
163
465
|
close(): Promise<void>
|
|
164
466
|
}
|
|
165
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
|
+
|
|
166
480
|
export function createProxy(deps: {
|
|
167
481
|
store: TokenStore
|
|
168
482
|
fetchImpl?: typeof fetch
|
|
169
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
|
|
170
491
|
}): ProxyServer {
|
|
171
492
|
const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
|
|
172
493
|
const headers: Record<string, string> = {}
|
|
@@ -214,6 +535,12 @@ export function createProxy(deps: {
|
|
|
214
535
|
readBody: async () => text,
|
|
215
536
|
signal: controller.signal,
|
|
216
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,
|
|
217
544
|
},
|
|
218
545
|
).catch(() => {
|
|
219
546
|
if (controller.signal.aborted) return
|
|
@@ -226,7 +553,8 @@ export function createProxy(deps: {
|
|
|
226
553
|
start: (port) =>
|
|
227
554
|
new Promise<void>((resolve, reject) => {
|
|
228
555
|
server.once("error", reject)
|
|
229
|
-
|
|
556
|
+
const options = { ...DEFAULT_LISTEN_OPTIONS, ...deps.listenOptions }
|
|
557
|
+
server.listen({ port, host: "127.0.0.1", ...options }, () => resolve())
|
|
230
558
|
}),
|
|
231
559
|
close: () =>
|
|
232
560
|
new Promise<void>((resolve, reject) => {
|
|
@@ -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
|
+
}
|