mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 20:32:20 +03:00
* chore(release): open v3.8.18 development cycle * fix(catalog): stop Codex CLI model-catalog refresh from erroring (#3481) Codex's model-catalog refresh (codex_models_manager) does GET /v1/models?client_version=<v> and decodes a JSON object with a TOP-LEVEL `models` array. OmniRoute answers in the OpenAI-standard `{object,data}` shape, so codex fails with "missing field `models`" and logs "failed to refresh available models" on every startup. Detect codex clients via the `originator` / `user-agent` = `codex_*` headers they send and add an EMPTY top-level `models: []` so the decode succeeds. Non-codex OpenAI clients keep the byte-identical `{object,data}` response. The array is intentionally empty: codex replaces its built-in per-model agent prompt (`base_instructions`, ~21k chars) with whatever a populated entry carries for the selected model, so emitting our catalog would drop the agent prompt to nothing and break codex's agent behaviour (verified empirically against codex 0.137). An empty list keeps codex on its built-in model info — same inference as before, minus the error. Validated end-to-end with the real handler against codex 0.137: "failed to refresh available models" → 0 occurrences, instructions preserved (built-in Codex agent prompt, not empty). Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore: ignore quality reports and local prompt artifacts Add generated quality gate reports, metrics files, and local setup prompt artifacts to .gitignore to prevent committing environment-specific or temporary files. * fix(provider): detect Responses API format when body has `input` but … (#3490) Integrated into release/v3.8.18 * fix(sse): normalize numeric provider ids to strings (#3451) Integrated into release/v3.8.18 * feat(browserPool): resolve Playwright proxy from proxy_registry DB (#3492) Integrated into release/v3.8.18 * fix(theoldllm): generate X-Request-Token server-side, drop Playwright (#3491) Integrated into release/v3.8.18 * feat(plugins): add lifecycle hooks and theme-manager plugin (#3473) Integrated into release/v3.8.18 * fix(combo): parallel pre-screen + circuit-breaker fast-exit for priority combos (#3169) Integrated into release/v3.8.18 * feat(ui): unifi active and finished requests into single view #1422 (#3401) Integrated into release/v3.8.18 * docs(changelog): record #3401, #3473, #3492, #3490, #3451, #3491, #3169 under v3.8.18 * feat(docs): add doc accuracy gate + refresh AGENTS.md counts (#3510) Integrated into release/v3.8.18 * fix(sse): drop empty-choices chunks without usage instead of injecting retry text (#3513) PR #3422 ('allow OpenAI usage-only empty choices chunks') reintroduced the assistant-content injection '[OmniRoute] Upstream returned an empty response. Please retry.' for empty `choices: []` chunks that carry no valid usage. Clients (Goose/opencode) feed that text back as a turn and spin in a retry loop -- the exact regression #3400 had fixed by dropping the chunk. Restore the drop behavior for the no-usage case while preserving #3422's standards-compliant forwarding of usage-only `include_usage` final chunks. Realign the mislabeled stream-utils test (it asserted the injection) and add a dedicated regression guard. Reported-by: @mochizzan Refs: #3502, #3388, #3400, #3422 * fix(authz): fall back to URL token when Authorization isn't a usable Bearer (#3504) Integrated into release/v3.8.18 * fix(playground): authenticate via session, test key policy by id (#3503) Integrated into release/v3.8.18 * docs(changelog): record #3510, #3504, #3503 under v3.8.18 * fix: llama base url normalization (#3519) * docs(changelog): reconcile v3.8.18 — add #3519, #3513, #3435-repair, gitignore chore (full commit↔changelog coverage) * fix(opencode-plugin): bound regex quantifiers in normaliseFreeLabel (polynomial-ReDoS) CodeQL js/polynomial-redos: unbounded \s* before an anchored \s*$ allowed O(n²) backtracking on attacker-influenced display names. Bounded to {0,8}/{1,8} (ample for any real label spacing). Plugin builds + 254 tests green. * fix(types): restore clean typecheck:core for v3.8.18 release gate - getPendingRequests() typed to real shape (was widened to object) → fixes unknown 'count' in the unified-requests view (#3401) - streamChunks log payload cast to its declared type (callLogs.ts) - preScreenTargets aligned to canonical IsModelAvailable signature (#3169), Promise.resolve-normalized so .catch never hits a bare boolean All 5 gates green: lint(0 err) + typecheck:core + cycles + docs-all + unit + vitest(146). --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Andrey Borodulin <borodulin@gmail.com> Co-authored-by: Dmitrii Safronov <zimniy@cyberbrain.cc> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: PizzaV <103120356+pizzav-xyz@users.noreply.github.com> Co-authored-by: Markus Hartung <mail@hartmark.se> Co-authored-by: Felipe Almeman <4226997+zhiru@users.noreply.github.com>
362 lines
9.7 KiB
TypeScript
362 lines
9.7 KiB
TypeScript
import { trackPendingRequest } from "@/lib/usageDb";
|
|
import { FORMATS } from "../translator/formats.ts";
|
|
import { PENDING_REQUEST_CLEARED_MARKER } from "./stream.ts";
|
|
|
|
// Stream handler with disconnect detection - shared for all providers
|
|
|
|
const DISCONNECT_ABORT_DELAY_MS = 2_000;
|
|
|
|
type StreamDisconnectEvent = {
|
|
reason: string;
|
|
duration: number;
|
|
};
|
|
|
|
type StreamControllerOptions = {
|
|
onDisconnect?: (event: StreamDisconnectEvent) => void;
|
|
provider?: string;
|
|
model?: string;
|
|
connectionId?: string | null;
|
|
clientResponseFormat?: string | null;
|
|
};
|
|
|
|
type StreamController = ReturnType<typeof createStreamController>;
|
|
|
|
type StreamErrorStatusKind = "rate_limit" | "authentication" | "permission" | "client" | "server";
|
|
|
|
type StreamErrorStatusMapping = {
|
|
responses: {
|
|
type: string;
|
|
code: string;
|
|
};
|
|
claude: {
|
|
type: string;
|
|
};
|
|
};
|
|
|
|
function isResponsesClientFormat(clientResponseFormat?: string | null): boolean {
|
|
return (
|
|
clientResponseFormat === FORMATS.OPENAI_RESPONSES ||
|
|
clientResponseFormat === FORMATS.OPENAI_RESPONSE
|
|
);
|
|
}
|
|
|
|
function getStreamErrorStatusKind(statusCode: number): StreamErrorStatusKind {
|
|
if (statusCode === 429) return "rate_limit";
|
|
if (statusCode === 401) return "authentication";
|
|
if (statusCode === 403) return "permission";
|
|
if (statusCode >= 400 && statusCode < 500) return "client";
|
|
return "server";
|
|
}
|
|
|
|
function getStreamErrorStatusMapping(statusCode: number): StreamErrorStatusMapping {
|
|
switch (getStreamErrorStatusKind(statusCode)) {
|
|
case "rate_limit":
|
|
return {
|
|
responses: { type: "rate_limit_error", code: "rate_limit_exceeded" },
|
|
claude: { type: "rate_limit_error" },
|
|
};
|
|
case "authentication":
|
|
return {
|
|
responses: { type: "authentication_error", code: "invalid_authentication" },
|
|
claude: { type: "authentication_error" },
|
|
};
|
|
case "permission":
|
|
return {
|
|
responses: { type: "authentication_error", code: "permission_denied" },
|
|
claude: { type: "permission_error" },
|
|
};
|
|
case "client":
|
|
return {
|
|
responses: { type: "invalid_request_error", code: "bad_request" },
|
|
claude: { type: "invalid_request_error" },
|
|
};
|
|
case "server":
|
|
return {
|
|
responses: { type: "server_error", code: "server_error" },
|
|
claude: { type: "api_error" },
|
|
};
|
|
default:
|
|
return {
|
|
responses: { type: "server_error", code: "server_error" },
|
|
claude: { type: "api_error" },
|
|
};
|
|
}
|
|
}
|
|
|
|
function encodeSseEvent(
|
|
data: unknown,
|
|
{
|
|
event,
|
|
includeDone = false,
|
|
}: {
|
|
event?: string;
|
|
includeDone?: boolean;
|
|
} = {}
|
|
) {
|
|
if (event && /[\r\n]/.test(event)) {
|
|
throw new Error("SSE event names must not contain newlines");
|
|
}
|
|
|
|
const encoder = new TextEncoder();
|
|
const prefix = event ? `event: ${event}\n` : "";
|
|
const chunks = [encoder.encode(`${prefix}data: ${JSON.stringify(data)}\n\n`)];
|
|
if (includeDone) {
|
|
chunks.push(encoder.encode("data: [DONE]\n\n"));
|
|
}
|
|
return chunks;
|
|
}
|
|
|
|
// Get HH:MM:SS timestamp
|
|
function getTimeString() {
|
|
return new Date().toLocaleTimeString("en-US", {
|
|
hour12: false,
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
second: "2-digit",
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create stream controller with abort and disconnect detection
|
|
* @param {object} options
|
|
* @param {function} options.onDisconnect - Callback when client disconnects
|
|
* @param {object} options.log - Logger instance
|
|
* @param {string} options.provider - Provider name
|
|
* @param {string} options.model - Model name
|
|
*/
|
|
/** @param {StreamControllerOptions} options */
|
|
export function createStreamController({
|
|
onDisconnect,
|
|
provider,
|
|
model,
|
|
connectionId,
|
|
clientResponseFormat,
|
|
}: StreamControllerOptions = {}) {
|
|
const abortController = new AbortController();
|
|
const startTime = Date.now();
|
|
let disconnected = false;
|
|
let abortTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
let pendingRequestCleared = false;
|
|
|
|
const logStream = (status) => {
|
|
const duration = Date.now() - startTime;
|
|
const p = provider?.toUpperCase() || "UNKNOWN";
|
|
console.log(
|
|
`[${getTimeString()}] 🌊 [STREAM] ${p} | ${model || "unknown"} | ${duration}ms | ${status}`
|
|
);
|
|
};
|
|
|
|
const clearPendingRequest = (error?: unknown) => {
|
|
if (pendingRequestCleared) return;
|
|
if (
|
|
error &&
|
|
typeof error === "object" &&
|
|
(error as Record<string, unknown>)[PENDING_REQUEST_CLEARED_MARKER] === true
|
|
) {
|
|
pendingRequestCleared = true;
|
|
return;
|
|
}
|
|
|
|
pendingRequestCleared = true;
|
|
if (!model && !provider && !connectionId) return;
|
|
try {
|
|
trackPendingRequest(model || "", provider || "", connectionId ?? null, false);
|
|
} catch {}
|
|
};
|
|
|
|
return {
|
|
signal: abortController.signal,
|
|
startTime,
|
|
|
|
isConnected: () => !disconnected,
|
|
|
|
// Call when client disconnects
|
|
handleDisconnect: (reason = "client_closed") => {
|
|
if (disconnected) return;
|
|
disconnected = true;
|
|
|
|
logStream(`disconnect: ${reason}`);
|
|
|
|
// Decrement pending request counter — the TransformStream flush() won't
|
|
// fire when the client aborts mid-stream, so we must clean up here.
|
|
clearPendingRequest();
|
|
|
|
// Delay abort to allow cleanup
|
|
abortTimeout = setTimeout(() => {
|
|
abortController.abort();
|
|
}, DISCONNECT_ABORT_DELAY_MS);
|
|
|
|
onDisconnect?.({ reason, duration: Date.now() - startTime });
|
|
},
|
|
|
|
// Call when stream completes normally
|
|
handleComplete: () => {
|
|
if (disconnected) return;
|
|
disconnected = true;
|
|
|
|
logStream("complete");
|
|
|
|
if (abortTimeout) {
|
|
clearTimeout(abortTimeout);
|
|
abortTimeout = null;
|
|
}
|
|
},
|
|
|
|
// Call on error
|
|
handleError: (error: unknown) => {
|
|
if (abortTimeout) {
|
|
clearTimeout(abortTimeout);
|
|
abortTimeout = null;
|
|
}
|
|
|
|
clearPendingRequest(error);
|
|
|
|
if (error instanceof Error && error.name === "AbortError") {
|
|
logStream("aborted");
|
|
return;
|
|
}
|
|
|
|
if (error instanceof Error) {
|
|
logStream(`error: ${error.message}`);
|
|
return;
|
|
}
|
|
logStream("error: unknown");
|
|
},
|
|
|
|
abort: () => abortController.abort(),
|
|
clientResponseFormat,
|
|
};
|
|
}
|
|
|
|
function buildStreamErrorChunks(
|
|
errorMsg: string,
|
|
statusCode: number,
|
|
clientResponseFormat?: string | null
|
|
) {
|
|
const statusMapping = getStreamErrorStatusMapping(statusCode);
|
|
|
|
if (isResponsesClientFormat(clientResponseFormat)) {
|
|
const errorEvent = {
|
|
type: "response.failed",
|
|
response: {
|
|
id: null,
|
|
status: "failed",
|
|
error: {
|
|
message: errorMsg,
|
|
type: statusMapping.responses.type,
|
|
code: statusMapping.responses.code,
|
|
},
|
|
},
|
|
};
|
|
|
|
return encodeSseEvent(errorEvent, { event: "response.failed" });
|
|
}
|
|
|
|
if (clientResponseFormat === FORMATS.CLAUDE) {
|
|
const errorEvent = {
|
|
type: "error",
|
|
error: {
|
|
type: statusMapping.claude.type,
|
|
message: errorMsg,
|
|
},
|
|
};
|
|
|
|
return encodeSseEvent(errorEvent, { event: "error" });
|
|
}
|
|
|
|
const errorEvent = {
|
|
object: "chat.completion.chunk",
|
|
choices: [
|
|
{
|
|
index: 0,
|
|
delta: {},
|
|
finish_reason: "error",
|
|
},
|
|
],
|
|
error: {
|
|
message: errorMsg,
|
|
type: statusMapping.responses.type,
|
|
code: statusMapping.responses.code,
|
|
},
|
|
};
|
|
|
|
return encodeSseEvent(errorEvent, { includeDone: true });
|
|
}
|
|
|
|
/**
|
|
* Create transform stream with disconnect detection
|
|
* Wraps existing transform stream and adds abort capability
|
|
*/
|
|
export function createDisconnectAwareStream(transformStream, streamController) {
|
|
const reader = transformStream.readable.getReader();
|
|
const writer = transformStream.writable.getWriter();
|
|
|
|
return new ReadableStream(
|
|
{
|
|
async pull(controller) {
|
|
if (!streamController.isConnected()) {
|
|
controller.close();
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const { done, value } = await reader.read();
|
|
if (done) {
|
|
streamController.handleComplete();
|
|
controller.close();
|
|
return;
|
|
}
|
|
controller.enqueue(value);
|
|
} catch (error) {
|
|
streamController.handleError(error);
|
|
|
|
// T35: Encapsulate mid-stream errors as SSE events instead of abruptly aborting
|
|
// This prevents TransferEncodingError on the client side
|
|
const errorMsg = error instanceof Error ? error.message : "Upstream stream error";
|
|
const statusCode =
|
|
typeof error === "object" && error !== null && "statusCode" in error
|
|
? Number((error as { statusCode?: unknown }).statusCode) || 500
|
|
: 500;
|
|
|
|
for (const chunk of buildStreamErrorChunks(
|
|
errorMsg,
|
|
statusCode,
|
|
streamController.clientResponseFormat
|
|
)) {
|
|
controller.enqueue(chunk);
|
|
}
|
|
|
|
controller.close();
|
|
}
|
|
},
|
|
|
|
cancel(reason) {
|
|
streamController.handleDisconnect(reason || "cancelled");
|
|
reader.cancel();
|
|
setTimeout(() => {
|
|
writer.abort();
|
|
}, DISCONNECT_ABORT_DELAY_MS).unref?.();
|
|
},
|
|
},
|
|
{ highWaterMark: 16384 }
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Pipe provider response through transform with disconnect detection
|
|
* @param {Response} providerResponse - Response from provider
|
|
* @param {TransformStream} transformStream - Transform stream for SSE
|
|
* @param {object} streamController - Stream controller from createStreamController
|
|
*/
|
|
export function pipeWithDisconnect(
|
|
providerResponse: Response,
|
|
transformStream: TransformStream<Uint8Array, Uint8Array>,
|
|
streamController: StreamController
|
|
) {
|
|
const transformedBody = providerResponse.body.pipeThrough(transformStream);
|
|
return createDisconnectAwareStream(
|
|
{ readable: transformedBody, writable: { getWriter: () => ({ abort: () => {} }) } },
|
|
streamController
|
|
);
|
|
}
|