Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(openai-compat): support opt-in custom request headers

jonathanwxh-cell62f14341f869
diff --git a/server/claude-accounts.ts b/server/claude-accounts.ts
index f9ae5fcb0a..d74160ba93 100644
--- a/server/claude-accounts.ts
+++ b/server/claude-accounts.ts
@@ -7,6 +7,7 @@ import { z } from "zod";
import { DATA_DIR, persistableInstanceConfigs, type AppConfig } from "./config.ts";
import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
import { addEndpointSchema } from "./openai-compat-endpoints.ts";
+import { customHeadersPatchSchema } from "./drivers/openai-compat-headers.ts";
import { CLAUDE_ACCOUNT_ENV_KEYS, resolveClaudeConfigDir } from "./drivers/claude.ts";
import { resolveCli } from "./procs.ts";
@@ -27,6 +28,8 @@ export const instanceSettingsSchema = z.object({
url: addEndpointSchema.shape.url.optional(),
/** Its new API key; omitted keeps the saved one, unless the URL's host changes. */
apiKey: addEndpointSchema.shape.key.optional(),
+ /** Opt-in outbound HTTP headers with trusted runtime variables, or null to clear. */
+ customHeaders: customHeadersPatchSchema.nullable().optional(),
}).strict().refine((value) => Object.keys(value).length > 0, "No settings supplied");
function rawConfig(entry: InstanceConfig): Record<string, unknown> {
diff --git a/server/config.test.ts b/server/config.test.ts
index 12cc042746..c39cbecced 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -1322,6 +1322,44 @@ describe("Instance CLI override", () => {
(persisted.custom.config as Record<string, unknown>).url = "https://changed.example.test/v1";
expect(cfg.instances!.custom.config).toMatchObject({ url: "https://custom.example.test/v1" });
});
+
+ it("validates openaiCompat.customHeaders in config and propagates them only to non-overridden non-built-in compat instances", () => {
+ const parsed = parseStoredConfig({
+ openaiCompat: {
+ url: "https://gw.example/v1",
+ customHeaders: { enabled: true, headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}" }] },
+ },
+ });
+ expect(parsed.openaiCompat?.customHeaders).toEqual({
+ enabled: true,
+ headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false }],
+ });
+ expect(() => parseConfigPatch({
+ openaiCompat: { customHeaders: { enabled: true, headers: [{ name: "Authorization", value: "Bearer evil" }] } },
+ })).toThrow();
+ expect(() => parseConfigPatch({
+ openaiCompat: { customHeaders: { enabled: true, headers: [{ name: "X-Bad", value: "a\r\nb" }] } },
+ })).toThrow();
+
+ const cfg: AppConfig = {
+ openaiCompat: parsed.openaiCompat,
+ instances: {
+ openaiCompat: { driver: "openai-compat", config: {} },
+ inherited: { driver: "openai-compat" },
+ openai: { driver: "openai-compat", config: { url: "https://api.openai.com/v1", apiKeyEnv: "OMB_OPENAI_API_KEY" } },
+ openrouter: { driver: "openai-compat", config: { url: "https://openrouter.ai/api/v1", apiKeyEnv: "OMB_OPENROUTER_API_KEY" } },
+ "openai-compat-added": { driver: "openai-compat", config: { url: "https://generativelanguage.googleapis.com/v1beta/openai", key: "gemini-key" } },
+ override: { driver: "openai-compat", config: { url: "https://other.example/v1", customHeaders: { enabled: false, headers: [] } } },
+ },
+ };
+ const resolved = instanceConfigs(cfg);
+ expect(resolved.openaiCompat!.config).toMatchObject({ customHeaders: parsed.openaiCompat!.customHeaders });
+ expect(resolved.inherited!.config).toMatchObject({ customHeaders: parsed.openaiCompat!.customHeaders });
+ expect(resolved.openai!.config).not.toHaveProperty("customHeaders");
+ expect(resolved.openrouter!.config).not.toHaveProperty("customHeaders");
+ expect(resolved["openai-compat-added"]!.config).not.toHaveProperty("customHeaders");
+ expect(resolved.override!.config).toMatchObject({ customHeaders: { enabled: false, headers: [] } });
+ });
});
describe("OpenCode Go configuration", () => {
diff --git a/server/config.ts b/server/config.ts
index 08ed3234a7..8469a80b4d 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -30,6 +30,7 @@ import { settledFileCache, settledFileStamp } from "./settled-file.ts";
import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer } from "./mcp-registry.ts"; import { postizKeyHeaders } from "./postiz/connection.ts";
import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schema.ts";
import { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";
+import { applyOpenAiCompatHeaderDefaults, openAiCompatConfigHeadersSchema, type OpenAICompatCustomHeadersConfig } from "./drivers/openai-compat-headers.ts";
import { fishKeyFromLiveKey, liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts"; import { hearingConfigShape } from "./tts/hearing-config.ts";
import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";
import { roomContextSettings } from "./room-context-settings.ts"; import { usageCapsSchema, type UsageCapsConfig } from "./usage-caps-config.ts";
@@ -338,9 +339,7 @@ const appConfigSchema = z.object({
})
.optional(),
/** `model` seeds the default selection; `provider` pins an OpenRouter upstream (e.g. "fireworks"). */
- openaiCompat: z
- .object({ key: optionalText, url: optionalText, model: optionalText, provider: optionalText })
- .optional(),
+ openaiCompat: z.object({ key: optionalText, url: optionalText, model: optionalText, provider: optionalText, customHeaders: openAiCompatConfigHeadersSchema.optional() }).optional(),
/** Composio project key; `userId`/`sessionId` reuse one Composio Session. */
composio: z.object({ apiKey: optionalText, userId: optionalText, sessionId: optionalText }).optional(),
box: z.object({ token: optionalText }).optional(),
@@ -449,7 +448,7 @@ export interface AppConfig extends HelperConfig {
loopGuard?: LoopGuardConfig;
safetyFloor?: { enabled?: boolean };
billing?: { currency?: string; prices?: Record<string, { inputPerMillion: number; outputPerMillion: number; cachedInputPerMillion?: number }> };
- openaiCompat?: { key?: string; url?: string; model?: string; provider?: string };
+ openaiCompat?: { key?: string; url?: string; model?: string; provider?: string; customHeaders?: OpenAICompatCustomHeadersConfig };
composio?: { apiKey?: string; userId?: string; sessionId?: string };
/** Boat token (ascii.dev renamed Box to Boat); config key "box", env BOX_TOKEN. */
box?: { token?: string };
@@ -1179,16 +1178,16 @@ export function instanceConfigs(cfg: AppConfig): InstanceConfigMap {
if (cfg.openaiCompat.url) defaults.url = cfg.openaiCompat.url;
if (cfg.openaiCompat.model) defaults.model = cfg.openaiCompat.model;
if (cfg.openaiCompat.provider) defaults.provider = cfg.openaiCompat.provider;
- if (Object.keys(defaults).length) {
+ if (Object.keys(defaults).length || (!ownsRouting && cfg.openaiCompat.customHeaders)) {
const raw = entry.config;
- const current =
- typeof raw === "object" && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
+ const current = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
const merged = { ...current };
for (const [k, v] of Object.entries(defaults)) {
// An empty provider means "no upstream pin"; never fill it from the workspace.
if (k === "provider" && typeof merged[k] === "string") continue;
if (typeof merged[k] !== "string" || !(merged[k] as string).trim()) merged[k] = v;
}
+ applyOpenAiCompatHeaderDefaults(merged, ownsRouting ? undefined : cfg.openaiCompat.customHeaders);
entry.config = merged;
}
}
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 15b3fc52a5..a228c2d809 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -1,15 +1,8 @@
import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";
import { createHash } from "node:crypto";
-import type {
- DriverCreateInput,
- ModelCatalog,
- ProviderInstance, ProviderSnapshot,
- RuntimeEvent,
- RuntimeEventListener,
- SendTurnInput,
- TextGenerationOptions,
-} from "../contracts.ts";
+import type { DriverCreateInput, ModelCatalog, ProviderInstance, ProviderSnapshot, RuntimeEvent, RuntimeEventListener, SendTurnInput, TextGenerationOptions } from "../contracts.ts";
import { newEventId, newId } from "../contracts.ts";
+import { CustomHeaderError, customHeaderSecrets, resolveCustomHeaders, type OpenAICompatCustomHeadersConfig, type RuntimeHeaderContext } from "./openai-compat-headers.ts";
import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQuestions, questionChoices } from "../../shared/ask-question.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
@@ -96,6 +89,7 @@ interface RuntimeOptions<Config> {
missingKeyError: string;
unavailableReason: string;
timeoutMs: number;
+ customHeaders?: OpenAICompatCustomHeadersConfig;
/** Ask a server on this machine or network for its models this often while a reply is pending, and stop the reply
* when it misses LIVENESS_MISSES checks in a row: it crashed, froze or left the network. */
livenessEveryMs?: number;
@@ -257,7 +251,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string,
+ onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string, headerContext?: RuntimeHeaderContext,
): Promise<Completion> => {
const timeoutController = new AbortController();
let idleTimer: NodeJS.Timeout | null = null;
@@ -287,10 +281,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
...(tools.length ? { tools } : {}),
});
const send = options.timeoutMs > FETCH_LIMIT_MS ? fetchPastLimit : fetch;
+ const customHeaders = options.customHeaders ? resolveCustomHeaders(options.customHeaders, headerContext ?? { threadId, providerInstanceId: input.instanceId }) : undefined;
const response = await send(`${options.apiUrl}/${route === "responses" ? "responses" : "chat/completions"}`, {
method: "POST",
...(messages.some(message => Array.isArray(message.content) && message.content.some(part => part.type === "image_url")) ? { redirect: "error" as const } : {}),
- headers: { authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
+ headers: { ...customHeaders, authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
body: payload,
signal: activeSignal,
});
@@ -462,7 +457,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string,
+ onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string, headerContext?: RuntimeHeaderContext,
): Promise<Completion> => {
for (;;) {
let replied = false;
@@ -470,7 +465,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
return await completeOn(routes.routeFor(model, tools.length > 0), messages, model, stream, signal, onDelta && ((text, kind) => {
replied = true;
onDelta(text, kind);
- }), tools, onUsage, variant, threadId);
+ }), tools, onUsage, variant, threadId, headerContext);
} catch (error) {
if (!(error instanceof ModelRouteRefused) || replied || signal?.aborted) throw error;
if (!routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));
@@ -524,7 +519,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const retainImages = chatImageBudget();
let model = turn.model || options.models().default;
const maskable = (value: unknown): value is string => typeof value === "string" && value.length >= 8; // a short placeholder key ("1") would redact every match
- const secrets = [options.apiKey].filter(maskable);
+ const headerContext: RuntimeHeaderContext = { threadId: turn.threadId, botId: turn.botId, turnId, providerInstanceId: input.instanceId };
+ const secrets = [...[options.apiKey].filter(maskable), ...customHeaderSecrets(options.customHeaders, headerContext)];
for (const integration of Object.values(turn.integrations ?? {})) {
const entries = object(integration);
const specs = entries && "command" in entries ? [entries] : Object.values(entries ?? {}).map(object);
@@ -661,7 +657,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (streamKind === "assistant_text") answerStreamed = true;
const shown = holdback && streamKind === "assistant_text" ? holdback.feed(text) : text;
if (shown) delta(shown, streamKind);
- }, tools.definitions, undefined, turn.variant, turn.threadId);
+ }, tools.definitions, undefined, turn.variant, turn.threadId, headerContext);
// A reply cut off at the token limit may be a call cut short; running half of one is worse than saying so.
const written = holdback && !completion.toolCalls.length && completion.finishReason !== "length" ? textToolCalls(completion.text, tools.definitions) : null;
unreadable = written?.kind === "unreadable" && !askedAgain;
@@ -723,7 +719,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
// Never replay a handled call. A stream closed before any completion marker ran nothing upstream, so it may resend even where the caller never opted into retries.
const truncation = error instanceof StreamTruncatedError, retryScale = truncation ? options.retryScale ?? 1 : options.retryScale;
- if (retryScale === undefined || abort.signal.aborted || streamed || seenCalls.size || error instanceof RuntimeNoticeError || (!truncation && (error instanceof ChatProtocolError || !verdict.transient)) || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
+ if (retryScale === undefined || abort.signal.aborted || streamed || seenCalls.size || error instanceof RuntimeNoticeError || error instanceof CustomHeaderError || (!truncation && (error instanceof ChatProtocolError || !verdict.transient)) || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
const delayMs = computeBackoff(attempt++);
emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: truncation ? "stream_truncated" : verdict.reason });
await interruptibleDelay(delayMs * retryScale, abort.signal).promise;
@@ -986,7 +982,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const model = named ?? options.generateModel?.() ?? options.models().default;
signal?.throwIfAborted();
checkModel?.(model);
- const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage);
+ const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, undefined, { providerInstanceId: input.instanceId });
if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
return text.trim() ? text : reasoning;
},
diff --git a/server/drivers/openai-compat-headers.test.ts b/server/drivers/openai-compat-headers.test.ts
new file mode 100644
index 0000000000..067c27fd7c
--- /dev/null
+++ b/server/drivers/openai-compat-headers.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ CustomHeaderError,
+ CustomHeaderValidationError,
+ customHeaderSecrets,
+ decodeCustomHeaders,
+ mergeCustomHeadersPatch,
+ resolveCustomHeaders,
+ summarizeCustomHeaders,
+} from "./openai-compat-headers.ts";
+
+describe("OpenAI-compatible custom headers config & resolution", () => {
+ it("normalizes record and rule-array shapes and validates names, duplicates, protected headers, CR/LF, and variables", () => {
+ expect(decodeCustomHeaders({
+ enabled: true,
+ headers: {
+ "X-Maus-Thread-ID": "{threadId}",
+ "X-Maus-Bot-ID": "{botId}",
+ "X-Maus-Turn-ID": "{turnId}",
+ "X-Provider": "{providerInstanceId}",
+ "X-Gateway-Client": "maus",
+ },
+ })).toEqual({
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
+ { name: "X-Maus-Bot-ID", value: "{botId}", required: true, secret: false },
+ { name: "X-Maus-Turn-ID", value: "{turnId}", required: true, secret: false },
+ { name: "X-Provider", value: "{providerInstanceId}", required: true, secret: false },
+ { name: "X-Gateway-Client", value: "maus", required: true, secret: false },
+ ],
+ });
+
+ for (const badName of ["", "Bad Name", "X:Header", "X\r\nInject", "Authorization", "authorization", "Content-Type", "Proxy-Authorization", "Host", "Cookie", "Transfer-Encoding"]) {
+ expect(() => decodeCustomHeaders({ enabled: true, headers: [{ name: badName, value: "ok" }] })).toThrow(CustomHeaderValidationError);
+ }
+
+ expect(() => decodeCustomHeaders({
+ enabled: true,
+ headers: [{ name: "X-Thread", value: "{threadId}" }, { name: "x-thread", value: "{botId}" }],
+ })).toThrow(/duplicate/i);
+
+ for (const badValue of ["", " ", "val\r\nX-Inject: 1", "val\nnext", "val\0zero", "{unknownVar}", "prefix-{thredId}"]) {
+ expect(() => decodeCustomHeaders({ enabled: true, headers: [{ name: "X-Ok", value: badValue }] })).toThrow(CustomHeaderValidationError);
+ }
+ });
+
+ it("preserves disabled behavior, performs single-pass substitution, and handles required vs optional variables cleanly", () => {
+ const off = decodeCustomHeaders({ enabled: false, headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}" }] });
+ expect(resolveCustomHeaders(off, {})).toEqual({});
+
+ const on = decodeCustomHeaders({
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "thread:{threadId}", required: true },
+ { name: "X-Maus-Bot-ID", value: "{botId}", required: false },
+ { name: "X-Maus-Turn-ID", value: "{turnId}", required: true },
+ { name: "X-Provider-ID", value: "{providerInstanceId}" },
+ ],
+ });
+ expect(resolveCustomHeaders(on, {
+ threadId: "{botId}",
+ turnId: "turn-1",
+ providerInstanceId: "openai-compat-1",
+ })).toEqual({
+ "X-Maus-Thread-ID": "thread:{botId}",
+ "X-Maus-Turn-ID": "turn-1",
+ "X-Provider-ID": "openai-compat-1",
+ });
+
+ expect(() => resolveCustomHeaders(on, { turnId: "turn-1", providerInstanceId: "openai-compat-1" }))
+ .toThrow(CustomHeaderError);
+ expect(() => resolveCustomHeaders(on, { threadId: "t1\r\nInject: 1", turnId: "turn-1", providerInstanceId: "p1" }))
+ .toThrow(CustomHeaderError);
+ });
+
+ it("auto-detects sensitive headers, redacts summaries, preserves keepExisting secrets on patch, and collects log secrets", () => {
+ const config = decodeCustomHeaders({
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}" },
+ { name: "X-Gateway-Token", value: "gw-tok-secret-123456" },
+ { name: "X-Tenant-Pin", value: "pin-987654", secret: true },
+ ],
+ });
+ expect(summarizeCustomHeaders(config)).toEqual({
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", configured: true, required: true, secret: false },
+ { name: "X-Gateway-Token", configured: true, required: true, secret: true },
+ { name: "X-Tenant-Pin", configured: true, required: true, secret: true },
+ ],
+ });
+ expect(customHeaderSecrets(config, { threadId: "thr-1" })).toEqual([
+ "gw-tok-secret-123456",
+ "pin-987654",
+ ]);
+
+ const merged = mergeCustomHeadersPatch({
+ enabled: true,
+ headers: [
+ { name: "X-Gateway-Token", keepExisting: true, secret: true },
+ { name: "X-Maus-Thread-ID", value: "{threadId}" },
+ ],
+ }, config);
+ expect(merged).toEqual({
+ enabled: true,
+ headers: [
+ { name: "X-Gateway-Token", value: "gw-tok-secret-123456", required: true, secret: true },
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
+ ],
+ });
+ expect(() => mergeCustomHeadersPatch({
+ enabled: true,
+ headers: [{ name: "X-Missing-Secret", keepExisting: true, secret: true }],
+ }, config)).toThrow(CustomHeaderValidationError);
+
+ expect(() => mergeCustomHeadersPatch({
+ enabled: true,
+ headers: [{ name: "X-Tenant-Pin", keepExisting: true, secret: false }],
+ }, config)).toThrow(CustomHeaderValidationError);
+
+ const nonSecretBase = decodeCustomHeaders({
+ enabled: true,
+ headers: [{ name: "X-Env", value: "prod", secret: false }],
+ });
+ expect(mergeCustomHeadersPatch({
+ enabled: true,
+ headers: [{ name: "X-Env", keepExisting: true }],
+ }, nonSecretBase)).toEqual({
+ enabled: true,
+ headers: [{ name: "X-Env", value: "prod", required: true, secret: false }],
+ });
+
+ const dynamicSecrets = decodeCustomHeaders({
+ enabled: true,
+ headers: [
+ { name: "X-Short-Pin", value: "pass", secret: true },
+ { name: "X-Templated-Secret", value: "tok-{threadId}", secret: true },
+ ],
+ });
+ expect(customHeaderSecrets(dynamicSecrets, { threadId: "thread-99" })).toEqual(["tok-thread-99"]);
+ expect(customHeaderSecrets(dynamicSecrets, { threadId: "1" })).toEqual([]);
+ });
+});
diff --git a/server/drivers/openai-compat-headers.ts b/server/drivers/openai-compat-headers.ts
new file mode 100644
index 0000000000..5e1c2726b4
--- /dev/null
+++ b/server/drivers/openai-compat-headers.ts
@@ -0,0 +1,315 @@
+import { z } from "zod";
+import { holdsCredential } from "../../shared/redact.ts";
+import { isSecretName } from "../redact.ts";
+
+export const RUNTIME_HEADER_VARIABLES = ["threadId", "botId", "turnId", "providerInstanceId"] as const;
+export type RuntimeHeaderVariable = (typeof RUNTIME_HEADER_VARIABLES)[number];
+
+export interface RuntimeHeaderContext {
+ threadId?: string;
+ botId?: string;
+ turnId?: string;
+ providerInstanceId?: string;
+}
+
+export interface OpenAICompatCustomHeaderRule {
+ name: string;
+ value: string;
+ required: boolean;
+ secret: boolean;
+}
+
+export interface OpenAICompatCustomHeadersConfig {
+ enabled: boolean;
+ headers: OpenAICompatCustomHeaderRule[];
+}
+
+export interface OpenAICompatCustomHeaderSummary {
+ name: string;
+ value?: string;
+ configured: boolean;
+ required: boolean;
+ secret: boolean;
+}
+
+export interface OpenAICompatCustomHeadersSummary {
+ enabled: boolean;
+ headers: OpenAICompatCustomHeaderSummary[];
+}
+
+export class CustomHeaderValidationError extends Error {
+ readonly status = 400;
+ constructor(message: string) {
+ super(message);
+ this.name = "CustomHeaderValidationError";
+ }
+}
+
+export class CustomHeaderError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "CustomHeaderError";
+ }
+}
+
+const MIN_MASKABLE_SECRET_LENGTH = 8;
+const MAX_CUSTOM_HEADERS = 32;
+const MAX_HEADER_NAME_LENGTH = 128;
+const MAX_HEADER_VALUE_LENGTH = 2048;
+const HEADER_TOKEN_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+const CONTROL_CHARS = /\p{Cc}/u;
+const PLACEHOLDER_RE = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
+const PLACEHOLDER_TEST = /\{[A-Za-z_][A-Za-z0-9_]*\}/;
+const KNOWN_VARS = new Set<string>(RUNTIME_HEADER_VARIABLES);
+const PROTECTED_HEADERS = new Set([
+ "authorization",
+ "proxy-authorization",
+ "content-type",
+ "content-length",
+ "host",
+ "connection",
+ "keep-alive",
+ "transfer-encoding",
+ "te",
+ "trailer",
+ "upgrade",
+ "cookie",
+ "set-cookie",
+ "origin",
+ "referer",
+ "accept-encoding",
+]);
+
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function isSensitiveHeader(rule: Pick<OpenAICompatCustomHeaderRule, "name" | "value" | "secret">): boolean {
+ return rule.secret === true || isSecretName(rule.name) || holdsCredential(rule.value);
+}
+
+function validateHeaderName(raw: unknown): string {
+ if (typeof raw !== "string") throw new CustomHeaderValidationError("Header name must be a string.");
+ const name = raw.trim();
+ if (!name || name.length > MAX_HEADER_NAME_LENGTH || CONTROL_CHARS.test(name) || !HEADER_TOKEN_NAME.test(name)) {
+ throw new CustomHeaderValidationError(`Invalid HTTP header name "${name || raw}".`);
+ }
+ if (PROTECTED_HEADERS.has(name.toLowerCase())) {
+ throw new CustomHeaderValidationError(`Header "${name}" is protected and cannot be overridden.`);
+ }
+ return name;
+}
+
+function validateHeaderValue(raw: unknown, name: string): string {
+ if (typeof raw !== "string") throw new CustomHeaderValidationError(`Header "${name}" value must be a string.`);
+ if (CONTROL_CHARS.test(raw)) {
+ throw new CustomHeaderValidationError(`Header "${name}" value cannot contain CR, LF, or control characters.`);
+ }
+ const value = raw.trim();
+ if (!value) throw new CustomHeaderValidationError(`Header "${name}" value cannot be empty.`);
+ if (value.length > MAX_HEADER_VALUE_LENGTH) {
+ throw new CustomHeaderValidationError(`Header "${name}" value exceeds ${MAX_HEADER_VALUE_LENGTH} characters.`);
+ }
+ for (const match of value.matchAll(PLACEHOLDER_RE)) {
+ if (!KNOWN_VARS.has(match[1]!)) {
+ throw new CustomHeaderValidationError(
+ `Header "${name}" references unknown runtime variable "{${match[1]}}". Supported: ${RUNTIME_HEADER_VARIABLES.map((v) => `{${v}}`).join(", ")}.`,
+ );
+ }
+ }
+ return value;
+}
+
+function normalizeEntries(rawHeaders: unknown): Array<Record<string, unknown>> {
+ if (rawHeaders === undefined) return [];
+ if (Array.isArray(rawHeaders)) {
+ if (rawHeaders.length > MAX_CUSTOM_HEADERS) {
+ throw new CustomHeaderValidationError(`Use at most ${MAX_CUSTOM_HEADERS} custom headers.`);
+ }
+ return rawHeaders.map((entry) => {
+ if (!isPlainRecord(entry)) throw new CustomHeaderValidationError("Each custom header must be an object.");
+ return entry;
+ });
+ }
+ if (isPlainRecord(rawHeaders)) {
+ const entries = Object.entries(rawHeaders);
+ if (entries.length > MAX_CUSTOM_HEADERS) {
+ throw new CustomHeaderValidationError(`Use at most ${MAX_CUSTOM_HEADERS} custom headers.`);
+ }
+ return entries.map(([name, value]) => ({ name, value }));
+ }
+ throw new CustomHeaderValidationError("customHeaders.headers must be an array or object map.");
+}
+
+export function decodeCustomHeaders(raw: unknown): OpenAICompatCustomHeadersConfig {
+ if (!isPlainRecord(raw)) throw new CustomHeaderValidationError("customHeaders must be an object.");
+ if (typeof raw.enabled !== "boolean") throw new CustomHeaderValidationError("customHeaders.enabled must be a boolean.");
+ const seen = new Set<string>();
+ const headers: OpenAICompatCustomHeaderRule[] = [];
+ for (const entry of normalizeEntries(raw.headers)) {
+ const name = validateHeaderName(entry.name);
+ const lower = name.toLowerCase();
+ if (seen.has(lower)) throw new CustomHeaderValidationError(`Duplicate custom header name "${name}".`);
+ seen.add(lower);
+ if (entry.required !== undefined && typeof entry.required !== "boolean") {
+ throw new CustomHeaderValidationError(`Header "${name}" required flag must be a boolean.`);
+ }
+ if (entry.secret !== undefined && typeof entry.secret !== "boolean") {
+ throw new CustomHeaderValidationError(`Header "${name}" secret flag must be a boolean.`);
+ }
+ const value = validateHeaderValue(entry.value, name);
+ const rule: OpenAICompatCustomHeaderRule = {
+ name,
+ value,
+ required: entry.required !== false,
+ secret: entry.secret === true || isSecretName(name) || holdsCredential(value),
+ };
+ headers.push(rule);
+ }
+ return { enabled: raw.enabled, headers };
+}
+
+export function mergeCustomHeadersPatch(
+ patch: unknown,
+ previous?: OpenAICompatCustomHeadersConfig,
+): OpenAICompatCustomHeadersConfig {
+ if (!isPlainRecord(patch)) throw new CustomHeaderValidationError("customHeaders must be an object.");
+ if (typeof patch.enabled !== "boolean") throw new CustomHeaderValidationError("customHeaders.enabled must be a boolean.");
+ const prevByName = new Map((previous?.headers ?? []).map((entry) => [entry.name.toLowerCase(), entry]));
+ const rawEntries = normalizeEntries(patch.headers);
+ const resolved = rawEntries.map((entry) => {
+ const name = validateHeaderName(entry.name);
+ const keepExisting = entry.keepExisting === true || (entry.value === undefined && entry.secret === true);
+ if (keepExisting && (entry.value === undefined || entry.value === "")) {
+ const prior = prevByName.get(name.toLowerCase());
+ if (!prior) {
+ throw new CustomHeaderValidationError(`Header "${name}" has no saved secret value to keep; enter a value.`);
+ }
+ if (isSensitiveHeader(prior) && entry.secret === false) {
+ throw new CustomHeaderValidationError(
+ `Header "${name}" has a saved secret value; enter a new value to mark it non-secret.`,
+ );
+ }
+ return {
+ name,
+ value: prior.value,
+ required: entry.required ?? prior.required,
+ secret: entry.secret ?? prior.secret,
+ };
+ }
+ return {
+ name,
+ value: entry.value,
+ ...(entry.required !== undefined ? { required: entry.required } : {}),
+ ...(entry.secret !== undefined ? { secret: entry.secret } : {}),
+ };
+ });
+ return decodeCustomHeaders({ enabled: patch.enabled, headers: resolved });
+}
+
+export function summarizeCustomHeaders(raw: unknown): OpenAICompatCustomHeadersSummary | undefined {
+ let decoded: OpenAICompatCustomHeadersConfig;
+ try {
+ decoded = decodeCustomHeaders(raw);
+ } catch {
+ return undefined;
+ }
+ return {
+ enabled: decoded.enabled,
+ headers: decoded.headers.map((rule) => {
+ const sensitive = isSensitiveHeader(rule);
+ return {
+ name: rule.name,
+ ...(sensitive ? {} : { value: rule.value }),
+ configured: true,
+ required: rule.required,
+ secret: sensitive,
+ };
+ }),
+ };
+}
+
+export function resolveCustomHeaders(
+ config: OpenAICompatCustomHeadersConfig | undefined,
+ context: RuntimeHeaderContext,
+): Record<string, string> {
+ if (!config?.enabled || config.headers.length === 0) return {};
+ const resolved: Record<string, string> = {};
+ for (const rule of config.headers) {
+ let missingVar: string | null = null;
+ const value = rule.value.replace(PLACEHOLDER_RE, (_whole, key: string) => {
+ const raw = context[key as RuntimeHeaderVariable];
+ const text = typeof raw === "string" ? raw.trim() : "";
+ if (!text) {
+ missingVar ??= key;
+ return "";
+ }
+ return text;
+ });
+ if (missingVar) {
+ if (rule.required !== false) {
+ throw new CustomHeaderError(
+ `Cannot send required custom header "${rule.name}": runtime variable "{${missingVar}}" is unavailable for this request.`,
+ );
+ }
+ continue;
+ }
+ if (CONTROL_CHARS.test(value)) {
+ throw new CustomHeaderError(`Cannot send custom header "${rule.name}": resolved value contains unsafe control characters.`);
+ }
+ resolved[rule.name] = value;
+ }
+ return resolved;
+}
+
+export function customHeaderSecrets(
+ config: OpenAICompatCustomHeadersConfig | undefined,
+ context: RuntimeHeaderContext,
+): string[] {
+ if (!config?.enabled || config.headers.length === 0) return [];
+ const out = new Set<string>();
+ for (const rule of config.headers) {
+ if (!isSensitiveHeader(rule)) continue;
+ if (!PLACEHOLDER_TEST.test(rule.value) && rule.value.length >= MIN_MASKABLE_SECRET_LENGTH) {
+ out.add(rule.value);
+ }
+ try {
+ const one = resolveCustomHeaders({ enabled: true, headers: [rule] }, context)[rule.name];
+ if (one && one.length >= MIN_MASKABLE_SECRET_LENGTH) out.add(one);
+ } catch {
+ // Missing optional/required runtime var here simply has no resolved secret to register.
+ }
+ }
+ return [...out];
+}
+
+export function applyOpenAiCompatHeaderDefaults(
+ merged: Record<string, unknown>,
+ defaults: OpenAICompatCustomHeadersConfig | undefined,
+): void {
+ if (defaults && merged.customHeaders === undefined) {
+ merged.customHeaders = defaults;
+ }
+}
+
+export const openAiCompatConfigHeadersSchema: z.ZodType<OpenAICompatCustomHeadersConfig> = z.unknown().transform((val, ctx) => {
+ try {
+ return decodeCustomHeaders(val);
+ } catch (error) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: error instanceof Error ? error.message : String(error) });
+ return z.NEVER;
+ }
+});
+
+const patchEntrySchema = z.object({
+ name: z.string(),
+ value: z.string().optional(),
+ keepExisting: z.boolean().optional(),
+ required: z.boolean().optional(),
+ secret: z.boolean().optional(),
+}).strict();
+
+export const customHeadersPatchSchema = z.object({
+ enabled: z.boolean(),
+ headers: z.union([z.array(patchEntrySchema).max(MAX_CUSTOM_HEADERS), z.record(z.string(), z.string())]).default([]),
+}).strict();
diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.ts
index 1a6c215f64..27533517eb 100644
--- a/server/drivers/openai-compat.test.ts
+++ b/server/drivers/openai-compat.test.ts
@@ -1334,3 +1334,114 @@ describe("how long a turn waits for a reply", () => {
});
});
+describe("opt-in custom OpenAI-compatible request headers", () => {
+ it("preserves standard headers when disabled and injects per-thread/bot/turn/provider headers consistently across threads, compaction, retries, non-streaming, and secret scrubbing", async () => {
+ const seenRequests: Array<{ url: string; headers: Record<string, string>; body: Record<string, unknown> }> = [];
+ let chatAttempt = 0;
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL, init?: RequestInit) => {
+ const target = String(url);
+ if (target.endsWith("/models")) return Response.json({ data: [] });
+ const rawHeaders = Object.fromEntries(new Headers(init?.headers).entries());
+ seenRequests.push({ url: target, headers: rawHeaders, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> });
+ chatAttempt++;
+ if (chatAttempt === 4) {
+ return new Response("", { status: 200, headers: { "content-type": "text/event-stream" } });
+ }
+ if (JSON.parse(String(init?.body ?? "{}")).stream === false) {
+ return new Response(JSON.stringify({ choices: [{ message: { content: "non-stream ok" }, finish_reason: "stop" }] }), { headers: { "content-type": "application/json" } });
+ }
+ return new Response(
+ `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "ok gw-secret-token-xyz " } }] })}\n\n` +
+ `data: ${JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1 } })}\n\n`,
+ { headers: { "content-type": "text/event-stream" } },
+ );
+ }));
+
+ // 1. Disabled by default: standard headers only
+ const offInst = await OpenAICompatDriver.create({
+ instanceId: "gw-off", displayName: "Off", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({
+ url: "https://gw.example/v1", model: "m1",
+ customHeaders: { enabled: false, headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}" }] },
+ }),
+ environment: { OPENAI_COMPAT_API_KEY: "test-api-key-123456" },
+ });
+ const recOff = recordEvents(offInst.adapter);
+ await offInst.adapter.sendTurn({ threadId: "t-off", botId: "b1", text: "hi" });
+ await recOff.until((e) => e.type === "turn.completed");
+ expect(seenRequests[0]!.headers["x-maus-thread-id"]).toBeUndefined();
+ recOff.stop();
+ await offInst.dispose();
+
+ // 2. Enabled: two separate threads -> distinct headers; second turn / compacted turn on thread-1 keeps same threadId; retry preserves turnId
+ const onInst = await OpenAICompatDriver.create({
+ instanceId: "gw-on", displayName: "On", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({
+ url: "https://gw.example/v1", model: "m1",
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true },
+ { name: "X-Maus-Bot-ID", value: "{botId}", required: false },
+ { name: "X-Maus-Turn-ID", value: "{turnId}", required: false },
+ { name: "X-Provider-ID", value: "{providerInstanceId}", required: true },
+ { name: "X-Gateway-Token", value: "gw-secret-token-xyz", secret: true },
+ ],
+ },
+ }),
+ environment: { OPENAI_COMPAT_API_KEY: "test-api-key-123456" },
+ });
+ const recOn = recordEvents(onInst.adapter);
+ const completedCount = () => recOn.events.filter((e) => e.type === "turn.completed").length;
+ await onInst.adapter.sendTurn({ threadId: "thread-alpha", botId: "bot-one", text: "first" });
+ await recOn.until(() => completedCount() >= 1);
+ await onInst.adapter.sendTurn({ threadId: "thread-beta", botId: "bot-two", text: "second" });
+ await recOn.until(() => completedCount() >= 2);
+ await onInst.adapter.sendTurn({ threadId: "thread-alpha", botId: "bot-one", text: "compacted", transcript: [{ role: "user", text: "summary" }] });
+ await recOn.until(() => completedCount() >= 3);
+
+ const chatReqs = seenRequests.slice(1);
+ expect(chatReqs[0]!.headers["x-maus-thread-id"]).toBe("thread-alpha");
+ expect(chatReqs[0]!.headers["x-maus-bot-id"]).toBe("bot-one");
+ expect(chatReqs[0]!.headers["x-provider-id"]).toBe("gw-on");
+ expect(chatReqs[0]!.headers["x-gateway-token"]).toBe("gw-secret-token-xyz");
+ expect(chatReqs[1]!.headers["x-maus-thread-id"]).toBe("thread-beta");
+ // chatAttempt === 4 was truncated, so retried once on attempt 5 for thread-alpha: same turnId!
+ expect(chatReqs[2]!.headers["x-maus-thread-id"]).toBe("thread-alpha");
+ expect(chatReqs[3]!.headers["x-maus-thread-id"]).toBe("thread-alpha");
+ expect(chatReqs[2]!.headers["x-maus-turn-id"]).toBe(chatReqs[3]!.headers["x-maus-turn-id"]);
+ // Echoed sensitive custom header value must be scrubbed from streamed deltas.
+ const completed = recOn.events.filter((e) => e.type === "item.completed");
+ expect(completed.some((e) => JSON.stringify(e).includes("gw-secret-token-xyz"))).toBe(false);
+ expect(completed.some((e) => JSON.stringify(e).includes("[redacted]"))).toBe(true);
+
+ // 3. Non-streaming generateText without threadId fails cleanly when {threadId} is required, never sending an empty header
+ const countBeforeFail = seenRequests.length;
+ await expect(onInst.generateText!("summarize")).rejects.toThrow(/threadId/);
+ expect(seenRequests).toHaveLength(countBeforeFail);
+
+ // Non-streaming generateText with optional {threadId} omits it cleanly and still sends static/{providerInstanceId} headers
+ const optInst = await OpenAICompatDriver.create({
+ instanceId: "gw-opt", displayName: "Opt", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({
+ url: "https://gw.example/v1", model: "m1",
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: false },
+ { name: "X-Gateway-Client", value: "maus", required: true },
+ ],
+ },
+ }),
+ environment: { OPENAI_COMPAT_API_KEY: "test-api-key-123456" },
+ });
+ await expect(optInst.generateText!("summarize")).resolves.toBe("non-stream ok");
+ const nonStreamReq = seenRequests.at(-1)!;
+ expect(nonStreamReq.headers["x-gateway-client"]).toBe("maus");
+ expect(nonStreamReq.headers["x-maus-thread-id"]).toBeUndefined();
+ await optInst.dispose();
+ recOn.stop();
+ await onInst.dispose();
+ });
+});
+
diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.ts
index 8e93e89df0..a57c222e81 100644
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@ -7,6 +7,7 @@ import { lmStudioV1Catalog } from "./local-inject.ts";
import { isContextName, isOllama, pickedName, serveWithWindow } from "./ollama-context.ts";
import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, thinkingEffort, type OllamaModel, type OllamaStatus } from "./ollama.ts";
import { createOpenAIChatRuntime } from "./openai-chat.ts";
+import { decodeCustomHeaders, type OpenAICompatCustomHeadersConfig } from "./openai-compat-headers.ts";
import { decodeReasoningEfforts, reasoningBody, reasoningCatalog, reasoningChoices, rememberReasoning, waitForCatalog, type ReasoningChoices } from "./compat-reasoning.ts";
import {
freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,
@@ -106,6 +107,8 @@ export interface OpenAICompatConfig {
reasoningEfforts?: Record<string, string[]>;
/** How long a turn waits for the next piece of a reply before giving up; unset follows the server's default. */
replyWaitMinutes?: number;
+ /** Opt-in outbound HTTP headers with trusted runtime variables such as {threadId}. */
+ customHeaders?: OpenAICompatCustomHeadersConfig;
}
const CATALOGS = ["openai", "lmstudio", "ollama"] as const;
@@ -169,6 +172,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {
...(config.managedModels ? { managedModels: config.managedModels as string[] } : {}),
...(reasoningEfforts ? { reasoningEfforts } : {}),
...(isReplyWait(config.replyWaitMinutes) ? { replyWaitMinutes: config.replyWaitMinutes } : {}),
+ ...(config.customHeaders !== undefined ? { customHeaders: decodeCustomHeaders(config.customHeaders) } : {}),
url: (typeof config.url === "string" && config.url ? config.url : envUrl || "https://openrouter.ai/api/v1")
.replace(/\/+$/, ""),
apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv
@@ -432,6 +436,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
missingKeyError: missingKey,
unavailableReason: missingKey,
timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),
+ ...(config.customHeaders ? { customHeaders: config.customHeaders } : {}),
...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),
reasoning: true,
billing: "metered",
diff --git a/server/index.ts b/server/index.ts
index a91036467f..7af409cdd9 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -9,7 +9,7 @@ import { existsSync, realpathSync, rmSync } from "node:fs";
import { homedir } from "node:os";
import { rm as removeDirectory } from "node:fs/promises";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
-import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts"; import { startToolResultsSweep } from "./host/tool-results-sweep.ts";
+import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts"; import { startToolResultsSweep } from "./host/tool-results-sweep.ts"; import { openAiCompatSummaryFields, summarizeCustomHeaders } from "./openai-compat-endpoints.ts";
import { basename, join } from "node:path";
import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";
import { z } from "zod";
@@ -11580,7 +11580,7 @@ function configStatus() {
billing: { currency: cfg.billing?.currency ?? "USD", prices: cfg.billing?.prices ?? {} },
decisions: { retentionDays: decisionRetentionDays(cfg.decisions?.retentionDays) },
safetyFloor: { enabled: safetyFloorOn() },
- openaiCompat: { ...keyStatus(cfg.openaiCompat?.key), url: cfg.openaiCompat?.url ?? "" },
+ openaiCompat: { ...keyStatus(cfg.openaiCompat?.key), url: cfg.openaiCompat?.url ?? "", ...(cfg.openaiCompat?.customHeaders ? { customHeaders: summarizeCustomHeaders(cfg.openaiCompat.customHeaders) } : {}) },
composio: {
...(composio.connectionMode(cfg) === "self-hosted" ? keyHint(cfg.composio?.apiKey) : {}),
configured: composio.configured(cfg), mode: composio.connectionMode(cfg),
@@ -11692,7 +11692,7 @@ async function describeInstances() {
const described = {
...instance, ...testedAi.info(instance), ...engineUpdates.shown(instance.driverKind, "version" in instance.snapshot ? instance.snapshot.version : null),
...instanceLook(entry),
- ...(entry?.access ? { access: entry.access } : {}), ...(entry?.driver === "openai-compat" && typeof (entry.config as { replyWaitMinutes?: unknown } | undefined)?.replyWaitMinutes === "number" ? { replyWaitMinutes: (entry.config as { replyWaitMinutes: number }).replyWaitMinutes } : {}), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),
+ ...(entry?.access ? { access: entry.access } : {}), ...openAiCompatSummaryFields(entry), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),
};
if (hostedModels) return { ...described, readOnly: true,
install: undefined, authentication: undefined, cli: undefined, cliCandidates: [],
diff --git a/server/openai-compat-endpoints.ts b/server/openai-compat-endpoints.ts
index 13ce4602af..7ba504b443 100644
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@ -1,8 +1,11 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
+import { customHeadersPatchSchema, decodeCustomHeaders, summarizeCustomHeaders } from "./drivers/openai-compat-headers.ts";
import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, probeOllama } from "./drivers/ollama.ts";
+export { summarizeCustomHeaders };
+
export const ADDED_ENDPOINT_PREFIX = "openai-compat-";
/** Origin and path only. The driver appends /models and /chat/completions, and fetch refuses URLs with credentials. */
@@ -32,6 +35,7 @@ export const addEndpointSchema = z.object({
key: z.string().trim().min(1).max(4096),
models: z.array(z.string().trim().min(1).max(200)).max(64).optional(),
catalog: z.enum(["lmstudio", "ollama"]).optional(),
+ customHeaders: customHeadersPatchSchema.optional(),
}).strict();
export type AddEndpoint = z.infer<typeof addEndpointSchema>;
@@ -53,9 +57,10 @@ export function addEndpoint(instances: InstanceConfigMap, body: AddEndpoint): {
if (/^https?:\/\//i.test(body.key)) return { error: "That API key looks like a URL. Paste the secret key itself, not a web address." };
const instanceId = `${ADDED_ENDPOINT_PREFIX}${randomUUID()}`;
const models = [...new Set(body.models ?? [])];
+ const customHeaders = body.customHeaders !== undefined ? decodeCustomHeaders(body.customHeaders) : undefined;
instances[instanceId] = {
driver: "openai-compat", displayName: body.displayName, access: "api",
- config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}) },
+ config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}), ...(customHeaders ? { customHeaders } : {}) },
};
return { instanceId };
}
@@ -101,14 +106,29 @@ export async function endpointModelsReadable(config: { url: string; key: string;
}
}
+export function openAiCompatSummaryFields(entry: InstanceConfig | undefined): Record<string, unknown> {
+ if (!entry || entry.driver !== "openai-compat") return {};
+ const config = entry.config as { replyWaitMinutes?: unknown; customHeaders?: unknown } | undefined;
+ const replyWaitMinutes = typeof config?.replyWaitMinutes === "number" ? config.replyWaitMinutes : undefined;
+ const customHeaders = config?.customHeaders !== undefined ? summarizeCustomHeaders(config.customHeaders) : undefined;
+ return {
+ ...(replyWaitMinutes !== undefined ? { replyWaitMinutes } : {}),
+ ...(customHeaders ? { customHeaders } : {}),
+ };
+}
+
export function withEndpointUrls(described: unknown, configs: InstanceConfigMap): unknown {
if (!Array.isArray(described)) return described;
return described.map((instance: { instanceId?: string }) => {
const entry = instance.instanceId ? configs[instance.instanceId] : undefined;
- if (!entry || !isAddedEndpoint(instance.instanceId!, entry)) return instance;
+ if (!entry) return instance;
+ const compat = openAiCompatSummaryFields(entry);
+ if (!isAddedEndpoint(instance.instanceId!, entry)) {
+ return Object.keys(compat).length ? { ...instance, ...compat } : instance;
+ }
const url = endpointDisplayUrl(entry.config);
const managedModels = (entry.config as { managedModels?: unknown } | undefined)?.managedModels;
const placeholderKey = (entry.config as { key?: unknown } | undefined)?.key === OLLAMA_PLACEHOLDER_KEY;
- return { ...instance, ...(url ? { url } : {}), ...(Array.isArray(managedModels) ? { managedModels } : {}), ...(placeholderKey ? { placeholderKey } : {}) };
+ return { ...instance, ...compat, ...(url ? { url } : {}), ...(Array.isArray(managedModels) ? { managedModels } : {}), ...(placeholderKey ? { placeholderKey } : {}) };
});
}
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index a8d841ddb3..24021c9553 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -349,6 +349,92 @@ describe("a server's reply wait", () => {
expect(persisted.at(-1)!.openaiCompat).toEqual({ driver: "openai-compat", config: { replyWaitMinutes: 30 } });
expect(instanceConfigs(cfg as unknown as AppConfig).openaiCompat!.config).toMatchObject({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: 30 });
});
+
+ it("saves custom request headers per OpenAI-compatible instance, preserves existing secret values, masks summaries, and enforces validation + owner/admin access", async () => {
+ const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
+ const cfg = {
+ instances: {
+ a: { driver: "fake" },
+ "openai-compat-1": { driver: "openai-compat", config: { url: "https://gw.example/v1", key: "k" } },
+ },
+ };
+ const { call, base } = await serve({
+ cfg: cfg as unknown as AppConfig,
+ describeInstances: async () => [
+ { instanceId: "a", driverKind: "fake" },
+ { instanceId: "openai-compat-1", driverKind: "openai-compat" },
+ ],
+ persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
+ persisted.push(structuredClone(instances));
+ (cfg as { instances: unknown }).instances = instances;
+ },
+ });
+ const saved = await call("PATCH", "/api/instances/openai-compat-1", {
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true },
+ { name: "X-Gateway-Token", value: "gw-secret-value-123", secret: true },
+ ],
+ },
+ });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
+ { name: "X-Gateway-Token", value: "gw-secret-value-123", required: true, secret: true },
+ ],
+ },
+ });
+ const listText = JSON.stringify(saved);
+ expect(listText).not.toContain("gw-secret-value-123");
+ const updated = await call("PATCH", "/api/instances/openai-compat-1", {
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true },
+ { name: "X-Gateway-Token", keepExisting: true, secret: true },
+ ],
+ },
+ });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
+ customHeaders: {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
+ { name: "X-Gateway-Token", value: "gw-secret-value-123", required: true, secret: true },
+ ],
+ },
+ });
+ expect(JSON.stringify(updated)).not.toContain("gw-secret-value-123");
+
+ const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+ })).status;
+ expect(await status("a", { customHeaders: { enabled: true, headers: [{ name: "X-Ok", value: "1" }] } })).toBe(400);
+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "Authorization", value: "Bearer bad" }] } })).toBe(400);
+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Bad", value: "line1\r\nline2" }] } })).toBe(400);
+
+ await call("PATCH", "/api/instances/openai-compat-1", {
+ customHeaders: { enabled: true, headers: [{ name: "X-Tenant-Pin", value: "pin-987654", secret: true }] },
+ });
+ expect(await status("openai-compat-1", {
+ customHeaders: { enabled: true, headers: [{ name: "X-Tenant-Pin", keepExisting: true, secret: false }] },
+ })).toBe(400);
+
+ await call("PATCH", "/api/instances/openai-compat-1", { customHeaders: null });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://gw.example/v1", key: "k" });
+
+ const nonOwner = await serve(
+ { cfg: cfg as unknown as AppConfig, persistProviderInstance: async () => {} },
+ { kind: "loopback", scopes: ["admin"], trust: "service" },
+ );
+ expect((await fetch(`${nonOwner.base}/api/instances/openai-compat-1`, {
+ method: "PATCH", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ customHeaders: { enabled: true, headers: [] } }),
+ })).status).toBe(403);
+ });
});
describe("hiding a provider", () => {
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index e1342008c9..aea286f123 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -29,6 +29,7 @@ import {
import { updateClaudeCli } from "../claude-update.ts";
import { persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";
import { addEndpoint, addEndpointSchema, changeEndpointAddress, endpointBaseUrl, endpointModelsReadable, isAddedEndpoint, localServerAlreadyAdded, withEndpointUrls } from "../openai-compat-endpoints.ts";
+import { CustomHeaderValidationError, mergeCustomHeadersPatch, type OpenAICompatCustomHeadersConfig } from "../drivers/openai-compat-headers.ts";
import { findOllama, probeOllama } from "../drivers/ollama.ts";
import type { InstanceConfigMap, ModelSelection, ProviderInstance } from "../contracts.ts";
import { removeAntigravityProfile } from "../drivers/antigravity-acp.ts";
@@ -198,10 +199,15 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
// Checked again here, inside the busy section, so two quick adds cannot both pass the settings check.
const duplicate = parsed.data.catalog ? localServerAlreadyAdded(instances, parsed.data.url) : null;
if (duplicate) return json(res, 409, { error: duplicate });
- const added = addEndpoint(instances, parsed.data);
- if ("error" in added) return json(res, 400, { error: added.error });
- await persistProviderInstance(added.instanceId, instances);
- return json(res, 201, { instanceId: added.instanceId, instances: await describeInstances() });
+ try {
+ const added = addEndpoint(instances, parsed.data);
+ if ("error" in added) return json(res, 400, { error: added.error });
+ await persistProviderInstance(added.instanceId, instances);
+ return json(res, 201, { instanceId: added.instanceId, instances: await describeInstances() });
+ } catch (error) {
+ if (error instanceof CustomHeaderValidationError) return json(res, 400, { error: error.message });
+ throw error;
+ }
} finally { providerConfigBusy.set(false); }
}
@@ -517,6 +523,19 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
const { replyWaitMinutes: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };
}
+ if (body.customHeaders !== undefined) {
+ if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can configure custom headers." });
+ if (entry.driver !== "openai-compat") return json(res, 400, { error: "Custom request headers are available for OpenAI-compatible instances only." });
+ const { customHeaders: previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
+ try {
+ entry.config = body.customHeaders === null
+ ? rest
+ : { ...rest, customHeaders: mergeCustomHeadersPatch(body.customHeaders, previous as OpenAICompatCustomHeadersConfig | undefined) };
+ } catch (error) {
+ if (error instanceof CustomHeaderValidationError) return json(res, 400, { error: error.message });
+ throw error;
+ }
+ }
if (body.models !== undefined) {
if (!isAddedEndpoint(instanceId, entry)) return json(res, 400, { ...userError("serverError.instance.modelsUnsupported") });
const { managedModels: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
diff --git a/src/components/OpenAiCompatCustomHeaders.test.ts b/src/components/OpenAiCompatCustomHeaders.test.ts
new file mode 100644
index 0000000000..5373e41bed
--- /dev/null
+++ b/src/components/OpenAiCompatCustomHeaders.test.ts
@@ -0,0 +1,151 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { setLocale } from "@/lib/i18n";
+import * as store from "@/state/store";
+import { BuiltInCustomHeaders, OpenAiCompatCustomHeaders } from "./OpenAiCompatCustomHeaders";
+
+const fixture = vi.hoisted(() => ({
+ api: vi.fn(),
+ dispatch: vi.fn(),
+ refreshInstances: vi.fn(),
+ instances: [] as store.InstanceInfo[],
+ config: undefined as store.ConfigStatus | undefined,
+}));
+
+vi.mock("@/state/store", async (original) => ({
+ ...await original<typeof import("@/state/store")>(),
+ api: fixture.api,
+ useStore: () => ({
+ state: { ...store.initialState, config: fixture.config, instances: fixture.instances },
+ dispatch: fixture.dispatch,
+ flushBotPatches: vi.fn(),
+ refreshInstances: fixture.refreshInstances,
+ refreshModels: vi.fn(),
+ }),
+}));
+
+let host: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ setLocale("en");
+ host = document.createElement("div");
+ document.body.appendChild(host);
+ root = createRoot(host);
+ fixture.api.mockReset();
+ fixture.dispatch.mockReset();
+ fixture.refreshInstances.mockReset();
+ fixture.instances = [];
+ fixture.config = undefined;
+});
+
+afterEach(() => {
+ root.unmount();
+ host.remove();
+});
+
+const instance = (instanceId: string, customHeaders?: store.InstanceInfo["customHeaders"]): store.InstanceInfo => ({
+ instanceId,
+ driverKind: "openai-compat",
+ displayName: "Gateway",
+ snapshot: { state: "available" },
+ models: { default: "m1", options: [] },
+ ...(customHeaders ? { customHeaders } : {}),
+}) as unknown as store.InstanceInfo;
+
+describe("OpenAI-compatible custom request headers UI", () => {
+ it("toggles enabled, adds header rows, inserts runtime {threadId} variable, and saves via PATCH /api/instances/:id", async () => {
+ const server = instance("openai-compat-1");
+ fixture.instances = [server];
+ flushSync(() => root.render(createElement(OpenAiCompatCustomHeaders, { server })));
+
+ const toggle = host.querySelector<HTMLButtonElement>('button[role="switch"]')!;
+ expect(toggle.getAttribute("aria-checked")).toBe("false");
+ flushSync(() => toggle.click());
+ expect(toggle.getAttribute("aria-checked")).toBe("true");
+
+ const addBtn = [...host.querySelectorAll("button")].find((b) => b.textContent?.includes("Add header"))!;
+ flushSync(() => addBtn.click());
+
+ const nameInput = host.querySelector<HTMLInputElement>('input[aria-label="Header name 1"]')!;
+ const valueInput = host.querySelector<HTMLInputElement>('input[aria-label="Header value 1"]')!;
+ const varSelect = host.querySelector<HTMLSelectElement>('select[aria-label="Insert runtime variable 1"]')!;
+
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(nameInput, "X-Maus-Thread-ID");
+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ varSelect.value = "{threadId}";
+ varSelect.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ expect(valueInput.value).toBe("{threadId}");
+
+ fixture.api.mockResolvedValue({ instances: [server] });
+ const saveBtn = [...host.querySelectorAll("button")].find((b) => b.textContent === "Save headers")!;
+ flushSync(() => saveBtn.click());
+ await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledTimes(1));
+ expect(fixture.api).toHaveBeenCalledWith("/api/instances/openai-compat-1", {
+ method: "PATCH",
+ body: JSON.stringify({
+ customHeaders: {
+ enabled: true,
+ headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false }],
+ },
+ }),
+ });
+ });
+
+ it("keeps configured secret header values unexposed via keepExisting and hides BuiltInCustomHeaders until base URL is set", async () => {
+ fixture.config = { openaiCompat: {} } as unknown as store.ConfigStatus;
+ fixture.instances = [instance("openaiCompat")];
+ flushSync(() => root.render(createElement(BuiltInCustomHeaders)));
+ expect(host.querySelector('button[role="switch"]')).toBeNull();
+
+ const server = instance("openaiCompat", {
+ enabled: true,
+ headers: [{ name: "X-Gateway-Token", configured: true, required: true, secret: true }],
+ });
+ fixture.config = { openaiCompat: { url: "https://gw.example/v1" } } as unknown as store.ConfigStatus;
+ fixture.instances = [server];
+ flushSync(() => root.render(createElement(BuiltInCustomHeaders)));
+
+ fixture.api.mockResolvedValue({ instances: [server] });
+ const saveBtn = [...host.querySelectorAll("button")].find((b) => b.textContent === "Save headers")!;
+ flushSync(() => saveBtn.click());
+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledTimes(1));
+ await vi.waitFor(() => expect(saveBtn.disabled).toBe(false));
+ expect(fixture.api).toHaveBeenCalledWith("/api/instances/openaiCompat", {
+ method: "PATCH",
+ body: JSON.stringify({
+ customHeaders: {
+ enabled: true,
+ headers: [{ name: "X-Gateway-Token", keepExisting: true, required: true, secret: true }],
+ },
+ }),
+ });
+
+ const checkboxes = host.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
+ const secretBox = checkboxes[1]!;
+ const valueInput = host.querySelector<HTMLInputElement>('input[aria-label="Header value 1"]')!;
+ expect(valueInput.type).toBe("password");
+ flushSync(() => secretBox.click());
+ expect(secretBox.checked).toBe(false);
+ expect(valueInput.type).toBe("text");
+
+ fixture.api.mockClear();
+ flushSync(() => saveBtn.click());
+ await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledTimes(1));
+ expect(fixture.api).toHaveBeenCalledWith("/api/instances/openaiCompat", {
+ method: "PATCH",
+ body: JSON.stringify({
+ customHeaders: {
+ enabled: true,
+ headers: [{ name: "X-Gateway-Token", value: "", required: true, secret: false }],
+ },
+ }),
+ });
+ });
+});
diff --git a/src/components/OpenAiCompatCustomHeaders.tsx b/src/components/OpenAiCompatCustomHeaders.tsx
new file mode 100644
index 0000000000..e02fda4de6
--- /dev/null
+++ b/src/components/OpenAiCompatCustomHeaders.tsx
@@ -0,0 +1,216 @@
+import { useEffect, useState } from "react";
+import { Plus, Trash2 } from "lucide-react";
+
+import { api, type InstanceInfo } from "@/state/store";
+import { useStoreActions, useStoreSelector } from "@/state/store-select";
+import { t } from "@/lib/i18n";
+import { cn } from "@/lib/cn";
+import { KEY_FIELD } from "./keys/KeyRow";
+import { Switch } from "./SettingsPrimitives";
+import { Select } from "./Select";
+
+const INPUT = cn(KEY_FIELD, "font-sans");
+const ICON_BUTTON = "ui-icon-button shrink-0 hover:text-ink";
+const VARS_LABEL = "{threadId}, {botId}, {turnId}, {providerInstanceId}";
+
+interface HeaderDraft {
+ name: string;
+ value: string;
+ keepExisting: boolean;
+ required: boolean;
+ secret: boolean;
+}
+
+function toDrafts(summary: InstanceInfo["customHeaders"] | undefined): HeaderDraft[] {
+ return (summary?.headers ?? []).map((entry) => ({
+ name: entry.name,
+ value: entry.secret ? "" : entry.value ?? "",
+ keepExisting: Boolean(entry.secret && entry.configured),
+ required: entry.required,
+ secret: entry.secret,
+ }));
+}
+
+export function OpenAiCompatCustomHeaders({ server, disabled = false }: { server: InstanceInfo; disabled?: boolean }) {
+ const { dispatch, refreshInstances } = useStoreActions();
+ const [enabled, setEnabled] = useState(Boolean(server.customHeaders?.enabled));
+ const [rows, setRows] = useState<HeaderDraft[]>(() => toDrafts(server.customHeaders));
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const syncedKey = JSON.stringify(server.customHeaders ?? null);
+ useEffect(() => {
+ setEnabled(Boolean(server.customHeaders?.enabled));
+ setRows(toDrafts(server.customHeaders));
+ setError(null);
+ }, [server.instanceId, syncedKey]);
+
+ const updateRow = (index: number, patch: Partial<HeaderDraft>) => {
+ setRows((current) => current.map((row, at) => (at === index ? { ...row, ...patch } : row)));
+ };
+
+ const addRow = () => {
+ setRows((current) => [...current, { name: "", value: "", keepExisting: false, required: true, secret: false }]);
+ };
+
+ const removeRow = (index: number) => {
+ setRows((current) => current.filter((_row, at) => at !== index));
+ };
+
+ const insertVariable = (index: number, variable: string) => {
+ if (!variable) return;
+ setRows((current) =>
+ current.map((row, at) => {
+ if (at !== index) return row;
+ const base = row.keepExisting ? "" : row.value;
+ return { ...row, value: `${base}${variable}`, keepExisting: false };
+ }),
+ );
+ };
+
+ const save = () => {
+ if (busy || disabled) return;
+ setBusy(true);
+ setError(null);
+ const payload = {
+ enabled,
+ headers: rows.map((row) => ({
+ name: row.name.trim(),
+ ...(row.keepExisting && !row.value ? { keepExisting: true } : { value: row.value }),
+ required: row.required,
+ secret: row.secret,
+ })),
+ };
+ void api(`/api/instances/${encodeURIComponent(server.instanceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ customHeaders: payload }),
+ })
+ .then(async (response: { instances?: unknown }) => {
+ if (Array.isArray(response.instances)) {
+ dispatch({ type: "instances", instances: response.instances as InstanceInfo[] });
+ } else {
+ await refreshInstances({ reportErrors: true });
+ }
+ })
+ .catch((cause: unknown) => {
+ setError(cause instanceof Error && cause.message ? cause.message : t("apiInstances.failed"));
+ })
+ .finally(() => setBusy(false));
+ };
+
+ return (
+ <div className="mt-2 flex flex-col gap-1.5 rounded-lg border border-control p-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[12px] font-medium leading-4 text-ink">{t("apiInstances.customHeadersTitle")}</span>
+ <div className="flex items-center gap-1.5">
+ <span className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.customHeadersEnable")}</span>
+ <Switch
+ checked={enabled}
+ aria-label={t("apiInstances.customHeadersEnableFor", { name: server.displayName })}
+ disabled={busy || disabled}
+ onClick={() => setEnabled((on) => !on)}
+ />
+ </div>
+ </div>
+ <p className="text-[12px] leading-4 text-ink-secondary">
+ {t("apiInstances.customHeadersHint", { vars: VARS_LABEL })}
+ </p>
+ {rows.map((row, index) => (
+ <div key={index} className="flex flex-col gap-1 rounded-lg border border-control p-2">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <input
+ value={row.name}
+ onChange={(event) => updateRow(index, { name: event.target.value })}
+ placeholder="X-Maus-Thread-ID"
+ aria-label={t("apiInstances.customHeaderNameAria", { index: index + 1 })}
+ spellCheck={false}
+ disabled={busy || disabled}
+ className={cn(INPUT, "min-w-0 flex-1")}
+ />
+ <input
+ type={row.secret ? "password" : "text"}
+ value={row.value}
+ onChange={(event) => updateRow(index, { value: event.target.value, keepExisting: false })}
+ placeholder={row.keepExisting ? t("apiInstances.customHeadersKeepSecret") : "{threadId}"}
+ aria-label={t("apiInstances.customHeaderValueAria", { index: index + 1 })}
+ autoComplete="off"
+ spellCheck={false}
+ disabled={busy || disabled}
+ className={cn(INPUT, "min-w-0 flex-1")}
+ />
+ <button
+ type="button"
+ onClick={() => removeRow(index)}
+ disabled={busy || disabled}
+ aria-label={t("apiInstances.customHeadersRemove", { index: index + 1 })}
+ className={`${ICON_BUTTON} hover:bg-danger/10 hover:text-danger`}
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-1.5">
+ <Select
+ size="sm"
+ value=""
+ aria-label={t("apiInstances.customHeaderVariableAria", { index: index + 1 })}
+ disabled={busy || disabled}
+ onChange={(event) => insertVariable(index, event.target.value)}
+ >
+ <option value="">{t("apiInstances.customHeaderVarPlaceholder")}</option>
+ <option value="{threadId}">{t("apiInstances.customHeadersVarThreadId")}</option>
+ <option value="{botId}">{t("apiInstances.customHeadersVarBotId")}</option>
+ <option value="{turnId}">{t("apiInstances.customHeadersVarTurnId")}</option>
+ <option value="{providerInstanceId}">{t("apiInstances.customHeadersVarProviderId")}</option>
+ </Select>
+ <div className="flex items-center gap-2 text-[12px] leading-4 text-ink-secondary">
+ <label className="flex items-center gap-1">
+ <input
+ type="checkbox"
+ checked={row.required}
+ disabled={busy || disabled}
+ onChange={(event) => updateRow(index, { required: event.target.checked })}
+ />
+ {t("apiInstances.customHeadersRequired")}
+ </label>
+ <label className="flex items-center gap-1">
+ <input
+ type="checkbox"
+ checked={row.secret}
+ disabled={busy || disabled}
+ onChange={(event) => {
+ const nextSecret = event.target.checked;
+ updateRow(index, {
+ secret: nextSecret,
+ ...(!nextSecret && row.keepExisting ? { keepExisting: false } : {}),
+ });
+ }}
+ />
+ {t("apiInstances.customHeadersSecret")}
+ </label>
+ </div>
+ </div>
+ </div>
+ ))}
+ <div className="flex flex-wrap items-center justify-between gap-1.5">
+ <button type="button" onClick={addRow} disabled={busy || disabled} className="ui-button inline-flex items-center gap-1">
+ <Plus size={12} aria-hidden="true" />
+ {t("apiInstances.customHeadersAdd")}
+ </button>
+ <button type="button" onClick={save} disabled={busy || disabled} className="ui-button">
+ {busy ? t("apiInstances.customHeadersSaving") : t("apiInstances.customHeadersSave")}
+ </button>
+ </div>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
+
+/** Custom headers for the built-in OpenAI-compatible server when its base URL is configured. */
+export function BuiltInCustomHeaders() {
+ const server = useStoreSelector((s) =>
+ s.instances.find((instance) => instance.instanceId === "openaiCompat" && instance.driverKind === "openai-compat"),
+ );
+ const compatUrl = useStoreSelector((s) => s.config?.openaiCompat?.url);
+ if (!server || (!compatUrl && !server.customHeaders)) return null;
+ return <OpenAiCompatCustomHeaders server={server} />;
+}
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index fcc203afa9..55d4e89099 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -6,6 +6,7 @@ import { keySaved } from "@/lib/product-events";
import { addedServers } from "@/lib/openai-compat-endpoints";
import { cn } from "@/lib/cn";
import { KEY_FIELD } from "./keys/KeyRow";
+import { OpenAiCompatCustomHeaders } from "./OpenAiCompatCustomHeaders";
import { Select } from "./Select";
export function modelIds(text: string): string[] {
@@ -234,6 +235,7 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
</div>
{error?.at === server.instanceId && <div role="alert" className="text-[12px] leading-4 text-danger">{error.text}</div>}
{unreadable === server.instanceId && <p role="status" className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.modelsUnreadable")}</p>}
+ <OpenAiCompatCustomHeaders server={server} disabled={busy !== null} />
</div>
)}
</div>
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
index 3779b51ebf..9755186008 100644
--- a/src/components/keys/KeysPage.tsx
+++ b/src/components/keys/KeysPage.tsx
@@ -9,6 +9,7 @@ import { BoatOfferPanel } from "../BoatOffer";
import { LiveProviderSettings } from "../LiveProviderSettings";
import { VoiceEveryReplySetting } from "../VoiceEveryReplySetting";
import { VoiceHearingSetting } from "../VoiceHearingSetting";
+import { BuiltInCustomHeaders } from "../OpenAiCompatCustomHeaders";
import { BuiltInReplyWait, LmStudioServer, OtherOpenAiCompatServers } from "../OpenAiCompatServers";
import { OllamaServer } from "../OllamaServer";
import { KEY_CATALOG, KEY_SECTIONS, keyHidden, keyMatches, savedState, type KeyEntry, type KeyId, type KeySectionId } from "./key-catalog";
@@ -30,7 +31,7 @@ const PANELS: Partial<Record<KeyId, (visible: boolean) => ReactNode>> = {
const EXTRAS: Partial<Record<KeyId, () => ReactNode>> = {
anthropic: () => <AnthropicEveryClaudeBot />,
- openaiCompat: () => <><OpenAiCompatUrl /><BuiltInReplyWait /><OtherOpenAiCompatServers /></>,
+ openaiCompat: () => <><OpenAiCompatUrl /><BuiltInReplyWait /><BuiltInCustomHeaders /><OtherOpenAiCompatServers /></>,
box: () => <BoatOfferPanel />,
liveKey: () => <LiveProviderSettings />,
};
diff --git a/src/locales/en.json b/src/locales/en.json
index 293b0f0101..636836bd14 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7576,6 +7576,25 @@
"apiInstances.replyWaitHint": "How long to wait for the next words of a reply before giving up. Local models can take a while to answer on a slow computer.",
"apiInstances.replyWaitDefault": "Wait: default",
"apiInstances.replyWaitMinutes": "Wait {minutes} min",
+ "apiInstances.customHeadersTitle": "Custom request headers",
+ "apiInstances.customHeadersEnable": "Enable custom request headers",
+ "apiInstances.customHeadersEnableFor": "Enable custom request headers for {name}",
+ "apiInstances.customHeadersHint": "Sent with each model request when enabled. Supports {vars} resolved safely by OpenMausBot at request time.",
+ "apiInstances.customHeadersAdd": "Add header",
+ "apiInstances.customHeadersSave": "Save headers",
+ "apiInstances.customHeadersSaving": "Saving…",
+ "apiInstances.customHeadersRemove": "Remove header {index}",
+ "apiInstances.customHeaderNameAria": "Header name {index}",
+ "apiInstances.customHeaderValueAria": "Header value {index}",
+ "apiInstances.customHeaderVariableAria": "Insert runtime variable {index}",
+ "apiInstances.customHeaderVarPlaceholder": "Insert variable…",
+ "apiInstances.customHeadersKeepSecret": "Saved secret (leave empty to keep)",
+ "apiInstances.customHeadersRequired": "Required",
+ "apiInstances.customHeadersSecret": "Secret",
+ "apiInstances.customHeadersVarThreadId": "{threadId} — Thread ID",
+ "apiInstances.customHeadersVarBotId": "{botId} — Bot ID",
+ "apiInstances.customHeadersVarTurnId": "{turnId} — Turn ID",
+ "apiInstances.customHeadersVarProviderId": "{providerInstanceId} — Provider ID",
"botOverview.loading": "Loading…",
"botOverview.refreshError": "Couldn’t refresh. Showing the last loaded overview.",
"botOverview.readAll": "Read all",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 0c597e8acf..c6f3b5ac98 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -37,7 +37,13 @@ export interface ConfigStatus {
anthropic?: SavedKey & { everyClaudeBot?: boolean };
openai?: SavedKey;
openrouter?: SavedKey;
- openaiCompat?: SavedKey & { url?: string };
+ openaiCompat?: SavedKey & {
+ url?: string;
+ customHeaders?: {
+ enabled: boolean;
+ headers: Array<{ name: string; value?: string; configured: boolean; required: boolean; secret: boolean }>;
+ };
+ };
/** what this server is entitled to; Settings shows only what works here.
* `license` reaches admins only, and only while the key is inside its
* warning window or grace period. */
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 24e766dae7..d6e7fb7330 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -462,7 +462,7 @@ export interface InstanceInfo extends InstanceEndpointInfo {
cliDefault?: string;
cliCandidates?: string[];
claudeAccount?: { configDir: string; signInCommand: string; signInShell: "powershell" | "sh"; isDefault: boolean };
- freeUpSpace?: boolean; replyWaitMinutes?: number; modelsUnconfirmed?: true; /** Why the engine's last read of its list failed. */ modelsUnreadable?: "signedOut" | "timedOut" | "failed"; /** The app updated its own copy of this engine to this version lately. */ autoUpdated?: { version: string; at: number };
+ freeUpSpace?: boolean; replyWaitMinutes?: number; customHeaders?: NonNullable<ConfigStatus["openaiCompat"]>["customHeaders"]; modelsUnconfirmed?: true; /** Why the engine's last read of its list failed. */ modelsUnreadable?: "signedOut" | "timedOut" | "failed"; /** The app updated its own copy of this engine to this version lately. */ autoUpdated?: { version: string; at: number };
}
/** A Settings page (`SettingsPageId`) or an older page name that `settings-index.ts` sends to its new page and section. */