opencode-codebuddy-quota 0.1.0 → 0.1.3
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/README.md +1 -0
- package/config.default.json +41 -38
- package/package.json +2 -1
- package/rpc.ts +92 -92
- package/server.ts +133 -19
- 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 +622 -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 +306 -0
- package/src/server/gateway-setup.ts +74 -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 +379 -8
- package/src/server/stream-collect.ts +166 -0
- package/src/server/wire.ts +67 -67
- package/src/shared.ts +3 -0
package/src/server/proxy.ts
CHANGED
|
@@ -1,9 +1,38 @@
|
|
|
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
|
+
* Base fields of `GET /health`. Cross-task contract: a probe parses
|
|
12
|
+
* `status === "ok" && service === "codebuddy-quota"`, so both the keys and the
|
|
13
|
+
* spelling are part of the API. The live body adds a process nonce (below) so a
|
|
14
|
+
* probe can tell its own gateway from another OpenCode instance on the port.
|
|
15
|
+
*/
|
|
16
|
+
export const HEALTH_BODY = '{"status":"ok","service":"codebuddy-quota"}'
|
|
17
|
+
|
|
18
|
+
const NONCE_KEY = Symbol.for("codebuddy-quota.gateway.nonce")
|
|
19
|
+
|
|
20
|
+
/** Process-wide nonce, stable across plugin module reloads via globalThis. */
|
|
21
|
+
export function processNonce(): string {
|
|
22
|
+
const g = globalThis as unknown as Record<PropertyKey, string | undefined>
|
|
23
|
+
if (!g[NONCE_KEY]) g[NONCE_KEY] = crypto.randomUUID()
|
|
24
|
+
return g[NONCE_KEY] as string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Live health body: base fields plus the process nonce. */
|
|
28
|
+
export function healthBody(): string {
|
|
29
|
+
return JSON.stringify({
|
|
30
|
+
status: "ok",
|
|
31
|
+
service: "codebuddy-quota",
|
|
32
|
+
nonce: processNonce(),
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
|
|
7
36
|
export function routeSite(url: string): Site | null {
|
|
8
37
|
if (url.startsWith("/cn/v2/")) return "cn"
|
|
9
38
|
if (url.startsWith("/intl/v2/")) return "intl"
|
|
@@ -14,6 +43,62 @@ export function upstreamUrl(site: Site, pathAfterV2: string): string {
|
|
|
14
43
|
return `${SITE_ENDPOINTS[site].endpoint}/v2/${pathAfterV2}`
|
|
15
44
|
}
|
|
16
45
|
|
|
46
|
+
/**
|
|
47
|
+
* The path after `/v2/` with any query string stripped.
|
|
48
|
+
*
|
|
49
|
+
* Every route decision in `handleRequest` (embeddings, models, Accept
|
|
50
|
+
* injection, aggregation) must key off this one helper: keying some branches off
|
|
51
|
+
* the raw `req.url` made `?foo=1` silently skip aggregation, and a `startsWith`
|
|
52
|
+
* test accepted nonsense like `chat/completionsXYZ`.
|
|
53
|
+
*/
|
|
54
|
+
export function pathOf(url: string): string {
|
|
55
|
+
const after = url.split("/v2/")[1] ?? ""
|
|
56
|
+
const query = after.indexOf("?")
|
|
57
|
+
return query === -1 ? after : after.slice(0, query)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Local, quota-free routes; each is matched exactly, never by prefix. */
|
|
61
|
+
const EMBEDDINGS_PATH = "embeddings"
|
|
62
|
+
const MODELS_PATH = "models"
|
|
63
|
+
const CHAT_PATH = "chat/completions"
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Input limits for the in-process embedder. transformers.js runs on the same
|
|
67
|
+
* event loop as every proxied chat stream, so one oversized embeddings call
|
|
68
|
+
* would stall unrelated conversations. bge-m3 truncates at 8192 tokens, so
|
|
69
|
+
* 20000 characters is already past everything the model reads, and 64 inputs
|
|
70
|
+
* keeps one batch's compute bounded while matching the batch sizes clients use.
|
|
71
|
+
*/
|
|
72
|
+
const MAX_EMBEDDING_INPUTS = 64
|
|
73
|
+
const MAX_EMBEDDING_CHARS = 20_000
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Budget for a warm local `embed` call. A cold build (~600 MB download) is not
|
|
77
|
+
* timed on purpose: a fixed limit would turn a slow first download into a
|
|
78
|
+
* spurious 502. This only bounds compute on an already-built pipeline.
|
|
79
|
+
*/
|
|
80
|
+
const EMBEDDING_TIMEOUT_MS = 30_000
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `routeEmbedding` only accepts ids with the local `Xenova/` prefix. When the
|
|
84
|
+
* configured mode is local, the request body's `model` is an arbitrary
|
|
85
|
+
* identifier and must not decide routing, so the router gets this fixed
|
|
86
|
+
* internal id and the caller's id is restored on the response instead.
|
|
87
|
+
*/
|
|
88
|
+
const INTERNAL_LOCAL_MODEL = "Xenova/bge-m3"
|
|
89
|
+
|
|
90
|
+
/** Reject with `reason` after `ms`, clearing the timer when `task` settles. */
|
|
91
|
+
function withTimeout<T>(task: Promise<T>, ms: number, reason: string): Promise<T> {
|
|
92
|
+
return new Promise<T>((resolve, reject) => {
|
|
93
|
+
const timer = setTimeout(() => reject(new Error(reason)), ms)
|
|
94
|
+
timer.unref?.()
|
|
95
|
+
task.then(
|
|
96
|
+
(value) => { clearTimeout(timer); resolve(value) },
|
|
97
|
+
(error: unknown) => { clearTimeout(timer); reject(error) },
|
|
98
|
+
)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
17
102
|
/** The bits of an HTTP request the handler needs. */
|
|
18
103
|
export interface ProxyRequest {
|
|
19
104
|
url: string
|
|
@@ -38,6 +123,82 @@ export interface HandleRequestDeps {
|
|
|
38
123
|
signal?: AbortSignal
|
|
39
124
|
/** Optional logger; errors are logged here, never echoed to the client body. */
|
|
40
125
|
log?: (message: string) => void
|
|
126
|
+
/** Local source for GET /v2/models; unwired in tests that don't exercise it. */
|
|
127
|
+
models?: (site: Site) => Promise<ModelsListResponse>
|
|
128
|
+
/** In-process embedder for `Xenova/*` model ids; defaults to the lazy ONNX one. */
|
|
129
|
+
local?: LocalEmbedding
|
|
130
|
+
/** Configured local model id for the lazy fallback; undefined keeps the shipped default. */
|
|
131
|
+
localEmbeddingModel?: string
|
|
132
|
+
/** Factory seam so tests can observe the id without triggering a real download. */
|
|
133
|
+
createLocalEmbedder?: (modelId?: string) => LocalEmbedding
|
|
134
|
+
/** Budget for one warm local `embed` call; injectable so a test need not wait 30s. */
|
|
135
|
+
embeddingTimeoutMs?: number
|
|
136
|
+
/** Configured backend for embeddings; absent keeps the legacy body-prefix routing. */
|
|
137
|
+
embeddingMode?: "cloud" | "local"
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Emit OpenAI's error envelope, not a stack trace or a gateway-specific body. */
|
|
141
|
+
function sendModelsError(res: ProxyResponse, status: number, type: string, code: string, message: string): void {
|
|
142
|
+
res.setHeader("Content-Type", "application/json")
|
|
143
|
+
res.status(status)
|
|
144
|
+
res.end(JSON.stringify({ error: { message, type, code } }))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Pull the model id and input out of an embeddings body, or null when unusable. */
|
|
148
|
+
function parseEmbeddingBody(
|
|
149
|
+
raw: string,
|
|
150
|
+
): { model: string; input: string | string[] } | null {
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(raw) as { model?: unknown; input?: unknown } | null
|
|
153
|
+
const model = parsed?.model
|
|
154
|
+
const input = parsed?.input
|
|
155
|
+
if (typeof model !== "string" || model === "") return null
|
|
156
|
+
if (typeof input === "string") return { model, input }
|
|
157
|
+
// OpenAI also allows token arrays (and arrays of them); transformers.js only
|
|
158
|
+
// takes text. A batch is all-strings or nothing: a mixed array like
|
|
159
|
+
// `["a", ["b"]]` would otherwise reach the extractor and be read as
|
|
160
|
+
// vocabulary ids, producing a silent garbage vector.
|
|
161
|
+
if (Array.isArray(input) && input.every((part) => typeof part === "string")) {
|
|
162
|
+
return { model, input }
|
|
163
|
+
}
|
|
164
|
+
return null
|
|
165
|
+
} catch {
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* True when the body names a local `Xenova/*` model but its `input` is not a
|
|
172
|
+
* plain string or a plain array of strings.
|
|
173
|
+
*
|
|
174
|
+
* `parseEmbeddingBody` returns null for those shapes — it cannot tell why — so
|
|
175
|
+
* the model id is read separately here. Without this, `Xenova/bge-m3` with a
|
|
176
|
+
* token array would fall through to the cloud path and be forwarded, which the
|
|
177
|
+
* caller has every reason not to expect.
|
|
178
|
+
*/
|
|
179
|
+
function rawModelIsLocalButUnsupported(raw: string): boolean {
|
|
180
|
+
try {
|
|
181
|
+
const parsed = JSON.parse(raw) as { model?: unknown } | null
|
|
182
|
+
return typeof parsed?.model === "string" && isLocalModel(parsed.model)
|
|
183
|
+
} catch {
|
|
184
|
+
return false
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Name the reason an input set cannot be answered within the local budget, or
|
|
190
|
+
* null when it is acceptable.
|
|
191
|
+
*/
|
|
192
|
+
function oversizeEmbeddingReason(input: string | string[]): string | null {
|
|
193
|
+
const parts = Array.isArray(input) ? input : [input]
|
|
194
|
+
if (parts.length === 0) return "input must not be empty"
|
|
195
|
+
if (parts.length > MAX_EMBEDDING_INPUTS) {
|
|
196
|
+
return `input must contain at most ${MAX_EMBEDDING_INPUTS} strings`
|
|
197
|
+
}
|
|
198
|
+
if (parts.some((part) => part.length > MAX_EMBEDDING_CHARS)) {
|
|
199
|
+
return `each input must be at most ${MAX_EMBEDDING_CHARS} characters`
|
|
200
|
+
}
|
|
201
|
+
return null
|
|
41
202
|
}
|
|
42
203
|
|
|
43
204
|
/** Official identity the intl gateway requires as the first system message. */
|
|
@@ -60,7 +221,10 @@ function identityText(content: unknown): string | null {
|
|
|
60
221
|
* gateway's channel verification checks for. A caller-supplied leading system
|
|
61
222
|
* message is kept as-is; only the identity prompt is prepended when missing.
|
|
62
223
|
*/
|
|
63
|
-
function prepareBody(body: string, site: Site): string {
|
|
224
|
+
function prepareBody(body: string, site: Site, pathAfterV2: string): string {
|
|
225
|
+
// /embeddings has no stream concept; injecting it makes the gateway answer
|
|
226
|
+
// 10001 "Unmarshal embedding params failed".
|
|
227
|
+
if (pathAfterV2 === EMBEDDINGS_PATH) return body
|
|
64
228
|
try {
|
|
65
229
|
const parsed = JSON.parse(body) as Record<string, unknown>
|
|
66
230
|
parsed.stream = true
|
|
@@ -107,26 +271,158 @@ export async function handleRequest(
|
|
|
107
271
|
res: ProxyResponse,
|
|
108
272
|
deps: HandleRequestDeps,
|
|
109
273
|
): Promise<void> {
|
|
274
|
+
// Identify this listener before routing, auth, or the body read: the probe
|
|
275
|
+
// must be answered even with no account configured. Exact match only — a
|
|
276
|
+
// lookalike path must keep its existing 404 behaviour.
|
|
277
|
+
if ((req.method === "GET" || req.method === undefined) && req.url === "/health") {
|
|
278
|
+
res.setHeader("Content-Type", "application/json")
|
|
279
|
+
res.status(200)
|
|
280
|
+
res.end(healthBody())
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
|
|
110
284
|
const site = routeSite(req.url ?? "")
|
|
111
285
|
if (!site) {
|
|
112
286
|
res.status(404)
|
|
113
287
|
res.end("not found")
|
|
114
288
|
return
|
|
115
289
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
290
|
+
|
|
291
|
+
// The cloud has no /v2/models route; serve the list locally so OpenAI clients
|
|
292
|
+
// can discover exactly the models the provider actually imported. This must
|
|
293
|
+
// return before any upstream fetch.
|
|
294
|
+
const pathAfterV2 = pathOf(req.url ?? "")
|
|
295
|
+
if (req.method === "GET" && pathAfterV2 === MODELS_PATH) {
|
|
296
|
+
if (!deps.models) {
|
|
297
|
+
sendModelsError(res, 501, "not_implemented", "not_implemented", "models endpoint is not available")
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
// No account means there is no catalog to build the list from.
|
|
301
|
+
if (!deps.store.get(site)) {
|
|
302
|
+
sendModelsError(res, 503, "service_unavailable", "no_account", `no account for ${site}`)
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
let list: ModelsListResponse
|
|
306
|
+
try {
|
|
307
|
+
list = await deps.models(site)
|
|
308
|
+
} catch (error) {
|
|
309
|
+
deps.log?.(`models endpoint error: ${String((error as Error)?.message ?? error)}`)
|
|
310
|
+
sendModelsError(res, 502, "bad_gateway", "catalog_failed", "failed to load the model catalog")
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
res.setHeader("Content-Type", "application/json")
|
|
314
|
+
res.status(200)
|
|
315
|
+
res.end(JSON.stringify(list))
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
|
|
119
319
|
const readBody = deps.readBody ?? (() => Promise.resolve(""))
|
|
320
|
+
// Read once: `readBody` is an injectable seam and need not be replayable.
|
|
120
321
|
const raw = await readBody(req)
|
|
121
|
-
const
|
|
322
|
+
const isEmbeddings = pathAfterV2 === EMBEDDINGS_PATH
|
|
323
|
+
// A local-mode embedding (configured, or a legacy `Xenova/*` body id) runs
|
|
324
|
+
// in-process, so it must return before the upstream fetch and before any auth
|
|
325
|
+
// is required: it costs no quota, so a logged-out gateway can still serve it.
|
|
326
|
+
// Cloud mode — including a body that names `Xenova/*` — keeps the pass-through
|
|
327
|
+
// behaviour below. An unusable local body must fail here, not silently go
|
|
328
|
+
// upstream.
|
|
329
|
+
if (isEmbeddings) {
|
|
330
|
+
const requested = parseEmbeddingBody(raw)
|
|
331
|
+
// An injected mode is authoritative; only callers that inject nothing keep
|
|
332
|
+
// the legacy body-prefix rule. The body's `model` is an identifier, never a
|
|
333
|
+
// routing signal once configuration has decided.
|
|
334
|
+
const isLocal =
|
|
335
|
+
deps.embeddingMode === "local" ||
|
|
336
|
+
(deps.embeddingMode === undefined && rawModelIsLocalButUnsupported(raw))
|
|
337
|
+
// A body we cannot parse as a text-input request is not a local request at
|
|
338
|
+
// all: `Xenova/*` with token arrays, a mixed array, or a model-less body.
|
|
339
|
+
// Answering 400 here beats forwarding a request the caller believes is local.
|
|
340
|
+
if (isLocal && requested === null) {
|
|
341
|
+
sendModelsError(
|
|
342
|
+
res, 400, "invalid_request_error", "invalid_input",
|
|
343
|
+
"input must be a string or an array of strings",
|
|
344
|
+
)
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
if (isLocal && requested) {
|
|
348
|
+
const { model, input } = requested
|
|
349
|
+
const oversize = oversizeEmbeddingReason(input)
|
|
350
|
+
if (oversize) {
|
|
351
|
+
sendModelsError(res, 400, "invalid_request_error", "invalid_input", oversize)
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
const local =
|
|
355
|
+
deps.local ??
|
|
356
|
+
(deps.createLocalEmbedder ?? createLocalEmbedder)(deps.localEmbeddingModel)
|
|
357
|
+
const budget = deps.embeddingTimeoutMs ?? EMBEDDING_TIMEOUT_MS
|
|
358
|
+
// Configured-local mode bypasses the body id when choosing the backend,
|
|
359
|
+
// but `routeEmbedding` still needs a local-prefixed id to pass its guard.
|
|
360
|
+
// The legacy path passes the body id through unchanged.
|
|
361
|
+
const routeModel = deps.embeddingMode === "local" ? INTERNAL_LOCAL_MODEL : model
|
|
362
|
+
let result: Awaited<ReturnType<typeof routeEmbedding>>
|
|
363
|
+
try {
|
|
364
|
+
result = await withTimeout(
|
|
365
|
+
routeEmbedding(routeModel, input, { local }),
|
|
366
|
+
budget,
|
|
367
|
+
`local embedding exceeded ${budget} ms`,
|
|
368
|
+
)
|
|
369
|
+
} catch (error) {
|
|
370
|
+
deps.log?.(`local embedding error: ${String((error as Error)?.message ?? error)}`)
|
|
371
|
+
sendModelsError(res, 502, "bad_gateway", "embedding_failed", "failed to compute the embedding locally")
|
|
372
|
+
return
|
|
373
|
+
}
|
|
374
|
+
// Defensive: `routeEmbedding` returns null only for a non-local model,
|
|
375
|
+
// which `isLocalModel` already excluded, but keeping the guard means a
|
|
376
|
+
// future non-nullable record type cannot silently forward an empty body.
|
|
377
|
+
if (result) {
|
|
378
|
+
if (result.data.some((row) => row.embedding.length !== local.dimension)) {
|
|
379
|
+
deps.log?.(`local embedding returned an incomplete vector (expected ${local.dimension} values)`)
|
|
380
|
+
sendModelsError(res, 502, "bad_gateway", "embedding_failed", "failed to compute the embedding locally")
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
// Echo the caller's id: in configured-local mode the body model is only
|
|
384
|
+
// an identifier, and the router saw the fixed internal id above. On the
|
|
385
|
+
// legacy path this is a no-op (the values are identical).
|
|
386
|
+
result.model = model
|
|
387
|
+
res.setHeader("Content-Type", "application/json")
|
|
388
|
+
res.status(200)
|
|
389
|
+
res.end(JSON.stringify(result))
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// A cloud embeddings call needs an account just like a chat call, but
|
|
396
|
+
// `ensureFresh` rejects when none exists. Left uncaught that rejection became
|
|
397
|
+
// an opaque empty 500 from `createProxy`'s last-resort catch, while the local
|
|
398
|
+
// branch above answered 200 — two meanings for "logged out" on one endpoint.
|
|
399
|
+
// Emit the models branch's envelope instead so it stays uncaught for real bugs.
|
|
400
|
+
if (!deps.store.get(site)) {
|
|
401
|
+
sendModelsError(res, 503, "service_unavailable", "no_account", `no account for ${site}`)
|
|
402
|
+
return
|
|
403
|
+
}
|
|
404
|
+
const auth = await deps.store.ensureFresh(site)
|
|
405
|
+
const url = upstreamUrl(site, pathAfterV2)
|
|
406
|
+
// A plain OpenAI client omits `stream` (or sends false) and expects one JSON
|
|
407
|
+
// object. Only an explicit `stream: false` triggers aggregation; a missing
|
|
408
|
+
// field stays on the existing streaming path. A malformed body is streaming.
|
|
409
|
+
let wantsStream = true
|
|
410
|
+
try {
|
|
411
|
+
const parsed = JSON.parse(raw) as Record<string, unknown> | null
|
|
412
|
+
wantsStream = parsed?.stream !== false
|
|
413
|
+
} catch {
|
|
414
|
+
// Malformed bodies fall through to the original streaming behaviour.
|
|
415
|
+
}
|
|
416
|
+
const body = prepareBody(raw, site, pathAfterV2)
|
|
122
417
|
const doFetch = deps.fetchImpl ?? fetch
|
|
418
|
+
const isChat = pathAfterV2 === CHAT_PATH
|
|
123
419
|
|
|
124
420
|
let upstream: Response
|
|
125
421
|
try {
|
|
126
422
|
upstream = await doFetch(url, {
|
|
127
423
|
method: "POST",
|
|
128
424
|
headers: {
|
|
129
|
-
...apiHeaders(auth, { accept: "text/event-stream" }),
|
|
425
|
+
...(isChat ? apiHeaders(auth, { accept: "text/event-stream" }) : apiHeaders(auth)),
|
|
130
426
|
// Only intl is channel-gated; keep CN's existing header set untouched.
|
|
131
427
|
...(site === "intl" ? channelHeaders() : {}),
|
|
132
428
|
"Content-Type": "application/json",
|
|
@@ -141,6 +437,42 @@ export async function handleRequest(
|
|
|
141
437
|
return
|
|
142
438
|
}
|
|
143
439
|
|
|
440
|
+
// Plain OpenAI clients expect a single JSON object. Upstream errors are never
|
|
441
|
+
// aggregated — they pass through unchanged so error bodies stay intact.
|
|
442
|
+
const isAggregate = !wantsStream && upstream.ok && isChat
|
|
443
|
+
if (isAggregate) {
|
|
444
|
+
// Aggregate through a reader rather than `text()`: a client that walks away
|
|
445
|
+
// must not still pay for the whole completion. Abort ends the response so
|
|
446
|
+
// `createProxy`'s catch sees a closed socket, not an unhandled rejection.
|
|
447
|
+
const body = upstream.body
|
|
448
|
+
let text: string
|
|
449
|
+
if (body) {
|
|
450
|
+
text = await collectSseFromStream(body, {
|
|
451
|
+
signal: deps.signal,
|
|
452
|
+
onAbort: () => { res.end() },
|
|
453
|
+
})
|
|
454
|
+
} else {
|
|
455
|
+
text = await upstream.text()
|
|
456
|
+
}
|
|
457
|
+
if (deps.signal?.aborted) return
|
|
458
|
+
const result = toChatCompletion(collectSse(text))
|
|
459
|
+
res.setHeader("Content-Type", "application/json")
|
|
460
|
+
res.status(upstream.status)
|
|
461
|
+
res.end(JSON.stringify(result))
|
|
462
|
+
return
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// An upstream 401/403 on a request we authenticated is actionable: the shared
|
|
466
|
+
// gateway uses the first plugin instance's credential store (by design), so a
|
|
467
|
+
// re-login in a later instance can leave this store holding a stale token.
|
|
468
|
+
// Keep the response untouched; only emit a hint that maps the symptom to the
|
|
469
|
+
// known trade-off so it is diagnosable instead of a silent failure.
|
|
470
|
+
if ((upstream.status === 401 || upstream.status === 403) && !isAggregate) {
|
|
471
|
+
deps.log?.(
|
|
472
|
+
`upstream ${upstream.status}: the shared gateway may hold a stale credential from the first plugin instance; restart OpenCode or re-login to refresh it`,
|
|
473
|
+
)
|
|
474
|
+
}
|
|
475
|
+
|
|
144
476
|
copyHeaders(upstream.headers, res)
|
|
145
477
|
res.status(upstream.status)
|
|
146
478
|
|
|
@@ -163,10 +495,36 @@ export interface ProxyServer {
|
|
|
163
495
|
close(): Promise<void>
|
|
164
496
|
}
|
|
165
497
|
|
|
498
|
+
/**
|
|
499
|
+
* Bind options for the listener. An injected object overrides the defaults
|
|
500
|
+
* field by field. Only options Node/Bun actually recognize belong here.
|
|
501
|
+
*/
|
|
502
|
+
export interface ListenOptions {
|
|
503
|
+
exclusive?: boolean
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Bind options for the fixed local port. `exclusive:false` is an explicit
|
|
508
|
+
* `server.listen` option (disables SO_EXCLUSIVEADDRUSE on Windows). A genuinely
|
|
509
|
+
* occupied/orphaned port is NOT recovered here — that is the EADDRINUSE probe's
|
|
510
|
+
* job in gateway-owner.ts. There is no `reuseAddr` server.listen option (it is
|
|
511
|
+
* silently ignored), so none is carried; `reusePort` must never be set because
|
|
512
|
+
* under Bun it lets two processes share the port and split requests across
|
|
513
|
+
* per-process token stores, causing intermittent 401s. A guard test pins this.
|
|
514
|
+
*/
|
|
515
|
+
export const DEFAULT_LISTEN_OPTIONS: Required<ListenOptions> = { exclusive: false }
|
|
516
|
+
|
|
166
517
|
export function createProxy(deps: {
|
|
167
518
|
store: TokenStore
|
|
168
519
|
fetchImpl?: typeof fetch
|
|
169
520
|
log?: (message: string) => void
|
|
521
|
+
models?: (site: Site) => Promise<ModelsListResponse>
|
|
522
|
+
local?: LocalEmbedding
|
|
523
|
+
localEmbeddingModel?: string
|
|
524
|
+
createLocalEmbedder?: (modelId?: string) => LocalEmbedding
|
|
525
|
+
embeddingTimeoutMs?: number
|
|
526
|
+
embeddingMode?: "cloud" | "local"
|
|
527
|
+
listenOptions?: ListenOptions
|
|
170
528
|
}): ProxyServer {
|
|
171
529
|
const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
|
|
172
530
|
const headers: Record<string, string> = {}
|
|
@@ -214,6 +572,12 @@ export function createProxy(deps: {
|
|
|
214
572
|
readBody: async () => text,
|
|
215
573
|
signal: controller.signal,
|
|
216
574
|
log: deps.log,
|
|
575
|
+
models: deps.models,
|
|
576
|
+
local: deps.local,
|
|
577
|
+
localEmbeddingModel: deps.localEmbeddingModel,
|
|
578
|
+
createLocalEmbedder: deps.createLocalEmbedder,
|
|
579
|
+
embeddingTimeoutMs: deps.embeddingTimeoutMs,
|
|
580
|
+
embeddingMode: deps.embeddingMode,
|
|
217
581
|
},
|
|
218
582
|
).catch(() => {
|
|
219
583
|
if (controller.signal.aborted) return
|
|
@@ -225,8 +589,15 @@ export function createProxy(deps: {
|
|
|
225
589
|
return {
|
|
226
590
|
start: (port) =>
|
|
227
591
|
new Promise<void>((resolve, reject) => {
|
|
228
|
-
|
|
229
|
-
server.
|
|
592
|
+
const onError = (error: Error) => reject(error)
|
|
593
|
+
server.once("error", onError)
|
|
594
|
+
const options = { ...DEFAULT_LISTEN_OPTIONS, ...deps.listenOptions }
|
|
595
|
+
server.listen({ port, host: "127.0.0.1", ...options }, () => {
|
|
596
|
+
// The temporary bind-error listener must not linger after a successful
|
|
597
|
+
// listen; otherwise it accumulates on repeated start attempts.
|
|
598
|
+
server.removeListener("error", onError)
|
|
599
|
+
resolve()
|
|
600
|
+
})
|
|
230
601
|
}),
|
|
231
602
|
close: () =>
|
|
232
603
|
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
|
+
}
|