Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(system-transforms): generic per-provider DSL closing OpenWebUI bypass
Mourad Maatoug634b4fe0ce0a
diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.tsindex c25de9aa1c..721bfde73a 100644--- a/open-sse/executors/base.ts+++ b/open-sse/executors/base.ts@@ -13,6 +13,7 @@ import {import { getClaudeCodeCompatibleRequestDefaults } from "@/lib/providers/requestDefaults";import { remapToolNamesInRequest } from "../services/claudeCodeToolRemapper.ts";import { obfuscateInBody } from "../services/claudeCodeObfuscation.ts";+import { applySystemTransformPipeline, PROVIDER_CLAUDE } from "../services/systemTransforms.ts";import { randomUUID } from "node:crypto";import {CLAUDE_CODE_VERSION,@@ -781,6 +782,15 @@ export class BaseExecutor {sysBlocks.unshift({ type: "text", text: billingLine }, { type: "text", text: SENTINEL });tb.system = sysBlocks;+ // Run the configurable system-transforms pipeline for the native+ // `claude` provider (issue #2260 / comment 4459544580). The default+ // claude pipeline runs cosmetic ops only (Open WebUI paragraph+ // anchors, identity-prefix paragraph drop, ZWJ obfuscation of+ // sensitive words). It deliberately does NOT include+ // `inject_billing_header` — billing + sentinel are already+ // prepended above. Users can extend the pipeline via Settings UI.+ applySystemTransformPipeline(PROVIDER_CLAUDE, tb);+if (!tb.metadata || typeof tb.metadata !== "object") tb.metadata = {};(tb.metadata as Record<string, unknown>).user_id = buildUserIdJson({deviceId,diff --git a/open-sse/services/claudeCodeCompatible.ts b/open-sse/services/claudeCodeCompatible.tsindex 93a6cacb6c..ae2d779973 100644--- a/open-sse/services/claudeCodeCompatible.ts+++ b/open-sse/services/claudeCodeCompatible.ts@@ -12,7 +12,7 @@ import {enforceCacheControlLimit,} from "./claudeCodeConstraints.ts";import { obfuscateInBody } from "./claudeCodeObfuscation.ts";-import { applyCcBridgeTransformPipeline } from "./ccBridgeTransforms.ts";+import { applySystemTransformPipeline, PROVIDER_CC_BRIDGE } from "./systemTransforms.ts";/*** `anthropic-compatible-cc-*` targets Anthropic relay gateways that only accept@@ -333,10 +333,16 @@ export async function buildAndSignClaudeCodeRequest(// Step 5: Cache controlenforceCacheControlLimit(body);- // Step 5b: Config-driven CC bridge transforms (issue #2260)- // Normalizes system blocks to classifier-correct structure regardless of source- // client (OpenCode, Cline, Cursor, Continue, raw API). Idempotent on re-run.- applyCcBridgeTransformPipeline(body as Parameters<typeof applyCcBridgeTransformPipeline>[0]);+ // Step 5b: Config-driven system transforms (issue #2260, v2)+ // Normalizes system blocks to classifier-correct structure regardless of+ // source client (OpenCode, Cline, Cursor, Continue, Open WebUI, raw API).+ // Routed via the generic per-provider DSL so the same pipeline shape covers+ // the CC bridge, the native `claude` path, and any other configured+ // provider. Idempotent on re-run.+ applySystemTransformPipeline(+ PROVIDER_CC_BRIDGE,+ body as Parameters<typeof applySystemTransformPipeline>[1]+ );// Step 6: Obfuscation (optional, per-provider setting)if (enableObfuscation) {@@ -368,6 +374,27 @@ export {disableThinkingIfToolChoiceForced,enforceCacheControlLimit,} from "./claudeCodeConstraints.ts";+// Preferred (v2): generic per-provider DSL.+export {+ applySystemTransformPipeline,+ setSystemTransformsConfig,+ getSystemTransformsConfig,+ resetSystemTransformsConfig,+ DEFAULT_SYSTEM_TRANSFORMS_CONFIG,+ DEFAULT_CLAUDE_PIPELINE,+ DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE,+ DEFAULT_OBFUSCATE_WORDS,+ OPENWEBUI_PARAGRAPH_ANCHORS,+ OPENWEBUI_IDENTITY_PREFIXES,+ PROVIDER_CLAUDE,+ PROVIDER_CC_BRIDGE,+} from "./systemTransforms.ts";+export type { SystemTransformsConfig, ProviderTransformsConfig } from "./systemTransforms.ts";++// Legacy (deprecated, kept for transitional API consumers).+// The base executor is still used internally by systemTransforms.ts;+// these exports let downstream code reference the building blocks directly+// while we migrate UI + settings to the v2 shape.export {applyCcBridgeTransformPipeline,buildBillingHeaderValue,diff --git a/open-sse/services/systemTransforms.ts b/open-sse/services/systemTransforms.tsnew file mode 100644index 0000000000..50009b4273--- /dev/null+++ b/open-sse/services/systemTransforms.ts@@ -0,0 +1,472 @@+/**+ * System Transforms — generic, per-provider, config-driven body normalization.+ *+ * Generalises the CC-bridge-only transforms (`ccBridgeTransforms.ts`) into+ * a per-provider registry so the same pipeline DSL can run against ANY+ * provider's request body: native `claude` OAuth, `anthropic-compatible-cc-*`+ * bridge, `gemini`, `codex`, `openai`, etc.+ *+ * Each provider has its own `{ enabled, pipeline }`. Defaults shipped:+ * - `claude`: obfuscate_words ON (adds Open WebUI words on top of native+ * ZWJ pass). Billing+sentinel handled by native code (executors/base.ts+ * :753-782); DSL on this path does NOT inject billing.+ * - `anthropic-compatible-cc-*`: full T4-200 pipeline (anchors + identity+ * prefixes + replacements + prepend identity + inject_billing_header).+ * - all other providers: `{ enabled: false, pipeline: [] }`.+ *+ * Adds a new op kind `obfuscate_words` (ZWJ insertion driven by configurable+ * word list, replaces the hardcoded `claudeCodeObfuscation.ts` defaults for+ * users who opt-in).+ *+ * Migration: legacy `ccBridgeTransforms` config (single-pipeline shape) is+ * accepted and normalized into `systemTransforms.providers["anthropic-compatible-cc-*"]`.+ *+ * Reference: OmniRoute issue #2260 + comment 4459544580 (Open WebUI bypass).+ */+import { obfuscateSensitiveWords } from "./claudeCodeObfuscation.ts";+import {+ applyCcBridgeTransformPipeline,+ CLAUDE_AGENT_SDK_IDENTITY,+ DEFAULT_CC_BRIDGE_PIPELINE,+ DEFAULT_IDENTITY_PREFIXES,+ DEFAULT_PARAGRAPH_REMOVAL_ANCHORS,+ DEFAULT_TEXT_REPLACEMENTS,+} from "./ccBridgeTransforms.ts";+import type {+ CcBridgeTransformsConfig,+ TransformOp as BaseTransformOp,+} from "./ccBridgeTransforms.ts";++// Re-export base DSL types so external callers depend only on systemTransforms.+export {+ CLAUDE_AGENT_SDK_IDENTITY,+ DEFAULT_CC_BRIDGE_PIPELINE,+ DEFAULT_IDENTITY_PREFIXES,+ DEFAULT_PARAGRAPH_REMOVAL_ANCHORS,+ DEFAULT_TEXT_REPLACEMENTS,+};++// ────────────────────────────────────────────────────────────────────────────+// DSL — extends base TransformOp with the new `obfuscate_words` op kind.+// ────────────────────────────────────────────────────────────────────────────++export interface ObfuscateWordsOp {+ kind: "obfuscate_words";+ /** Words to obfuscate via zero-width joiner insertion. Case-insensitive. */+ words: string[];+ /** Where to apply obfuscation. Defaults to ["system", "messages", "tools"]. */+ targets?: Array<"system" | "messages" | "tools">;+}++export type TransformOp = BaseTransformOp | ObfuscateWordsOp;++export interface ProviderTransformsConfig {+ enabled: boolean;+ pipeline: TransformOp[];+}++export interface SystemTransformsConfig {+ providers: Record<string, ProviderTransformsConfig>;+}++// ────────────────────────────────────────────────────────────────────────────+// Default word lists (legacy hardcoded + OpenWebUI additions).+// ────────────────────────────────────────────────────────────────────────────++/**+ * Default obfuscation word list — current hardcoded set from+ * `claudeCodeObfuscation.ts` PLUS Open WebUI additions per issue #2260+ * comment 4459544580.+ */+export const DEFAULT_OBFUSCATE_WORDS = [+ // legacy hardcoded set+ "opencode",+ "open-code",+ "cline",+ "roo-cline",+ "roo_cline",+ "cursor",+ "windsurf",+ "aider",+ "continue.dev",+ "copilot",+ "avante",+ "codecompanion",+ // Open WebUI additions+ "openwebui",+ "open-webui",+];++/**+ * Open WebUI paragraph anchors — URLs identifying Open WebUI deployments.+ * Added on top of `DEFAULT_PARAGRAPH_REMOVAL_ANCHORS` for the CC bridge+ * default pipeline.+ */+export const OPENWEBUI_PARAGRAPH_ANCHORS = [+ "github.com/open-webui/open-webui",+ "openwebui.com",+ "docs.openwebui.com",+];++/** Open WebUI identity paragraph prefixes. */+export const OPENWEBUI_IDENTITY_PREFIXES = ["You are Open WebUI"];++// ────────────────────────────────────────────────────────────────────────────+// Per-provider defaults.+// ────────────────────────────────────────────────────────────────────────────++/**+ * Provider key for the native Claude OAuth path (`executors/base.ts`).+ * Billing+sentinel is already prepended by native code; DSL on this path+ * runs cosmetic ops only (no `inject_billing_header`).+ */+export const PROVIDER_CLAUDE = "claude";++/**+ * Provider key prefix for the Claude-Code-compatible bridge.+ * `claudeCodeCompatible.ts` invokes the pipeline via+ * `applyCcBridgeTransformPipeline` (kept for backward compatibility).+ */+export const PROVIDER_CC_BRIDGE = "anthropic-compatible-cc";++/**+ * Default pipeline for the native `claude` provider path.+ *+ * Cosmetic ops only — native executor already injects billing+sentinel.+ * Obfuscates sensitive words (Open WebUI etc.) and drops Open WebUI+ * paragraph anchors. Does NOT inject billing header (would conflict+ * with native code at executors/base.ts:753-782).+ */+export const DEFAULT_CLAUDE_PIPELINE: TransformOp[] = [+ // Open WebUI paragraph anchors (Gap 2 from comment 4459544580).+ {+ kind: "drop_paragraph_if_contains",+ needles: [...OPENWEBUI_PARAGRAPH_ANCHORS],+ },+ // Open WebUI identity prefixes.+ {+ kind: "drop_paragraph_if_starts_with",+ prefixes: [...OPENWEBUI_IDENTITY_PREFIXES],+ },+ // ZWJ obfuscation of sensitive words (closes Gap 1 + Gap 3).+ {+ kind: "obfuscate_words",+ words: [...DEFAULT_OBFUSCATE_WORDS],+ targets: ["system", "messages", "tools"],+ },+];++/**+ * Default pipeline for the CC bridge provider.+ *+ * Wraps the existing `DEFAULT_CC_BRIDGE_PIPELINE` (T4-200 proven layout)+ * and layers Open WebUI defenses on top: extra paragraph anchors + ZWJ+ * obfuscation of Open WebUI words.+ */+export const DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE: TransformOp[] = [+ // Extra Open WebUI anchors (the base pipeline only carries OpenCode/Cline/+ // Cursor/Continue anchors).+ {+ kind: "drop_paragraph_if_contains",+ needles: [...OPENWEBUI_PARAGRAPH_ANCHORS],+ },+ {+ kind: "drop_paragraph_if_starts_with",+ prefixes: [...OPENWEBUI_IDENTITY_PREFIXES],+ },+ // ZWJ obfuscate Open WebUI words across system+messages+tools.+ {+ kind: "obfuscate_words",+ words: ["openwebui", "open-webui"],+ targets: ["system", "messages", "tools"],+ },+ // Base CC bridge pipeline (anchors + identity prefixes + replacements ++ // prepend SDK identity + inject billing header).+ ...DEFAULT_CC_BRIDGE_PIPELINE,+];++export const DEFAULT_SYSTEM_TRANSFORMS_CONFIG: SystemTransformsConfig = {+ providers: {+ [PROVIDER_CLAUDE]: {+ enabled: true,+ pipeline: DEFAULT_CLAUDE_PIPELINE,+ },+ [PROVIDER_CC_BRIDGE]: {+ enabled: true,+ pipeline: DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE,+ },+ },+};++// ────────────────────────────────────────────────────────────────────────────+// Body shape helpers (mirrors ccBridgeTransforms.ts internals).+// ────────────────────────────────────────────────────────────────────────────++interface RequestBody {+ system?: unknown;+ messages?: unknown;+ tools?: unknown;+ [key: string]: unknown;+}++// ────────────────────────────────────────────────────────────────────────────+// Op: obfuscate_words (the only op kind beyond the base set).+// ────────────────────────────────────────────────────────────────────────────++function setWordsForOp(words: string[]): void {+ // Reuse the existing obfuscation engine — but it reads from its own module+ // singleton. We swap the words for this op invocation; obfuscateSensitiveWords+ // uses the module-level `sensitiveWords` array via setSensitiveWords.+ // To keep this stateless across concurrent requests, we instead call+ // obfuscateSensitiveWordsCustom (defined below) which takes the words list+ // explicitly.+ // — unused (intentional, see obfuscateWithList below).+ void words;+}+void setWordsForOp;++function escapeRegex(str: string): string {+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++const ZWJ = "\u200d";++function obfuscateWord(word: string): string {+ if (word.length <= 1) return word;+ return word[0] + ZWJ + word.slice(1);+}++/**+ * Stateless variant of `obfuscateSensitiveWords` — uses the supplied word+ * list instead of the module-level singleton, so concurrent requests with+ * different op configs do not race.+ */+function obfuscateWithList(text: string, words: string[]): string {+ if (!text || words.length === 0) return text;+ let result = text;+ for (const word of words) {+ if (!word) continue;+ const regex = new RegExp(escapeRegex(word), "gi");+ result = result.replace(regex, (match) => obfuscateWord(match));+ }+ return result;+}++function applyObfuscateWords(body: RequestBody, op: ObfuscateWordsOp): void {+ const words = op.words || [];+ if (words.length === 0) return;+ const targets =+ op.targets && op.targets.length > 0 ? op.targets : ["system", "messages", "tools"];++ if (targets.includes("system")) {+ if (typeof body.system === "string") {+ body.system = obfuscateWithList(body.system, words);+ } else if (Array.isArray(body.system)) {+ for (const block of body.system as Array<Record<string, unknown>>) {+ if (typeof block.text === "string") {+ block.text = obfuscateWithList(block.text, words);+ }+ }+ }+ }++ if (targets.includes("messages") && Array.isArray(body.messages)) {+ for (const msg of body.messages as Array<Record<string, unknown>>) {+ const content = msg.content;+ if (typeof content === "string") {+ msg.content = obfuscateWithList(content, words);+ } else if (Array.isArray(content)) {+ for (const block of content as Array<Record<string, unknown>>) {+ if (typeof block.text === "string") {+ block.text = obfuscateWithList(block.text, words);+ }+ }+ }+ }+ }++ if (targets.includes("tools") && Array.isArray(body.tools)) {+ for (const tool of body.tools as Array<Record<string, unknown>>) {+ if (typeof tool.description === "string") {+ tool.description = obfuscateWithList(tool.description, words);+ }+ const fn = tool.function as Record<string, unknown> | undefined;+ if (fn && typeof fn.description === "string") {+ fn.description = obfuscateWithList(fn.description, words);+ }+ }+ }+}++// Silence unused-import warning on obfuscateSensitiveWords — re-export for+// callers that want the global-singleton variant.+export { obfuscateSensitiveWords };++// ────────────────────────────────────────────────────────────────────────────+// Pipeline executor (delegates base ops to applyCcBridgeTransformPipeline).+// ────────────────────────────────────────────────────────────────────────────++export interface ApplyPipelineResult {+ body: RequestBody;+ appliedOpKinds: string[];+}++function isObfuscateWordsOp(op: TransformOp): op is ObfuscateWordsOp {+ return op.kind === "obfuscate_words";+}++/**+ * Apply a pipeline of generic transforms to a request body.+ *+ * Strategy:+ * 1. Split the pipeline into runs of `obfuscate_words` ops vs base ops.+ * 2. Base-op runs delegate to `applyCcBridgeTransformPipeline` (preserves+ * the well-tested base executor, including ordering semantics).+ * 3. `obfuscate_words` ops mutate the body in place between base-op runs.+ *+ * This preserves declared order (e.g. drop paragraphs first → obfuscate+ * what survives) while reusing the existing executor.+ */+export function applyTransformPipeline(+ body: RequestBody,+ pipeline: TransformOp[]+): ApplyPipelineResult {+ if (!body || typeof body !== "object") return { body, appliedOpKinds: [] };+ if (!Array.isArray(pipeline) || pipeline.length === 0) {+ return { body, appliedOpKinds: [] };+ }++ const appliedOpKinds: string[] = [];+ let baseRun: BaseTransformOp[] = [];++ const flushBaseRun = () => {+ if (baseRun.length === 0) return;+ const config: CcBridgeTransformsConfig = { enabled: true, pipeline: baseRun };+ const result = applyCcBridgeTransformPipeline(body, config);+ appliedOpKinds.push(...result.appliedOpKinds);+ baseRun = [];+ };++ for (const op of pipeline) {+ if (isObfuscateWordsOp(op)) {+ flushBaseRun();+ applyObfuscateWords(body, op);+ appliedOpKinds.push(op.kind);+ } else {+ baseRun.push(op);+ }+ }+ flushBaseRun();++ return { body, appliedOpKinds };+}++/**+ * Apply the configured per-provider pipeline to `body`. No-op when the+ * provider is unconfigured or disabled.+ *+ * `providerId` matches OmniRoute's provider key (`claude`,+ * `anthropic-compatible-cc-…`, `gemini`, etc.). For CC bridge providers,+ * the bridge-prefix match falls back to the `PROVIDER_CC_BRIDGE` key so+ * a single config entry covers every cc/* variant.+ */+export function applySystemTransformPipeline(+ providerId: string,+ body: RequestBody,+ config: SystemTransformsConfig = getSystemTransformsConfig()+): ApplyPipelineResult {+ if (!body || typeof body !== "object") return { body, appliedOpKinds: [] };+ if (!config || !config.providers) return { body, appliedOpKinds: [] };++ const providerConfig = resolveProviderConfig(providerId, config);+ if (!providerConfig || !providerConfig.enabled) {+ return { body, appliedOpKinds: [] };+ }++ return applyTransformPipeline(body, providerConfig.pipeline);+}++function resolveProviderConfig(+ providerId: string,+ config: SystemTransformsConfig+): ProviderTransformsConfig | undefined {+ if (!providerId) return undefined;+ const exact = config.providers[providerId];+ if (exact) return exact;++ // CC bridge providers (anthropic-compatible-cc-*) all share one config.+ if (providerId.startsWith(`${PROVIDER_CC_BRIDGE}-`) || providerId === PROVIDER_CC_BRIDGE) {+ return config.providers[PROVIDER_CC_BRIDGE];+ }+ return undefined;+}++// ────────────────────────────────────────────────────────────────────────────+// Runtime singleton.+// ────────────────────────────────────────────────────────────────────────────++let _systemTransformsConfig: SystemTransformsConfig = DEFAULT_SYSTEM_TRANSFORMS_CONFIG;++/**+ * Replace the active system-transforms config. Called from+ * `runtimeSettings.applySystemTransformsSection()` on Settings UI save.+ *+ * Accepts a legacy `CcBridgeTransformsConfig` shape (single-provider) and+ * migrates it into `providers[PROVIDER_CC_BRIDGE]`.+ */+export function setSystemTransformsConfig(input: unknown): void {+ if (!input || typeof input !== "object") {+ _systemTransformsConfig = DEFAULT_SYSTEM_TRANSFORMS_CONFIG;+ return;+ }+ const candidate = input as Record<string, unknown>;++ // Legacy shape: { enabled, pipeline } → migrate to per-provider map.+ if ("pipeline" in candidate && Array.isArray(candidate.pipeline)) {+ _systemTransformsConfig = {+ providers: {+ ...DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers,+ [PROVIDER_CC_BRIDGE]: {+ enabled: candidate.enabled !== false,+ pipeline: candidate.pipeline as TransformOp[],+ },+ },+ };+ return;+ }++ // Per-provider shape: { providers: Record<string, { enabled, pipeline }> }+ if ("providers" in candidate && candidate.providers && typeof candidate.providers === "object") {+ const next: SystemTransformsConfig = { providers: {} };+ const providers = candidate.providers as Record<string, unknown>;+ for (const [providerId, providerEntry] of Object.entries(providers)) {+ if (!providerEntry || typeof providerEntry !== "object") continue;+ const entry = providerEntry as Record<string, unknown>;+ next.providers[providerId] = {+ enabled: entry.enabled !== false,+ pipeline: Array.isArray(entry.pipeline) ? (entry.pipeline as TransformOp[]) : [],+ };+ }+ // Merge defaults for any unset provider — keeps ZWJ on by default even+ // when the user only configured one provider explicitly.+ for (const [providerId, providerDefault] of Object.entries(+ DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers+ )) {+ if (!next.providers[providerId]) {+ next.providers[providerId] = providerDefault;+ }+ }+ _systemTransformsConfig = next;+ return;+ }++ _systemTransformsConfig = DEFAULT_SYSTEM_TRANSFORMS_CONFIG;+}++export function getSystemTransformsConfig(): SystemTransformsConfig {+ return _systemTransformsConfig;+}++export function resetSystemTransformsConfig(): void {+ _systemTransformsConfig = DEFAULT_SYSTEM_TRANSFORMS_CONFIG;+}diff --git a/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx b/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsxindex 9630be847d..fb75173834 100644--- a/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx@@ -10,57 +10,136 @@ import {normalizeCliCompatProviderId,} from "@/shared/constants/cliCompatProviders";-// Mirror of DEFAULT_CC_BRIDGE_PIPELINE from open-sse/services/ccBridgeTransforms.ts.+// Provider keys (mirror of open-sse/services/systemTransforms.ts).+const PROVIDER_CLAUDE = "claude";+const PROVIDER_CC_BRIDGE = "anthropic-compatible-cc";++const OPENWEBUI_PARAGRAPH_ANCHORS = [+ "github.com/open-webui/open-webui",+ "openwebui.com",+ "docs.openwebui.com",+];++const DEFAULT_OBFUSCATE_WORDS = [+ "opencode",+ "open-code",+ "cline",+ "roo-cline",+ "roo_cline",+ "cursor",+ "windsurf",+ "aider",+ "continue.dev",+ "copilot",+ "avante",+ "codecompanion",+ "openwebui",+ "open-webui",+];++// Mirror of DEFAULT_SYSTEM_TRANSFORMS_CONFIG from open-sse/services/systemTransforms.ts.// Kept client-side so the UI can render + reset to defaults without a server roundtrip.-// Server is the source of truth — if pipeline is empty/missing on PATCH, server falls back to its own defaults.-const DEFAULT_CC_BRIDGE_PIPELINE_CLIENT = [- {- kind: "drop_paragraph_if_contains",- needles: [- "github.com/anomalyco/opencode",- "opencode.ai/docs",- "github.com/cline/cline",- "github.com/getcursor/cursor",- "continue.dev",- ],- },- {- kind: "drop_paragraph_if_starts_with",- prefixes: ["You are OpenCode"],- },- {- kind: "replace_text",- match: "if OpenCode honestly",- replacement: "if the assistant honestly",- },- {- kind: "replace_text",- match: "Here is some useful information about the environment you are running in:",- replacement: "Environment context you are running in:",+// Server remains the source of truth — UI just lets the user inspect, edit, and reset.+const DEFAULT_SYSTEM_TRANSFORMS_CLIENT = {+ providers: {+ [PROVIDER_CLAUDE]: {+ enabled: true,+ pipeline: [+ {+ kind: "drop_paragraph_if_contains",+ needles: [...OPENWEBUI_PARAGRAPH_ANCHORS],+ },+ {+ kind: "drop_paragraph_if_starts_with",+ prefixes: ["You are Open WebUI"],+ },+ {+ kind: "obfuscate_words",+ words: [...DEFAULT_OBFUSCATE_WORDS],+ targets: ["system", "messages", "tools"],+ },+ ],+ },+ [PROVIDER_CC_BRIDGE]: {+ enabled: true,+ pipeline: [+ {+ kind: "drop_paragraph_if_contains",+ needles: [...OPENWEBUI_PARAGRAPH_ANCHORS],+ },+ {+ kind: "drop_paragraph_if_starts_with",+ prefixes: ["You are Open WebUI"],+ },+ {+ kind: "obfuscate_words",+ words: ["openwebui", "open-webui"],+ targets: ["system", "messages", "tools"],+ },+ {+ kind: "drop_paragraph_if_contains",+ needles: [+ "github.com/anomalyco/opencode",+ "opencode.ai/docs",+ "github.com/cline/cline",+ "github.com/getcursor/cursor",+ "continue.dev",+ ],+ },+ {+ kind: "drop_paragraph_if_starts_with",+ prefixes: ["You are OpenCode"],+ },+ {+ kind: "replace_text",+ match: "if OpenCode honestly",+ replacement: "if the assistant honestly",+ allOccurrences: true,+ },+ {+ kind: "replace_text",+ match: "Here is some useful information about the environment you are running in:",+ replacement: "Environment context you are running in:",+ allOccurrences: true,+ },+ {+ kind: "prepend_system_block",+ text: "You are a Claude agent, built on Anthropic's Claude Agent SDK.",+ idempotencyKey: "claude-agent-sdk-identity",+ },+ {+ kind: "inject_billing_header",+ entrypoint: "sdk-cli",+ versionFormat: "ex-machina",+ cchAlgo: "sha256-first-user",+ },+ ],+ },},- {- kind: "prepend_system_block",- text: "You are a Claude agent, built on Anthropic's Claude Agent SDK.",- idempotencyKey: "claude-agent-sdk-identity",+} as const;++// Provider display metadata for the per-provider tiles.+// Mirrors the names from CLI_COMPAT_PROVIDER_DISPLAY where applicable so the+// header-fingerprint toggle row stays consistent with the rest of the card.+const PROVIDER_TILE_DISPLAY: Record<+ string,+ { name: string; description: string; icon: string; tone: string }+> = {+ [PROVIDER_CLAUDE]: {+ name: "Claude (OAuth)",+ description:+ "Native Claude provider — handles OAuth-issued tokens. Header fingerprint is force-applied for account safety; transforms are cosmetic-only (no billing/identity prepend — native code already does that).",+ icon: "anthropic",+ tone: "indigo",},- {- kind: "inject_billing_header",- entrypoint: "sdk-cli",- versionFormat: "ex-machina",- cchAlgo: "sha256-first-user",+ [PROVIDER_CC_BRIDGE]: {+ name: "Claude-Code Bridge (anthropic-compatible-cc-*)",+ description:+ "Relay endpoints that accept Anthropic-shaped requests on behalf of API-key callers. The full transform pipeline ships here (paragraph anchors + identity prefixes + text replacements + SDK identity + billing header) — that's the T4-200 layout proven on the live OmniRoute deployment.",+ icon: "hub",+ tone: "purple",},-];--const TRANSFORM_OP_KINDS = [- "drop_paragraph_if_contains",- "drop_paragraph_if_starts_with",- "replace_text",- "replace_regex",- "drop_block_if_contains",- "prepend_system_block",- "append_system_block",- "inject_billing_header",-] as const;+};function summarizeTransformOp(op: any): string {switch (op?.kind) {@@ -80,37 +159,42 @@ function summarizeTransformOp(op: any): string {return `append block: "${(op.text || "").slice(0, 60)}${(op.text || "").length > 60 ? "…" : ""}"`;case "inject_billing_header":return `inject billing header (entrypoint=${op.entrypoint}, version=${op.versionFormat}, cch=${op.cchAlgo})`;+ case "obfuscate_words":+ return `obfuscate ${(op.words || []).length} word(s) via ZWJ in ${(op.targets || ["system", "messages", "tools"]).join("+")}`;default:return JSON.stringify(op);}}-function makeBlankOp(kind: string): any {- switch (kind) {- case "drop_paragraph_if_contains":- return { kind, needles: [""] };- case "drop_paragraph_if_starts_with":- return { kind, prefixes: [""] };- case "replace_text":- return { kind, match: "", replacement: "" };- case "replace_regex":- return { kind, pattern: "", flags: "g", replacement: "" };- case "drop_block_if_contains":- return { kind, needles: [""] };- case "prepend_system_block":- return { kind, text: "" };- case "append_system_block":- return { kind, text: "" };- case "inject_billing_header":- return {- kind,- entrypoint: "sdk-cli",- versionFormat: "ex-machina",- cchAlgo: "sha256-first-user",- };- default:- return { kind };+// Client-side validator — light shape check before we PATCH; the server+// re-validates with the full zod schema in settingsSchemas.ts.+function validateProviderTransformsConfig(value: unknown): string | null {+ if (!value || typeof value !== "object") return "Config must be a JSON object";+ const cfg = value as { enabled?: unknown; pipeline?: unknown };+ if (typeof cfg.enabled !== "boolean") return "`enabled` must be true or false";+ if (!Array.isArray(cfg.pipeline)) return "`pipeline` must be an array of ops";+ if (cfg.pipeline.length > 50) return "Pipeline cannot exceed 50 ops";+ for (let i = 0; i < cfg.pipeline.length; i++) {+ const op = cfg.pipeline[i] as { kind?: unknown };+ if (!op || typeof op !== "object" || typeof op.kind !== "string") {+ return `Op #${i + 1}: missing or invalid \`kind\``;+ }+ const validKinds = [+ "drop_paragraph_if_contains",+ "drop_paragraph_if_starts_with",+ "replace_text",+ "replace_regex",+ "drop_block_if_contains",+ "prepend_system_block",+ "append_system_block",+ "inject_billing_header",+ "obfuscate_words",+ ];+ if (!validKinds.includes(op.kind)) {+ return `Op #${i + 1}: unknown kind "${op.kind}"`;+ }}+ return null;}export default function RoutingTab() {@@ -120,9 +204,14 @@ export default function RoutingTab() {cliCompatProviders: [],autoRoutingEnabled: true,autoRoutingDefaultVariant: "lkgp",- ccBridgeTransforms: { enabled: true, pipeline: DEFAULT_CC_BRIDGE_PIPELINE_CLIENT },+ systemTransforms: DEFAULT_SYSTEM_TRANSFORMS_CLIENT,});- const [addOpKind, setAddOpKind] = useState<string>("drop_paragraph_if_contains");+ // Per-provider JSON draft + error state for the system-transforms editor.+ // Map keyed by provider id; values track the textarea content + last+ // validation error string (null when valid). Synced from settings via+ // effect so server-side values flow into the editor.+ const [jsonDrafts, setJsonDrafts] = useState<Record<string, string>>({});+ const [jsonErrors, setJsonErrors] = useState<Record<string, string | null>>({});const [loading, setLoading] = useState(true);const [lkgpCacheLoading, setLkgpCacheLoading] = useState(false);const [lkgpCacheStatus, setLkgpCacheStatus] = useState({ type: "", message: "" });@@ -164,40 +253,86 @@ export default function RoutingTab() {);const cliCompatProviderSet = useMemo(() => new Set(cliCompatProviders), [cliCompatProviders]);- const ccBridgeTransforms = useMemo(() => {- const raw = settings.ccBridgeTransforms;- if (raw && typeof raw === "object" && Array.isArray(raw.pipeline)) {- return { enabled: raw.enabled !== false, pipeline: raw.pipeline };+ // Normalize the server snapshot into a per-provider map. Legacy v1+ // `ccBridgeTransforms` payloads from Phase 2 are migrated client-side+ // into providers[PROVIDER_CC_BRIDGE] so the editor never breaks.+ const systemTransforms = useMemo(() => {+ const raw = settings.systemTransforms;+ if (raw && typeof raw === "object" && raw.providers && typeof raw.providers === "object") {+ return raw as { providers: Record<string, { enabled: boolean; pipeline: any[] }> };+ }+ // Legacy migration shim: { enabled, pipeline } → providers[CC_BRIDGE].+ const legacy = settings.ccBridgeTransforms;+ if (legacy && typeof legacy === "object" && Array.isArray(legacy.pipeline)) {+ return {+ providers: {+ ...DEFAULT_SYSTEM_TRANSFORMS_CLIENT.providers,+ [PROVIDER_CC_BRIDGE]: {+ enabled: legacy.enabled !== false,+ pipeline: legacy.pipeline,+ },+ },+ };}- return { enabled: true, pipeline: DEFAULT_CC_BRIDGE_PIPELINE_CLIENT };- }, [settings.ccBridgeTransforms]);+ return DEFAULT_SYSTEM_TRANSFORMS_CLIENT;+ }, [settings.systemTransforms, settings.ccBridgeTransforms]);- const updateCcBridgeTransforms = (next: { enabled: boolean; pipeline: any[] }) => {- updateSetting({ ccBridgeTransforms: next });- };+ // Sync JSON drafts from settings whenever the server snapshot changes.+ useEffect(() => {+ const nextDrafts: Record<string, string> = {};+ for (const [providerId, providerCfg] of Object.entries(systemTransforms.providers)) {+ nextDrafts[providerId] = JSON.stringify(providerCfg, null, 2);+ }+ setJsonDrafts(nextDrafts);+ setJsonErrors({});+ }, [systemTransforms]);- const moveCcBridgeOp = (index: number, direction: -1 | 1) => {- const pipeline = [...ccBridgeTransforms.pipeline];- const target = index + direction;- if (target < 0 || target >= pipeline.length) return;- [pipeline[index], pipeline[target]] = [pipeline[target], pipeline[index]];- updateCcBridgeTransforms({ enabled: ccBridgeTransforms.enabled, pipeline });+ const updateProviderTransforms = (+ providerId: string,+ next: { enabled: boolean; pipeline: any[] }+ ) => {+ const merged = {+ providers: {+ ...systemTransforms.providers,+ [providerId]: next,+ },+ };+ updateSetting({ systemTransforms: merged });};- const deleteCcBridgeOp = (index: number) => {- const pipeline = ccBridgeTransforms.pipeline.filter((_, i) => i !== index);- updateCcBridgeTransforms({ enabled: ccBridgeTransforms.enabled, pipeline });+ const toggleProviderEnabled = (providerId: string, enabled: boolean) => {+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };+ updateProviderTransforms(providerId, { enabled, pipeline: current.pipeline });};- const addCcBridgeOp = () => {- const pipeline = [...ccBridgeTransforms.pipeline, makeBlankOp(addOpKind)];- updateCcBridgeTransforms({ enabled: ccBridgeTransforms.enabled, pipeline });+ const applyProviderJson = (providerId: string) => {+ const raw = jsonDrafts[providerId] ?? "";+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (err) {+ setJsonErrors((prev) => ({+ ...prev,+ [providerId]: `Invalid JSON: ${(err as Error).message}`,+ }));+ return;+ }+ const validationError = validateProviderTransformsConfig(parsed);+ if (validationError) {+ setJsonErrors((prev) => ({ ...prev, [providerId]: validationError }));+ return;+ }+ setJsonErrors((prev) => ({ ...prev, [providerId]: null }));+ updateProviderTransforms(providerId, parsed as { enabled: boolean; pipeline: any[] });};- const resetCcBridgePipeline = () => {- updateCcBridgeTransforms({- enabled: true,- pipeline: DEFAULT_CC_BRIDGE_PIPELINE_CLIENT.map((op) => ({ ...op })),+ const resetProviderTransforms = (providerId: string) => {+ const def = (DEFAULT_SYSTEM_TRANSFORMS_CLIENT.providers as Record<string, any>)[providerId];+ if (!def) return;+ setJsonErrors((prev) => ({ ...prev, [providerId]: null }));+ updateProviderTransforms(providerId, {+ enabled: def.enabled,+ pipeline: def.pipeline.map((op: any) => ({ ...op })),});};@@ -397,217 +532,225 @@ export default function RoutingTab() {</Card><Card>- <div className="flex items-center gap-3 mb-4">- <div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-500">+ <div className="flex items-start gap-3 mb-4">+ <div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-500 h-fit"><span className="material-symbols-outlined text-[20px]" aria-hidden="true">- fingerprint+ integration_instructions</span></div><div>- <h3 className="text-lg font-semibold">{t("cliFingerprint")}</h3>- <p className="text-sm text-text-muted">{t("cliFingerprintDesc")}</p>+ <h3 className="text-lg font-semibold">Provider Upstream Compatibility</h3>+ <p className="text-sm text-text-muted mt-1">+ Configure per-provider request normalization. The header-fingerprint row matches+ upstream CLI binary signatures (reordering headers/body shapes) and the+ system-transform pipeline rewrites system blocks so Anthropic-side classifiers (or+ equivalent guards on other providers) see a classifier-correct request regardless of+ which client sent it. Issue #2260 + comment 4459544580.+ </p><p className="mt-1 text-xs text-text-muted">- {t("cliFingerprintEnabled", { count: cliCompatProviderSet.size })}+ <span className="font-medium">No local CLI binary is required</span> — OmniRoute+ builds the upstream-compatible request server-side. The "Managed" badge on+ the Claude tile means the fingerprint is force-applied for OAuth account safety, not+ that the user must install the Claude Code CLI.</p></div></div>- <div className="grid gap-3 md:grid-cols-2">- {CLI_COMPAT_TOGGLE_IDS.map((providerId) => {- const normalizedProviderId = normalizeCliCompatProviderId(providerId);- const providerDisplay = CLI_COMPAT_PROVIDER_DISPLAY[providerId];- // Claude OAuth force-applies the fingerprint regardless of this toggle- // (base.ts: shouldFingerprint), so render the tile as locked-on.- const forced = providerId === "claude";- const checked = forced || cliCompatProviderSet.has(normalizedProviderId);- const label = providerDisplay?.name || providerId;- const description = providerDisplay?.description || providerId;- const titleText = forced- ? t("forcedFingerprintTitle", { provider: label })- : checked- ? t("disableFingerprintTitle", { provider: label })- : t("enableFingerprintTitle", { provider: label });-- return (- <button- key={providerId}- type="button"- onClick={() => {- if (forced) return;- toggleCliCompatProvider(providerId, !checked);- }}- disabled={loading || forced}- aria-pressed={checked}- aria-disabled={forced || undefined}- title={titleText}- className={`flex items-start gap-3 rounded-lg border p-3 text-left transition-all ${- checked- ? "border-indigo-500/50 bg-indigo-500/5 ring-1 ring-indigo-500/20"- : "border-border/50 hover:border-border hover:bg-surface/30"- } ${loading || forced ? "cursor-not-allowed" : ""} ${loading ? "opacity-60" : ""}`}- >- <span- className={`material-symbols-outlined mt-0.5 text-[18px] ${checked ? "text-indigo-400" : "text-text-muted"}`}- aria-hidden="true"+ <div className="mb-5">+ <h4 className="text-sm font-semibold mb-2">Header fingerprint (per provider)</h4>+ <p className="text-xs text-text-muted mb-2">+ {t("cliFingerprintEnabled", { count: cliCompatProviderSet.size })}+ </p>+ <div className="grid gap-3 md:grid-cols-2">+ {CLI_COMPAT_TOGGLE_IDS.map((providerId) => {+ const normalizedProviderId = normalizeCliCompatProviderId(providerId);+ const providerDisplay = CLI_COMPAT_PROVIDER_DISPLAY[providerId];+ // Claude OAuth force-applies the fingerprint regardless of this toggle+ // (base.ts: shouldFingerprint) — that's an account-safety constraint,+ // not a local-binary requirement.+ const forced = providerId === "claude";+ const checked = forced || cliCompatProviderSet.has(normalizedProviderId);+ const label = providerDisplay?.name || providerId;+ const description = providerDisplay?.description || providerId;+ const titleText = forced+ ? t("forcedFingerprintTitle", { provider: label })+ : checked+ ? t("disableFingerprintTitle", { provider: label })+ : t("enableFingerprintTitle", { provider: label });++ return (+ <button+ key={providerId}+ type="button"+ onClick={() => {+ if (forced) return;+ toggleCliCompatProvider(providerId, !checked);+ }}+ disabled={loading || forced}+ aria-pressed={checked}+ aria-disabled={forced || undefined}+ title={titleText}+ className={`flex items-start gap-3 rounded-lg border p-3 text-left transition-all ${+ checked+ ? "border-indigo-500/50 bg-indigo-500/5 ring-1 ring-indigo-500/20"+ : "border-border/50 hover:border-border hover:bg-surface/30"+ } ${loading || forced ? "cursor-not-allowed" : ""} ${loading ? "opacity-60" : ""}`}>- {forced ? "lock" : checked ? "check_circle" : "radio_button_unchecked"}- </span>- <span className="min-w-0 flex-1">- <span className="flex items-center gap-2">- <span- className={`block text-sm font-medium ${checked ? "text-indigo-400" : ""}`}- >- {label}- </span>- {forced ? (- <span className="rounded-full border border-indigo-500/40 bg-indigo-500/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-indigo-400">- {t("forcedFingerprintBadge")}+ <span+ className={`material-symbols-outlined mt-0.5 text-[18px] ${checked ? "text-indigo-400" : "text-text-muted"}`}+ aria-hidden="true"+ >+ {forced ? "lock" : checked ? "check_circle" : "radio_button_unchecked"}+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-2 flex-wrap">+ <span+ className={`block text-sm font-medium ${checked ? "text-indigo-400" : ""}`}+ >+ {label}</span>- ) : null}+ {forced ? (+ <span className="rounded-full border border-indigo-500/40 bg-indigo-500/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-indigo-400">+ Managed+ </span>+ ) : null}+ </span>+ <span className="mt-1 block text-xs text-text-muted">{description}</span></span>- <span className="mt-1 block text-xs text-text-muted">{description}</span>- </span>- </button>- );- })}- </div>- </Card>-- <Card>- <div className="flex items-start justify-between gap-4 mb-4">- <div className="flex gap-3">- <div className="p-2 rounded-lg bg-purple-500/10 text-purple-500 h-fit">- <span className="material-symbols-outlined text-[20px]" aria-hidden="true">- tune- </span>- </div>- <div>- <h3 className="text-lg font-semibold">{t("ccBridgeTransforms")}</h3>- <p className="text-sm text-text-muted mt-1">{t("ccBridgeTransformsDesc")}</p>- <p className="mt-1 text-xs text-text-muted">- {t("ccBridgeTransformsEnabled", { count: ccBridgeTransforms.pipeline.length })}- </p>- </div>- </div>- <div className="pt-1">- <label className="relative inline-flex items-center cursor-pointer">- <input- type="checkbox"- className="sr-only peer"- checked={ccBridgeTransforms.enabled}- onChange={(e) =>- updateCcBridgeTransforms({- enabled: e.target.checked,- pipeline: ccBridgeTransforms.pipeline,- })- }- disabled={loading}- />- <div className="w-11 h-6 bg-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>- </label>+ </button>+ );+ })}</div></div>- {ccBridgeTransforms.pipeline.length === 0 ? (- <p className="text-xs text-text-muted italic mb-3">{t("ccBridgeTransformsEmpty")}</p>- ) : (- <ol className="flex flex-col gap-2 mb-3">- {ccBridgeTransforms.pipeline.map((op: any, index: number) => (- <li- key={index}- className="flex items-start gap-2 rounded-lg border border-border/50 bg-surface/30 p-3"- >- <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-purple-500/10 text-xs font-semibold text-purple-400">- {index + 1}- </span>- <div className="min-w-0 flex-1">- <div className="text-sm font-mono text-purple-300">{op?.kind}</div>- <div className="mt-1 text-xs text-text-muted break-words">- {summarizeTransformOp(op)}+ <div>+ <h4 className="text-sm font-semibold mb-2">System-block transform pipeline</h4>+ <p className="text-xs text-text-muted mb-3">+ Per-provider DSL. Each provider has its own ordered pipeline of ops+ (drop_paragraph_if_contains, replace_text, obfuscate_words, inject_billing_header, …).+ Edit the JSON below and click <em>Apply JSON</em> — the server validates against the+ full zod schema before persisting. Click <em>Reset</em> to restore the shipped defaults+ for that provider.+ </p>++ <div className="flex flex-col gap-5">+ {Object.entries(systemTransforms.providers).map(([providerId, providerCfg]) => {+ const display = PROVIDER_TILE_DISPLAY[providerId] ?? {+ name: providerId,+ description:+ "Custom provider — pipeline only runs when an OmniRoute request targets this provider key.",+ icon: "extension",+ tone: "purple",+ };+ const draft = jsonDrafts[providerId] ?? JSON.stringify(providerCfg, null, 2);+ const errorMsg = jsonErrors[providerId] ?? null;+ const opCount = Array.isArray(providerCfg.pipeline) ? providerCfg.pipeline.length : 0;+ const hasDefault = Boolean(+ (DEFAULT_SYSTEM_TRANSFORMS_CLIENT.providers as Record<string, unknown>)[providerId]+ );++ return (+ <div+ key={providerId}+ className="rounded-lg border border-border/50 bg-surface/20 p-4"+ >+ <div className="flex items-start justify-between gap-3 mb-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <code className="text-xs font-mono rounded bg-surface px-1.5 py-0.5">+ {providerId}+ </code>+ <span className="text-sm font-medium">{display.name}</span>+ </div>+ <p className="text-xs text-text-muted mt-1">{display.description}</p>+ <p className="text-[11px] text-text-muted mt-1">+ {opCount} op{opCount === 1 ? "" : "s"}+ </p>+ </div>+ <label className="relative inline-flex items-center cursor-pointer shrink-0">+ <input+ type="checkbox"+ className="sr-only peer"+ checked={providerCfg.enabled !== false}+ onChange={(e) => toggleProviderEnabled(providerId, e.target.checked)}+ disabled={loading}+ />+ <div className="w-11 h-6 bg-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>+ </label></div>- </div>- <div className="flex shrink-0 items-center gap-1">- <button- type="button"- onClick={() => moveCcBridgeOp(index, -1)}- disabled={loading || index === 0}- title={t("ccBridgeTransformsMoveUp")}- aria-label={t("ccBridgeTransformsMoveUp")}- className="rounded p-1 text-text-muted hover:bg-surface hover:text-text disabled:cursor-not-allowed disabled:opacity-30"- >- <span className="material-symbols-outlined text-[16px]" aria-hidden="true">- arrow_upward- </span>- </button>- <button- type="button"- onClick={() => moveCcBridgeOp(index, 1)}- disabled={loading || index === ccBridgeTransforms.pipeline.length - 1}- title={t("ccBridgeTransformsMoveDown")}- aria-label={t("ccBridgeTransformsMoveDown")}- className="rounded p-1 text-text-muted hover:bg-surface hover:text-text disabled:cursor-not-allowed disabled:opacity-30"- >- <span className="material-symbols-outlined text-[16px]" aria-hidden="true">- arrow_downward- </span>- </button>- <button- type="button"- onClick={() => deleteCcBridgeOp(index)}++ {opCount > 0 && (+ <ol className="flex flex-col gap-1 mb-3">+ {(providerCfg.pipeline as any[]).map((op, index) => (+ <li+ key={index}+ className="flex items-start gap-2 rounded border border-border/30 bg-background/30 p-2 text-xs"+ >+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-purple-500/10 text-[10px] font-semibold text-purple-400">+ {index + 1}+ </span>+ <div className="min-w-0">+ <div className="font-mono text-purple-300">{op?.kind}</div>+ <div className="text-text-muted break-words">+ {summarizeTransformOp(op)}+ </div>+ </div>+ </li>+ ))}+ </ol>+ )}++ <label className="text-[11px] font-medium text-text-muted block mb-1">+ JSON configuration+ </label>+ <textarea+ value={draft}+ onChange={(e) =>+ setJsonDrafts((prev) => ({ ...prev, [providerId]: e.target.value }))+ }+ rows={Math.min(20, Math.max(8, draft.split("\n").length))}disabled={loading}- title={t("ccBridgeTransformsDelete")}- aria-label={t("ccBridgeTransformsDelete")}- className="rounded p-1 text-text-muted hover:bg-red-500/10 hover:text-red-400 disabled:cursor-not-allowed disabled:opacity-30"- >- <span className="material-symbols-outlined text-[16px]" aria-hidden="true">- delete- </span>- </button>+ spellCheck={false}+ className="w-full rounded border border-border/50 bg-background/40 p-2 font-mono text-[11px] text-text resize-y"+ />+ {errorMsg && (+ <p className="mt-2 text-xs text-red-400 break-words">⚠ {errorMsg}</p>+ )}+ <div className="flex flex-wrap items-center gap-2 mt-2">+ <Button+ onClick={() => applyProviderJson(providerId)}+ disabled={loading}+ variant="secondary"+ size="sm"+ icon="check"+ >+ Apply JSON+ </Button>+ {hasDefault && (+ <Button+ onClick={() => resetProviderTransforms(providerId)}+ disabled={loading}+ variant="ghost"+ size="sm"+ icon="restart_alt"+ >+ Reset to defaults+ </Button>+ )}+ </div></div>- </li>- ))}- </ol>- )}-- <div className="flex flex-wrap items-center gap-2">- <select- value={addOpKind}- onChange={(e) => setAddOpKind(e.target.value)}- disabled={loading}- className="rounded-lg border border-border/50 bg-surface px-3 py-1.5 text-xs text-text"- >- {TRANSFORM_OP_KINDS.map((kind) => (- <option key={kind} value={kind}>- {kind}- </option>- ))}- </select>- <Button- onClick={addCcBridgeOp}- disabled={loading}- variant="secondary"- size="sm"- icon="add"- >- {t("ccBridgeTransformsAddOp")}- </Button>- <Button- onClick={resetCcBridgePipeline}- disabled={loading}- variant="ghost"- size="sm"- icon="restart_alt"- >- {t("ccBridgeTransformsReset")}- </Button>- </div>+ );+ })}+ </div>- <p className="mt-3 text-[11px] text-text-muted">- Pipeline applies in order at step 5b of the CC bridge request build (after cache-control,- before ZWJ obfuscation). All ops are idempotent on re-run. Op editing beyond- reorder/delete requires PATCH via /api/settings — full per-op form is coming in a- follow-up; for now, edit the JSON directly via the API to fine-tune individual ops.- </p>+ <p className="mt-3 text-[11px] text-text-muted">+ Native <code>claude</code> path: the DSL runs after the existing billing+sentinel+ prepend (executors/base.ts) — its default pipeline therefore omits{" "}+ <code>inject_billing_header</code>. CC bridge (<code>anthropic-compatible-cc-*</code>):+ the DSL runs as step 5b of the bridge request build (claudeCodeCompatible.ts), after+ cache-control and before ZWJ obfuscation. All ops are idempotent on re-run.+ </p>+ </div></Card><Card>diff --git a/src/lib/config/runtimeSettings.ts b/src/lib/config/runtimeSettings.tsindex d0f9fbf56f..634fd5d9b0 100644--- a/src/lib/config/runtimeSettings.ts+++ b/src/lib/config/runtimeSettings.ts@@ -13,7 +13,8 @@ export type RuntimeReloadSection =| "thoughtSignature"| "modelsDevSync"| "corsOrigins"- | "ccBridgeTransforms";+ | "ccBridgeTransforms"+ | "systemTransforms";export interface RuntimeReloadChange {section: RuntimeReloadSection;@@ -33,6 +34,7 @@ interface RuntimeSettingsSnapshot {modelsDevSyncInterval: number | null;corsOrigins: string;ccBridgeTransforms: unknown;+ systemTransforms: unknown;}const DEFAULT_RUNTIME_SETTINGS_SNAPSHOT: RuntimeSettingsSnapshot = {@@ -48,6 +50,7 @@ const DEFAULT_RUNTIME_SETTINGS_SNAPSHOT: RuntimeSettingsSnapshot = {modelsDevSyncInterval: null,corsOrigins: "",ccBridgeTransforms: null,+ systemTransforms: null,};let lastAppliedSnapshot: RuntimeSettingsSnapshot | null = null;@@ -184,6 +187,7 @@ export function buildRuntimeSettingsSnapshot(modelsDevSyncInterval: normalizeNumber(settings.modelsDevSyncInterval),corsOrigins: typeof settings.corsOrigins === "string" ? settings.corsOrigins : "",ccBridgeTransforms: parseStoredJson(settings.ccBridgeTransforms, "ccBridgeTransforms"),+ systemTransforms: parseStoredJson(settings.systemTransforms, "systemTransforms"),};}@@ -261,22 +265,38 @@ async function applyCorsOriginsSection(corsOrigins: string) {setRuntimeAllowedOrigins(corsOrigins);}+/**+ * Legacy alias for the v2 systemTransforms config. The `ccBridgeTransforms`+ * settings field carried the single-provider shape `{ enabled, pipeline }`+ * during Phase 2 (commit e3e962db, pre-release). v2 unifies everything under+ * `systemTransforms.providers[*]`. We migrate the legacy shape into the v2+ * registry on every reload so users with persisted Phase-2 data keep working.+ *+ * `setSystemTransformsConfig` accepts both shapes and routes legacy into+ * `providers[PROVIDER_CC_BRIDGE]`.+ */async function applyCcBridgeTransformsSection(ccBridgeTransforms: unknown) {- const { setCcBridgeTransformsConfig, resetCcBridgeTransformsConfig } =- await import("@omniroute/open-sse/services/ccBridgeTransforms.ts");+ const { setSystemTransformsConfig } =+ await import("@omniroute/open-sse/services/systemTransforms.ts");+ if (ccBridgeTransforms && typeof ccBridgeTransforms === "object") {+ setSystemTransformsConfig(ccBridgeTransforms);+ }+}++async function applySystemTransformsSection(systemTransforms: unknown) {+ const { setSystemTransformsConfig, resetSystemTransformsConfig } =+ await import("@omniroute/open-sse/services/systemTransforms.ts");if (- ccBridgeTransforms === null ||- ccBridgeTransforms === undefined ||- typeof ccBridgeTransforms !== "object"+ systemTransforms === null ||+ systemTransforms === undefined ||+ typeof systemTransforms !== "object") {- resetCcBridgeTransformsConfig();+ resetSystemTransformsConfig();return;}- setCcBridgeTransformsConfig(- ccBridgeTransforms as Parameters<typeof setCcBridgeTransformsConfig>[0]- );+ setSystemTransformsConfig(systemTransforms);}async function applyModelsDevSyncSection(@@ -422,6 +442,11 @@ export async function applyRuntimeSettings(markChanged("ccBridgeTransforms");}+ if (force || hasChanged(currentSnapshot.systemTransforms, previousSnapshot.systemTransforms)) {+ await applySystemTransformsSection(currentSnapshot.systemTransforms);+ markChanged("systemTransforms");+ }+lastAppliedSnapshot = currentSnapshot;return changes;}diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.tsindex 8ed8804eba..d808007b32 100644--- a/src/shared/validation/settingsSchemas.ts+++ b/src/shared/validation/settingsSchemas.ts@@ -120,6 +120,76 @@ export const updateSettingsSchema = z.object({.max(50),}).optional(),+ // System Transforms (issue #2260 v2): generic per-provider DSL covering+ // native `claude`, `anthropic-compatible-cc-*` bridge, and any other+ // provider key. Adds `obfuscate_words` op kind on top of the base set.+ systemTransforms: z+ .object({+ providers: z.record(+ z.string().max(100),+ z.object({+ enabled: z.boolean(),+ pipeline: z+ .array(+ z.discriminatedUnion("kind", [+ z.object({+ kind: z.literal("drop_paragraph_if_contains"),+ needles: z.array(z.string().max(500)).max(50),+ caseSensitive: z.boolean().optional(),+ }),+ z.object({+ kind: z.literal("drop_paragraph_if_starts_with"),+ prefixes: z.array(z.string().max(500)).max(50),+ caseSensitive: z.boolean().optional(),+ }),+ z.object({+ kind: z.literal("replace_text"),+ match: z.string().min(1).max(500),+ replacement: z.string().max(500),+ allOccurrences: z.boolean().optional(),+ }),+ z.object({+ kind: z.literal("replace_regex"),+ pattern: z.string().min(1).max(500),+ flags: z.string().max(10).optional(),+ replacement: z.string().max(500),+ }),+ z.object({+ kind: z.literal("drop_block_if_contains"),+ needles: z.array(z.string().max(500)).max(50),+ }),+ z.object({+ kind: z.literal("prepend_system_block"),+ text: z.string().min(1).max(2000),+ idempotencyKey: z.string().max(100).optional(),+ }),+ z.object({+ kind: z.literal("append_system_block"),+ text: z.string().min(1).max(2000),+ idempotencyKey: z.string().max(100).optional(),+ }),+ z.object({+ kind: z.literal("inject_billing_header"),+ entrypoint: z.string().min(1).max(50),+ versionFormat: z.enum(["ex-machina", "omniroute-daystamp"]),+ cchAlgo: z.enum(["sha256-first-user", "xxhash64-body", "static-zero"]),+ version: z.string().max(50).optional(),+ }),+ z.object({+ kind: z.literal("obfuscate_words"),+ words: z.array(z.string().max(100)).max(200),+ targets: z+ .array(z.enum(["system", "messages", "tools"]))+ .max(3)+ .optional(),+ }),+ ])+ )+ .max(50),+ })+ ),+ })+ .optional(),// Strip provider/model prefix at proxy layer (e.g. "openai/gpt-4" → "gpt-4")stripModelPrefix: z.boolean().optional(),// Cache control preservation modediff --git a/tests/unit/system-transforms.test.ts b/tests/unit/system-transforms.test.tsnew file mode 100644index 0000000000..fbfcfef095--- /dev/null+++ b/tests/unit/system-transforms.test.ts@@ -0,0 +1,374 @@+import test from "node:test";+import assert from "node:assert/strict";++const {+ applySystemTransformPipeline,+ applyTransformPipeline,+ setSystemTransformsConfig,+ resetSystemTransformsConfig,+ getSystemTransformsConfig,+ DEFAULT_SYSTEM_TRANSFORMS_CONFIG,+ DEFAULT_CLAUDE_PIPELINE,+ DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE,+ DEFAULT_OBFUSCATE_WORDS,+ OPENWEBUI_PARAGRAPH_ANCHORS,+ OPENWEBUI_IDENTITY_PREFIXES,+ PROVIDER_CLAUDE,+ PROVIDER_CC_BRIDGE,+} = await import("../../open-sse/services/systemTransforms.ts");++const ZWJ = "\u200d";++// ────────────────────────────────────────────────────────────────────────────+// Defaults+// ────────────────────────────────────────────────────────────────────────────++test("defaults: PROVIDER_CLAUDE and PROVIDER_CC_BRIDGE keys are present", () => {+ assert.equal(PROVIDER_CLAUDE, "claude");+ assert.equal(PROVIDER_CC_BRIDGE, "anthropic-compatible-cc");+ assert.ok(DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers[PROVIDER_CLAUDE]);+ assert.ok(DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers[PROVIDER_CC_BRIDGE]);+});++test("defaults: claude pipeline omits inject_billing_header", () => {+ const kinds = DEFAULT_CLAUDE_PIPELINE.map((op: { kind: string }) => op.kind);+ assert.ok(!kinds.includes("inject_billing_header"));+ // It does include obfuscate_words and paragraph drops.+ assert.ok(kinds.includes("obfuscate_words"));+ assert.ok(kinds.includes("drop_paragraph_if_contains"));+});++test("defaults: CC bridge provider pipeline keeps inject_billing_header", () => {+ const kinds = DEFAULT_CC_BRIDGE_PROVIDER_PIPELINE.map((op: { kind: string }) => op.kind);+ assert.ok(kinds.includes("inject_billing_header"));+ assert.ok(kinds.includes("prepend_system_block"));+ // And layers Open WebUI obfuscation on top.+ assert.ok(kinds.includes("obfuscate_words"));+});++test("defaults: obfuscate_words list includes legacy + OpenWebUI words", () => {+ assert.ok(DEFAULT_OBFUSCATE_WORDS.includes("opencode"));+ assert.ok(DEFAULT_OBFUSCATE_WORDS.includes("cline"));+ assert.ok(DEFAULT_OBFUSCATE_WORDS.includes("openwebui"));+ assert.ok(DEFAULT_OBFUSCATE_WORDS.includes("open-webui"));+});++test("defaults: OpenWebUI anchors include canonical URLs", () => {+ assert.ok(OPENWEBUI_PARAGRAPH_ANCHORS.includes("github.com/open-webui/open-webui"));+ assert.ok(OPENWEBUI_PARAGRAPH_ANCHORS.includes("openwebui.com"));+ assert.ok(OPENWEBUI_IDENTITY_PREFIXES.includes("You are Open WebUI"));+});++// ────────────────────────────────────────────────────────────────────────────+// obfuscate_words op+// ────────────────────────────────────────────────────────────────────────────++test("obfuscate_words inserts ZWJ in system text blocks", () => {+ const body = {+ system: [{ type: "text", text: "Built on opencode framework." }],+ messages: [{ role: "user", content: "hi" }],+ };+ applyTransformPipeline(body, [+ { kind: "obfuscate_words", words: ["opencode"], targets: ["system"] },+ ]);+ const text = (body.system[0] as { text: string }).text;+ assert.ok(text.includes(`o${ZWJ}pencode`));+ assert.ok(!text.includes(" opencode ") || text.includes(`o${ZWJ}pencode`));+});++test("obfuscate_words handles string system field", () => {+ const body = {+ system: "I work with opencode daily.",+ messages: [{ role: "user", content: "hi" }],+ };+ applyTransformPipeline(body, [{ kind: "obfuscate_words", words: ["opencode"] }]);+ assert.ok((body.system as string).includes(`o${ZWJ}pencode`));+});++test("obfuscate_words respects targets — messages only", () => {+ const body = {+ system: [{ type: "text", text: "opencode is here" }],+ messages: [{ role: "user", content: "opencode rocks" }],+ tools: [{ description: "opencode tool" }],+ };+ applyTransformPipeline(body, [+ { kind: "obfuscate_words", words: ["opencode"], targets: ["messages"] },+ ]);+ // System untouched+ assert.equal((body.system[0] as { text: string }).text, "opencode is here");+ // Messages obfuscated+ assert.ok((body.messages[0].content as string).includes(`o${ZWJ}pencode`));+ // Tools untouched+ assert.equal((body.tools[0] as { description: string }).description, "opencode tool");+});++test("obfuscate_words walks tool descriptions (description + function.description)", () => {+ const body = {+ system: [],+ messages: [{ role: "user", content: "hi" }],+ tools: [{ description: "uses opencode" }, { function: { description: "uses open-webui" } }],+ };+ applyTransformPipeline(body, [+ { kind: "obfuscate_words", words: ["opencode", "open-webui"], targets: ["tools"] },+ ]);+ assert.ok((body.tools[0] as { description: string }).description.includes(`o${ZWJ}pencode`));+ assert.ok(+ (body.tools[1] as { function: { description: string } }).function.description.includes(+ `o${ZWJ}pen-webui`+ )+ );+});++test("obfuscate_words is case-insensitive and applies to all targets by default", () => {+ const body = {+ system: [{ type: "text", text: "OpenCode is great" }],+ messages: [{ role: "user", content: "I love OPENCODE" }],+ };+ applyTransformPipeline(body, [{ kind: "obfuscate_words", words: ["opencode"] }]);+ const sys = (body.system[0] as { text: string }).text;+ const msg = body.messages[0].content as string;+ assert.ok(sys.includes(`O${ZWJ}penCode`));+ assert.ok(msg.includes(`O${ZWJ}PENCODE`));+});++test("obfuscate_words with empty list is a no-op", () => {+ const body = {+ system: [{ type: "text", text: "opencode" }],+ messages: [{ role: "user", content: "hi" }],+ };+ applyTransformPipeline(body, [{ kind: "obfuscate_words", words: [] }]);+ assert.equal((body.system[0] as { text: string }).text, "opencode");+});++// ────────────────────────────────────────────────────────────────────────────+// Pipeline ordering: drop paragraph then obfuscate what survives+// ────────────────────────────────────────────────────────────────────────────++test("pipeline ordering: drop_paragraph_if_contains runs before obfuscate_words", () => {+ const body = {+ system: [+ {+ type: "text",+ text: "See github.com/open-webui/open-webui\n\nI use openwebui for chat.\n\nAlso try opencode.",+ },+ ],+ messages: [{ role: "user", content: "hi" }],+ };+ applyTransformPipeline(body, [+ {+ kind: "drop_paragraph_if_contains",+ needles: ["github.com/open-webui/open-webui"],+ },+ { kind: "obfuscate_words", words: ["openwebui", "opencode"], targets: ["system"] },+ ]);+ const out = (body.system[0] as { text: string }).text;+ assert.ok(!out.includes("github.com/open-webui/open-webui"));+ assert.ok(out.includes(`o${ZWJ}penwebui`));+ assert.ok(out.includes(`o${ZWJ}pencode`));+});++// ────────────────────────────────────────────────────────────────────────────+// Per-provider routing+// ────────────────────────────────────────────────────────────────────────────++test("applySystemTransformPipeline: provider not configured → no-op", () => {+ const body = {+ system: [{ type: "text", text: "opencode" }],+ messages: [{ role: "user", content: "hi" }],+ };+ const before = JSON.stringify(body);+ const result = applySystemTransformPipeline("gemini", body, {+ providers: { gemini: { enabled: false, pipeline: [] } },+ });+ assert.equal(result.appliedOpKinds.length, 0);+ assert.equal(JSON.stringify(body), before);+});++test("applySystemTransformPipeline: claude provider runs its default pipeline", () => {+ // Two paragraphs: first contains the OpenWebUI anchor (drop target),+ // second contains a survivable opencode reference (ZWJ target).+ const body = {+ system: [+ {+ type: "text",+ text: "See docs at github.com/open-webui/open-webui\n\nI am opencode helper.",+ },+ ],+ messages: [{ role: "user", content: "hi" }],+ };+ const result = applySystemTransformPipeline(+ PROVIDER_CLAUDE,+ body,+ DEFAULT_SYSTEM_TRANSFORMS_CONFIG+ );+ const blocks = body.system as Array<{ text: string }>;+ assert.ok(blocks.length >= 1);+ const out = blocks[0].text;+ // Open WebUI anchor paragraph dropped+ assert.ok(!out.includes("github.com/open-webui/open-webui"));+ // ZWJ inserted on opencode+ assert.ok(out.includes(`o${ZWJ}pencode`));+ // No billing header injected (native does that)+ assert.ok(!result.appliedOpKinds.includes("inject_billing_header"));+});++test("applySystemTransformPipeline: anthropic-compatible-cc-* falls back to PROVIDER_CC_BRIDGE config", () => {+ const body = {+ system: [{ type: "text", text: "I am OpenCode\n\nThird-party agent" }],+ messages: [{ role: "user", content: "hello world" }],+ };+ const result = applySystemTransformPipeline(+ "anthropic-compatible-cc-claude-opus-4-7",+ body,+ DEFAULT_SYSTEM_TRANSFORMS_CONFIG+ );+ // Full CC bridge pipeline ran → billing header injected at [0]+ assert.ok(result.appliedOpKinds.includes("inject_billing_header"));+ const blocks = body.system as Array<{ text: string }>;+ assert.ok(blocks[0].text.startsWith("x-anthropic-billing-header:"));+});++// ────────────────────────────────────────────────────────────────────────────+// OpenWebUI fixture — the headline bug from issue #2260 comment 4459544580+// ────────────────────────────────────────────────────────────────────────────++test("OpenWebUI fixture: claude provider drops anchor + obfuscates 'openwebui' word", () => {+ const body = {+ system: [+ {+ type: "text",+ text: "You are Open WebUI assistant.\n\nDocumentation at github.com/open-webui/open-webui.\n\nThis agent uses openwebui to render messages.",+ },+ ],+ messages: [{ role: "user", content: "Tell me about open-webui" }],+ };+ applySystemTransformPipeline(PROVIDER_CLAUDE, body, DEFAULT_SYSTEM_TRANSFORMS_CONFIG);+ const sysText = (body.system[0] as { text: string }).text;+ // "You are Open WebUI" identity paragraph dropped+ assert.ok(!sysText.includes("You are Open WebUI assistant"));+ // github.com/open-webui/open-webui anchor paragraph dropped+ assert.ok(!sysText.includes("github.com/open-webui/open-webui"));+ // remaining word "openwebui" ZWJ-obfuscated+ assert.ok(sysText.includes(`o${ZWJ}penwebui`));+ // Messages also obfuscated by default targets+ assert.ok((body.messages[0].content as string).includes(`o${ZWJ}pen-webui`));+});++// ────────────────────────────────────────────────────────────────────────────+// Disabled provider → pass-through+// ────────────────────────────────────────────────────────────────────────────++test("provider with enabled=false is a pass-through (opt-in posture)", () => {+ const body = {+ system: [{ type: "text", text: "opencode here" }],+ messages: [{ role: "user", content: "hi" }],+ };+ const before = JSON.stringify(body);+ const result = applySystemTransformPipeline(PROVIDER_CLAUDE, body, {+ providers: {+ [PROVIDER_CLAUDE]: { enabled: false, pipeline: DEFAULT_CLAUDE_PIPELINE },+ },+ });+ assert.equal(result.appliedOpKinds.length, 0);+ assert.equal(JSON.stringify(body), before);+});++// ────────────────────────────────────────────────────────────────────────────+// Legacy migration shim+// ────────────────────────────────────────────────────────────────────────────++test("setSystemTransformsConfig migrates legacy { enabled, pipeline } into providers[CC_BRIDGE]", () => {+ setSystemTransformsConfig({+ enabled: true,+ pipeline: [+ {+ kind: "replace_text",+ match: "legacy-key-marker",+ replacement: "rewritten",+ allOccurrences: true,+ },+ ],+ });+ const cfg = getSystemTransformsConfig();+ const cc = cfg.providers[PROVIDER_CC_BRIDGE];+ assert.ok(cc);+ assert.equal(cc.enabled, true);+ // The custom pipeline is now under the CC bridge provider+ const hasMarker = cc.pipeline.some(+ (op: { kind: string; match?: string }) =>+ op.kind === "replace_text" && op.match === "legacy-key-marker"+ );+ assert.ok(hasMarker);+ // Other providers still come from defaults (claude pipeline preserved)+ assert.ok(cfg.providers[PROVIDER_CLAUDE]);+ resetSystemTransformsConfig();+});++test("setSystemTransformsConfig accepts per-provider shape and merges defaults for unset providers", () => {+ setSystemTransformsConfig({+ providers: {+ gemini: {+ enabled: true,+ pipeline: [{ kind: "obfuscate_words", words: ["gemini-cli"] }],+ },+ },+ });+ const cfg = getSystemTransformsConfig();+ assert.ok(cfg.providers.gemini);+ assert.equal(cfg.providers.gemini.enabled, true);+ // Defaults still present for unset providers (no regression for claude/cc).+ assert.ok(cfg.providers[PROVIDER_CLAUDE]);+ assert.ok(cfg.providers[PROVIDER_CC_BRIDGE]);+ resetSystemTransformsConfig();+});++test("setSystemTransformsConfig(null) resets to defaults", () => {+ setSystemTransformsConfig({+ providers: { custom: { enabled: true, pipeline: [] } },+ });+ setSystemTransformsConfig(null);+ const cfg = getSystemTransformsConfig();+ // Defaults restored — `custom` key dropped.+ assert.ok(!cfg.providers.custom);+ assert.ok(cfg.providers[PROVIDER_CLAUDE]);+ assert.ok(cfg.providers[PROVIDER_CC_BRIDGE]);+ resetSystemTransformsConfig();+});++// ────────────────────────────────────────────────────────────────────────────+// Idempotency+// ────────────────────────────────────────────────────────────────────────────++test("idempotency: obfuscate_words running twice does not double-ZWJ", () => {+ const body = {+ system: [{ type: "text", text: "opencode here" }],+ messages: [{ role: "user", content: "hi" }],+ };+ applyTransformPipeline(body, [+ { kind: "obfuscate_words", words: ["opencode"], targets: ["system"] },+ ]);+ const once = (body.system[0] as { text: string }).text;+ applyTransformPipeline(body, [+ { kind: "obfuscate_words", words: ["opencode"], targets: ["system"] },+ ]);+ const twice = (body.system[0] as { text: string }).text;+ // Second pass cannot find "opencode" — the ZWJ broke it — so no further change.+ assert.equal(once, twice);+});++test("idempotency: full claude pipeline running twice does not duplicate blocks", () => {+ const body = {+ system: [+ {+ type: "text",+ text: "You are Open WebUI helper.\n\nopenwebui is the platform.",+ },+ ],+ messages: [{ role: "user", content: "hi" }],+ };+ applySystemTransformPipeline(PROVIDER_CLAUDE, body, DEFAULT_SYSTEM_TRANSFORMS_CONFIG);+ const onceLen = (body.system as Array<unknown>).length;+ applySystemTransformPipeline(PROVIDER_CLAUDE, body, DEFAULT_SYSTEM_TRANSFORMS_CONFIG);+ const twiceLen = (body.system as Array<unknown>).length;+ assert.equal(onceLen, twiceLen);+});