Compare commits

...

4 Commits

Author SHA1 Message Date
Markus Hartung
2981cdb5a9 fix(combos): use the routing-alias prefix, not raw providerId, when serializing combo model steps (#11433)
buildPrecisionComboModelStep() rebuilt a step's `model` field as
`${providerId}/${modelId}` from the canonical provider id. For the
no-auth "OpenCode Free" provider (id "opencode") this produced
"opencode/<model>", but "opencode" also doubles as a manual
routing-prefix override (open-sse/services/model.ts) that resolves to
the unrelated paid "OpenCode Zen" provider. So every step built this
way silently misrouted, even though step.providerId correctly said
"opencode".

Thread the provider's already-computed routing-alias prefix (e.g. "oc")
through an optional modelPrefix param, and pass it from the three
affected call sites: the precision single-select picker and
handleAddBuilderStep in combos/page.tsx, buildGlobalModelList (global
search), and buildManualComboModelStep (manual "oc/<model>" entry,
which now preserves the typed prefix instead of collapsing it back to
the canonical id). step.providerId keeps carrying the canonical id
unconditionally, so routing/duplicate-detection identity is unaffected.
findNextSuggestedConnectionId is unaffected since its duplicate check
keys off entry.providerId, not the parsed model prefix.

ALIAS_TO_PROVIDER_ID / resolveProviderAlias() / the routingPrefix
computation in builderOptions.ts are untouched — they were already
correct (#2901) and are the source of truth this fix threads through.
2026-08-26 13:15:31 -03:00
Diego Rodrigues de Sa e Souza
91aeca0440 fix(security): redact NVIDIA_API_KEY at the log sink in the ad-hoc diag script (#11639)
Merged via /merge-batch (2026-08-26, v3.8.51). Validado no worktree combinado.
2026-08-26 10:59:26 -03:00
Webman
49749eb0d0 fix(types): clear the two type regressions red on release/v3.8.51 (#11640)
Merged via /merge-batch (2026-08-26, v3.8.51). Confirma o fix do typecheck:core que eu vinha classificando como drift pré-existente nas últimas levas (zai-web.ts mimeType) — obrigado por resolver de vez. Validado: typecheck limpo, 7/7 testes passando.
2026-08-26 10:59:19 -03:00
Bob.Hou
8d17110082 fix(build): resolve workspace: protocol dependencies to concrete semver versions during prepublish (#11540) (#11641)
Merged via /merge-batch (2026-08-26, v3.8.51). Validado: typecheck/complexity/file-size/changelog verdes, 3/3 testes do prepublish workspace-protocol passando. Obrigado pela contribuição.
2026-08-26 10:59:14 -03:00
14 changed files with 743 additions and 15 deletions

View File

@@ -0,0 +1 @@
- **fix(combos):** the combo builder's precision-select, global-model-search, and manual-entry flows now serialize a model step's `model` string using the provider's already-computed routing-alias prefix (e.g. `oc/`) instead of rebuilding it from the raw canonical `providerId`, fixing the no-auth "OpenCode Free" provider (`opencode`) being routed to the unrelated paid "OpenCode Zen" provider (`opencode-zen`) because `opencode` doubles as a manual routing-prefix override ([#11433](https://github.com/diegosouzapw/OmniRoute/issues/11433)).

View File

@@ -90,13 +90,19 @@ async function resolveZaiBrowserAttachments(
> {
try {
// Browser-page upload: keep the original bytes/mimeType (no Cursor wire prep).
// EncodedImage.mimeType is optional on the wire type, but every producer
// reachable here (decodeDataUrl / fetchImageBytes) validates an image/*
// string before pushing; the fallback only satisfies the attachment type.
const images = await resolveCursorImages(imageUrls, { prepareForWire: false });
return {
attachments: images.map((image, index) => ({
name: zaiImageFileName(image.mimeType, index),
mimeType: image.mimeType,
buffer: image.data,
})),
attachments: images.map((image, index) => {
const mimeType = image.mimeType ?? "image/jpeg";
return {
name: zaiImageFileName(mimeType, index),
mimeType,
buffer: image.data,
};
}),
};
} catch (error) {
const message =

View File

@@ -15,6 +15,7 @@ interface ErrorResponseBody {
message: string;
type?: string;
code?: string;
reason?: string;
};
upstream_details?: Record<string, unknown> | null; // sanitized upstream provider body
}
@@ -108,6 +109,7 @@ export function sanitizeUpstreamDetails(value: unknown, depth = 0): unknown {
export type ErrorBodyClassification = {
type?: string;
code?: string;
reason?: string;
};
/**
@@ -132,6 +134,7 @@ export function buildErrorBody(
message: safeMessage,
type: classification?.type ?? errorInfo.type,
code: classification?.code ?? errorInfo.code,
reason: classification?.reason,
},
};

View File

@@ -19,12 +19,20 @@
*/
const KEY = process.env.NVIDIA_API_KEY ?? "";
const BASE_URL = process.env.NVIDIA_BASE_URL || "https://integrate.api.nvidia.com/v1/chat/completions";
const BASE_URL =
process.env.NVIDIA_BASE_URL || "https://integrate.api.nvidia.com/v1/chat/completions";
const MODEL = process.env.NVIDIA_MODEL || "openai/gpt-oss-120b";
// Neutralize CR/LF before logging so env-derived values (NVIDIA_MODEL, etc.)
// cannot forge extra log lines (S5145 log injection).
const line = (s = "") => console.log(String(s).replace(/[\r\n]+/g, " "));
// cannot forge extra log lines (S5145 log injection). Also strip any raw
// occurrence of the API key so an upstream error/response that echoes it
// back (e.g. inside err.stack or a validation result) never reaches the
// terminal in clear text (js/clear-text-logging, CWE-312/532).
const line = (s = "") => {
let out = String(s).replace(/[\r\n]+/g, " ");
if (KEY) out = out.split(KEY).join("[REDACTED]");
console.log(out);
};
const hr = () => line("─".repeat(72));
function show(label: string, value: unknown) {
@@ -52,8 +60,13 @@ async function partA() {
});
line(" ✅ validateProviderApiKey retornou (sem crash):");
show("resultado", result);
if (typeof (result as any)?.error === "string" && (result as any).error.includes("startsWith")) {
line(" ⚠️ A mensagem de erro contém 'startsWith' → crash CAPTURADO dentro do try/catch da validação.");
if (
typeof (result as any)?.error === "string" &&
(result as any).error.includes("startsWith")
) {
line(
" ⚠️ A mensagem de erro contém 'startsWith' → crash CAPTURADO dentro do try/catch da validação."
);
}
} catch (err: any) {
line(" ❌ validateProviderApiKey LANÇOU (crash não tratado):");

View File

@@ -23,7 +23,7 @@ import {
statSync,
chmodSync,
} from "node:fs";
import { join, dirname } from "node:path";
import { join, dirname, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { assembleStandalone } from "./assembleStandalone.mjs";
@@ -35,6 +35,12 @@ import {
APP_STAGING_REMOVAL_PATHS,
findUnexpectedArtifactPaths,
} from "./pack-artifact-policy.ts";
import {
collectWorkspaceVersions,
findPackageJsonFiles,
hasWorkspaceProtocol,
resolvePackageJsonWorkspaceProtocols,
} from "./resolveWorkspaceProtocols.ts";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -707,6 +713,33 @@ if (remainingUnexpectedFiles.length > 0) {
process.exit(1);
}
// -- Step 11: Resolve workspace: protocol dependencies -----------------
// npm/pnpm workspace protocol specifiers (workspace:*, workspace:^, ...)
// are meaningless to the npm registry and make `npm install -g omniroute`
// fail with EUNSUPPORTEDPROTOCOL. Rewrite any that leaked into published
// package.json files to the concrete workspace package version.
// Only touch files inside the staged dist/ tree; workspace member source
// package.json files must never be mutated by the publish step.
const workspaceVersions = collectWorkspaceVersions(ROOT);
const publishablePackageJsonDirs = [DIST_DIR];
const publishablePackageJsonPaths = publishablePackageJsonDirs
.flatMap((dir) => (existsSync(dir) ? findPackageJsonFiles(dir) : []))
.filter((filePath) => existsSync(filePath));
for (const pkgJsonPath of publishablePackageJsonPaths) {
let pkg: Record<string, unknown>;
try {
pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as Record<string, unknown>;
} catch {
continue;
}
if (!hasWorkspaceProtocol(pkg)) continue;
const resolved = resolvePackageJsonWorkspaceProtocols(pkg, workspaceVersions);
writeFileSync(pkgJsonPath, JSON.stringify(resolved, null, 2) + "\n");
console.log(` [resolved] Resolved workspace: protocols in ${relative(ROOT, pkgJsonPath)}`);
}
// ── Done ───────────────────────────────────────────────────
const distPkg = join(DIST_DIR, "package.json");
if (existsSync(distPkg)) {

View File

@@ -0,0 +1,228 @@
/**
* Resolve pnpm/npm workspace protocol dependencies to concrete semver versions.
*
* The npm registry clients cannot parse `workspace:` specifiers. During prepublish
* we rewrite any `workspace:*`, `workspace:^`, `workspace:~` (or explicit
* `workspace:<range>`) dependency declarations to the matching workspace package's
* actual version before npm pack/publish sees them.
*/
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
import * as yaml from "js-yaml";
const WORKSPACE_PROTOCOL_RE = /^workspace:/;
const DEPENDENCY_FIELDS = [
"dependencies",
"devDependencies",
"peerDependencies",
"optionalDependencies",
] as const;
/**
* Parse a simple workspace glob entry into concrete directories relative to a root.
* Supports entries like "packages/*" and literal directory names like "open-sse".
*/
function expandWorkspaceEntry(root: string, entry: string): string[] {
const trimmed = entry.trim();
if (!trimmed) return [];
if (!trimmed.endsWith("/*")) {
const dir = join(root, trimmed);
try {
return statSync(dir).isDirectory() ? [dir] : [];
} catch {
return [];
}
}
const parent = join(root, trimmed.slice(0, -2));
let entries: string[] = [];
try {
entries = readdirSync(parent);
} catch {
return [];
}
return entries
.map((name) => join(parent, name))
.filter((dir) => {
try {
return statSync(dir).isDirectory();
} catch {
return false;
}
});
}
/**
* Read the root package.json and, if present, pnpm-workspace.yaml to discover
* workspace member directories. Returns a map of package name -> version.
*/
export function collectWorkspaceVersions(projectRoot: string): Map<string, string> {
const versions = new Map<string, string>();
const rootPkgPath = join(projectRoot, "package.json");
let workspaceEntries: string[] = [];
try {
const rootPkg = JSON.parse(readFileSync(rootPkgPath, "utf8")) as {
workspaces?: string[];
};
if (Array.isArray(rootPkg.workspaces)) {
workspaceEntries.push(...rootPkg.workspaces);
}
} catch {
// ignore unreadable root package.json
}
const pnpmWorkspacePath = join(projectRoot, "pnpm-workspace.yaml");
try {
const yamlContent = readFileSync(pnpmWorkspacePath, "utf8");
const doc = yaml.load(yamlContent) as { packages?: unknown } | null | undefined;
if (doc && Array.isArray(doc.packages)) {
for (const entry of doc.packages) {
if (typeof entry === "string" && entry) {
workspaceEntries.push(entry);
}
}
}
} catch {
// ignore missing or malformed pnpm-workspace.yaml
}
const seenDirs = new Set<string>();
for (const entry of workspaceEntries) {
for (const dir of expandWorkspaceEntry(projectRoot, entry)) {
if (seenDirs.has(dir)) continue;
seenDirs.add(dir);
try {
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as {
name?: string;
version?: string;
};
if (pkg.name && pkg.version) {
versions.set(pkg.name, pkg.version);
}
} catch {
// skip unreadable workspace member package.json
}
}
}
return versions;
}
/**
* Resolve workspace protocol dependencies inside a package.json object.
*
* Replaces `workspace:*`, `workspace:^`, `workspace:~`, `workspace:<range>`,
* and `workspace:<packageName>` with the concrete version of the referenced
* workspace package. Throws if a workspace specifier cannot be resolved.
*/
export function resolvePackageJsonWorkspaceProtocols(
pkg: Record<string, unknown>,
workspaceVersions: Map<string, string>
): Record<string, unknown> {
const resolved: Record<string, unknown> = { ...pkg };
for (const field of DEPENDENCY_FIELDS) {
const deps = pkg[field];
if (!deps || typeof deps !== "object" || Array.isArray(deps)) continue;
const resolvedDeps: Record<string, string> = {};
let changed = false;
for (const [depName, versionSpec] of Object.entries(deps as Record<string, unknown>)) {
if (typeof versionSpec !== "string") {
resolvedDeps[depName] = String(versionSpec ?? "");
continue;
}
if (!WORKSPACE_PROTOCOL_RE.test(versionSpec)) {
resolvedDeps[depName] = versionSpec;
continue;
}
const body = versionSpec.slice("workspace:".length);
let concrete: string | undefined;
if (body === "*") {
concrete = workspaceVersions.get(depName);
} else if (body === "^") {
const version = workspaceVersions.get(depName);
concrete = version ? `^${version}` : undefined;
} else if (body === "~") {
const version = workspaceVersions.get(depName);
concrete = version ? `~${version}` : undefined;
} else if (body.startsWith("^") || body.startsWith("~") || /^[\d<>=]/.test(body)) {
// Explicit range inside workspace: protocol - strip the protocol prefix.
concrete = body;
} else {
// workspace:<packageName> - resolve to that package's version.
concrete = workspaceVersions.get(body);
}
if (concrete) {
resolvedDeps[depName] = concrete;
changed = true;
} else {
throw new Error(
`Cannot resolve workspace protocol "${versionSpec}" for dependency "${depName}". ` +
"Make sure the referenced package is a declared workspace member with a version."
);
}
}
if (changed) {
resolved[field] = resolvedDeps;
}
}
return resolved;
}
/**
* Return true if any dependency field in the package contains a workspace: specifier.
*/
export function hasWorkspaceProtocol(pkg: Record<string, unknown>): boolean {
for (const field of DEPENDENCY_FIELDS) {
const deps = pkg[field];
if (!deps || typeof deps !== "object" || Array.isArray(deps)) continue;
for (const versionSpec of Object.values(deps as Record<string, unknown>)) {
if (typeof versionSpec === "string" && WORKSPACE_PROTOCOL_RE.test(versionSpec)) {
return true;
}
}
}
return false;
}
/**
* Recursively walk a directory and return every package.json path found.
* Stops descending after maxDepth to avoid runaway recursion on deep trees.
*/
export function findPackageJsonFiles(dir: string, maxDepth = 10): string[] {
const results: string[] = [];
if (maxDepth < 0) return results;
let entries: string[] = [];
try {
entries = readdirSync(dir);
} catch {
return results;
}
for (const entry of entries) {
if (entry === "node_modules") continue;
const fullPath = join(dir, entry);
let stat;
try {
stat = statSync(fullPath);
} catch {
continue;
}
if (stat.isDirectory()) {
results.push(...findPackageJsonFiles(fullPath, maxDepth - 1));
} else if (entry === "package.json") {
results.push(fullPath);
}
}
return results;
}

View File

@@ -2177,6 +2177,9 @@ function ComboFormModal({ isOpen, combo, onClose, onSave, activeProviders, combo
builderConnectionId !== COMBO_BUILDER_AUTO_CONNECTION ? builderConnectionId : null,
connectionLabel: selectedBuilderConnection?.label || null,
allowedConnectionIds: builderEffectiveAllowedConnectionIds,
// #11433: use the already-corrected routing prefix (e.g. "oc" for
// OpenCode Free) instead of letting it default to the raw providerId.
modelPrefix: parseQualifiedModel(selectedBuilderModel.qualifiedModel)?.providerId,
})
: null;
const builderHasDuplicate =
@@ -2501,6 +2504,9 @@ function ComboFormModal({ isOpen, combo, onClose, onSave, activeProviders, combo
builderConnectionId !== COMBO_BUILDER_AUTO_CONNECTION ? builderConnectionId : null,
connectionLabel: selectedBuilderConnection?.label || null,
allowedConnectionIds: builderEffectiveAllowedConnectionIds,
// #11433: use the already-corrected routing prefix (e.g. "oc" for
// OpenCode Free) instead of letting it default to the raw providerId.
modelPrefix: parseQualifiedModel(selectedBuilderModel.qualifiedModel)?.providerId,
});
if (hasExactModelStepDuplicate(models, nextStep)) {

View File

@@ -83,6 +83,7 @@ export function buildPrecisionComboModelStep({
connectionLabel,
allowedConnectionIds = null,
weight = 0,
modelPrefix,
}: {
providerId: string;
modelId: string;
@@ -91,9 +92,22 @@ export function buildPrecisionComboModelStep({
/** #3266: account allowlist scoping round-robin to a subset of connections. */
allowedConnectionIds?: string[] | null;
weight?: number;
/**
* #11433: the routing-prefix segment to serialize into `model` (e.g. "oc"
* for the no-auth OpenCode Free provider), when it differs from the
* canonical `providerId`. Some canonical provider ids collide with an
* unrelated manual `ALIAS_TO_PROVIDER_ID` routing override (`opencode` →
* `opencode-zen`), so reconstructing `model` from the raw `providerId`
* alone can round-trip to the wrong provider on request routing. Falls
* back to `providerId` when omitted/blank. `step.providerId` always stays
* the canonical id regardless, so routing/duplicate-detection identity is
* unaffected.
*/
modelPrefix?: string | null;
}): ComboModelStep {
const normalizedProviderId = toTrimmedString(providerId) || "provider";
const normalizedModelId = toTrimmedString(modelId) || "model";
const normalizedModelPrefix = toTrimmedString(modelPrefix) || normalizedProviderId;
const normalizedConnectionId = toTrimmedString(connectionId);
const normalizedConnectionLabel = toTrimmedString(connectionLabel);
// A pinned single connection wins over an allowlist, so only carry the allowlist
@@ -110,7 +124,7 @@ export function buildPrecisionComboModelStep({
return {
kind: "model",
providerId: normalizedProviderId,
model: `${normalizedProviderId}/${normalizedModelId}`,
model: `${normalizedModelPrefix}/${normalizedModelId}`,
...(normalizedConnectionId ? { connectionId: normalizedConnectionId } : {}),
...(normalizedConnectionLabel ? { label: normalizedConnectionLabel } : {}),
...(normalizedAllowed.length > 0 ? { allowedConnectionIds: normalizedAllowed } : {}),
@@ -160,10 +174,15 @@ export function buildManualComboModelStep({
const providerId = resolveComboBuilderProviderId(parsed.providerId, providers);
if (!providerId) return null;
// #11433: preserve the user-typed prefix (e.g. "oc") as the routing prefix
// instead of letting buildPrecisionComboModelStep rebuild `model` from the
// resolved canonical providerId, which can collide with an unrelated
// manual alias override (e.g. "opencode" -> "opencode-zen").
return buildPrecisionComboModelStep({
providerId,
modelId: parsed.modelId,
weight,
modelPrefix: parsed.providerId,
});
}
@@ -225,7 +244,7 @@ type ComboBuilderGlobalProvider = {
displayName?: unknown;
connectionCount?: unknown;
connections?: unknown[];
models?: Array<{ id?: unknown; name?: unknown }>;
models?: Array<{ id?: unknown; name?: unknown; qualifiedModel?: unknown }>;
};
/**
@@ -252,12 +271,18 @@ export function buildGlobalModelList(
const modelId = toTrimmedString(model?.id);
if (!modelId) return;
const modelName = toTrimmedString(model?.name) || modelId;
// #11433: derive the routing prefix from the model's already-corrected
// `qualifiedModel` (e.g. "oc/<model>" for the OpenCode Free provider)
// instead of defaulting to the raw providerId, which can collide with
// an unrelated manual alias override.
const modelPrefix = parseQualifiedModel(model?.qualifiedModel)?.providerId || providerId;
const step = buildPrecisionComboModelStep({
providerId,
modelId,
connectionId: null,
connectionLabel: null,
allowedConnectionIds: [],
modelPrefix,
});
list.push({
providerId,

View File

@@ -66,8 +66,8 @@ export function structuralRejectionResponse(status: 413 | 503, maxMessages: numb
{
type: historyLimit ? "payload_too_large" : "server_error",
code: historyLimit ? "chat_history_too_large" : "chat_admission_busy",
reason: historyLimit ? "message_limit" : "structure_limit",
}
);
body.error.reason = historyLimit ? "message_limit" : "structure_limit";
return new Response(JSON.stringify(body), { status, headers });
}

View File

@@ -0,0 +1,269 @@
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 {
collectWorkspaceVersions,
resolvePackageJsonWorkspaceProtocols,
hasWorkspaceProtocol,
findPackageJsonFiles,
} from "../../../scripts/build/resolveWorkspaceProtocols.ts";
function tmpDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
function writeJson(filePath: string, data: unknown): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}
function readJson(filePath: string): Record<string, unknown> {
return JSON.parse(fs.readFileSync(filePath, "utf8")) as Record<string, unknown>;
}
test("resolvePackageJsonWorkspaceProtocols replaces workspace:*, workspace:^, workspace:~", () => {
const versions = new Map([
["@omniroute/open-sse", "3.8.51"],
["@omniroute/shared", "1.2.3"],
]);
const resolved = resolvePackageJsonWorkspaceProtocols(
{
name: "omniroute",
version: "3.8.51",
dependencies: {
"@omniroute/open-sse": "workspace:^",
"@omniroute/shared": "workspace:*",
lodash: "^4.17.0",
},
devDependencies: {
"@omniroute/open-sse": "workspace:~",
},
peerDependencies: {
"@omniroute/shared": "workspace:1.2.3",
},
optionalDependencies: {
"@omniroute/open-sse": "workspace:>=3.0.0",
},
},
versions
);
assert.equal((resolved.dependencies as Record<string, string>)["@omniroute/open-sse"], "^3.8.51");
assert.equal((resolved.dependencies as Record<string, string>)["@omniroute/shared"], "1.2.3");
assert.equal((resolved.dependencies as Record<string, string>).lodash, "^4.17.0");
assert.equal(
(resolved.devDependencies as Record<string, string>)["@omniroute/open-sse"],
"~3.8.51"
);
assert.equal((resolved.peerDependencies as Record<string, string>)["@omniroute/shared"], "1.2.3");
assert.equal(
(resolved.optionalDependencies as Record<string, string>)["@omniroute/open-sse"],
">=3.0.0"
);
});
test("resolvePackageJsonWorkspaceProtocols leaves non-workspace specs untouched", () => {
const resolved = resolvePackageJsonWorkspaceProtocols(
{
name: "x",
dependencies: {
a: "^1.0.0",
b: "file:../b",
c: "npm:alias@1.0.0",
},
},
new Map()
);
assert.equal((resolved.dependencies as Record<string, string>).a, "^1.0.0");
assert.equal((resolved.dependencies as Record<string, string>).b, "file:../b");
assert.equal((resolved.dependencies as Record<string, string>).c, "npm:alias@1.0.0");
assert.equal(hasWorkspaceProtocol(resolved), false);
});
test("resolvePackageJsonWorkspaceProtocols throws for unresolvable workspace protocol", () => {
assert.throws(
() =>
resolvePackageJsonWorkspaceProtocols(
{
name: "x",
dependencies: {
"@missing/pkg": "workspace:^",
},
},
new Map()
),
/Cannot resolve workspace protocol/
);
});
test("collectWorkspaceVersions reads npm workspaces and pnpm-workspace.yaml", () => {
const root = tmpDir("workspace-versions-");
writeJson(path.join(root, "package.json"), {
name: "root",
version: "0.0.0",
workspaces: ["packages/*", "open-sse"],
});
fs.mkdirSync(path.join(root, "packages", "a"), { recursive: true });
writeJson(path.join(root, "packages", "a", "package.json"), {
name: "@scope/a",
version: "1.0.0",
});
fs.mkdirSync(path.join(root, "open-sse"), { recursive: true });
writeJson(path.join(root, "open-sse", "package.json"), {
name: "@scope/open-sse",
version: "2.0.0",
});
// pnpm-workspace.yaml adds an extra directory not in npm workspaces.
fs.mkdirSync(path.join(root, "packages", "b"), { recursive: true });
writeJson(path.join(root, "packages", "b", "package.json"), {
name: "@scope/b",
version: "3.0.0",
});
fs.writeFileSync(path.join(root, "pnpm-workspace.yaml"), "packages:\n - 'packages/*'\n");
const versions = collectWorkspaceVersions(root);
assert.equal(versions.get("@scope/a"), "1.0.0");
assert.equal(versions.get("@scope/open-sse"), "2.0.0");
assert.equal(versions.get("@scope/b"), "3.0.0");
});
test("findPackageJsonFiles skips node_modules and respects maxDepth", () => {
const root = tmpDir("pkg-json-files-");
fs.mkdirSync(path.join(root, "a"), { recursive: true });
writeJson(path.join(root, "a", "package.json"), {});
fs.mkdirSync(path.join(root, "node_modules", "x"), { recursive: true });
writeJson(path.join(root, "node_modules", "x", "package.json"), {});
const files = findPackageJsonFiles(root);
assert.equal(files.length, 1);
assert.ok(files[0].endsWith(path.join("a", "package.json")));
// Build a deep tree and confirm maxDepth bounds the walk.
const deep = tmpDir("pkg-json-deep-");
let current = deep;
for (let i = 0; i < 12; i += 1) {
current = path.join(current, `level${i}`);
fs.mkdirSync(current, { recursive: true });
}
writeJson(path.join(current, "package.json"), {});
assert.equal(findPackageJsonFiles(deep, 10).length, 0);
assert.equal(findPackageJsonFiles(deep, 12).length, 1);
});
test("collectWorkspaceVersions parses pnpm-workspace.yaml with js-yaml", () => {
const root = tmpDir("pnpm-yaml-");
writeJson(path.join(root, "package.json"), { name: "root", version: "0.0.0" });
// Flow-style array, nested quotes, comments inside the packages list, and an
// unrelated top-level key before packages are all valid YAML that the old line
// scanner could not handle.
fs.writeFileSync(
path.join(root, "pnpm-workspace.yaml"),
"preferWorkspacePackages: true\n" +
"packages:\n" +
' - "packages/*"\n' +
" - 'apps/*'\n" +
" # comment inside the list\n" +
" - open-sse\n"
);
fs.mkdirSync(path.join(root, "packages", "a"), { recursive: true });
writeJson(path.join(root, "packages", "a", "package.json"), {
name: "@scope/a",
version: "1.0.0",
});
fs.mkdirSync(path.join(root, "apps", "web"), { recursive: true });
writeJson(path.join(root, "apps", "web", "package.json"), {
name: "@scope/web",
version: "2.0.0",
});
fs.mkdirSync(path.join(root, "open-sse"), { recursive: true });
writeJson(path.join(root, "open-sse", "package.json"), {
name: "@scope/open-sse",
version: "3.0.0",
});
const versions = collectWorkspaceVersions(root);
assert.equal(versions.get("@scope/a"), "1.0.0");
assert.equal(versions.get("@scope/web"), "2.0.0");
assert.equal(versions.get("@scope/open-sse"), "3.0.0");
});
test("prepublish Step 11 fixture resolves workspace: protocols in dist package.json files", () => {
const root = tmpDir("prepublish-step11-");
const distDir = path.join(root, "dist");
// Workspace member source files contain a workspace: specifier (simulating the
// monorepo source). They must NOT be mutated by the publish step.
fs.mkdirSync(path.join(root, "packages", "shared"), { recursive: true });
const sourcePkgPath = path.join(root, "packages", "shared", "package.json");
writeJson(sourcePkgPath, {
name: "@scope/shared",
version: "1.2.3",
dependencies: {
"@scope/other": "workspace:*",
},
});
fs.mkdirSync(path.join(root, "packages", "other"), { recursive: true });
writeJson(path.join(root, "packages", "other", "package.json"), {
name: "@scope/other",
version: "4.5.6",
});
writeJson(path.join(root, "package.json"), {
name: "root",
version: "0.0.0",
workspaces: ["packages/*"],
});
// The staged dist/ package.json contains workspace: specifiers that leaked
// into the publish artifact and must be rewritten to concrete versions.
fs.mkdirSync(distDir, { recursive: true });
const distPkgPath = path.join(distDir, "package.json");
writeJson(distPkgPath, {
name: "omniroute",
version: "3.8.51",
dependencies: {
"@scope/shared": "workspace:^",
"@scope/other": "workspace:*",
lodash: "^4.17.0",
},
});
// This is the same logic prepublish.ts Step 11 runs, scoped to the fixture.
const workspaceVersions = collectWorkspaceVersions(root);
const publishablePackageJsonPaths = findPackageJsonFiles(distDir).filter((filePath) =>
fs.existsSync(filePath)
);
for (const pkgJsonPath of publishablePackageJsonPaths) {
const pkg = readJson(pkgJsonPath);
if (!hasWorkspaceProtocol(pkg)) continue;
const resolved = resolvePackageJsonWorkspaceProtocols(pkg, workspaceVersions);
fs.writeFileSync(pkgJsonPath, JSON.stringify(resolved, null, 2) + "\n");
}
// dist/package.json must have concrete versions.
const distPkg = readJson(distPkgPath);
assert.equal((distPkg.dependencies as Record<string, string>)["@scope/shared"], "^1.2.3");
assert.equal((distPkg.dependencies as Record<string, string>)["@scope/other"], "4.5.6");
assert.equal((distPkg.dependencies as Record<string, string>).lodash, "^4.17.0");
assert.equal(hasWorkspaceProtocol(distPkg), false);
// Source package.json must remain untouched.
const sourcePkg = readJson(sourcePkgPath);
assert.equal((sourcePkg.dependencies as Record<string, string>)["@scope/other"], "workspace:*");
});

View File

@@ -0,0 +1,35 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
structuralRejectionResponse,
} from "../../src/shared/middleware/chatAdmissionResponses.ts";
// Pins the machine-readable error.reason contract of the chat admission
// structural rejections (#TS2339 regression guard): buildErrorBody now owns
// the reason field via ErrorBodyClassification, so the response bodies keep
// carrying it without post-construction mutation of an untyped field.
test("structuralRejectionResponse 413 carries reason=message_limit classification", () => {
const res = structuralRejectionResponse(413, 40);
assert.equal(res.status, 413);
assert.ok(!res.headers.has("Retry-After"), "413 is not retryable-by-header");
return res.text().then((raw) => {
const body = JSON.parse(raw);
assert.equal(body.error.reason, "message_limit");
assert.equal(body.error.type, "payload_too_large");
assert.equal(body.error.code, "chat_history_too_large");
assert.ok(!body.error.message.includes("at /"), "must not leak stack traces");
});
});
test("structuralRejectionResponse 503 carries reason=structure_limit and Retry-After", () => {
const res = structuralRejectionResponse(503, 40);
assert.equal(res.status, 503);
assert.equal(res.headers.get("Retry-After"), "1");
return res.text().then((raw) => {
const body = JSON.parse(raw);
assert.equal(body.error.reason, "structure_limit");
assert.equal(body.error.type, "server_error");
assert.equal(body.error.code, "chat_admission_busy");
});
});

View File

@@ -42,6 +42,12 @@ test("buildPrecisionComboModelStep preserves provider/model/account triple", ()
});
test("buildManualComboModelStep resolves provider aliases and uses dynamic account", () => {
// #11433: `providerId` resolves to the canonical id ("codex") for
// duplicate-detection/routing identity, but the serialized `model` string
// now preserves the user-typed prefix ("cx/") verbatim instead of
// collapsing back to the canonical id — some canonical ids (e.g.
// "opencode") collide with an unrelated manual routing-alias override, so
// rebuilding `model` from the canonical id alone can silently misroute.
assert.deepEqual(
builderDraft.buildManualComboModelStep({
value: "cx/gpt-5.5",
@@ -50,7 +56,7 @@ test("buildManualComboModelStep resolves provider aliases and uses dynamic accou
{
kind: "model",
providerId: "codex",
model: "codex/gpt-5.5",
model: "cx/gpt-5.5",
weight: 0,
}
);

View File

@@ -0,0 +1,83 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
buildPrecisionComboModelStep,
buildGlobalModelList,
buildManualComboModelStep,
} from "../../src/lib/combos/builderDraft.ts";
import { resolveProviderAlias, parseModel } from "../../open-sse/services/model.ts";
// Issue #11433: the combo builder's precision-select path builds a step's
// `model` string as `${providerId}/${modelId}` using the CANONICAL provider id.
// For the no-auth "opencode" (OpenCode Free) provider this produces
// `model: "opencode/<modelId>"`, but `opencode` is ALSO a manual routing-prefix
// override (`ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen"`) intended only
// for user-typed `opencode/` prefixes referring to the OpenCode Zen (api-key)
// tier. Parsing the step's own `model` string therefore resolves to a
// DIFFERENT provider than the one recorded in `step.providerId`.
test('sanity: resolveProviderAlias("opencode") is the manual override causing the collision', () => {
// Documents the root cause directly: the manual alias override in
// open-sse/services/model.ts unconditionally rewrites "opencode" to
// "opencode-zen", even though "opencode" is also a registered canonical
// provider id (src/shared/constants/providers/noauth.ts).
assert.equal(resolveProviderAlias("opencode"), "opencode-zen");
});
test("issue #11433 fix: buildPrecisionComboModelStep honors an explicit modelPrefix override", () => {
// The combo builder call sites now thread through the already-computed
// routing-alias prefix (e.g. "oc") instead of letting the step default to
// the raw providerId, so the serialized `model` field round-trips to the
// correct provider.
const step = buildPrecisionComboModelStep({
providerId: "opencode",
modelId: "big-pickle",
modelPrefix: "oc",
});
assert.equal(step.providerId, "opencode");
assert.equal(step.model, "oc/big-pickle");
const parsed = parseModel(step.model);
assert.equal(parsed.provider, step.providerId);
});
test("issue #11433 fix: buildGlobalModelList derives modelPrefix from qualifiedModel for the no-auth OpenCode Free provider", () => {
// Mirrors what src/lib/combos/builderOptions.ts::rewriteQualifiedModelPrefix
// produces for the no-auth "opencode" provider entry: `qualifiedModel` is
// already rewritten to the "oc/" alias prefix, but (pre-fix)
// buildGlobalModelList ignored it and rebuilt `model` from the raw
// providerId, producing "opencode/big-pickle" which parses back to the
// wrong provider ("opencode-zen").
const [entry] = buildGlobalModelList([
{
providerId: "opencode",
displayName: "OpenCode Free",
connectionCount: 0,
connections: [],
models: [{ id: "big-pickle", name: "Big Pickle", qualifiedModel: "oc/big-pickle" }],
},
]);
assert.equal(entry.step.providerId, "opencode");
assert.equal(entry.step.model, "oc/big-pickle");
assert.equal(parseModel(entry.step.model).provider, entry.step.providerId);
});
test("issue #11433 fix: buildManualComboModelStep preserves a user-typed oc/<model> prefix", () => {
// buildManualComboModelStep resolves the typed alias ("oc") back to the
// canonical providerId ("opencode") before building the step. Pre-fix, it
// then handed that canonical id straight to buildPrecisionComboModelStep,
// which rebuilt `model` from it and collapsed "oc/<model>" back down to
// "opencode/<model>" — reproducing the same collision for manual entry.
const step = buildManualComboModelStep({
value: "oc/big-pickle",
providers: [{ providerId: "opencode", alias: "oc" }],
});
assert.ok(step);
assert.equal(step?.providerId, "opencode");
assert.equal(step?.model, "oc/big-pickle");
assert.equal(parseModel(step!.model).provider, step!.providerId);
});

View File

@@ -0,0 +1,20 @@
import test from "node:test";
import assert from "node:assert/strict";
import { resolveCursorImages } from "../../open-sse/utils/cursorImages.ts";
// zai-web maps resolveCursorImages() output into browser-upload attachments
// whose mimeType is REQUIRED. EncodedImage.mimeType is optional on the wire
// type, so zai-web carries an `?? "image/jpeg"` fallback — this test pins the
// producer contract that makes the fallback dead code in practice: every
// image that reaches a browser upload must arrive with a concrete image/*
// mime string (decodeDataUrl / fetchImageBytes validate it before pushing).
const PIXEL_PNG =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
test("resolveCursorImages (prepareForWire:false) always yields a concrete image/* mimeType", async () => {
const images = await resolveCursorImages([PIXEL_PNG], { prepareForWire: false });
assert.equal(images.length, 1);
assert.equal(typeof images[0]!.mimeType, "string");
assert.match(images[0]!.mimeType as string, /^image\//);
});