Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
9957d6246f fix(cli): run Node runtime guard before heavy import chain (#12296)
bin/omniroute.mjs imported getNodeRuntimeSupport/getNodeRuntimeWarning but
never called them. On a Node/V8 build predating v-flag regex support, the
subsequent tsx/esm + Commander command-registration chain pulls in ora ->
string-width, whose top-level v-flag regex literals fail to parse, throwing
a bare 'Invalid regular expression flags' SyntaxError instead of a clear
runtime-support message. Call the guard right after the --version fast path
(and before the heavy import chain), skipping it for the same read-only
invocations shouldProvisionStorageKey already exempts.
2026-09-10 14:48:13 -03:00
7 changed files with 92 additions and 104 deletions

View File

@@ -50,6 +50,34 @@ if (isVersionFastPath(process.argv)) {
process.exit(0);
}
// Detect an unsupported Node.js runtime BEFORE the heavy `tsx/esm` import and
// Commander's ~70-command registration chain run. That chain pulls in `ora` ->
// the hoisted `string-width` package, whose module contains top-level ES2024
// Unicode-set (`v` flag) regex literals. On a Node/V8 build that predates
// `v`-flag support, those literals fail to even *parse*, throwing a bare
// `SyntaxError: Invalid regular expression flags` deep inside a transitive
// dependency instead of an actionable message (#12296). Skip this for the
// same read-only invocations `shouldProvisionStorageKey` already exempts
// (`--help`/`-h`, `help`/`completion`) — those still need the full command
// registry to render their output, so an incompatible runtime crashing there
// is a separate, pre-existing limitation this fix does not attempt to solve.
if (shouldProvisionStorageKey(process.argv)) {
const nodeSupport = getNodeRuntimeSupport();
if (!nodeSupport.nodeCompatible) {
const runtimeWarning = getNodeRuntimeWarning() || "Unsupported Node.js runtime detected.";
console.error(
`\x1b[31m✖ Node.js ${nodeSupport.nodeVersion} is not supported.\x1b[0m\n` +
` ${runtimeWarning}\n` +
` Supported runtimes: ${nodeSupport.supportedDisplay}\n` +
` Recommended: Node.js ${nodeSupport.recommendedVersion}\n` +
` If you installed OmniRoute globally, run \`node -v\` and confirm \`omniroute\` is not resolving to\n` +
` a stale/distro-packaged \`nodejs\` binary (e.g. /usr/bin/node) instead of the version you expect —\n` +
` that mismatch is the most common cause even when package.json's engines range is correct.`
);
process.exit(1);
}
}
// MCP stdio transport uses stdout exclusively for JSON-RPC messages. Redirect
// console.log/warn to stderr before anything else runs — including the tsx/esm and
// polyfill imports below, since those (and their transitive module graphs, e.g. DB

View File

@@ -1 +0,0 @@
- fix(sse): require Responses-shaped body before native OpenAI-compatible passthrough (#12129)

View File

@@ -0,0 +1 @@
- fix(cli): run the Node.js runtime compatibility guard before the heavy `tsx/esm` + Commander import chain so an unsupported runtime gets a clear message instead of a raw `Invalid regular expression flags` crash (#12296)

View File

@@ -731,7 +731,6 @@ export async function handleChatCore({
sourceFormat,
endpointPath,
providerSpecificData: credentials?.providerSpecificData,
body,
});
const responsesInputItems = Array.isArray(body?.input) ? body.input : [];
const customToolNames = collectCustomToolNamesForSourceFormat(

View File

@@ -53,35 +53,19 @@ export function stampNativeResponsesPassthroughBody(
return { ...body, _nativeOpenAICompatibleResponsesPassthrough: true };
}
// A body only qualifies for the native-Responses passthrough fast path when it is
// actually shaped like a Responses API request (`input`, no `messages`). Endpoint
// path alone is not sufficient: an internally-synthesized Chat Completions-shaped
// body (e.g. the context-handoff summary request) can be dispatched through a
// closure that still carries the original client request's `/responses` endpoint,
// which otherwise makes `sourceFormat` resolve to "openai-responses" even though
// the body itself was never translated. See issue #12129.
function isResponsesShapedBody(body: unknown): boolean {
if (!body || typeof body !== "object") return false;
const candidate = body as Record<string, unknown>;
return candidate.input !== undefined && candidate.messages === undefined;
}
export function shouldUseNativeOpenAICompatibleResponsesPassthrough({
provider,
sourceFormat,
endpointPath,
providerSpecificData,
body,
}: {
provider?: string | null;
sourceFormat?: string | null;
endpointPath?: string | null;
providerSpecificData?: unknown;
body?: unknown;
}): boolean {
if (!provider?.startsWith("openai-compatible-")) return false;
if (sourceFormat !== FORMATS.OPENAI_RESPONSES) return false;
if (body !== undefined && !isResponsesShapedBody(body)) return false;
if (providerSpecificData && typeof providerSpecificData === "object") {
const psd = providerSpecificData as Record<string, unknown>;
if (psd.apiType === "responses" || psd._omnirouteForceResponsesUpstream === true) {

View File

@@ -1,86 +0,0 @@
// Regression test for issue #12129: an internal context-handoff summary request (built in
// Chat Completions shape -- `messages`, no `input`) is dispatched through the SAME
// handleSingleModel closure that carries the ORIGINAL client request's endpoint.
// When that original endpoint matched `/responses` and the resolved handoff-model
// provider is an openai-compatible-* connection configured with apiType "responses",
// the pipeline used to decide the body was already native-Responses-shaped and skip
// chat->responses translation entirely (`_nativeOpenAICompatibleResponsesPassthrough`),
// so the upstream received `messages` on `/v1/responses` and rejected it with zero input.
//
// Fix: `shouldUseNativeOpenAICompatibleResponsesPassthrough` now requires the body to
// actually look Responses-shaped (`input` present, `messages` absent) before allowing
// the passthrough fast path, so an internally-synthesized chat-shaped body is routed
// through the normal chat->responses translation layer instead.
import assert from "node:assert/strict";
import { test } from "node:test";
import { resolveChatCoreRequestFormat } from "../../open-sse/handlers/chatCore/requestFormat.ts";
import { shouldUseNativeOpenAICompatibleResponsesPassthrough } from "../../open-sse/handlers/chatCore/passthroughHelpers.ts";
test("internal chat-shaped handoff body is no longer treated as native Responses passthrough", () => {
const clientRawRequest = {
endpoint: "/v1/responses",
headers: new Headers(),
};
const summaryBody = {
model: "some-handoff-model",
messages: [{ role: "user", content: "Summarize this conversation." }],
stream: false,
max_tokens: 800,
temperature: 0.1,
_omnirouteSkipContextRelay: true,
_omnirouteInternalRequest: "context-handoff",
};
const { sourceFormat, endpointPath } = resolveChatCoreRequestFormat({
clientRawRequest,
body: summaryBody,
provider: "openai-compatible-responses-cliproxy",
userAgent: null,
});
assert.equal(sourceFormat, "openai-responses");
assert.equal(endpointPath, "/v1/responses");
const providerSpecificData = { apiType: "responses" };
const nativePassthrough = shouldUseNativeOpenAICompatibleResponsesPassthrough({
provider: "openai-compatible-responses-cliproxy",
sourceFormat,
endpointPath,
providerSpecificData,
body: summaryBody,
});
assert.equal(
nativePassthrough,
false,
"fixed: chat-shaped internal body must not take the native-Responses passthrough shortcut"
);
assert.equal((summaryBody as Record<string, unknown>).input, undefined);
assert.ok(Array.isArray(summaryBody.messages) && summaryBody.messages.length > 0);
});
test("genuine Responses-shaped body still takes the native passthrough fast path", () => {
const genuineResponsesBody = {
model: "gpt-5.6-sol",
input: [{ role: "user", content: [{ type: "input_text", text: "Hello" }] }],
stream: false,
};
const nativePassthrough = shouldUseNativeOpenAICompatibleResponsesPassthrough({
provider: "openai-compatible-responses-cliproxy",
sourceFormat: "openai-responses",
endpointPath: "/v1/responses",
providerSpecificData: { apiType: "responses" },
body: genuineResponsesBody,
});
assert.equal(
nativePassthrough,
true,
"a genuine Responses-shaped client body must keep the zero-translation fast path"
);
});

View File

@@ -0,0 +1,63 @@
// Regression test for issue #12296: "Invalid regular expression flags" crash
// right after STORAGE_ENCRYPTION_KEY generation on first run.
//
// Root cause: bin/omniroute.mjs imports getNodeRuntimeSupport/getNodeRuntimeWarning
// from ./nodeRuntimeSupport.mjs (intended to detect an unsupported Node.js runtime
// and print a friendly warning) but never actually CALLED either function before
// doing the heavy `await import("tsx/esm")` + Commander command-registration import
// chain. That chain pulls in `ora` -> `string-width@8.x`, whose index.js contains
// top-level ES2024 Unicode-set (`v` flag) regex literals
// (e.g. `/^\p{RGI_Emoji}$/v`) that fail to even PARSE on a V8/Node build that
// predates `v`-flag support - throwing exactly
// `SyntaxError: Invalid regular expression flags` (no flag value in the message,
// matching the report) deep inside a transitive dependency's module graph, instead
// of the intended actionable "Node.js vX is not supported" message.
//
// The only two call sites of getNodeRuntimeSupport/getNodeRuntimeWarning in bin/
// used to be inside `serve.mjs` and `doctor.mjs` - both unreachable if the import
// chain itself crashed first. This test asserts the guard actually runs (is
// called) in bin/omniroute.mjs, and that it runs BEFORE the heavy import chain
// that pulls in string-width.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { join, dirname } from "node:path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const OMNIROUTE_MJS = join(__dirname, "..", "..", "bin", "omniroute.mjs");
test("bin/omniroute.mjs invokes the Node runtime compatibility guard before the heavy tsx/esm + command-registration import chain", () => {
const src = readFileSync(OMNIROUTE_MJS, "utf8");
const heavyImportIdx = src.indexOf('await import("tsx/esm")');
assert.ok(
heavyImportIdx > -1,
"expected bin/omniroute.mjs to still contain the tsx/esm dynamic import this test anchors on"
);
const callPattern = /getNodeRuntime(?:Support|Warning)\s*\(/g;
let firstCallIdx = -1;
for (const match of src.matchAll(callPattern)) {
firstCallIdx = match.index ?? -1;
break;
}
assert.notEqual(
firstCallIdx,
-1,
"getNodeRuntimeSupport()/getNodeRuntimeWarning() is imported in bin/omniroute.mjs but never called there - " +
"an unsupported/too-old Node.js runtime gets no early friendly warning and instead crashes with a raw " +
"native SyntaxError (e.g. 'Invalid regular expression flags' from string-width@8's v-flag regex literals) " +
"deep inside the tsx/esm + Commander import chain. See issue #12296."
);
assert.ok(
firstCallIdx < heavyImportIdx,
"the Node runtime compatibility guard must run BEFORE `await import(\"tsx/esm\")` and the rest of the heavy " +
"import chain (Commander command registry, ora/boxen/update-notifier, etc.) so an unsupported Node.js " +
"version is reported with a clear message and a clean exit instead of crashing on a native parse error " +
"raised while loading a transitive dependency."
);
});