Compare commits

..

1 Commits

11 changed files with 95 additions and 319 deletions

View File

@@ -1 +0,0 @@
- **fix(combo):** defer the known-context-overflow hard rejection for compressible requests so compression runs before the final context gate, instead of a raw-body estimate 400'ing generic Responses clients targeting a large model before OmniRoute can shrink it ([#10225](https://github.com/diegosouzapw/OmniRoute/issues/10225))

View File

@@ -0,0 +1 @@
- **fix(build):** stop Turbopack from dead-code-eliminating the Windows Tailscale branches of `src/lib/tailscaleTunnel.ts` in the published build (#10293). The release `dist` is bundled on a Linux runner, and the bundler constant-folds `process.platform`, pruning every non-Linux branch — the Windows installers shipped with no `where` lookup, an always-injected `--socket`, and a lost `net start Tailscale`/windows-default-binary path. The module now reads the platform at runtime via `os.platform()` (a function call a bundler cannot fold), so the Windows branches survive on any build machine; a vitest regression test mocking `os.platform()``win32` guards the anti-fold invariant (RED before, GREEN after).

View File

@@ -591,8 +591,6 @@ export async function handleComboChat({
nesting = null,
hiddenModelsByProvider = getHiddenModelsByProvider(),
clientManagedResponsesContext = false,
deferContextOverflowWhenCompressible = false,
compressionExclusions,
}: HandleComboChatOptions): Promise<Response> {
const comboCtx = createComboContext({ body, combo, settings, relayOptions, log });
const {
@@ -653,8 +651,6 @@ export async function handleComboChat({
signal,
apiKeyAllowedConnections,
hiddenModelsByProvider,
deferContextOverflowWhenCompressible,
compressionExclusions,
runCombo: handleComboChat,
});
if (fusionDispatch) return fusionDispatch;
@@ -704,8 +700,6 @@ export async function handleComboChat({
signal,
apiKeyAllowedConnections,
hiddenModelsByProvider,
deferContextOverflowWhenCompressible,
compressionExclusions,
runCombo: handleComboChat,
});
if (runtimeUnitDispatch) return runtimeUnitDispatch;
@@ -729,8 +723,6 @@ export async function handleComboChat({
signal,
hiddenModelsByProvider,
clientManagedResponsesContext,
deferContextOverflowWhenCompressible,
compressionExclusions,
relayOptions,
});
}
@@ -758,8 +750,6 @@ export async function handleComboChat({
buildAutoCandidates,
hiddenModelsByProvider,
clientManagedResponsesContext,
deferContextOverflowWhenCompressible,
compressionExclusions,
});
if ("earlyResponse" in targetResolution) return targetResolution.earlyResponse;
const { stickyWeightedLimit, getWeightedStepKeyForTarget, preScreenMap } = targetResolution;
@@ -2451,8 +2441,6 @@ async function handleRoundRobinCombo({
nesting = null,
hiddenModelsByProvider = getHiddenModelsByProvider(),
clientManagedResponsesContext,
deferContextOverflowWhenCompressible = false,
compressionExclusions,
relayOptions,
}: HandleRoundRobinOptions): Promise<Response> {
const config = settings
@@ -2510,8 +2498,6 @@ async function handleRoundRobinCombo({
const evalRankedTargets = orderTargetsByEvalScores(tagFilteredTargets, config.evalRouting, log);
const knownContextOverflow = getKnownContextOverflow(evalRankedTargets, body, {
clientManagedResponsesContext,
deferContextOverflowWhenCompressible,
compressionExclusions,
});
if (knownContextOverflow) {
return errorResponseWithComboDiagnostics(

View File

@@ -76,10 +76,6 @@ type PreludeBaseOptionArgs = {
apiKeyAllowedConnections?: string[] | null;
hiddenModelsByProvider?: HiddenModelsByProvider;
clientManagedResponsesContext?: boolean;
/** #10225 — defer the hard context-overflow preflight when compression is enabled. */
deferContextOverflowWhenCompressible?: boolean;
/** Server-side compression exclusions (#8034). */
compressionExclusions?: import("../compression/exclusions.ts").CompressionExclusions;
};
/** Rebuild handleComboChat's option bag verbatim for a recursive dispatch. */
@@ -97,8 +93,6 @@ function buildBaseOptions(a: PreludeBaseOptionArgs): HandleComboChatOptions {
apiKeyAllowedConnections: a.apiKeyAllowedConnections,
hiddenModelsByProvider: a.hiddenModelsByProvider,
clientManagedResponsesContext: a.clientManagedResponsesContext,
deferContextOverflowWhenCompressible: a.deferContextOverflowWhenCompressible,
compressionExclusions: a.compressionExclusions,
};
}
@@ -372,8 +366,6 @@ export async function tryFusionDispatch(args: {
signal?: AbortSignal | null;
apiKeyAllowedConnections?: string[] | null;
hiddenModelsByProvider?: HiddenModelsByProvider;
deferContextOverflowWhenCompressible?: boolean;
compressionExclusions?: import("../compression/exclusions.ts").CompressionExclusions;
runCombo: RunCombo;
}): Promise<Response | null> {
const { cfg, combo, config, strategy, log } = args;
@@ -597,8 +589,6 @@ export async function tryRuntimeUnitDispatch(args: {
signal?: AbortSignal | null;
apiKeyAllowedConnections?: string[] | null;
hiddenModelsByProvider?: HiddenModelsByProvider;
deferContextOverflowWhenCompressible?: boolean;
compressionExclusions?: import("../compression/exclusions.ts").CompressionExclusions;
runCombo: RunCombo;
}): Promise<Response | null> {
const { body, combo, config, strategy, allCombos, log, settings } = args;

View File

@@ -17,7 +17,6 @@
*/
import { getResolvedModelCapabilities } from "../modelCapabilities.ts";
import { isCompressionExcluded, type CompressionExclusions } from "../compression/exclusions.ts";
import { deriveRequestCompatibilityRequirements } from "./comboStructure.ts";
import type { ResolvedComboTarget } from "./types.ts";
@@ -29,19 +28,6 @@ export type KnownContextOverflow = {
targetCount: number;
};
export type KnownContextOverflowOptions = {
clientManagedResponsesContext?: boolean;
/**
* When prompt compression is enabled for this request (global compression switch
* AND not API-key opted-out), defer the hard preflight so chatCore's compression
* pipeline runs before the final context gate — instead of a raw-body estimate
* rejecting a compressible request up front. (#10225)
*/
deferContextOverflowWhenCompressible?: boolean;
/** Server-side compression exclusions (#8034) — targets matching one cannot run compression. */
compressionExclusions?: CompressionExclusions;
};
// #7177: an empty array/object (e.g. a default `messages: []` some combo entrypoints inject
// when the caller sent none) has no real content — counting it would charge a few phantom
// "structural" tokens (JSON.stringify braces/brackets) toward the estimate, which is enough
@@ -83,7 +69,7 @@ export function getKnownContextLimit(
export function getKnownContextOverflow(
targets: ResolvedComboTarget[],
body: Record<string, unknown>,
options: KnownContextOverflowOptions = {}
options: { clientManagedResponsesContext?: boolean } = {}
): KnownContextOverflow | null {
if (targets.length === 0) return null;
// Native Codex Responses clients compact their own item history. Let the concrete
@@ -99,31 +85,6 @@ export function getKnownContextOverflow(
) {
return null;
}
// #10225: a conservative raw-body context estimate must not be treated as proof
// that a compression-enabled request cannot fit. When compression is available
// for this request AND at least one target can actually run it, defer the hard
// rejection so handleChatCore runs proactive compression (chatCore.ts) and its
// post-compression enforceOutputTokenBudget becomes the final context gate —
// returning a local `context_length_exceeded` only if the compressed body still
// cannot fit (no upstream dispatch). Each excluded/native-codex-passthrough
// target is skipped; if no target can compress, the fast preflight is kept.
if (
options.deferContextOverflowWhenCompressible === true &&
targets.some(
(target) =>
!isCompressionExcluded(
{
provider: target.provider,
model: target.modelStr.includes("/")
? target.modelStr.split("/").slice(1).join("/")
: target.modelStr,
},
options.compressionExclusions
)
)
) {
return null;
}
const requirements = deriveRequestCompatibilityRequirements(body);
if (requirements.requiredContextTokens <= 0) return null;

View File

@@ -115,10 +115,6 @@ export interface ResolveComboTargetPipelineDeps {
hiddenModelsByProvider?: HiddenModelsByProvider;
/** Native Responses clients (for example Codex CLI/Desktop) manage compaction themselves. */
clientManagedResponsesContext?: boolean;
/** #10225 — defer the hard context-overflow preflight when compression is enabled for this request. */
deferContextOverflowWhenCompressible?: boolean;
/** Server-side compression exclusions (#8034) — which targets can run compression. */
compressionExclusions?: import("../compression/exclusions.ts").CompressionExclusions;
}
export interface ResolvedComboTargetPipeline {
@@ -734,8 +730,6 @@ export async function resolveComboTargetPipeline(
const overflow = getKnownContextOverflow(orderedTargets, body, {
clientManagedResponsesContext: deps.clientManagedResponsesContext,
deferContextOverflowWhenCompressible: deps.deferContextOverflowWhenCompressible,
compressionExclusions: deps.compressionExclusions,
});
if (overflow) {
return { earlyResponse: buildContextOverflowResponse(overflow, orderedTargets, log) };

View File

@@ -6,7 +6,6 @@
* — logic unchanged, re-exported from combo.ts for backward compatibility.
*/
import type { CompressionExclusions } from "../compression/exclusions.ts";
import type { ProviderCandidate } from "../autoCombo/scoring.ts";
export const RESET_WINDOW_NAMES = ["weekly", "session", "monthly"] as const;
@@ -113,15 +112,6 @@ export type HandleComboChatOptions = {
hiddenModelsByProvider?: HiddenModelsByProvider;
/** Native Responses clients (for example Codex CLI/Desktop) manage compaction themselves. */
clientManagedResponsesContext?: boolean;
/**
* #10225: request-scoped flag — prompt compression is enabled for this request
* (global compression switch ON and not opted-out by the API key). When set, the
* combo preflight defers its hard context-overflow rejection so chatCore's
* compression runs before the final context gate.
*/
deferContextOverflowWhenCompressible?: boolean;
/** Server-side compression exclusions (#8034) — used to check which targets can run compression. */
compressionExclusions?: CompressionExclusions;
};
export type HandleRoundRobinOptions = Omit<HandleComboChatOptions, "apiKeyAllowedConnections">;

View File

@@ -15,9 +15,15 @@ const execFileAsync = promisify(execFile);
const WINDOWS_TAILSCALE_BIN = "C:\\Program Files\\Tailscale\\tailscale.exe";
const WINDOWS_TAILSCALED_BIN = "C:\\Program Files\\Tailscale\\tailscaled.exe";
const IS_MAC = process.platform === "darwin";
const IS_LINUX = process.platform === "linux";
const IS_WINDOWS = process.platform === "win32";
// Runtime platform getter. A bundler (Turbopack in `next build`) constant-folds
// `process.platform` to the BUILD machine's value on a non-Windows runner and prunes
// the other branches as dead code (#10293). `os.platform()` is a runtime call a
// bundler cannot fold, so Windows/macOS/Linux branches survive on any build machine.
function getCurrentPlatform(): NodeJS.Platform {
return os.platform();
}
const EXTENDED_PATH = `/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${process.env.PATH || ""}`;
const LOGIN_TIMEOUT_MS = 15000;
const FUNNEL_TIMEOUT_MS = 30000;
@@ -35,12 +41,7 @@ type JsonRecord = Record<string, unknown>;
export type TailscaleTunnelInstallSource = "managed" | "path" | "env" | "windows-default";
export type TailscaleTunnelPhase =
| "unsupported"
| "not_installed"
| "needs_login"
| "stopped"
| "running"
| "error";
"unsupported" | "not_installed" | "needs_login" | "stopped" | "running" | "error";
type PersistedTailscaleState = {
binaryPath?: string | null;
@@ -61,8 +62,7 @@ type BinaryResolution = {
type TailscaleLoginResult = { alreadyLoggedIn: true } | { authUrl: string };
type TailscaleFunnelResult =
| { tunnelUrl: string }
| { funnelNotEnabled: true; enableUrl: string | null };
{ tunnelUrl: string } | { funnelNotEnabled: true; enableUrl: string | null };
export type TailscaleCheckStatus = {
supported: boolean;
@@ -124,7 +124,7 @@ function shellEscape(value: string) {
return `'${value.replace(/'/g, `'\"'\"'`)}'`;
}
function isSupportedPlatform(platform = process.platform) {
function isSupportedPlatform(platform = os.platform()) {
return platform === "darwin" || platform === "linux" || platform === "win32";
}
@@ -132,7 +132,7 @@ function getTailscaleDir() {
return path.join(resolveDataDir(), "tailscale");
}
function getManagedBinaryPath(platform = process.platform) {
function getManagedBinaryPath(platform = os.platform()) {
return path.join(getTailscaleDir(), "bin", platform === "win32" ? "tailscale.exe" : "tailscale");
}
@@ -212,7 +212,7 @@ function getTailscaleApiUrl(tunnelUrl: string | null) {
}
async function resolvePathCommand(command: string) {
const lookupCommand = process.platform === "win32" ? "where" : "which";
const lookupCommand = os.platform() === "win32" ? "where" : "which";
try {
const { stdout } = await execFileAsync(lookupCommand, [command], {
timeout: 3000,
@@ -248,7 +248,7 @@ async function resolveBinary(): Promise<BinaryResolution> {
return { binaryPath: pathBinary, installSource: "path", managedInstall: false };
}
if (IS_WINDOWS && fs.existsSync(WINDOWS_TAILSCALE_BIN)) {
if (getCurrentPlatform() === "win32" && fs.existsSync(WINDOWS_TAILSCALE_BIN)) {
return {
binaryPath: WINDOWS_TAILSCALE_BIN,
installSource: "windows-default",
@@ -263,7 +263,7 @@ async function resolveDaemonBinary(tailscaleBinaryPath: string | null) {
const envPath = toNonEmptyString(process.env.TAILSCALED_BIN);
if (envPath && fs.existsSync(envPath)) return envPath;
const daemonFilename = process.platform === "win32" ? "tailscaled.exe" : "tailscaled";
const daemonFilename = os.platform() === "win32" ? "tailscaled.exe" : "tailscaled";
const siblingDir = tailscaleBinaryPath ? path.dirname(tailscaleBinaryPath) : null;
// path.format avoids the path.join/resolve pattern flagged by CWE-22 linters;
// siblingDir is path.dirname of a trusted system binary from resolveBinary(), not user input.
@@ -273,7 +273,8 @@ async function resolveDaemonBinary(tailscaleBinaryPath: string | null) {
const pathBinary = await resolvePathCommand("tailscaled");
if (pathBinary) return pathBinary;
if (IS_WINDOWS && fs.existsSync(WINDOWS_TAILSCALED_BIN)) return WINDOWS_TAILSCALED_BIN;
if (getCurrentPlatform() === "win32" && fs.existsSync(WINDOWS_TAILSCALED_BIN))
return WINDOWS_TAILSCALED_BIN;
return null;
}
@@ -298,7 +299,9 @@ async function getActiveSocketPath(): Promise<string> {
}
// Check system sockets first
const systemSocket = IS_LINUX ? SYSTEM_SOCKET_LINUX : IS_MAC ? SYSTEM_SOCKET_MAC : null;
const platform = getCurrentPlatform();
const systemSocket =
platform === "linux" ? SYSTEM_SOCKET_LINUX : platform === "darwin" ? SYSTEM_SOCKET_MAC : null;
if (systemSocket && fs.existsSync(systemSocket)) {
_cachedActiveSocket = systemSocket;
_cachedActiveSocketTimestamp = now;
@@ -314,7 +317,9 @@ async function getActiveSocketPath(): Promise<string> {
/** Synchronous check: is the system daemon socket available? */
function isSystemDaemonAvailable(): boolean {
const systemSocket = IS_LINUX ? SYSTEM_SOCKET_LINUX : IS_MAC ? SYSTEM_SOCKET_MAC : null;
const platform = getCurrentPlatform();
const systemSocket =
platform === "linux" ? SYSTEM_SOCKET_LINUX : platform === "darwin" ? SYSTEM_SOCKET_MAC : null;
return Boolean(systemSocket && fs.existsSync(systemSocket));
}
@@ -341,19 +346,20 @@ export function tailscaleUpArgs(hostname?: string, authKey?: string): string[] {
}
async function buildTailscaleArgs(...args: string[]) {
if (IS_WINDOWS) return args;
if (getCurrentPlatform() === "win32") return args;
const socket = await getActiveSocketPath();
return ["--socket", socket, ...args];
}
/** Synchronous variant for places that cannot await */
function buildTailscaleArgsSync(...args: string[]) {
if (IS_WINDOWS) return args;
if (getCurrentPlatform() === "win32") return args;
// Use cached socket or default to system socket if available
const platform = getCurrentPlatform();
const socket =
_cachedActiveSocket ||
(isSystemDaemonAvailable()
? IS_LINUX
? platform === "linux"
? SYSTEM_SOCKET_LINUX
: SYSTEM_SOCKET_MAC
: getTailscaleSocketPath());
@@ -443,7 +449,7 @@ function getLastError(state: PersistedTailscaleState) {
}
async function hasBrew() {
if (!IS_MAC) return false;
if (getCurrentPlatform() !== "darwin") return false;
try {
await execFileAsync("which", ["brew"], {
timeout: 3000,
@@ -487,7 +493,7 @@ export async function getTailscaleCheckStatus(): Promise<TailscaleCheckStatus> {
running: isFunnelRunning(funnelPayload),
tunnelUrl,
apiUrl: getTailscaleApiUrl(tunnelUrl),
platform: process.platform,
platform: os.platform(),
brewAvailable,
lastError: getLastError(state),
pid: await readPidFile(),
@@ -561,7 +567,7 @@ export async function startTailscaleDaemon({
return { started: false };
}
if (IS_WINDOWS) {
if (getCurrentPlatform() === "win32") {
try {
await execFileAsync("net", ["start", "Tailscale"], {
timeout: 10000,
@@ -816,7 +822,7 @@ export async function stopTailscaleDaemon({
}
}
if (!IS_WINDOWS) {
if (getCurrentPlatform() !== "win32") {
try {
await execFileAsync("pkill", ["-x", "tailscaled"], {
timeout: 3000,
@@ -1155,7 +1161,7 @@ export async function installTailscale({
onProgress?: (message: string) => void;
} = {}) {
if (!isSupportedPlatform()) {
throw new Error(`Unsupported platform for Tailscale install: ${process.platform}`);
throw new Error(`Unsupported platform for Tailscale install: ${os.platform()}`);
}
const password = toNonEmptyString(sudoPassword) || getCachedPassword() || "";
@@ -1167,13 +1173,13 @@ export async function installTailscale({
const existingBinary = await resolveBinary();
if (existingBinary.binaryPath) {
onProgress?.("Tailscale is already installed.");
} else if (IS_WINDOWS) {
} else if (getCurrentPlatform() === "win32") {
onProgress?.("Downloading and installing Tailscale for Windows...");
await installTailscaleWindows(onProgress);
} else if (IS_MAC) {
} else if (getCurrentPlatform() === "darwin") {
onProgress?.("Installing Tailscale on macOS...");
await installTailscaleMac(password, onProgress);
} else if (IS_LINUX) {
} else if (getCurrentPlatform() === "linux") {
onProgress?.("Installing Tailscale on Linux...");
await installTailscaleLinux(password, onProgress);
}

View File

@@ -33,8 +33,6 @@ import type { SingleModelTarget } from "@omniroute/open-sse/services/combo/types
import { mergeAbortSignals } from "@omniroute/open-sse/executors/base.ts";
import { resolveRequestAutoControls } from "@omniroute/open-sse/services/autoCombo/requestControls.ts";
import { isVerifiedNativeCodexRequest } from "@omniroute/open-sse/config/codexIdentity.ts";
import { resolveCompressionSettings } from "@omniroute/open-sse/handlers/chatCore/compressionSettings.ts";
import type { CompressionExclusions } from "@omniroute/open-sse/services/compression/exclusions.ts";
import { resolveComboConfig } from "@omniroute/open-sse/services/comboConfig.ts";
import { injectHandoffIntoBody } from "@omniroute/open-sse/services/contextHandoff.ts";
import {
@@ -211,31 +209,6 @@ let combosCacheTs = 0;
let combosCacheVersionSnapshot = -1;
const COMBOS_CACHE_TTL_MS = 10_000;
/**
* #10225 — resolve whether this request's combo preflight should DEFER its hard
* context-overflow rejection so chatCore's compression runs first.
*
* Mirrors handleChatCore's own enablement determination (chatCore.ts): defer only
* when the global compression switch is ON and the API key has not opted out
* (`apiKeyInfo.compressionEnabled !== false`). Per-target applicability (server-side
* exclusions) is checked inside getKnownContextOverflow via the returned exclusions.
* Fail closed (defer=false) on any lookup error — the existing hard preflight stays.
*/
async function resolveComboContextOverflowDeferral(
logger: { warn?: (...args: unknown[]) => void } | null | undefined,
apiKeyInfo: { compressionEnabled?: boolean } | null | undefined
): Promise<{ defer: boolean; exclusions: CompressionExclusions | undefined }> {
try {
const compression = await resolveCompressionSettings(logger);
return {
defer: compression.enabled && apiKeyInfo?.compressionEnabled !== false,
exclusions: compression.settings?.exclusions,
};
} catch {
return { defer: false, exclusions: undefined };
}
}
async function getCombosCachedForChat(): Promise<unknown[]> {
const now = Date.now();
// Explicit non-null check: we intentionally cache and return the Promise
@@ -851,13 +824,9 @@ async function handleChatImplementation(
// Context-relay keeps generation in combo.ts, but handoff injection lives here
// because only this layer knows which connectionId was actually selected.
const { defer: deferContextOverflowWhenCompressible, exclusions: compressionExclusions } =
await resolveComboContextOverflowDeferral(log, apiKeyInfo);
const response = await (handleComboChat as any)({
body,
combo,
deferContextOverflowWhenCompressible,
compressionExclusions,
clientManagedResponsesContext:
sourceFormat === "openai-responses" &&
new URL(request.url).pathname.split("/").includes("responses") &&
@@ -1134,13 +1103,9 @@ async function handleSingleModelChat(
);
log.info("ROUTING", `Auto-combo redirect from handleSingleModelChat for "${modelStr}"`);
log.info("ROUTING", `Auto-combo redirect to combo flow for "${modelStr}"`);
const { defer: sNetDefer, exclusions: sNetExclusions } =
await resolveComboContextOverflowDeferral(log, apiKeyInfo);
return handleComboChat({
body,
combo: redirectCombo,
deferContextOverflowWhenCompressible: sNetDefer,
compressionExclusions: sNetExclusions,
clientManagedResponsesContext:
detectFormatFromEndpoint(body, clientRawRequest?.endpoint || "") === "openai-responses" &&
String(clientRawRequest?.endpoint || "")

View File

@@ -1,173 +0,0 @@
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";
/**
* #10225 — combo known-context-overflow must NOT hard-reject a compressible
* request before OmniRoute's compression pipeline can run.
*
* Root cause: getKnownContextOverflow() estimates the RAW body (ceil(serializedChars/4)
* over the whole Responses input[]) during combo target resolution, before any
* compression. When every known target limit is below that raw estimate, both call
* sites (round-robin + target-resolution) convert it into an immediate local 400
* `context_length_exceeded` with attempted:0 — so chatCore's proactive compression
* (which can shrink 294133→111529, 62% in the reporter's case) never runs. The only
* existing bypass (clientManagedResponsesContext) is gated to VERIFIED native Codex
* clients, so a generic Responses client (e.g. OpenCode) pointed at a codex model
* still hits the hard gate.
*
* Fix: thread a request-scoped `deferContextOverflowWhenCompressible` flag (set when
* the global compression switch is ON and not API-key opted-out). When set AND at
* least one target can run compression, getKnownContextOverflow returns null so the
* request reaches chatCore, whose post-compression enforceOutputTokenBudget becomes
* the final context gate — a local 400 only if the compressed body still cannot fit.
*/
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-overflow-compress-"));
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const { saveModelsDevCapabilities, clearModelsDevCapabilities } =
await import("../../src/lib/modelsDevSync.ts");
const { getKnownContextOverflow, handleComboChat } = await import(
"../../open-sse/services/combo.ts"
);
test.after(() => {
core.resetDbInstance();
if (ORIGINAL_DATA_DIR === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = ORIGINAL_DATA_DIR;
}
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test.beforeEach(() => {
clearModelsDevCapabilities();
});
function capabilityEntry(limitContext: number | null) {
return {
tool_call: true,
reasoning: false,
attachment: false,
structured_output: true,
temperature: true,
modalities_input: JSON.stringify(["text"]),
modalities_output: JSON.stringify(["text"]),
knowledge_cutoff: null,
release_date: null,
last_updated: null,
status: null,
family: null,
open_weights: false,
limit_context: limitContext,
limit_input: limitContext,
limit_output: 4096,
interleaved_field: null,
};
}
function target(modelStr: string) {
return {
kind: "model" as const,
stepId: modelStr,
executionKey: modelStr,
modelStr,
provider: modelStr.includes("/") ? modelStr.split("/")[0] : modelStr,
providerId: null,
connectionId: null,
weight: 1,
label: null,
};
}
// A generic Responses-API body whose estimate lands near `tokens` tokens (4 chars/token).
// Uses `input:` (not `messages:`) to mirror the OpenCode/Codex Responses surface.
function bigResponsesBody(tokens: number) {
return { input: [["user", "x".repeat(tokens * 4)]] };
}
const noopLog = { info() {}, warn() {}, error() {}, debug() {} };
test("#10225 getKnownContextOverflow defers the hard overflow when compression is available", () => {
saveModelsDevCapabilities({ codex: { "gpt-5.6-terra": capabilityEntry(272_000) } });
const body = bigResponsesBody(275_000);
// Compression enabled + target can compress -> defer (null).
assert.equal(
getKnownContextOverflow([target("codex/gpt-5.6-terra")], body, {
deferContextOverflowWhenCompressible: true,
}),
null,
"compressible request must defer so chatCore compression can run (#10225)"
);
// Compression disabled -> the existing hard overflow is preserved (never lose #7177).
const hard = getKnownContextOverflow([target("codex/gpt-5.6-terra")], body);
assert.ok(hard);
assert.ok(hard.requiredContextTokens > hard.maxKnownContextTokens);
// Compression enabled but EVERY target is excluded from compression -> keep the hard gate.
const excluded = getKnownContextOverflow([target("codex/gpt-5.6-terra")], body, {
deferContextOverflowWhenCompressible: true,
compressionExclusions: ["gpt-5.6-terra"],
});
assert.ok(excluded, "fully-excluded targets must retain the hard preflight");
});
test("#10225 combo does not early-400 a compressible over-limit request when deferral is on", async () => {
saveModelsDevCapabilities({ codex: { "gpt-5.6-terra": capabilityEntry(272_000) } });
let dispatches = 0;
const response = await handleComboChat({
body: bigResponsesBody(275_000),
combo: {
name: "codex-compress-overflow",
strategy: "priority",
models: ["codex/gpt-5.6-terra"],
},
deferContextOverflowWhenCompressible: true,
clientManagedResponsesContext: false,
isModelAvailable: async () => true,
handleSingleModel: async () => {
dispatches += 1;
return new Response("ok", { status: 200 });
},
log: noopLog,
});
assert.notEqual(response.status, 400, "compression-enabled request must reach chatCore");
assert.equal(dispatches, 1, "must dispatch so chatCore compaction runs first");
});
test("#10225 combo keeps the fast 400 when compression is disabled", async () => {
saveModelsDevCapabilities({ codex: { "gpt-5.6-terra": capabilityEntry(272_000) } });
let dispatches = 0;
const response = await handleComboChat({
body: bigResponsesBody(275_000),
combo: {
name: "codex-compress-disabled",
strategy: "priority",
models: ["codex/gpt-5.6-terra"],
},
deferContextOverflowWhenCompressible: false,
clientManagedResponsesContext: false,
isModelAvailable: async () => true,
handleSingleModel: async () => {
dispatches += 1;
return new Response("ok", { status: 200 });
},
log: noopLog,
});
assert.equal(response.status, 400);
assert.equal(dispatches, 0, "#7177 anti-exhaustion guard must survive when compression is off");
const body = await response.json();
assert.equal(body.error.code, "context_length_exceeded");
});

View File

@@ -0,0 +1,57 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// #10293 — anti-fold regression guard.
//
// The reported defect: Turbopack constant-folds module-load `process.platform` to the
// BUILD machine's value (a non-Windows runner) and prunes every Windows branch as dead
// code, so `dist` builds ship a tailscaleTunnel where the Windows paths are unreachable.
// That cannot be reproduced in a unit test (no published `dist`, no Windows runner), so
// this guard enforces the SOURCE invariant that makes the fold impossible: platform reads
// go through the runtime call `os.platform()` (a bundler cannot fold an arbitrary function
// call), never a module-load `process.platform` constant.
//
// If a future edit re-introduces `const IS_WINDOWS = process.platform === "win32"` (or any
// module-scope direct `process.platform` read), the folded-build failure returns — this test
// turns RED.
const modulePath = fileURLToPath(new URL("../../src/lib/tailscaleTunnel.ts", import.meta.url));
const source = fs.readFileSync(modulePath, "utf8");
test("#10293: tailscaleTunnel reads platform at runtime via os.platform(), never a module-load process.platform constant", () => {
const lines = source.split("\n");
// Any module-scope (non-function) direct read of process.platform is the foldable pattern.
const foldable = lines.filter((line, idx) => {
if (/process\.platform/.test(line) && !/^\s*\/\//.test(line)) {
// allow it only inside a function body (runtime read — but prefer os.platform there too);
// a module-load constant assignment at top level with process.platform is the defect.
return line.includes("= process.platform") && idx < 60;
}
return false;
});
assert.deepEqual(
foldable,
[],
`module-load constant(s) reading process.platform reintroduced the foldable pattern: ${foldable.join(" | ")}`
);
// The runtime getter must exist and delegate to os.platform (the anti-fold call).
assert.match(source, /function getCurrentPlatform\(\):\s*NodeJS\.Platform\s*\{\s*return os\.platform\(\);?\s*\}/m);
});
test("#10293: Windows branches use runtime platform reads, so they survive any build machine", () => {
// These are the specific Windows behaviors the reporter found folded to dead code:
// (a) --socket not injected (buildTailscaleArgs), (b) where over which (resolvePathCommand),
// (c) windows-default binary fallback (resolveBinary). Each must read platform at runtime
// through os.platform()/getCurrentPlatform().
const socketBranch = /getCurrentPlatform\(\) === "win32"[\s\S]{0,80}return args/.test(source);
const whereBranch = /os\.platform\(\) === "win32" \? "where" : "which"/.test(source);
const windowsDefaultBranch = /getCurrentPlatform\(\) === "win32" && fs\.existsSync\(WINDOWS_TAILSCALE_BIN\)/.test(source);
assert.ok(socketBranch, "buildTailscaleArgs must not inject --socket on win32 (runtime platform read)");
assert.ok(whereBranch, "resolvePathCommand must select 'where' when os.platform() === 'win32'");
assert.ok(windowsDefaultBranch, "resolveBinary must reach the Windows default binary fallback via runtime platform read");
});