Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ _In development — bullets added per PR; finalized at release._
- **fix(pollinations):** stop forcing `jsonMode` on every request. Pollinations treats `jsonMode=true` as "the model MUST return JSON" and rejects (HTTP 400 "messages must contain the word 'json'") any normal chat request whose messages don't mention "json", so all non-JSON chat was broken. `jsonMode` is now only enabled when the caller actually requests JSON output (`response_format.type` of `json_object` or `json_schema`). (#3981)
- **fix(antigravity):** default `safetySettings` to all-OFF for parity with the native Gemini paths. The Antigravity (Google Cloud Code) request builder set `safetySettings: undefined`, which `JSON.stringify` drops — so no safety settings reached Google and its server-side defaults false-flagged benign technical prompts as `prohibited_content` (HTTP 200 + blocked body, which combo failover treats as terminal). Now honors a caller-supplied value and otherwise defaults to `DEFAULT_SAFETY_SETTINGS`, matching the claude-to-gemini / openai-to-gemini paths (#5003)
- **fix(chatgpt-web):** map the advertised `gpt-5.5`, `gpt-5.5-pro`, `gpt-5.4-pro` and `gpt-5.2-pro` catalog ids to their dash-form ChatGPT backend slugs. They were missing from `MODEL_MAP`, so the executor sent the dot-form id verbatim, which the ChatGPT backend silently ignored and served the default Plus model instead of the requested one. Adds a drift guard asserting no advertised dot-form id reaches the backend verbatim. (#4665)
- **fix(api):** stop `GET /api/system/env/repair` from returning HTTP 500 on packaged installs, which broke the onboarding wizard. `scripts/dev/sync-env.mjs` ran `createRequire(import.meta.url)` at module top-level; once webpack bundles it into the standalone route, `import.meta.url` is frozen to the build-machine path and `createRequire` throws during module evaluation, so the whole route failed to load and every hit 500'd. `createRequire` is now resolved lazily inside the guarded `better-sqlite3` block, root-dir resolution falls back to `process.cwd()` when `import.meta.url` is unusable, and the route passes an explicit `rootDir`. (#5006)
- **fix(headroom):** translate openai-responses input through OpenAI for external compression. `adaptBodyForCompression` now serialises `function_call_output` items whose `output` field is a JSON object (not a string) so compression engines can process the content — previously those items were excluded from compression because `hasTextContent()` returned false for object values. (thanks @anki1kr)
- **fix(executors):** preserve literal `reasoning_effort: "max"` for Ollama Cloud instead of normalizing it to `xhigh`. Ollama Cloud accepts `high|medium|low|max|none` and rejects `xhigh` (`invalid reasoning value: 'xhigh'`); `ollama-cloud` is now in `supportsMaxEffortForProvider()`, covering both top-level `reasoning_effort` and nested `reasoning.effort`. OpenRouter DeepSeek `max→xhigh` is unaffected. ([#4993](https://github.com/diegosouzapw/OmniRoute/pull/4993) — thanks @Thinkscape)
- **fix(copilot):** replace `execSync` shell interpolation with `execFile` in the `runOmniRouteCli` tool to prevent command injection. The user-supplied command is now split into an argv array and passed to `execFile` (no shell), so shell metacharacters are treated as literal text; error output is routed through `sanitizeErrorMessage()`. ([#5024](https://github.com/diegosouzapw/OmniRoute/pull/5024) — thanks @hamsa0x7)
Expand Down
6 changes: 3 additions & 3 deletions config/quality/file-size-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
"_rebaseline_pr1043_minimax_tts": "Upstream port decolua/9router#1043 (toanalien) own growth: audioSpeech.ts 965->1061 (+96). Adds MiniMax T2A v2 TTS dispatch (handleMinimaxSpeech + hexToBytes helper) — provider entry was already in audioRegistry (format: minimax-tts) but no handler existed, falling through to the OpenAI-compatible default that fails (T2A has custom shape + hex-encoded audio + base_resp envelope). New branch sits next to the other inline provider branches (xiaomi-mimo, coqui, tortoise, aws-polly) — extracting would just create indirection. Covered by tests/unit/minimax-tts-1043.test.ts (3 tests, GREEN: success, base_resp error, invalid-hex).",
"open-sse/config/providerRegistry.ts": 4731,
"open-sse/executors/antigravity.ts": 1735,
"open-sse/executors/base.ts": 1414,
"open-sse/executors/base.ts": 1416,
"open-sse/executors/chatgpt-web.ts": 2870,
"open-sse/executors/claude-web.ts": 1057,
"open-sse/executors/codex.ts": 1528,
Expand Down Expand Up @@ -168,7 +168,7 @@
"src/app/(dashboard)/dashboard/combos/page.tsx": 4485,
"src/app/(dashboard)/dashboard/costs/CostOverviewTab.tsx": 1495,
"src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx": 1007,
"src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx": 2570,
"src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx": 2612,
"src/app/(dashboard)/dashboard/health/page.tsx": 1091,
"src/app/(dashboard)/dashboard/playground/components/tabs/ApiTab.tsx": 847,
"src/app/(dashboard)/dashboard/providers/[id]/ProviderDetailPageClient.tsx": 784,
Expand Down Expand Up @@ -206,7 +206,7 @@
"src/lib/db/models.ts": 1259,
"src/lib/db/providers.ts": 1063,
"src/lib/db/proxies.ts": 1060,
"src/lib/db/settings.ts": 1149,
"src/lib/db/settings.ts": 1151,
"src/lib/db/usageAnalytics.ts": 925,
"src/lib/evals/evalRunner.ts": 961,
"src/lib/memory/retrieval.ts": 1171,
Expand Down
27 changes: 24 additions & 3 deletions scripts/dev/sync-env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,23 @@ import { dirname, join, resolve } from "node:path";
import { homedir } from "node:os";
import { fileURLToPath } from "node:url";

const require = createRequire(import.meta.url);
/**
* Resolve the repository/package root that holds `.env` / `.env.example`.
*
* When this module is statically bundled into a Next.js standalone route,
* `import.meta.url` is frozen to the build-machine path
* (`file:///home/runner/.../sync-env.mjs`) and `fileURLToPath` can throw at
* runtime. Callers (e.g. the env-repair route) pass an explicit `rootDir`;
* when they don't, fall back to `process.cwd()` instead of crashing. (#5006)
*/
function resolveRootDir(rootDir) {
if (rootDir) return rootDir;
try {
return dirname(dirname(fileURLToPath(import.meta.url)));
} catch {
return process.cwd();
}
}
Comment on lines +31 to +38

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If import.meta.url is a valid file URL but points to a build-machine path (which is common when bundled), fileURLToPath(import.meta.url) will not throw, but the resolved directory will not exist on the user's machine. This will cause getEnvSyncPlan to look for .env.example in a non-existent directory and silently return available: false instead of falling back to process.cwd(). Checking if the resolved directory actually exists before returning it makes this fallback much more robust.

function resolveRootDir(rootDir) {
  if (rootDir) return rootDir;
  try {
    const resolved = dirname(dirname(fileURLToPath(import.meta.url)));
    if (existsSync(resolved)) {
      return resolved;
    }
  } catch {}
  return process.cwd();
}


const CRYPTO_SECRETS = {
JWT_SECRET: () => randomBytes(64).toString("hex"),
Expand Down Expand Up @@ -68,6 +84,11 @@ function hasEncryptedCredentials(dataDir) {
if (!existsSync(dbPath)) return false;

try {
// Resolve `require` lazily here (not at module top-level): when this file is
// bundled into a standalone route, a top-level `createRequire(import.meta.url)`
// throws during module evaluation and 500s the whole route (#5006). Inside this
// guarded block, any failure simply returns false (the safe default below).
const require = createRequire(import.meta.url);
const Database = require("better-sqlite3");
const db = new Database(dbPath, { readonly: true, fileMustExist: true });
try {
Expand Down Expand Up @@ -170,7 +191,7 @@ function parseExampleEntries(content, scope = "full") {
}

export function getEnvSyncPlan({ rootDir, scope = "full" } = {}) {
const root = rootDir || dirname(dirname(fileURLToPath(import.meta.url)));
const root = resolveRootDir(rootDir);
const envExamplePath = join(root, ".env.example");
const envPath = join(root, ".env");

Expand Down Expand Up @@ -237,7 +258,7 @@ function replaceBlankSecret(content, key, value) {

export function syncEnv({ rootDir, quiet = false, scope = "full" } = {}) {
const log = quiet ? () => {} : (message) => process.stderr.write(`[sync-env] ${message}\n`);
const root = rootDir || dirname(dirname(fileURLToPath(import.meta.url)));
const root = resolveRootDir(rootDir);
const envExamplePath = join(root, ".env.example");
const envPath = join(root, ".env");

Expand Down
11 changes: 8 additions & 3 deletions src/app/api/system/env/repair/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ export async function GET(request: Request) {

try {
const { getEnvSyncPlan } = await loadSyncHelpers();
const plan = getEnvSyncPlan({ scope: "oauth" });
// Pass an explicit rootDir so the helper never derives the root from a
// webpack-frozen `import.meta.url` (build-machine path) — that froze the
// path and 500'd this route on packaged installs (#5006). cwd matches the
// `.env` target used by createEnvBackup() above.
const plan = getEnvSyncPlan({ scope: "oauth", rootDir: process.cwd() });

return NextResponse.json({
available: plan.available,
Expand All @@ -63,8 +67,9 @@ export async function POST(request: Request) {
try {
const { syncEnv, getEnvSyncPlan } = await loadSyncHelpers();
const backupPath = createEnvBackup();
const result = syncEnv({ scope: "oauth", quiet: true });
const plan = getEnvSyncPlan({ scope: "oauth" });
// Explicit rootDir (cwd) — see GET above (#5006).
const result = syncEnv({ scope: "oauth", quiet: true, rootDir: process.cwd() });
const plan = getEnvSyncPlan({ scope: "oauth", rootDir: process.cwd() });

return NextResponse.json({
success: true,
Expand Down
102 changes: 102 additions & 0 deletions tests/unit/sync-env-bundled-require-5006.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* Regression guard for #5006 — `/api/system/env/repair` 500s on packaged install.
*
* Root cause: `route.ts` statically imports `scripts/dev/sync-env.mjs`, so webpack
* inlines it into the standalone route bundle. `sync-env.mjs` then ran
* `createRequire(import.meta.url)` at TOP-LEVEL module scope — when bundled,
* `import.meta.url` is frozen to the build-machine path
* (`file:///home/runner/.../sync-env.mjs`), which `createRequire` rejects at runtime.
* Because the throw happens during module evaluation (reached via the static import),
* the whole route module fails to load → every hit returns HTTP 500 → onboarding breaks.
*
* The fix moves `createRequire` out of top-level scope into the single function that
* needs `better-sqlite3` (guarded by the existing try/catch), and makes the root-dir
* resolution tolerant of an unusable `import.meta.url` (falls back to `process.cwd()`),
* so importing/evaluating the module — and calling its exports — never throws.
*/
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const SYNC_ENV_PATH = fileURLToPath(new URL("../../scripts/dev/sync-env.mjs", import.meta.url));

const mod = (await import("../../scripts/dev/sync-env.mjs")) as {
getEnvSyncPlan: (opts?: { rootDir?: string; scope?: string }) => {
available: boolean;
created: boolean;
added: number;
missingEntries: Array<{ key: string; value: string }>;
};
syncEnv: (opts?: { rootDir?: string; quiet?: boolean; scope?: string }) => {
created: boolean;
added: number;
};
};

function writeOauthEnvExample(rootDir: string) {
fs.writeFileSync(
path.join(rootDir, ".env.example"),
[
"# ═══════════════════════════════════════════════════",
"# OAUTH PROVIDER CREDENTIALS",
"# ═══════════════════════════════════════════════════",
"CLAUDE_OAUTH_CLIENT_ID=claude-default",
"CODEX_OAUTH_CLIENT_ID=codex-default",
"# ─────────────────────────────────────────────────────────────────────────────",
"# Provider User-Agent Overrides (optional)",
"# ─────────────────────────────────────────────────────────────────────────────",
"",
].join("\n"),
"utf8"
);
}

test("#5006: sync-env.mjs does not call createRequire at module top-level scope", () => {
const source = fs.readFileSync(SYNC_ENV_PATH, "utf8");

// A top-level `const require = createRequire(import.meta.url)` (column 0, no
// leading indentation) is the exact crash vector: it runs during module
// evaluation with a webpack-frozen `import.meta.url`. It must live inside a
// function body / try-catch instead.
assert.doesNotMatch(
source,
/^const\s+require\s*=\s*createRequire\s*\(/m,
"createRequire(import.meta.url) must not run at top-level module scope (bundled import.meta.url is frozen → throws on module load → route 500)"
);

// `createRequire` is still used lazily where better-sqlite3 is needed — but only
// from inside a function (every occurrence is indented, never column 0).
for (const line of source.split(/\r?\n/)) {
if (/createRequire\s*\(/.test(line)) {
assert.match(
line,
/^\s+/,
`createRequire must be called from inside a function (indented), found top-level: ${line}`
);
}
}
});

test("#5006: getEnvSyncPlan(oauth) works with explicit rootDir and never throws on bad DATA_DIR", () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-5006-"));
const origDataDir = process.env.DATA_DIR;
try {
writeOauthEnvExample(rootDir);
// Point DATA_DIR at a dir with no real SQLite DB — exercises the
// better-sqlite3 / createRequire path that used to crash at module load.
process.env.DATA_DIR = rootDir;

const plan = mod.getEnvSyncPlan({ rootDir, scope: "oauth" });

assert.equal(plan.available, true);
assert.equal(plan.added, 2);
const keys = plan.missingEntries.map((e) => e.key);
assert.deepEqual(keys.sort(), ["CLAUDE_OAUTH_CLIENT_ID", "CODEX_OAUTH_CLIENT_ID"]);
} finally {
process.env.DATA_DIR = origDataDir;
fs.rmSync(rootDir, { recursive: true, force: true });
}
Comment on lines +98 to +101

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In Node.js, assigning undefined to a property of process.env (e.g., process.env.DATA_DIR = undefined) can sometimes coerce the value to the string "undefined" depending on the Node.js version and environment, rather than deleting it. It is safer to explicitly delete the property if it was originally undefined to avoid polluting the environment for subsequent tests.

  } finally {
    if (origDataDir === undefined) {
      delete process.env.DATA_DIR;
    } else {
      process.env.DATA_DIR = origDataDir;
    }
    fs.rmSync(rootDir, { recursive: true, force: true });
  }

});
Loading