Skip to content

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

feat(cc-bridge): config-driven per-provider system-block transform DSL (#2286, closes #2260)

diegosouzapw5221a81a7575
diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.ts
index e9750e2dc5..3d33b7f900 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,
@@ -619,6 +620,15 @@ export class BaseExecutor {
remapToolNamesInRequest(tb);
obfuscateInBody(tb);
+ // NOTE (issue #2260): This is the native `claude` provider OAuth path.
+ // It is intentionally NOT routed through applyCcBridgeTransformPipeline.
+ // The native OAuth path already prepends its own billing line + sentinel
+ // (see lines ~744-773 below, dayStamp-based, cc_entrypoint=cli, cch=00000
+ // placeholder, signed at body level). The CC bridge transforms DSL is
+ // wired into buildAndSignClaudeCodeRequest (claudeCodeCompatible.ts step 5b)
+ // which is the anthropic-compatible-cc-* relay path — a different,
+ // separately classified surface. Do not double-prepend here.
+
// Real CLI never sets cache_control on tools.
if (Array.isArray(tb.tools)) {
for (const t of tb.tools as Array<Record<string, unknown>>) {
@@ -772,6 +782,22 @@ 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.
+ {
+ const transformResult = applySystemTransformPipeline(PROVIDER_CLAUDE, tb);
+ if (transformResult.appliedOpKinds.length > 0) {
+ console.log(
+ `[SystemTransforms] claude-native: ${transformResult.appliedOpKinds.join(", ")}`
+ );
+ }
+ }
+
if (!tb.metadata || typeof tb.metadata !== "object") tb.metadata = {};
(tb.metadata as Record<string, unknown>).user_id = buildUserIdJson({
deviceId,
@@ -830,6 +856,11 @@ export class BaseExecutor {
// CLI fingerprint ordering — always-on for native Claude OAuth, opt-in
// for other providers. Header + body field order is itself a fingerprint.
let finalHeaders = headers;
+ // Strip internal sentinel fields set by remapToolNamesInRequest before
+ // serializing — Anthropic rejects unknown top-level fields (issue #2260).
+ delete (transformedBody as Record<string, unknown>)[
+ "_claudeCodeRequiresLowercaseToolNames"
+ ];
let bodyString = JSON.stringify(transformedBody);
const shouldFingerprint =
diff --git a/open-sse/services/ccBridgeTransforms.ts b/open-sse/services/ccBridgeTransforms.ts
new file mode 100644
index 0000000000..065b613a33
--- /dev/null
+++ b/open-sse/services/ccBridgeTransforms.ts
@@ -0,0 +1,581 @@
+/**
+ * CC Bridge Transforms — config-driven request body normalization for the
+ * Claude Code Compatible (`anthropic-compatible-cc-*`) bridge.
+ *
+ * Goal: ensure the final request body OmniRoute sends to Anthropic's
+ * `/v1/messages?beta=true` endpoint has classifier-correct structure
+ * regardless of which client (OpenCode, Cline, Cursor, Continue, raw API
+ * consumer) supplied the prompt.
+ *
+ * Approach: an ordered pipeline of declarative `TransformOp` entries that
+ * mutate the request body in place. Each op is idempotent; the executor is
+ * pure (no I/O); new defenses can be added through Settings UI by appending
+ * a new op — no new TypeScript needed.
+ *
+ * Reference implementation: ex-machina/opencode-anthropic-auth `transform.ts`
+ * and `cch.ts`. Ported with the same defaults (paragraph anchors, identity
+ * prefixes, text replacements, billing header algorithm) but generalised
+ * behind a discriminated-union DSL so future fingerprints are configurable.
+ *
+ * Related: OmniRoute issue #2260.
+ */
+import { createHash } from "node:crypto";
+
+// ────────────────────────────────────────────────────────────────────────────
+// DSL types
+// ────────────────────────────────────────────────────────────────────────────
+
+export type TransformOp =
+ | DropParagraphIfContainsOp
+ | DropParagraphIfStartsWithOp
+ | ReplaceTextOp
+ | ReplaceRegexOp
+ | DropBlockIfContainsOp
+ | PrependSystemBlockOp
+ | AppendSystemBlockOp
+ | InjectBillingHeaderOp;
+
+export interface DropParagraphIfContainsOp {
+ kind: "drop_paragraph_if_contains";
+ needles: string[];
+ caseSensitive?: boolean;
+}
+
+export interface DropParagraphIfStartsWithOp {
+ kind: "drop_paragraph_if_starts_with";
+ prefixes: string[];
+ caseSensitive?: boolean;
+}
+
+export interface ReplaceTextOp {
+ kind: "replace_text";
+ match: string;
+ replacement: string;
+ allOccurrences?: boolean;
+}
+
+export interface ReplaceRegexOp {
+ kind: "replace_regex";
+ pattern: string;
+ flags?: string;
+ replacement: string;
+}
+
+export interface DropBlockIfContainsOp {
+ kind: "drop_block_if_contains";
+ needles: string[];
+}
+
+export interface PrependSystemBlockOp {
+ kind: "prepend_system_block";
+ text: string;
+ /** Skip if any earlier block already starts with this prefix. */
+ idempotencyKey?: string;
+}
+
+export interface AppendSystemBlockOp {
+ kind: "append_system_block";
+ text: string;
+ idempotencyKey?: string;
+}
+
+export interface InjectBillingHeaderOp {
+ kind: "inject_billing_header";
+ /** Anthropic billing entrypoint label (e.g. `sdk-cli`, `cli`). */
+ entrypoint: string;
+ /**
+ * Version suffix algorithm:
+ * - ex-machina: sha256(SALT + chars-at-positions + version).slice(0,3)
+ * - omniroute-daystamp: sha256(YYYY-MM-DD + version).slice(0,3)
+ */
+ versionFormat: "ex-machina" | "omniroute-daystamp";
+ /**
+ * CCH attestation algorithm:
+ * - sha256-first-user: sha256(firstUserMessageText).slice(0,5) (ex-machina)
+ * - xxhash64-body: defer to body-level signRequestBody; emit "00000" here
+ * - static-zero: emit "00000" (relay endpoints don't validate)
+ */
+ cchAlgo: "sha256-first-user" | "xxhash64-body" | "static-zero";
+ /** Override the embedded `cc_version=` value. Defaults to `2.1.137`. */
+ version?: string;
+}
+
+export interface CcBridgeTransformsConfig {
+ enabled: boolean;
+ pipeline: TransformOp[];
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Ported constants (ex-machina/constants.ts)
+// ────────────────────────────────────────────────────────────────────────────
+
+/** Stable salt used by ex-machina/cch.ts for the version-suffix hash. */
+export const CCH_SALT = "59cf53e54c78";
+/** Character positions sampled from the first user message text. */
+export const CCH_POSITIONS = [4, 7, 20] as const;
+/** Default `cc_version=` value embedded in the billing header. */
+export const DEFAULT_CLAUDE_CODE_VERSION = "2.1.137";
+/** Identity sentinel prepended for Claude Agent SDK callers. */
+export const CLAUDE_AGENT_SDK_IDENTITY =
+ "You are a Claude agent, built on Anthropic's Claude Agent SDK.";
+/** Paragraph anchors from ex-machina (URLs identifying third-party agents). */
+export const DEFAULT_PARAGRAPH_REMOVAL_ANCHORS = [
+ "github.com/anomalyco/opencode",
+ "opencode.ai/docs",
+ "github.com/cline/cline",
+ "github.com/getcursor/cursor",
+ "continue.dev",
+];
+/** Identity paragraph prefixes that signal a third-party agent. */
+export const DEFAULT_IDENTITY_PREFIXES = ["You are OpenCode"];
+/** Text replacements (last entry is the v1.7.5 phrase-shape filter fix). */
+export const DEFAULT_TEXT_REPLACEMENTS: Array<{ match: string; replacement: string }> = [
+ { match: "if OpenCode honestly", replacement: "if the assistant honestly" },
+ {
+ match: "Here is some useful information about the environment you are running in:",
+ replacement: "Environment context you are running in:",
+ },
+];
+
+/**
+ * Default pipeline shipped with the PR — matches the T4-200 fixture layout
+ * proven against the live OmniRoute deployment (call log
+ * f0c2fedb-b27a-4f1d-9ee6-0c88646a6d42).
+ *
+ * Layout after pipeline (system blocks):
+ * [0] x-anthropic-billing-header: cc_version=…; cc_entrypoint=sdk-cli; cch=…
+ * [1] You are a Claude agent, built on Anthropic's Claude Agent SDK.
+ * [2..] sanitized caller-supplied system blocks
+ */
+export const DEFAULT_CC_BRIDGE_PIPELINE: TransformOp[] = [
+ // Sanitize caller-supplied system blocks first so dropped paragraphs do not
+ // accidentally contain a stale billing header from a previous pass.
+ {
+ kind: "drop_paragraph_if_contains",
+ needles: [...DEFAULT_PARAGRAPH_REMOVAL_ANCHORS],
+ },
+ {
+ kind: "drop_paragraph_if_starts_with",
+ prefixes: [...DEFAULT_IDENTITY_PREFIXES],
+ },
+ ...DEFAULT_TEXT_REPLACEMENTS.map<ReplaceTextOp>((r) => ({
+ kind: "replace_text",
+ match: r.match,
+ replacement: r.replacement,
+ allOccurrences: true,
+ })),
+ // Then prepend the SDK identity (becomes block[1] after billing prepend).
+ {
+ kind: "prepend_system_block",
+ text: CLAUDE_AGENT_SDK_IDENTITY,
+ idempotencyKey: "claude-agent-sdk-identity",
+ },
+ // Billing header always lands at block[0] — matches T4-200 fixture layout.
+ {
+ kind: "inject_billing_header",
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ },
+];
+
+export const DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG: CcBridgeTransformsConfig = {
+ enabled: true,
+ pipeline: DEFAULT_CC_BRIDGE_PIPELINE,
+};
+
+// ────────────────────────────────────────────────────────────────────────────
+// Billing header value
+// ────────────────────────────────────────────────────────────────────────────
+
+interface SystemBlock {
+ type: string;
+ text?: string;
+ [key: string]: unknown;
+}
+
+interface MessageContentBlock {
+ type?: string;
+ text?: string;
+ [key: string]: unknown;
+}
+
+interface Message {
+ role?: string;
+ content?: string | MessageContentBlock[];
+ [key: string]: unknown;
+}
+
+/**
+ * Pull the textual content of the first user message in the request.
+ * Returns "" when no user message has text content.
+ */
+export function extractFirstUserMessageText(messages: Message[]): string {
+ if (!Array.isArray(messages)) return "";
+
+ for (const msg of messages) {
+ if (msg?.role !== "user") continue;
+ if (typeof msg.content === "string") return msg.content;
+ if (Array.isArray(msg.content)) {
+ for (const block of msg.content) {
+ if (block?.type === "text" && typeof block.text === "string") {
+ return block.text;
+ }
+ }
+ }
+ }
+ return "";
+}
+
+function sha256Hex(input: string): string {
+ return createHash("sha256").update(input, "utf8").digest("hex");
+}
+
+function pickCharsAtPositions(text: string, positions: readonly number[]): string {
+ return positions.map((p) => (typeof text[p] === "string" ? text[p] : "\0")).join("");
+}
+
+/**
+ * Compute the `cc_version` suffix per the ex-machina algorithm.
+ *
+ * `sha256(CCH_SALT + chars-at-CCH_POSITIONS(firstUserMessage) + version).slice(0, 3)`
+ */
+export function computeExMachinaVersionSuffix(firstUserText: string, version: string): string {
+ const picks = pickCharsAtPositions(firstUserText, CCH_POSITIONS);
+ return sha256Hex(`${CCH_SALT}${picks}${version}`).slice(0, 3);
+}
+
+/**
+ * Compute the `cc_version` suffix per the OmniRoute native-OAuth algorithm:
+ * sha256(YYYY-MM-DD + version).slice(0,3). Stable per UTC day.
+ */
+export function computeDaystampVersionSuffix(version: string, now: Date = new Date()): string {
+ const dayStamp = now.toISOString().slice(0, 10);
+ return sha256Hex(`${dayStamp}${version}`).slice(0, 3);
+}
+
+/**
+ * Compute the `cch=` attestation value per ex-machina algorithm:
+ * sha256(firstUserMessage).slice(0,5).
+ */
+export function computeCchSha256FirstUser(firstUserText: string): string {
+ return sha256Hex(firstUserText).slice(0, 5);
+}
+
+interface BuildBillingHeaderOptions {
+ entrypoint: string;
+ versionFormat: "ex-machina" | "omniroute-daystamp";
+ cchAlgo: "sha256-first-user" | "xxhash64-body" | "static-zero";
+ version?: string;
+ now?: Date;
+}
+
+/**
+ * Build the `x-anthropic-billing-header: …` string injected as system block[0].
+ *
+ * `xxhash64-body` and `static-zero` both emit `cch=00000` here because the
+ * actual body-level CCH attestation is computed later by
+ * `claudeCodeCCH.signRequestBody()` and replaces a 00000 placeholder in the
+ * serialized JSON. ex-machina's `sha256-first-user` value lives in the
+ * header itself.
+ */
+export function buildBillingHeaderValue(
+ messages: Message[],
+ options: BuildBillingHeaderOptions
+): string {
+ const version = options.version || DEFAULT_CLAUDE_CODE_VERSION;
+ const firstUserText = extractFirstUserMessageText(messages);
+
+ const suffix =
+ options.versionFormat === "omniroute-daystamp"
+ ? computeDaystampVersionSuffix(version, options.now)
+ : computeExMachinaVersionSuffix(firstUserText, version);
+
+ let cch: string;
+ switch (options.cchAlgo) {
+ case "sha256-first-user":
+ cch = computeCchSha256FirstUser(firstUserText);
+ break;
+ case "xxhash64-body":
+ case "static-zero":
+ default:
+ cch = "00000";
+ break;
+ }
+
+ return `x-anthropic-billing-header: cc_version=${version}.${suffix}; cc_entrypoint=${options.entrypoint}; cch=${cch};`;
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Body shape helpers
+// ────────────────────────────────────────────────────────────────────────────
+
+interface RequestBody {
+ system?: string | SystemBlock[];
+ messages?: Message[];
+ [key: string]: unknown;
+}
+
+function normalizeSystemToBlocks(system: unknown): SystemBlock[] {
+ if (system === null || system === undefined) return [];
+ if (typeof system === "string") {
+ return system.length > 0 ? [{ type: "text", text: system }] : [];
+ }
+ if (Array.isArray(system)) {
+ return system
+ .filter((b): b is SystemBlock => !!b && typeof b === "object")
+ .map((b) => ({ ...b }));
+ }
+ if (typeof system === "object") {
+ const block = system as SystemBlock;
+ return block && typeof block.text === "string" ? [{ ...block }] : [];
+ }
+ return [];
+}
+
+function isTextBlock(block: SystemBlock): block is SystemBlock & { text: string } {
+ return block.type === "text" && typeof block.text === "string";
+}
+
+function containsString(haystack: string, needle: string, caseSensitive: boolean): boolean {
+ if (caseSensitive) return haystack.includes(needle);
+ return haystack.toLowerCase().includes(needle.toLowerCase());
+}
+
+function startsWithString(haystack: string, prefix: string, caseSensitive: boolean): boolean {
+ if (caseSensitive) return haystack.startsWith(prefix);
+ return haystack.toLowerCase().startsWith(prefix.toLowerCase());
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Op executors
+// ────────────────────────────────────────────────────────────────────────────
+
+function applyDropParagraphIfContains(
+ blocks: SystemBlock[],
+ op: DropParagraphIfContainsOp
+): SystemBlock[] {
+ const caseSensitive = op.caseSensitive !== false;
+ const needles = op.needles || [];
+ if (needles.length === 0) return blocks;
+
+ return blocks.map((block) => {
+ if (!isTextBlock(block)) return block;
+ const paragraphs = block.text.split(/\n\n+/);
+ const filtered = paragraphs.filter(
+ (p) => !needles.some((n) => containsString(p, n, caseSensitive))
+ );
+ return { ...block, text: filtered.join("\n\n") };
+ });
+}
+
+function applyDropParagraphIfStartsWith(
+ blocks: SystemBlock[],
+ op: DropParagraphIfStartsWithOp
+): SystemBlock[] {
+ const caseSensitive = op.caseSensitive !== false;
+ const prefixes = op.prefixes || [];
+ if (prefixes.length === 0) return blocks;
+
+ return blocks.map((block) => {
+ if (!isTextBlock(block)) return block;
+ const paragraphs = block.text.split(/\n\n+/);
+ const filtered = paragraphs.filter(
+ (p) => !prefixes.some((prefix) => startsWithString(p.trimStart(), prefix, caseSensitive))
+ );
+ return { ...block, text: filtered.join("\n\n") };
+ });
+}
+
+function applyReplaceText(blocks: SystemBlock[], op: ReplaceTextOp): SystemBlock[] {
+ if (!op.match) return blocks;
+ return blocks.map((block) => {
+ if (!isTextBlock(block)) return block;
+ if (!block.text.includes(op.match)) return block;
+ let next = block.text;
+ if (op.allOccurrences) {
+ next = next.split(op.match).join(op.replacement);
+ } else {
+ next = next.replace(op.match, op.replacement);
+ }
+ return { ...block, text: next };
+ });
+}
+
+function applyReplaceRegex(blocks: SystemBlock[], op: ReplaceRegexOp): SystemBlock[] {
+ if (!op.pattern) return blocks;
+ let regex: RegExp;
+ try {
+ regex = new RegExp(op.pattern, op.flags ?? "u");
+ } catch {
+ return blocks;
+ }
+ return blocks.map((block) => {
+ if (!isTextBlock(block)) return block;
+ return { ...block, text: block.text.replace(regex, op.replacement) };
+ });
+}
+
+function applyDropBlockIfContains(blocks: SystemBlock[], op: DropBlockIfContainsOp): SystemBlock[] {
+ const needles = op.needles || [];
+ if (needles.length === 0) return blocks;
+ return blocks.filter((block) => {
+ if (!isTextBlock(block)) return true;
+ return !needles.some((n) => block.text.includes(n));
+ });
+}
+
+function applyPrependSystemBlock(blocks: SystemBlock[], op: PrependSystemBlockOp): SystemBlock[] {
+ if (!op.text) return blocks;
+ // Idempotency: skip if any text block already starts with idempotencyKey (when
+ // set) or with op.text itself (default). Scans ALL blocks, not just the first.
+ const prefix = op.idempotencyKey ?? op.text;
+ const alreadyPresent = blocks.some((b) => isTextBlock(b) && b.text.startsWith(prefix));
+ if (alreadyPresent) return blocks;
+ return [{ type: "text", text: op.text }, ...blocks];
+}
+
+function applyAppendSystemBlock(blocks: SystemBlock[], op: AppendSystemBlockOp): SystemBlock[] {
+ if (!op.text) return blocks;
+ // Idempotency: skip if any text block already starts with idempotencyKey (when
+ // set) or is an exact match of op.text (default). Scans ALL blocks.
+ const prefix = op.idempotencyKey;
+ const alreadyPresent = prefix
+ ? blocks.some((b) => isTextBlock(b) && b.text.startsWith(prefix))
+ : blocks.some((b) => isTextBlock(b) && b.text === op.text);
+ if (alreadyPresent) return blocks;
+ return [...blocks, { type: "text", text: op.text }];
+}
+
+function applyInjectBillingHeader(
+ body: RequestBody,
+ blocks: SystemBlock[],
+ op: InjectBillingHeaderOp
+): SystemBlock[] {
+ // No user message → no billing header (ex-machina parity, transform.ts:340).
+ const messages = Array.isArray(body.messages) ? body.messages : [];
+ const hasUser = messages.some((m) => m?.role === "user");
+ if (!hasUser) return blocks;
+
+ const headerValue = buildBillingHeaderValue(messages, {
+ entrypoint: op.entrypoint,
+ versionFormat: op.versionFormat,
+ cchAlgo: op.cchAlgo,
+ version: op.version,
+ });
+
+ // Idempotency: replace any existing billing header block (ex-machina + native
+ // OAuth path both rebuild on retry; see executors/base.ts issue #1712).
+ const headerPrefix = "x-anthropic-billing-header:";
+ const filtered = blocks.filter((b) => !(isTextBlock(b) && b.text.startsWith(headerPrefix)));
+ return [{ type: "text", text: headerValue }, ...filtered];
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Pipeline executor
+// ────────────────────────────────────────────────────────────────────────────
+
+export interface ApplyPipelineResult {
+ body: RequestBody;
+ appliedOpKinds: string[];
+}
+
+/**
+ * Run the configured transform pipeline against a request body.
+ *
+ * The body is mutated in place (its `system` field is replaced); returned for
+ * chaining. `appliedOpKinds` lists the ops that ran (omitting no-ops when
+ * config is disabled). When `config.enabled === false`, the body is returned
+ * unchanged and `appliedOpKinds` is empty.
+ */
+export function applyCcBridgeTransformPipeline(
+ body: RequestBody,
+ config: CcBridgeTransformsConfig = getCcBridgeTransformsConfig()
+): ApplyPipelineResult {
+ if (!body || typeof body !== "object") {
+ return { body, appliedOpKinds: [] };
+ }
+ if (!config.enabled || !Array.isArray(config.pipeline) || config.pipeline.length === 0) {
+ return { body, appliedOpKinds: [] };
+ }
+
+ let blocks = normalizeSystemToBlocks(body.system);
+ const appliedOpKinds: string[] = [];
+
+ for (const op of config.pipeline) {
+ switch (op.kind) {
+ case "drop_paragraph_if_contains":
+ blocks = applyDropParagraphIfContains(blocks, op);
+ break;
+ case "drop_paragraph_if_starts_with":
+ blocks = applyDropParagraphIfStartsWith(blocks, op);
+ break;
+ case "replace_text":
+ blocks = applyReplaceText(blocks, op);
+ break;
+ case "replace_regex":
+ blocks = applyReplaceRegex(blocks, op);
+ break;
+ case "drop_block_if_contains":
+ blocks = applyDropBlockIfContains(blocks, op);
+ break;
+ case "prepend_system_block":
+ blocks = applyPrependSystemBlock(blocks, op);
+ break;
+ case "append_system_block":
+ blocks = applyAppendSystemBlock(blocks, op);
+ break;
+ case "inject_billing_header":
+ blocks = applyInjectBillingHeader(body, blocks, op);
+ break;
+ default: {
+ // Unknown op kind — skip silently to keep forward compatibility.
+ continue;
+ }
+ }
+ appliedOpKinds.push(op.kind);
+ }
+
+ // Drop empty text blocks left behind by paragraph removal (matches
+ // ex-machina sanitizeSystemText trim semantics).
+ blocks = blocks.filter((b) => !isTextBlock(b) || b.text.length > 0);
+
+ body.system = blocks;
+ return { body, appliedOpKinds };
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Runtime singleton (mirrors cliFingerprints `_cliCompatProviders` pattern).
+// ────────────────────────────────────────────────────────────────────────────
+
+let _runtimeConfig: CcBridgeTransformsConfig = DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG;
+
+/**
+ * Replace the active CC bridge transforms config. Called from
+ * `runtimeSettings.applyCcBridgeTransformsSection()` when the Settings UI
+ * saves a new pipeline.
+ */
+export function setCcBridgeTransformsConfig(config: CcBridgeTransformsConfig | null): void {
+ if (!config) {
+ _runtimeConfig = DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG;
+ return;
+ }
+ _runtimeConfig = {
+ enabled: config.enabled !== false,
+ pipeline: Array.isArray(config.pipeline) ? config.pipeline : DEFAULT_CC_BRIDGE_PIPELINE,
+ };
+}
+
+/**
+ * Read the currently active config (defaults to DEFAULT_CC_BRIDGE_PIPELINE).
+ */
+export function getCcBridgeTransformsConfig(): CcBridgeTransformsConfig {
+ return _runtimeConfig;
+}
+
+/**
+ * Reset to defaults — exposed for tests and the Settings UI "Reset" button.
+ */
+export function resetCcBridgeTransformsConfig(): void {
+ _runtimeConfig = DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG;
+}
diff --git a/open-sse/services/claudeCodeCompatible.ts b/open-sse/services/claudeCodeCompatible.ts
index c8439ef118..2b67bc7092 100644
--- a/open-sse/services/claudeCodeCompatible.ts
+++ b/open-sse/services/claudeCodeCompatible.ts
@@ -12,6 +12,7 @@ import {
enforceCacheControlLimit,
} from "./claudeCodeConstraints.ts";
import { obfuscateInBody } from "./claudeCodeObfuscation.ts";
+import { applySystemTransformPipeline, PROVIDER_CC_BRIDGE } from "./systemTransforms.ts";
/**
* `anthropic-compatible-cc-*` targets Anthropic relay gateways that only accept
@@ -332,12 +333,29 @@ export async function buildAndSignClaudeCodeRequest(
// Step 5: Cache control
enforceCacheControlLimit(body);
+ // 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.
+ {
+ const transformResult = applySystemTransformPipeline(
+ PROVIDER_CC_BRIDGE,
+ body as Parameters<typeof applySystemTransformPipeline>[1]
+ );
+ if (transformResult.appliedOpKinds.length > 0) {
+ console.log(`[SystemTransforms] cc-bridge: ${transformResult.appliedOpKinds.join(", ")}`);
+ }
+ }
+
// Step 6: Obfuscation (optional, per-provider setting)
if (enableObfuscation) {
obfuscateInBody(body);
}
- // Step 7: Serialize with CCH placeholder
+ // Step 7: Serialize with CCH placeholder (strip internal sentinel fields)
+ delete (body as Record<string, unknown>)["_claudeCodeRequiresLowercaseToolNames"];
const serialized = JSON.stringify(body);
// Step 8: Sign with xxHash64
@@ -362,6 +380,40 @@ 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,
+ setCcBridgeTransformsConfig,
+ getCcBridgeTransformsConfig,
+ resetCcBridgeTransformsConfig,
+ DEFAULT_CC_BRIDGE_PIPELINE,
+ DEFAULT_PARAGRAPH_REMOVAL_ANCHORS,
+ DEFAULT_IDENTITY_PREFIXES,
+ DEFAULT_TEXT_REPLACEMENTS,
+ CLAUDE_AGENT_SDK_IDENTITY,
+} from "./ccBridgeTransforms.ts";
+export type { TransformOp, CcBridgeTransformsConfig } from "./ccBridgeTransforms.ts";
export function resolveClaudeCodeCompatibleEffort(
sourceBody?: Record<string, unknown> | null,
diff --git a/open-sse/services/systemTransforms.ts b/open-sse/services/systemTransforms.ts
new file mode 100644
index 0000000000..ebdaaae0d3
--- /dev/null
+++ b/open-sse/services/systemTransforms.ts
@@ -0,0 +1,461 @@
+/**
+ * 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 {
+ 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: false,
+ 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 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);
+ }
+ }
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// 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 };
+ // Local `RequestBody` interface is intentionally looser than the strict one
+ // exported by ccBridgeTransforms — system transforms accept any shape.
+ const result = applyCcBridgeTransformPipeline(
+ body as Parameters<typeof applyCcBridgeTransformPipeline>[0],
+ 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.tsx
index 82f5110939..c80b875ed6 100644
--- a/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { Button, Card } from "@/shared/components";
+import { Button, Card, Collapsible, Input, Select, Toggle } from "@/shared/components";
import { useTranslations } from "next-intl";
import FallbackChainsEditor from "./FallbackChainsEditor";
import {
@@ -9,6 +9,599 @@ import {
CLI_COMPAT_TOGGLE_IDS,
normalizeCliCompatProviderId,
} from "@/shared/constants/cliCompatProviders";
+import { AI_PROVIDERS } from "@/shared/constants/providers";
+
+// Provider keys (mirror of open-sse/services/systemTransforms.ts).
+const PROVIDER_CLAUDE = "claude";
+const PROVIDER_CC_BRIDGE = "anthropic-compatible-cc";
+const BUILTIN_PROVIDERS = new Set([PROVIDER_CLAUDE, PROVIDER_CC_BRIDGE]);
+
+// Canonical provider catalog for the "Add provider" dropdown. Pulled from the
+// shared AI_PROVIDERS registry so the UI stays in sync with backend provider
+// definitions. We add the CC bridge synthetic ID (no AI_PROVIDERS entry — it's
+// a relay surface, not an upstream provider). Sorted by display name.
+type ProviderCatalogEntry = { id: string; name: string };
+const PROVIDER_CATALOG: ProviderCatalogEntry[] = (() => {
+ const entries: ProviderCatalogEntry[] = Object.values(AI_PROVIDERS).map((p) => ({
+ id: p.id,
+ name: p.name ?? p.id,
+ }));
+ entries.push({ id: PROVIDER_CC_BRIDGE, name: "Anthropic-compatible CC bridge" });
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ return entries;
+})();
+
+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 remains the source of truth — UI just lets the user inspect, edit, and reset.
+const DEFAULT_SYSTEM_TRANSFORMS_CLIENT = {
+ providers: {
+ [PROVIDER_CLAUDE]: {
+ enabled: false,
+ 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",
+ },
+ ],
+ },
+ },
+} as const;
+
+const PROVIDER_TILE_DISPLAY: Record<
+ string,
+ { name: string; description: string; icon: string; tone: string }
+> = {
+ [PROVIDER_CLAUDE]: {
+ name: "Claude (OAuth)",
+ description: "Native Claude provider with OAuth-issued tokens.",
+ icon: "anthropic",
+ tone: "indigo",
+ },
+ [PROVIDER_CC_BRIDGE]: {
+ name: "Claude-Code Bridge",
+ description: "Relay endpoints using API keys (anthropic-compatible-cc-*).",
+ icon: "hub",
+ tone: "purple",
+ },
+};
+
+type TransformOpKind =
+ | "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";
+
+const OP_KIND_LABELS: Record<TransformOpKind, string> = {
+ drop_paragraph_if_contains: "Drop paragraph (contains)",
+ drop_paragraph_if_starts_with: "Drop paragraph (starts with)",
+ replace_text: "Replace text",
+ replace_regex: "Replace regex",
+ drop_block_if_contains: "Drop block (contains)",
+ prepend_system_block: "Prepend system block",
+ append_system_block: "Append system block",
+ inject_billing_header: "Inject billing header",
+ obfuscate_words: "Obfuscate words (ZWJ)",
+};
+
+// Human-readable description shown above each op's editor. Explains in one
+// sentence what the op DOES (transformation effect) and one sentence WHEN
+// to use it (the typical fingerprint-sanitization use-case).
+const OP_KIND_DESCRIPTIONS: Record<TransformOpKind, string> = {
+ drop_paragraph_if_contains:
+ "Removes any paragraph (text block split on blank lines) inside the system prompt whose text contains ANY of the listed substrings. Use to strip third-party client fingerprints like 'github.com/anomalyco/opencode' or 'docs.openwebui.com' that Anthropic's classifier flags.",
+ drop_paragraph_if_starts_with:
+ "Removes any paragraph that STARTS WITH one of the listed prefixes. Use for identity lines like 'You are OpenCode' or 'You are Open WebUI' that announce the calling client.",
+ replace_text:
+ "Replaces a literal substring with another literal substring. Use for known trigger phrases — e.g. rewrite 'Here is some useful information about the environment you are running in:' to 'Environment context you are running in:' (an empirically-validated trigger phrase).",
+ replace_regex:
+ "Replaces text matching a regular expression. Use when you need patterns (character classes, optional whitespace, anchors) instead of literal substrings. A malformed pattern is caught at runtime when the op runs.",
+ drop_block_if_contains:
+ "Removes ENTIRE system blocks (not just paragraphs) whose text contains any of the listed substrings. Use when a whole block is fingerprint-bearing and you want it gone — e.g. an injected MCP-server description.",
+ prepend_system_block:
+ "Inserts a new text block at the FRONT of the system array. Use to add the SDK identity 'You are a Claude agent, built on Anthropic's Claude Agent SDK.' that Anthropic's classifier expects.",
+ append_system_block:
+ "Inserts a new text block at the END of the system array. Use for cosmetic additions that don't need to be at position [0].",
+ inject_billing_header:
+ "Prepends the special 'x-anthropic-billing-header: cc_version=...; cc_entrypoint=...; cch=...;' text block that Anthropic's classifier validates. Required for CC bridge relay endpoints; for the native claude provider OmniRoute already injects its own billing line so this op is usually redundant there.",
+ obfuscate_words:
+ "Inserts a Zero-Width-Joiner character after the first letter of each listed word, so 'opencode' becomes 'o\u200dpencode'. Reads identical to humans but bypasses classifier word matches. Targets system blocks, user/assistant messages, and tool descriptions.",
+};
+
+// Per-field hints rendered under each Input/Select/Toggle inside the
+// editor. Short, plain-English. Keep under ~120 chars each.
+const FIELD_HINTS = {
+ needles:
+ "List of substrings. A paragraph matches if it contains ANY one of them. Add one per line via 'Add entry'.",
+ prefixes:
+ "List of strings. A paragraph matches if it starts with any one of them (leading whitespace is trimmed before matching).",
+ caseSensitive:
+ "When ON, 'OpenCode' and 'opencode' are different strings. When OFF (default), the comparison ignores case.",
+ matchLiteral:
+ "Exact literal substring to find. No regex syntax — special chars like . * ? are treated as themselves.",
+ replacementText:
+ "Replacement string. Leave blank to delete the match. The output preserves surrounding text.",
+ allOccurrences:
+ "When ON (default), every instance is replaced. When OFF, only the first match is replaced.",
+ pattern:
+ "JavaScript regex source. Don't wrap in slashes — just 'foo(.*)bar'. Server rejects patterns that fail to compile.",
+ regexFlags:
+ "JavaScript regex flags (g = all matches, i = case-insensitive, s = dot matches newline, m = multiline). Default 'g'.",
+ blockText:
+ "Full text of the new system block. Use a literal string; the system block stores text only.",
+ idempotencyKey:
+ "Optional. If set, the op skips when a block whose text starts with this key is already present. Prevents double-prepend on retries.",
+ billingEntrypoint:
+ "Value injected as 'cc_entrypoint='. Anthropic accepts 'sdk-cli' (Agent SDK), 'cli' (Claude Code CLI), or other documented values.",
+ billingVersionFormat:
+ "How the 3-char build hash after cc_version= is computed. 'ex-machina' = sha256 of CCH_SALT+chars-from-first-user-msg+version (per-message). 'omniroute-daystamp' = sha256 of YYYY-MM-DD+version (stable per-day).",
+ billingCchAlgo:
+ "How the 5-char cch= token is computed. 'sha256-first-user' = sha256 of first user message text. 'xxhash64-body' = body-level signing fills it later. 'static-zero' = literal '00000' placeholder.",
+ obfuscateWords:
+ "Lowercase words to obfuscate. ZWJ insertion is applied case-insensitively, so 'opencode' also matches 'OpenCode' and 'OPENCODE'.",
+ obfuscateTargets:
+ "Which body regions to scan for the words: system blocks, user/assistant messages, and/or tool descriptions.",
+};
+
+function makeDefaultOp(kind: TransformOpKind): 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: "", allOccurrences: true };
+ case "replace_regex":
+ return { kind, pattern: "", flags: "g", replacement: "" };
+ case "drop_block_if_contains":
+ return { kind, needles: [""] };
+ case "prepend_system_block":
+ return { kind, text: "", idempotencyKey: "" };
+ case "append_system_block":
+ return { kind, text: "", idempotencyKey: "" };
+ case "inject_billing_header":
+ return {
+ kind,
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ };
+ case "obfuscate_words":
+ return { kind, words: [""], targets: ["system", "messages", "tools"] };
+ }
+}
+
+function StringListEditor({
+ label,
+ hint,
+ items,
+ onChange,
+ disabled,
+}: {
+ label: string;
+ hint?: string;
+ items: string[];
+ onChange: (next: string[]) => void;
+ disabled?: boolean;
+}) {
+ return (
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs font-medium text-text-main">{label}</span>
+ {hint && <p className="text-xs text-text-muted">{hint}</p>}
+ {items.map((item, idx) => (
+ <div key={idx} className="flex items-center gap-2">
+ <Input
+ className="flex-1"
+ value={item}
+ disabled={disabled}
+ onChange={(e) => {
+ const next = [...items];
+ next[idx] = e.target.value;
+ onChange(next);
+ }}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="close"
+ disabled={disabled}
+ aria-label="Remove entry"
+ onClick={() => {
+ const next = [...items];
+ next.splice(idx, 1);
+ onChange(next);
+ }}
+ />
+ </div>
+ ))}
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="add"
+ disabled={disabled}
+ onClick={() => onChange([...items, ""])}
+ className="self-start"
+ >
+ Add entry
+ </Button>
+ </div>
+ );
+}
+
+function OpEditor({
+ op,
+ onChange,
+ disabled,
+}: {
+ op: any;
+ onChange: (next: any) => void;
+ disabled?: boolean;
+}) {
+ const updateField = (field: string, value: any) => onChange({ ...op, [field]: value });
+ const kind = op?.kind as TransformOpKind | undefined;
+ const opDescription = kind ? OP_KIND_DESCRIPTIONS[kind] : null;
+
+ const wrap = (body: React.ReactNode) => (
+ <div className="flex flex-col gap-3">
+ {opDescription && (
+ <p className="text-[11px] leading-relaxed text-text-muted border-l-2 border-purple-500/30 pl-2 italic">
+ {opDescription}
+ </p>
+ )}
+ {body}
+ </div>
+ );
+
+ switch (op?.kind) {
+ case "drop_paragraph_if_contains":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <StringListEditor
+ label="Needles (substrings to match)"
+ hint={FIELD_HINTS.needles}
+ items={op.needles || []}
+ onChange={(next) => updateField("needles", next)}
+ disabled={disabled}
+ />
+ <Toggle
+ label="Case sensitive"
+ description={FIELD_HINTS.caseSensitive}
+ checked={op.caseSensitive !== false}
+ onChange={(c) => updateField("caseSensitive", c)}
+ size="sm"
+ disabled={disabled}
+ />
+ </div>
+ );
+ case "drop_paragraph_if_starts_with":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <StringListEditor
+ label="Prefixes"
+ hint={FIELD_HINTS.prefixes}
+ items={op.prefixes || []}
+ onChange={(next) => updateField("prefixes", next)}
+ disabled={disabled}
+ />
+ <Toggle
+ label="Case sensitive"
+ description={FIELD_HINTS.caseSensitive}
+ checked={op.caseSensitive !== false}
+ onChange={(c) => updateField("caseSensitive", c)}
+ size="sm"
+ disabled={disabled}
+ />
+ </div>
+ );
+ case "replace_text":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <Input
+ label="Match"
+ hint={FIELD_HINTS.matchLiteral}
+ value={op.match || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("match", e.target.value)}
+ />
+ <Input
+ label="Replacement"
+ hint={FIELD_HINTS.replacementText}
+ value={op.replacement || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("replacement", e.target.value)}
+ />
+ <Toggle
+ label="Replace all occurrences"
+ description={FIELD_HINTS.allOccurrences}
+ checked={op.allOccurrences !== false}
+ onChange={(c) => updateField("allOccurrences", c)}
+ size="sm"
+ disabled={disabled}
+ />
+ </div>
+ );
+ case "replace_regex":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <Input
+ label="Pattern (regex)"
+ hint={FIELD_HINTS.pattern}
+ value={op.pattern || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("pattern", e.target.value)}
+ />
+ <Input
+ label="Flags"
+ hint={FIELD_HINTS.regexFlags}
+ value={op.flags || "g"}
+ disabled={disabled}
+ onChange={(e) => updateField("flags", e.target.value)}
+ />
+ <Input
+ label="Replacement"
+ hint={FIELD_HINTS.replacementText}
+ value={op.replacement || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("replacement", e.target.value)}
+ />
+ </div>
+ );
+ case "drop_block_if_contains":
+ return wrap(
+ <StringListEditor
+ label="Needles"
+ hint={FIELD_HINTS.needles}
+ items={op.needles || []}
+ onChange={(next) => updateField("needles", next)}
+ disabled={disabled}
+ />
+ );
+ case "prepend_system_block":
+ case "append_system_block":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-sm font-medium text-text-main">Block text</label>
+ <textarea
+ rows={3}
+ value={op.text || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("text", e.target.value)}
+ className="w-full rounded-md border border-black/10 dark:border-white/10 bg-white dark:bg-white/5 px-3 py-2 text-sm text-text-main font-mono focus:ring-1 focus:ring-primary/30 focus:border-primary/50 focus:outline-none transition-all shadow-inner disabled:opacity-50 disabled:cursor-not-allowed"
+ />
+ <p className="text-xs text-text-muted">{FIELD_HINTS.blockText}</p>
+ </div>
+ <Input
+ label="Idempotency key"
+ hint={FIELD_HINTS.idempotencyKey}
+ value={op.idempotencyKey || ""}
+ disabled={disabled}
+ onChange={(e) => updateField("idempotencyKey", e.target.value)}
+ />
+ </div>
+ );
+ case "inject_billing_header":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <Input
+ label="Entrypoint"
+ hint={FIELD_HINTS.billingEntrypoint}
+ value={op.entrypoint || "sdk-cli"}
+ disabled={disabled}
+ onChange={(e) => updateField("entrypoint", e.target.value)}
+ />
+ <Select
+ label="Version format"
+ hint={FIELD_HINTS.billingVersionFormat}
+ value={op.versionFormat || "ex-machina"}
+ disabled={disabled}
+ onChange={(e) => updateField("versionFormat", e.target.value)}
+ options={[
+ { value: "ex-machina", label: "ex-machina (sha256 per-msg suffix)" },
+ { value: "omniroute-daystamp", label: "omniroute-daystamp (sha256 day+version)" },
+ ]}
+ />
+ <Select
+ label="CCH algorithm"
+ hint={FIELD_HINTS.billingCchAlgo}
+ value={op.cchAlgo || "sha256-first-user"}
+ disabled={disabled}
+ onChange={(e) => updateField("cchAlgo", e.target.value)}
+ options={[
+ { value: "sha256-first-user", label: "sha256-first-user (ex-machina style)" },
+ { value: "xxhash64-body", label: "xxhash64-body (body-level signing)" },
+ { value: "static-zero", label: "static-zero (00000 placeholder)" },
+ ]}
+ />
+ </div>
+ );
+ case "obfuscate_words":
+ return wrap(
+ <div className="flex flex-col gap-2">
+ <StringListEditor
+ label="Words to obfuscate (ZWJ inserted after first char)"
+ hint={FIELD_HINTS.obfuscateWords}
+ items={op.words || []}
+ onChange={(next) => updateField("words", next)}
+ disabled={disabled}
+ />
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs font-medium text-text-main">Targets</span>
+ <p className="text-xs text-text-muted">{FIELD_HINTS.obfuscateTargets}</p>
+ <div className="flex flex-wrap gap-4">
+ {(["system", "messages", "tools"] as const).map((target) => {
+ const targets: string[] = op.targets || ["system", "messages", "tools"];
+ const checked = targets.includes(target);
+ return (
+ <Toggle
+ key={target}
+ label={target}
+ checked={checked}
+ size="sm"
+ disabled={disabled}
+ onChange={(c) => {
+ const next = c ? [...targets, target] : targets.filter((x) => x !== target);
+ updateField("targets", next);
+ }}
+ />
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+ default:
+ return <p className="text-xs text-text-muted">Unknown op kind: {op?.kind}</p>;
+ }
+}
+
+function summarizeTransformOp(op: any): string {
+ switch (op?.kind) {
+ case "drop_paragraph_if_contains":
+ return `drop paragraphs containing: ${(op.needles || []).slice(0, 3).join(", ")}${(op.needles || []).length > 3 ? "…" : ""}`;
+ case "drop_paragraph_if_starts_with":
+ return `drop paragraphs starting with: ${(op.prefixes || []).slice(0, 3).join(", ")}${(op.prefixes || []).length > 3 ? "…" : ""}`;
+ case "replace_text":
+ return `replace "${(op.match || "").slice(0, 40)}${(op.match || "").length > 40 ? "…" : ""}" → "${(op.replacement || "").slice(0, 40)}${(op.replacement || "").length > 40 ? "…" : ""}"`;
+ case "replace_regex":
+ return `regex /${op.pattern}/${op.flags || ""} → "${(op.replacement || "").slice(0, 40)}"`;
+ case "drop_block_if_contains":
+ return `drop blocks containing: ${(op.needles || []).slice(0, 3).join(", ")}`;
+ case "prepend_system_block":
+ return `prepend block: "${(op.text || "").slice(0, 60)}${(op.text || "").length > 60 ? "…" : ""}"`;
+ case "append_system_block":
+ 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);
+ }
+}
+
+// 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() {
const [settings, setSettings] = useState<any>({
@@ -17,7 +610,21 @@ export default function RoutingTab() {
cliCompatProviders: [],
autoRoutingEnabled: true,
autoRoutingDefaultVariant: "lkgp",
+ systemTransforms: DEFAULT_SYSTEM_TRANSFORMS_CLIENT,
});
+ // 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>>({});
+ // Save-state messages for the per-op structured editor (separate from
+ // jsonErrors which belongs to the JSON textarea). Cleared when the user
+ // makes a fresh edit; populated when the server rejects a PATCH.
+ const [providerSaveErrors, setProviderSaveErrors] = useState<Record<string, string | null>>({});
+ const [showJsonEditor, setShowJsonEditor] = useState<Record<string, boolean>>({});
+ const [addOpKind, setAddOpKind] = useState<Record<string, TransformOpKind>>({});
+ const [newProviderId, setNewProviderId] = useState("");
const [loading, setLoading] = useState(true);
const [lkgpCacheLoading, setLkgpCacheLoading] = useState(false);
const [lkgpCacheStatus, setLkgpCacheStatus] = useState({ type: "", message: "" });
@@ -33,18 +640,43 @@ export default function RoutingTab() {
.catch(() => setLoading(false));
}, []);
- const updateSetting = async (patch) => {
+ // Optimistic update: apply the patch to local state FIRST so the UI never
+ // appears to drop the user's edit, then PATCH the server. If the server
+ // rejects (e.g. blank required field on a freshly-added op), surface the
+ // error to the caller via onError so the editor can render it inline. Local
+ // state is intentionally NOT rolled back — the user keeps editing and
+ // re-saves once the validation passes.
+ const updateSetting = async (patch: Record<string, unknown>, onError?: (msg: string) => void) => {
+ setSettings((prev: any) => ({ ...prev, ...patch }));
try {
const res = await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
- if (res.ok) {
- setSettings((prev) => ({ ...prev, ...patch }));
+ if (!res.ok) {
+ let serverMsg = `HTTP ${res.status}`;
+ try {
+ const body = await res.json();
+ const details = Array.isArray(body?.error?.details)
+ ? body.error.details
+ .map((d: { field?: string; message?: string }) =>
+ d.field ? `${d.field}: ${d.message ?? "invalid"}` : d.message
+ )
+ .filter(Boolean)
+ .join("; ")
+ : null;
+ serverMsg = details || body?.error?.message || serverMsg;
+ } catch {
+ // body wasn't JSON — keep the HTTP status fallback
+ }
+ if (onError) onError(serverMsg);
+ else console.error("Failed to update settings:", serverMsg);
}
} catch (err) {
- console.error("Failed to update settings:", err);
+ const msg = err instanceof Error ? err.message : String(err);
+ if (onError) onError(msg);
+ else console.error("Failed to update settings:", msg);
}
};
@@ -59,6 +691,142 @@ export default function RoutingTab() {
);
const cliCompatProviderSet = useMemo(() => new Set(cliCompatProviders), [cliCompatProviders]);
+ // 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 DEFAULT_SYSTEM_TRANSFORMS_CLIENT;
+ }, [settings.systemTransforms, settings.ccBridgeTransforms]);
+
+ // 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 updateProviderTransforms = (
+ providerId: string,
+ next: { enabled: boolean; pipeline: any[] }
+ ) => {
+ const merged = {
+ providers: {
+ ...systemTransforms.providers,
+ [providerId]: next,
+ },
+ };
+ // Clear any prior save error for this provider so the user sees a fresh
+ // state. If the server rejects, the callback below will repopulate it.
+ setProviderSaveErrors((prev) => ({ ...prev, [providerId]: null }));
+ updateSetting({ systemTransforms: merged }, (msg) =>
+ setProviderSaveErrors((prev) => ({ ...prev, [providerId]: msg }))
+ );
+ };
+
+ const toggleProviderEnabled = (providerId: string, enabled: boolean) => {
+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };
+ updateProviderTransforms(providerId, { enabled, pipeline: current.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 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 })),
+ });
+ };
+
+ const updateOp = (providerId: string, opIndex: number, next: any) => {
+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };
+ const pipeline = [...(current.pipeline as any[])];
+ pipeline[opIndex] = next;
+ updateProviderTransforms(providerId, { enabled: current.enabled, pipeline });
+ };
+
+ const deleteOp = (providerId: string, opIndex: number) => {
+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };
+ const pipeline = (current.pipeline as any[]).filter((_, i) => i !== opIndex);
+ updateProviderTransforms(providerId, { enabled: current.enabled, pipeline });
+ };
+
+ const moveOp = (providerId: string, opIndex: number, direction: -1 | 1) => {
+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };
+ const pipeline = [...(current.pipeline as any[])];
+ const target = opIndex + direction;
+ if (target < 0 || target >= pipeline.length) return;
+ [pipeline[opIndex], pipeline[target]] = [pipeline[target], pipeline[opIndex]];
+ updateProviderTransforms(providerId, { enabled: current.enabled, pipeline });
+ };
+
+ const addOp = (providerId: string) => {
+ const kind = addOpKind[providerId] ?? "drop_paragraph_if_contains";
+ const current = systemTransforms.providers[providerId] ?? { enabled: false, pipeline: [] };
+ const pipeline = [...(current.pipeline as any[]), makeDefaultOp(kind)];
+ updateProviderTransforms(providerId, { enabled: current.enabled, pipeline });
+ };
+
+ const availableProvidersToAdd = useMemo(
+ () => PROVIDER_CATALOG.filter((p) => !systemTransforms.providers[p.id]),
+ [systemTransforms.providers]
+ );
+
+ const addProvider = () => {
+ const id = newProviderId;
+ if (!id || systemTransforms.providers[id]) return;
+ updateProviderTransforms(id, { enabled: false, pipeline: [] });
+ setNewProviderId("");
+ };
+
+ const removeProvider = (providerId: string) => {
+ if (BUILTIN_PROVIDERS.has(providerId)) return;
+ const providers = systemTransforms.providers as Record<string, unknown>;
+ const { [providerId]: _removed, ...rest } = providers;
+ updateSetting({ systemTransforms: { providers: rest } });
+ };
+
const toggleCliCompatProvider = (providerId: string, enabled: boolean) => {
const normalizedProviderId = normalizeCliCompatProviderId(providerId);
const nextProviders = new Set(cliCompatProviders);
@@ -255,80 +1023,339 @@ 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
+ security
</span>
</div>
<div>
<h3 className="text-lg font-semibold">{t("cliFingerprint")}</h3>
- <p className="text-sm text-text-muted">{t("cliFingerprintDesc")}</p>
- <p className="mt-1 text-xs text-text-muted">
- {t("cliFingerprintEnabled", { count: cliCompatProviderSet.size })}
- </p>
+ <p className="text-sm text-text-muted mt-1">{t("cliFingerprintDesc")}</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
+ <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];
+ const checked = cliCompatProviderSet.has(normalizedProviderId);
+ const label = providerDisplay?.name || providerId;
+ const description = providerDisplay?.description || providerId;
+ const titleText = 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"
+ return (
+ <button
+ key={providerId}
+ type="button"
+ onClick={() => toggleCliCompatProvider(providerId, !checked)}
+ disabled={loading}
+ aria-pressed={checked}
+ 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 ? "cursor-not-allowed 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={`material-symbols-outlined mt-0.5 text-[18px] ${checked ? "text-indigo-400" : "text-text-muted"}`}
+ aria-hidden="true"
+ >
+ {checked ? "check_circle" : "radio_button_unchecked"}
+ </span>
+ <span className="min-w-0 flex-1">
<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>
- ) : null}
+ <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>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </Card>
+
+ <Card>
+ <div className="flex items-start gap-3 mb-4">
+ <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("systemTransforms")}</h3>
+ <p className="text-sm text-text-muted mt-1">{t("systemTransformsDesc")}</p>
+ </div>
+ </div>
+
+ {/* Add provider — moved to TOP per UX brief. */}
+ <div className="mb-4 flex items-end gap-2 rounded-lg border border-dashed border-border/40 bg-surface/30 p-3">
+ <Select
+ label={t("systemTransformsAddProvider")}
+ value={newProviderId}
+ disabled={loading || availableProvidersToAdd.length === 0}
+ onChange={(e) => setNewProviderId(e.target.value)}
+ className="flex-1"
+ >
+ <option value="">
+ {availableProvidersToAdd.length === 0
+ ? t("systemTransformsAddProviderAllConfigured")
+ : t("systemTransformsAddProviderPlaceholder")}
+ </option>
+ {availableProvidersToAdd.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name} ({p.id})
+ </option>
+ ))}
+ </Select>
+ <Button
+ variant="secondary"
+ size="sm"
+ icon="add"
+ disabled={loading || !newProviderId || !!systemTransforms.providers[newProviderId]}
+ onClick={addProvider}
+ >
+ {t("systemTransformsAddProvider")}
+ </Button>
+ </div>
+
+ {Object.keys(systemTransforms.providers).length === 0 && (
+ <p className="text-sm text-text-muted py-2">{t("systemTransformsNoProviders")}</p>
+ )}
+
+ <div className="flex flex-col gap-3">
+ {Object.entries(systemTransforms.providers).map(([providerId, providerCfg]) => {
+ const isBuiltin = BUILTIN_PROVIDERS.has(providerId);
+ const display = PROVIDER_TILE_DISPLAY[providerId] ?? {
+ name: providerId,
+ description: "Custom provider.",
+ 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]
+ );
+ const isJsonOpen = showJsonEditor[providerId] ?? false;
+ const enabled = providerCfg.enabled !== false;
+ const selectedKind =
+ (addOpKind[providerId] as TransformOpKind | undefined) ??
+ "drop_paragraph_if_contains";
+
+ return (
+ <Collapsible
+ key={providerId}
+ defaultOpen={false}
+ title={
+ <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>
+ }
+ subtitle={`${opCount} op${opCount === 1 ? "" : "s"} · ${enabled ? "enabled" : "disabled"}`}
+ trailing={
+ <>
+ <Toggle
+ checked={enabled}
+ onChange={(checked) => toggleProviderEnabled(providerId, checked)}
+ disabled={loading}
+ ariaLabel={`Enable ${display.name} transforms`}
+ />
+ {!isBuiltin && (
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="delete"
+ disabled={loading}
+ aria-label={t("systemTransformsRemoveProvider")}
+ title={t("systemTransformsRemoveProvider")}
+ onClick={() => removeProvider(providerId)}
+ />
+ )}
+ </>
+ }
+ >
+ <p className="text-xs text-text-muted mb-3">{display.description}</p>
+ {providerSaveErrors[providerId] && (
+ <div
+ role="alert"
+ className="mb-3 rounded border border-red-500/40 bg-red-500/10 p-2 text-xs text-red-300"
+ >
+ <span className="font-medium">⚠ Server rejected save:</span>{" "}
+ <span className="break-words font-mono">{providerSaveErrors[providerId]}</span>
+ <p className="mt-1 text-[11px] text-red-200/80">
+ Your local edits are kept. Fix the field above and the next change will
+ re-save.
+ </p>
+ </div>
+ )}
+
+ {/* Pipeline op list — each op is itself collapsible. */}
+ {opCount > 0 && (
+ <ol className="flex flex-col gap-2 mb-3">
+ {(providerCfg.pipeline as any[]).map((op, index) => (
+ <li key={index}>
+ <Collapsible
+ variant="inline"
+ defaultOpen={false}
+ title={
+ <div className="flex items-center gap-2">
+ <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>
+ <span className="font-mono text-purple-300 text-xs">{op?.kind}</span>
+ </div>
+ }
+ trailing={
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="keyboard_arrow_up"
+ disabled={loading || index === 0}
+ aria-label={t("systemTransformsOpMoveUp")}
+ title={t("systemTransformsOpMoveUp")}
+ onClick={() => moveOp(providerId, index, -1)}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="keyboard_arrow_down"
+ disabled={loading || index === opCount - 1}
+ aria-label={t("systemTransformsOpMoveDown")}
+ title={t("systemTransformsOpMoveDown")}
+ onClick={() => moveOp(providerId, index, 1)}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="delete"
+ disabled={loading}
+ aria-label={t("systemTransformsOpDelete")}
+ title={t("systemTransformsOpDelete")}
+ onClick={() => deleteOp(providerId, index)}
+ />
+ </>
+ }
+ >
+ <OpEditor
+ op={op}
+ disabled={loading}
+ onChange={(next) => updateOp(providerId, index, next)}
+ />
+ </Collapsible>
+ </li>
+ ))}
+ </ol>
+ )}
+
+ {/* Add op row */}
+ <div className="flex items-end gap-2 mb-3">
+ <Select
+ label="Add a transform op"
+ className="flex-1"
+ value={selectedKind}
+ onChange={(e) =>
+ setAddOpKind((prev) => ({
+ ...prev,
+ [providerId]: e.target.value as TransformOpKind,
+ }))
+ }
+ disabled={loading}
+ options={(Object.keys(OP_KIND_LABELS) as TransformOpKind[]).map((kind) => ({
+ value: kind,
+ label: OP_KIND_LABELS[kind],
+ }))}
+ />
+ <Button
+ onClick={() => addOp(providerId)}
+ disabled={loading}
+ variant="secondary"
+ size="sm"
+ icon="add"
+ >
+ Add op
+ </Button>
+ </div>
+
+ {/* JSON import section (collapsible) */}
+ <div className="border-t border-border/20 pt-2 mt-2">
+ <button
+ type="button"
+ onClick={() =>
+ setShowJsonEditor((prev) => ({ ...prev, [providerId]: !isJsonOpen }))
+ }
+ className="text-[11px] text-primary hover:underline"
+ >
+ {isJsonOpen ? "▾ Hide JSON editor" : "▸ Import / export JSON"}
+ </button>
+ {isJsonOpen && (
+ <div className="mt-2">
+ <label className="text-[11px] font-medium text-text-muted block mb-1">
+ JSON (edit &amp; Apply, or paste to import)
+ </label>
+ <textarea
+ value={draft}
+ onChange={(e) =>
+ setJsonDrafts((prev) => ({ ...prev, [providerId]: e.target.value }))
+ }
+ rows={Math.min(40, Math.max(6, draft.split("\n").length))}
+ disabled={loading}
+ 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-1 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>
+ )}
+ </div>
+ </Collapsible>
);
})}
</div>
+
+ <p className="mt-3 text-[11px] text-text-muted">
+ All transform ops are idempotent on re-run. Changes take effect immediately on the next
+ request.
+ </p>
</Card>
<Card>
diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.json
index 59ae01039a..8b16903abc 100644
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@ -672,8 +672,6 @@
"cloudAgents": "Cloud Agents",
"memory": "Memory",
"skills": "Skills",
- "omniSkills": "OmniSkills",
- "agentSkills": "AgentSkills",
"docs": "Docs",
"issues": "Issues",
"endpoints": "Endpoints",
@@ -2338,7 +2336,6 @@
"skillsTab": "Skills",
"executionsTab": "Executions",
"sandboxTab": "Sandbox",
- "agentSkillsTab": "AI Skills",
"loading": "Loading skills...",
"noSkills": "No skills found",
"noExecutions": "No executions found",
@@ -2588,27 +2585,8 @@
"onboarding": {
"welcome": "Welcome",
"security": "Security",
- "tiers": "How It Works",
"test": "Test",
"ready": "Ready!",
- "tier": {
- "title": "How OmniRoute saves you money",
- "subtitle": "Three tiers, automatic fallback — never stop building.",
- "tier1": {
- "label": "Subscription",
- "description": "Use what you already pay for — every drop of quota before it resets."
- },
- "tier2": {
- "label": "Cheap",
- "description": "Pay-per-token under $1/1M — kicks in when subscription quotas hit."
- },
- "tier3": {
- "label": "Free",
- "description": "Generous free tiers and credit programs — final safety net."
- },
- "continue": "Continue",
- "configure": "Configure tiers now"
- },
"setPassword": "Set Password",
"addProvider": "Add your first provider",
"getStarted": "Get Started",
@@ -3402,12 +3380,20 @@
"blockProviderTitle": "Block {provider}",
"unblockProviderTitle": "Unblock {provider}",
"cliFingerprint": "CLI Fingerprint Matching",
- "cliFingerprintDesc": "Match native CLI binary signatures when proxying requests. Reorders headers and body fields to look identical to the official CLI tools. Your proxy IP is preserved.",
+ "cliFingerprintDesc": "Normalize request headers and body fields to match the official CLI tool signatures. Enable per provider.",
"cliFingerprintEnabled": "{count} provider(s) with CLI fingerprint active",
"enableFingerprintTitle": "Enable fingerprint for {provider}",
"disableFingerprintTitle": "Disable fingerprint for {provider}",
- "forcedFingerprintTitle": "Always enabled for {provider} — required for OAuth account safety; cannot be turned off.",
- "forcedFingerprintBadge": "Required",
+ "systemTransforms": "System-block Transform Pipeline",
+ "systemTransformsDesc": "Per-provider ordered pipeline of transforms applied to the request body before forwarding. Supports any provider ID.",
+ "systemTransformsAddProvider": "Add provider",
+ "systemTransformsAddProviderPlaceholder": "Select a provider…",
+ "systemTransformsAddProviderAllConfigured": "All providers already configured",
+ "systemTransformsRemoveProvider": "Remove provider",
+ "systemTransformsNoProviders": "No providers configured. Add a provider to get started.",
+ "systemTransformsOpMoveUp": "Move up",
+ "systemTransformsOpMoveDown": "Move down",
+ "systemTransformsOpDelete": "Delete op",
"routingStrategy": "Routing Strategy",
"routingAdvancedGuideTitle": "Advanced routing guidance",
"routingAdvancedGuideHint1": "Use Fill First for predictable priority, Round Robin for fairness, and P2C for latency resilience.",
@@ -4224,17 +4210,6 @@
"lastUsed": "Last Refreshed",
"actions": "Actions",
"refreshQuota": "Refresh quota",
- "quotaThresholdLabel": "Cutoff",
- "quotaThresholdInvalid": "Enter an integer 0–100, or leave blank to inherit the default.",
- "quotaCutoffsColumnHelp": "Stop using this account when any window's remaining quota drops to its cutoff. Numbers match the dashboard bars (remaining %).",
- "quotaCutoffsButtonDefault": "Default",
- "quotaCutoffsButtonHelp": "Click to set per-window cutoffs for this account (in remaining %).",
- "quotaCutoffsButtonDisabled": "Quota data hasn't loaded yet — refresh this row to enable cutoffs.",
- "quotaCutoffsTitle": "Quota cutoffs — {name} ({provider})",
- "quotaCutoffsExplainer": "Stop using this account when any window's REMAINING quota drops to the value below — same units as the dashboard bars. Empty inherits the resilience-settings default.",
- "quotaCutoffsDefaultHint": "Default: stop at {default}% remaining",
- "quotaCutoffsNoWindows": "This provider has no registered quota windows.",
- "quotaCutoffsResetAll": "Reset all",
"today": "Today",
"tomorrow": "Tomorrow",
"dayTimeFormat": "{day}, {time}",
diff --git a/src/lib/config/runtimeSettings.ts b/src/lib/config/runtimeSettings.ts
index 9df6d5985f..634fd5d9b0 100644
--- a/src/lib/config/runtimeSettings.ts
+++ b/src/lib/config/runtimeSettings.ts
@@ -12,7 +12,9 @@ export type RuntimeReloadSection =
| "healthCheckLogs"
| "thoughtSignature"
| "modelsDevSync"
- | "corsOrigins";
+ | "corsOrigins"
+ | "ccBridgeTransforms"
+ | "systemTransforms";
export interface RuntimeReloadChange {
section: RuntimeReloadSection;
@@ -31,6 +33,8 @@ interface RuntimeSettingsSnapshot {
modelsDevSyncEnabled: boolean;
modelsDevSyncInterval: number | null;
corsOrigins: string;
+ ccBridgeTransforms: unknown;
+ systemTransforms: unknown;
}
const DEFAULT_RUNTIME_SETTINGS_SNAPSHOT: RuntimeSettingsSnapshot = {
@@ -45,6 +49,8 @@ const DEFAULT_RUNTIME_SETTINGS_SNAPSHOT: RuntimeSettingsSnapshot = {
modelsDevSyncEnabled: false,
modelsDevSyncInterval: null,
corsOrigins: "",
+ ccBridgeTransforms: null,
+ systemTransforms: null,
};
let lastAppliedSnapshot: RuntimeSettingsSnapshot | null = null;
@@ -180,6 +186,8 @@ export function buildRuntimeSettingsSnapshot(
modelsDevSyncEnabled: settings.modelsDevSyncEnabled === true,
modelsDevSyncInterval: normalizeNumber(settings.modelsDevSyncInterval),
corsOrigins: typeof settings.corsOrigins === "string" ? settings.corsOrigins : "",
+ ccBridgeTransforms: parseStoredJson(settings.ccBridgeTransforms, "ccBridgeTransforms"),
+ systemTransforms: parseStoredJson(settings.systemTransforms, "systemTransforms"),
};
}
@@ -257,6 +265,40 @@ 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 { 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 (
+ systemTransforms === null ||
+ systemTransforms === undefined ||
+ typeof systemTransforms !== "object"
+ ) {
+ resetSystemTransformsConfig();
+ return;
+ }
+
+ setSystemTransformsConfig(systemTransforms);
+}
+
async function applyModelsDevSyncSection(
previousSnapshot: RuntimeSettingsSnapshot,
currentSnapshot: RuntimeSettingsSnapshot,
@@ -392,6 +434,19 @@ export async function applyRuntimeSettings(
markChanged("corsOrigins");
}
+ if (
+ force ||
+ hasChanged(currentSnapshot.ccBridgeTransforms, previousSnapshot.ccBridgeTransforms)
+ ) {
+ await applyCcBridgeTransformsSection(currentSnapshot.ccBridgeTransforms);
+ markChanged("ccBridgeTransforms");
+ }
+
+ if (force || hasChanged(currentSnapshot.systemTransforms, previousSnapshot.systemTransforms)) {
+ await applySystemTransformsSection(currentSnapshot.systemTransforms);
+ markChanged("systemTransforms");
+ }
+
lastAppliedSnapshot = currentSnapshot;
return changes;
}
diff --git a/src/shared/components/Collapsible.tsx b/src/shared/components/Collapsible.tsx
new file mode 100644
index 0000000000..3a3a63b21d
--- /dev/null
+++ b/src/shared/components/Collapsible.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+import { useState, type ReactNode } from "react";
+import { cn } from "@/shared/utils/cn";
+
+interface CollapsibleProps {
+ /** Header content (always visible, click-to-toggle). */
+ title: ReactNode;
+ /** Optional secondary line under the title. */
+ subtitle?: ReactNode;
+ /** Material symbol name shown left of the title. */
+ icon?: string;
+ /** Trailing element rendered next to the chevron (badges, op counts, etc). */
+ trailing?: ReactNode;
+ /** Whether the section is open on first render. Defaults to false. */
+ defaultOpen?: boolean;
+ /** Visual variant. `default` for top-level sections; `inline` for nested rows. */
+ variant?: "default" | "inline";
+ /** Custom class for the wrapper. */
+ className?: string;
+ /** Content rendered when expanded. */
+ children: ReactNode;
+}
+
+/**
+ * Minimal click-to-expand section. Stateless from the caller's perspective
+ * (open/closed lives in local state — does NOT survive page refresh, per the
+ * UX brief). Uses material-symbols-outlined chevrons to match the rest of
+ * the OmniRoute UI.
+ */
+export default function Collapsible({
+ title,
+ subtitle,
+ icon,
+ trailing,
+ defaultOpen = false,
+ variant = "default",
+ className,
+ children,
+}: CollapsibleProps) {
+ const [open, setOpen] = useState(defaultOpen);
+
+ const wrapperClasses = cn(
+ variant === "default"
+ ? "rounded-lg border border-black/5 dark:border-white/5 bg-surface"
+ : "rounded-md border border-black/5 dark:border-white/5 bg-black/[0.02] dark:bg-white/[0.02]",
+ className
+ );
+
+ const headerRowClasses = cn(
+ "flex items-center gap-3",
+ variant === "default" ? "p-4" : "p-3",
+ "hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors",
+ open && "border-b border-black/5 dark:border-white/5"
+ );
+
+ // The chevron + title region is the click target. Trailing interactive
+ // controls (Toggle, Button) live OUTSIDE the toggle button so we never nest
+ // <button> inside <button> (invalid HTML; breaks keyboard nav + ARIA).
+ return (
+ <div className={wrapperClasses}>
+ <div className={headerRowClasses}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="flex items-center gap-3 flex-1 min-w-0 text-left -m-1 p-1 rounded"
+ >
+ <span
+ className="material-symbols-outlined text-text-muted text-[20px] shrink-0"
+ aria-hidden="true"
+ >
+ {open ? "expand_more" : "chevron_right"}
+ </span>
+ {icon && (
+ <span
+ className="material-symbols-outlined text-text-muted text-[18px] shrink-0"
+ aria-hidden="true"
+ >
+ {icon}
+ </span>
+ )}
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-text-main truncate">{title}</div>
+ {subtitle && <div className="text-xs text-text-muted truncate">{subtitle}</div>}
+ </div>
+ </button>
+ {trailing && <div className="flex items-center gap-2 shrink-0">{trailing}</div>}
+ </div>
+ {open && <div className={variant === "default" ? "p-4" : "p-3"}>{children}</div>}
+ </div>
+ );
+}
diff --git a/src/shared/components/index.tsx b/src/shared/components/index.tsx
index 568c9e44e0..1039804883 100644
--- a/src/shared/components/index.tsx
+++ b/src/shared/components/index.tsx
@@ -3,6 +3,7 @@ export { default as Button } from "./Button";
export { default as Input } from "./Input";
export { default as Select } from "./Select";
export { default as Card } from "./Card";
+export { default as Collapsible } from "./Collapsible";
export { default as Modal, ConfirmModal } from "./Modal";
export { default as Loading, Spinner, PageLoading, Skeleton, CardSkeleton } from "./Loading";
export { default as Avatar } from "./Avatar";
diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.ts
index 7a5b1b3411..d808007b32 100644
--- a/src/shared/validation/settingsSchemas.ts
+++ b/src/shared/validation/settingsSchemas.ts
@@ -63,6 +63,133 @@ export const updateSettingsSchema = z.object({
wsAuth: z.boolean().optional(),
// CLI Fingerprint compatibility (per-provider)
cliCompatProviders: z.array(z.string().max(100)).optional(),
+ // CC bridge transforms (issue #2260): config-driven pipeline that normalizes
+ // system blocks at the Claude Code bridge so any client (OpenCode, Cline,
+ // Cursor, Continue, raw API) ends up with classifier-correct structure.
+ ccBridgeTransforms: 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(),
+ }),
+ ])
+ )
+ .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 mode
diff --git a/tests/unit/cc-bridge-transforms.test.ts b/tests/unit/cc-bridge-transforms.test.ts
new file mode 100644
index 0000000000..11666d0bc5
--- /dev/null
+++ b/tests/unit/cc-bridge-transforms.test.ts
@@ -0,0 +1,432 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+const {
+ DEFAULT_CC_BRIDGE_PIPELINE,
+ DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG,
+ DEFAULT_CLAUDE_CODE_VERSION,
+ CLAUDE_AGENT_SDK_IDENTITY,
+ DEFAULT_PARAGRAPH_REMOVAL_ANCHORS,
+ DEFAULT_IDENTITY_PREFIXES,
+ DEFAULT_TEXT_REPLACEMENTS,
+ applyCcBridgeTransformPipeline,
+ buildBillingHeaderValue,
+ computeCchSha256FirstUser,
+ computeExMachinaVersionSuffix,
+ computeDaystampVersionSuffix,
+ extractFirstUserMessageText,
+ setCcBridgeTransformsConfig,
+ getCcBridgeTransformsConfig,
+ resetCcBridgeTransformsConfig,
+} = await import("../../open-sse/services/ccBridgeTransforms.ts");
+
+type TransformOp = Parameters<typeof applyCcBridgeTransformPipeline>[1] extends infer C
+ ? C extends { pipeline: infer P }
+ ? P extends Array<infer T>
+ ? T
+ : never
+ : never
+ : never;
+
+function bodyWithSystem(systemBlocks: Array<{ type: string; text: string }>, userText = "hi") {
+ return {
+ model: "claude-opus-4-7",
+ messages: [{ role: "user", content: [{ type: "text", text: userText }] }],
+ system: systemBlocks,
+ };
+}
+
+function runPipeline(body: any, ops: any[]) {
+ return applyCcBridgeTransformPipeline(body, { enabled: true, pipeline: ops });
+}
+
+test.beforeEach(() => {
+ resetCcBridgeTransformsConfig();
+});
+
+// ── Defaults sanity ─────────────────────────────────────────────────────────
+
+test("DEFAULT_CC_BRIDGE_PIPELINE places billing header at [0] and identity at [1] in output", () => {
+ const result = runPipeline(
+ bodyWithSystem([{ type: "text", text: "body" }], "user prompt"),
+ DEFAULT_CC_BRIDGE_PIPELINE
+ );
+ const blocks = result.body.system as any[];
+ assert.ok(blocks[0].text.startsWith("x-anthropic-billing-header:"));
+ assert.equal(blocks[1].text, CLAUDE_AGENT_SDK_IDENTITY);
+});
+
+test("DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG is enabled", () => {
+ assert.equal(DEFAULT_CC_BRIDGE_TRANSFORMS_CONFIG.enabled, true);
+});
+
+test("DEFAULT_PARAGRAPH_REMOVAL_ANCHORS includes ex-machina v1.7.5 anchors", () => {
+ assert.ok(DEFAULT_PARAGRAPH_REMOVAL_ANCHORS.includes("github.com/anomalyco/opencode"));
+ assert.ok(DEFAULT_PARAGRAPH_REMOVAL_ANCHORS.includes("opencode.ai/docs"));
+});
+
+test("DEFAULT_IDENTITY_PREFIXES strips OpenCode identity", () => {
+ assert.ok(DEFAULT_IDENTITY_PREFIXES.includes("You are OpenCode"));
+});
+
+test("DEFAULT_TEXT_REPLACEMENTS includes v1.7.5 phrase fix", () => {
+ const phrase = "Here is some useful information about the environment you are running in:";
+ const rule = DEFAULT_TEXT_REPLACEMENTS.find((r) => r.match === phrase);
+ assert.ok(rule, "expected phrase replacement");
+ assert.equal(rule!.replacement, "Environment context you are running in:");
+});
+
+// ── Op: drop_paragraph_if_contains ─────────────────────────────────────────
+
+test("drop_paragraph_if_contains removes matching paragraphs only", () => {
+ const text = [
+ "Intro paragraph here.",
+ "See github.com/anomalyco/opencode for details.",
+ "Final paragraph survives.",
+ ].join("\n\n");
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "drop_paragraph_if_contains", needles: ["github.com/anomalyco/opencode"] },
+ ]);
+ const out = (result.body.system as any[])[0].text as string;
+ assert.ok(out.includes("Intro paragraph"));
+ assert.ok(out.includes("Final paragraph"));
+ assert.ok(!out.includes("anomalyco"));
+});
+
+test("drop_paragraph_if_contains with empty needles is a no-op", () => {
+ const text = "Stays put.";
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "drop_paragraph_if_contains", needles: [] },
+ ]);
+ assert.equal((result.body.system as any[])[0].text, text);
+});
+
+// ── Op: drop_paragraph_if_starts_with ──────────────────────────────────────
+
+test("drop_paragraph_if_starts_with drops identity-prefixed paragraphs", () => {
+ const text = ["You are OpenCode, a helper.", "Real content."].join("\n\n");
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "drop_paragraph_if_starts_with", prefixes: ["You are OpenCode"] },
+ ]);
+ const out = (result.body.system as any[])[0].text as string;
+ assert.ok(!out.includes("You are OpenCode"));
+ assert.ok(out.includes("Real content"));
+});
+
+// ── Op: replace_text ───────────────────────────────────────────────────────
+
+test("replace_text replaces v1.7.5 phrase exactly once by default", () => {
+ const phrase = "Here is some useful information about the environment you are running in:";
+ const text = `Prefix. ${phrase} body.`;
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ {
+ kind: "replace_text",
+ match: phrase,
+ replacement: "Environment context you are running in:",
+ },
+ ]);
+ const out = (result.body.system as any[])[0].text as string;
+ assert.ok(out.includes("Environment context you are running in:"));
+ assert.ok(!out.includes("Here is some useful information"));
+});
+
+test("replace_text allOccurrences=true replaces every hit", () => {
+ const text = "X X X";
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "replace_text", match: "X", replacement: "Y", allOccurrences: true },
+ ]);
+ assert.equal((result.body.system as any[])[0].text, "Y Y Y");
+});
+
+// ── Op: replace_regex ──────────────────────────────────────────────────────
+
+test("replace_regex handles flags and patterns", () => {
+ const text = "foo bar foo BAR";
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "replace_regex", pattern: "foo", flags: "gi", replacement: "baz" },
+ ]);
+ assert.equal((result.body.system as any[])[0].text, "baz bar baz BAR");
+});
+
+test("replace_regex invalid pattern is a no-op", () => {
+ const text = "stays.";
+ const result = runPipeline(bodyWithSystem([{ type: "text", text }]), [
+ { kind: "replace_regex", pattern: "[invalid(", replacement: "X" },
+ ]);
+ assert.equal((result.body.system as any[])[0].text, text);
+});
+
+// ── Op: drop_block_if_contains ─────────────────────────────────────────────
+
+test("drop_block_if_contains drops entire matching blocks", () => {
+ const body = bodyWithSystem([
+ { type: "text", text: "block A keep" },
+ { type: "text", text: "block B drop github.com/anomalyco/opencode" },
+ { type: "text", text: "block C keep" },
+ ]);
+ const result = runPipeline(body, [
+ { kind: "drop_block_if_contains", needles: ["github.com/anomalyco/opencode"] },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks.length, 2);
+ assert.equal(blocks[0].text, "block A keep");
+ assert.equal(blocks[1].text, "block C keep");
+});
+
+// ── Op: prepend_system_block ───────────────────────────────────────────────
+
+test("prepend_system_block adds identity at position [0]", () => {
+ const result = runPipeline(bodyWithSystem([{ type: "text", text: "body" }]), [
+ { kind: "prepend_system_block", text: CLAUDE_AGENT_SDK_IDENTITY },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks[0].text, CLAUDE_AGENT_SDK_IDENTITY);
+ assert.equal(blocks[1].text, "body");
+});
+
+test("prepend_system_block is idempotent when first block already matches", () => {
+ const body = bodyWithSystem([
+ { type: "text", text: CLAUDE_AGENT_SDK_IDENTITY },
+ { type: "text", text: "body" },
+ ]);
+ const result = runPipeline(body, [
+ { kind: "prepend_system_block", text: CLAUDE_AGENT_SDK_IDENTITY },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks.length, 2);
+ assert.equal(blocks[0].text, CLAUDE_AGENT_SDK_IDENTITY);
+});
+
+// ── Op: append_system_block ────────────────────────────────────────────────
+
+test("append_system_block adds to end and stays idempotent", () => {
+ const body = bodyWithSystem([{ type: "text", text: "body" }]);
+ const op = { kind: "append_system_block", text: "trailer" } as const;
+ let result = runPipeline(body, [op]);
+ result = runPipeline(result.body, [op]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks.length, 2);
+ assert.equal(blocks[1].text, "trailer");
+});
+
+// ── Op: inject_billing_header ──────────────────────────────────────────────
+
+test("inject_billing_header builds ex-machina sdk-cli header at [0]", () => {
+ const body = bodyWithSystem([{ type: "text", text: "body" }], "user prompt here");
+ const result = runPipeline(body, [
+ {
+ kind: "inject_billing_header",
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks[0].type, "text");
+ assert.match(
+ blocks[0].text,
+ /^x-anthropic-billing-header: cc_version=\d+\.\d+\.\d+\.[0-9a-f]{3}; cc_entrypoint=sdk-cli; cch=[0-9a-f]{5};$/
+ );
+});
+
+test("inject_billing_header is idempotent — replaces existing header in place", () => {
+ const body = bodyWithSystem([{ type: "text", text: "body" }], "p1");
+ const op = {
+ kind: "inject_billing_header",
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ } as const;
+ const first = runPipeline(body, [op]);
+ const second = runPipeline(first.body, [op]);
+ const blocks = second.body.system as any[];
+ const headerCount = blocks.filter(
+ (b: any) => typeof b.text === "string" && b.text.startsWith("x-anthropic-billing-header:")
+ ).length;
+ assert.equal(headerCount, 1);
+});
+
+test("inject_billing_header skips when no user message present", () => {
+ const result = applyCcBridgeTransformPipeline(
+ { messages: [], system: [{ type: "text", text: "body" }] } as any,
+ {
+ enabled: true,
+ pipeline: [
+ {
+ kind: "inject_billing_header",
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ },
+ ],
+ }
+ );
+ const blocks = result.body.system as any[];
+ assert.equal(blocks[0].text, "body");
+});
+
+test("inject_billing_header xxhash64-body uses 00000 placeholder", () => {
+ const result = runPipeline(bodyWithSystem([{ type: "text", text: "body" }], "user"), [
+ {
+ kind: "inject_billing_header",
+ entrypoint: "cli",
+ versionFormat: "omniroute-daystamp",
+ cchAlgo: "xxhash64-body",
+ },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.match(blocks[0].text, /cch=00000;$/);
+ assert.match(blocks[0].text, /cc_entrypoint=cli;/);
+});
+
+// ── Algorithm primitives ───────────────────────────────────────────────────
+
+test("extractFirstUserMessageText handles string and block content", () => {
+ assert.equal(extractFirstUserMessageText([{ role: "user", content: "hello" }] as any), "hello");
+ assert.equal(
+ extractFirstUserMessageText([
+ { role: "system", content: "ignore" } as any,
+ { role: "user", content: [{ type: "text", text: "world" }] as any },
+ ]),
+ "world"
+ );
+ assert.equal(extractFirstUserMessageText([] as any), "");
+});
+
+test("computeCchSha256FirstUser yields 5-hex digest", () => {
+ const hex = computeCchSha256FirstUser("hello");
+ assert.match(hex, /^[0-9a-f]{5}$/);
+});
+
+test("computeExMachinaVersionSuffix yields 3-hex digest", () => {
+ const hex = computeExMachinaVersionSuffix(
+ "the quick brown fox jumps",
+ DEFAULT_CLAUDE_CODE_VERSION
+ );
+ assert.match(hex, /^[0-9a-f]{3}$/);
+});
+
+test("computeDaystampVersionSuffix yields 3-hex digest", () => {
+ const hex = computeDaystampVersionSuffix(
+ DEFAULT_CLAUDE_CODE_VERSION,
+ new Date("2026-05-15T00:00:00Z")
+ );
+ assert.match(hex, /^[0-9a-f]{3}$/);
+});
+
+test("buildBillingHeaderValue produces the expected ex-machina format", () => {
+ const value = buildBillingHeaderValue([{ role: "user", content: "hello" }] as any, {
+ entrypoint: "sdk-cli",
+ versionFormat: "ex-machina",
+ cchAlgo: "sha256-first-user",
+ });
+ assert.match(
+ value,
+ /^x-anthropic-billing-header: cc_version=2\.1\.137\.[0-9a-f]{3}; cc_entrypoint=sdk-cli; cch=[0-9a-f]{5};$/
+ );
+});
+
+// ── Disabled config short-circuits ─────────────────────────────────────────
+
+test("applyCcBridgeTransformPipeline does nothing when config.enabled=false", () => {
+ const body = bodyWithSystem([{ type: "text", text: "body" }]);
+ const result = applyCcBridgeTransformPipeline(body, {
+ enabled: false,
+ pipeline: DEFAULT_CC_BRIDGE_PIPELINE,
+ });
+ assert.equal(result.appliedOpKinds.length, 0);
+ assert.equal((result.body.system as any[])[0].text, "body");
+});
+
+// ── Singleton config getters/setters ───────────────────────────────────────
+
+test("setCcBridgeTransformsConfig swaps the runtime config; reset restores defaults", () => {
+ setCcBridgeTransformsConfig({ enabled: false, pipeline: [] });
+ assert.equal(getCcBridgeTransformsConfig().enabled, false);
+ resetCcBridgeTransformsConfig();
+ assert.equal(getCcBridgeTransformsConfig().enabled, true);
+});
+
+// ── Pipeline ordering ──────────────────────────────────────────────────────
+
+test("pipeline ordering is preserved — replace runs before drop", () => {
+ const body = bodyWithSystem([{ type: "text", text: "X" }]);
+ const result = runPipeline(body, [
+ { kind: "replace_text", match: "X", replacement: "github.com/anomalyco/opencode" },
+ { kind: "drop_paragraph_if_contains", needles: ["github.com/anomalyco/opencode"] },
+ ]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks.length, 0);
+});
+
+// ── End-to-end: T4-200 fixture layout ──────────────────────────────────────
+
+test("DEFAULT_CC_BRIDGE_PIPELINE produces T4-200 fixture shape on verbatim OpenCode prompt", () => {
+ // Verbatim phrase from issue #2260 — the v1.7.5 trigger.
+ const fingerprintPhrase =
+ "Here is some useful information about the environment you are running in:";
+ const openCodePrompt = [
+ "You are OpenCode, a coding assistant.",
+ "See github.com/anomalyco/opencode for details.",
+ fingerprintPhrase,
+ "Working directory: /home/dev",
+ "If OpenCode honestly cannot find the answer, say so.",
+ ].join("\n\n");
+
+ const body = {
+ model: "claude-opus-4-7",
+ messages: [{ role: "user", content: [{ type: "text", text: "Say OK." }] }],
+ system: [
+ { type: "text", text: openCodePrompt },
+ { type: "text", text: "Memory protocol block." },
+ { type: "text", text: "Browser MCP block." },
+ ],
+ };
+
+ const result = applyCcBridgeTransformPipeline(body as any, {
+ enabled: true,
+ pipeline: DEFAULT_CC_BRIDGE_PIPELINE,
+ });
+ const blocks = result.body.system as any[];
+
+ // Layout: [billing][identity][sanitized][memory][browser]
+ assert.equal(blocks.length, 5, "expected 5 system blocks");
+ assert.ok(blocks[0].text.startsWith("x-anthropic-billing-header:"));
+ assert.equal(blocks[1].text, CLAUDE_AGENT_SDK_IDENTITY);
+
+ const sanitized = blocks[2].text as string;
+ assert.ok(!sanitized.includes("You are OpenCode"), "identity paragraph should be dropped");
+ assert.ok(
+ !sanitized.includes("github.com/anomalyco/opencode"),
+ "anchor paragraph should be dropped"
+ );
+ assert.ok(!sanitized.includes(fingerprintPhrase), "v1.7.5 phrase should be replaced");
+ assert.ok(
+ sanitized.includes("Environment context you are running in:"),
+ "replacement phrase should be present"
+ );
+ assert.ok(
+ sanitized.includes("Working directory: /home/dev"),
+ "non-fingerprint content preserved"
+ );
+
+ assert.equal(blocks[3].text, "Memory protocol block.");
+ assert.equal(blocks[4].text, "Browser MCP block.");
+
+ // Pipeline reports every op ran.
+ assert.equal(result.appliedOpKinds.length, DEFAULT_CC_BRIDGE_PIPELINE.length);
+});
+
+// ── String system field normalization ──────────────────────────────────────
+
+test("string system field is normalized to a single text block before transforms", () => {
+ const body = {
+ model: "claude-opus-4-7",
+ messages: [{ role: "user", content: "hi" }],
+ system: "raw string system",
+ };
+ const result = runPipeline(body as any, [{ kind: "prepend_system_block", text: "PREFIX" }]);
+ const blocks = result.body.system as any[];
+ assert.equal(blocks[0].text, "PREFIX");
+ assert.equal(blocks[1].text, "raw string system");
+});
diff --git a/tests/unit/system-transforms.test.ts b/tests/unit/system-transforms.test.ts
new file mode 100644
index 0000000000..324d0fcc8f
--- /dev/null
+++ b/tests/unit/system-transforms.test.ts
@@ -0,0 +1,503 @@
+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" }],
+ };
+ // Enable the claude provider explicitly for this test (default is opt-in/disabled).
+ const cfg = {
+ providers: {
+ ...DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers,
+ [PROVIDER_CLAUDE]: {
+ enabled: true,
+ pipeline: DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers[PROVIDER_CLAUDE].pipeline,
+ },
+ },
+ };
+ const result = applySystemTransformPipeline(PROVIDER_CLAUDE, body, cfg);
+ 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" }],
+ };
+ // Enable the claude provider explicitly for this test (default is opt-in/disabled).
+ const cfg = {
+ providers: {
+ ...DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers,
+ [PROVIDER_CLAUDE]: {
+ enabled: true,
+ pipeline: DEFAULT_SYSTEM_TRANSFORMS_CONFIG.providers[PROVIDER_CLAUDE].pipeline,
+ },
+ },
+ };
+ applySystemTransformPipeline(PROVIDER_CLAUDE, body, cfg);
+ 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);
+});
+
+// ────────────────────────────────────────────────────────────────────────────
+// UI ↔ server defaults parity
+// ────────────────────────────────────────────────────────────────────────────
+//
+// The Settings UI keeps a hand-maintained mirror of DEFAULT_SYSTEM_TRANSFORMS_CONFIG
+// in src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx so it can
+// render + reset to defaults without a server roundtrip. The snapshot below is
+// the contract between server and UI — if it drifts, both must be updated in
+// the same commit.
+
+const UI_DEFAULTS_SNAPSHOT = {
+ providers: {
+ claude: {
+ enabled: false,
+ pipeline: [
+ {
+ kind: "drop_paragraph_if_contains",
+ needles: ["github.com/open-webui/open-webui", "openwebui.com", "docs.openwebui.com"],
+ },
+ {
+ kind: "drop_paragraph_if_starts_with",
+ prefixes: ["You are Open WebUI"],
+ },
+ {
+ kind: "obfuscate_words",
+ words: [
+ "opencode",
+ "open-code",
+ "cline",
+ "roo-cline",
+ "roo_cline",
+ "cursor",
+ "windsurf",
+ "aider",
+ "continue.dev",
+ "copilot",
+ "avante",
+ "codecompanion",
+ "openwebui",
+ "open-webui",
+ ],
+ targets: ["system", "messages", "tools"],
+ },
+ ],
+ },
+ "anthropic-compatible-cc": {
+ enabled: true,
+ pipeline: [
+ {
+ kind: "drop_paragraph_if_contains",
+ needles: ["github.com/open-webui/open-webui", "openwebui.com", "docs.openwebui.com"],
+ },
+ {
+ 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",
+ },
+ ],
+ },
+ },
+};
+
+test("defaults parity: DEFAULT_SYSTEM_TRANSFORMS_CONFIG matches the UI mirror snapshot", () => {
+ assert.deepEqual(
+ JSON.parse(JSON.stringify(DEFAULT_SYSTEM_TRANSFORMS_CONFIG)),
+ UI_DEFAULTS_SNAPSHOT,
+ "Server DEFAULT_SYSTEM_TRANSFORMS_CONFIG drifted from the UI mirror in " +
+ "src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx " +
+ "(DEFAULT_SYSTEM_TRANSFORMS_CLIENT). Update both in the same commit."
+ );
+});