25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(ai): support custom headers for api services
二丫讲梵42c0dc7f8997
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex e3770e1f42..6066d41564 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -62,6 +62,7 @@ import {DUCKDB_WORKER_MAX_PROCESSES_MIN,normalizeDuckDbWorkerMaxProcesses,normalizeAiEnv,+ normalizeAiHeaders,type AiProvider,type AiApiStyle,type AiAuthMethod,@@ -325,6 +326,12 @@ interface AiEnvRow {value: string;}+interface AiHeaderRow {+ id: string;+ name: string;+ value: string;+}+function tableColumnTemplateRowsFromSettings(lines: readonly string[]): TableColumnTemplateGridRow[] {return parseTableColumnTemplateFields([...lines]).map((field) => ({id: uuid(),@@ -3341,6 +3348,7 @@ const aiEditEndpoint = ref("");const aiEditModel = ref("");const aiEditLegacyModels = ref<AiConfiguredModel[]>([]);const aiEditApiStyle = ref<AiApiStyle>("completions");+const aiEditCustomHeaderRows = ref<AiHeaderRow[]>([]);const aiEditProxyEnabled = ref(false);const aiEditProxyUrl = ref("");const aiEditEnableThinking = ref(true);@@ -3505,6 +3513,7 @@ const aiCliMcpActionLabel = computed(() => {return t("settings.mcpUpToDate");});const aiCliEnvError = computed(() => cliEnvValidationError());+const aiHeadersValidationError = computed(() => customHeadersValidationError());const aiCliPathError = computed(() => {const path = aiEditCliPath.value.trim();const firstToken = path.split(/\s+/)[0] || "";@@ -3520,6 +3529,49 @@ function aiEnvRowsFromConfig(env: unknown): AiEnvRow[] {}));}+function aiHeaderRowsFromConfig(headers: unknown): AiHeaderRow[] {+ return Object.entries(normalizeAiHeaders(headers)).map(([name, value]) => ({+ id: uuid(),+ name,+ value,+ }));+}++const AI_HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;+const RESERVED_AI_HEADERS = new Set(["host", "content-length", "content-type", "connection", "transfer-encoding", "proxy-authorization"]);++function customHeadersFromRows(): Record<string, string> {+ const result: Record<string, string> = {};+ for (const row of aiEditCustomHeaderRows.value) {+ const name = row.name.trim();+ if (name) result[name] = row.value;+ }+ return result;+}++function customHeadersValidationError(): string {+ const names = new Set<string>();+ for (const row of aiEditCustomHeaderRows.value) {+ const name = row.name.trim();+ if (!name && !row.value) continue;+ if (!AI_HEADER_NAME_RE.test(name)) return t("ai.customHeadersInvalidName", { name: row.name || "—" });+ const normalizedName = name.toLowerCase();+ if (RESERVED_AI_HEADERS.has(normalizedName)) return t("ai.customHeadersReserved", { name });+ if (names.has(normalizedName)) return t("ai.customHeadersDuplicate", { name });+ if (/\r|\n/.test(row.value)) return t("ai.customHeadersInvalidValue", { name });+ names.add(normalizedName);+ }+ return "";+}++function addAiCustomHeaderRow() {+ aiEditCustomHeaderRows.value.push({ id: uuid(), name: "", value: "" });+}++function removeAiCustomHeaderRow(id: string) {+ aiEditCustomHeaderRows.value = aiEditCustomHeaderRows.value.filter((row) => row.id !== id);+}+function cliEnvFromRows(rows = aiEditCliEnvRows.value): Record<string, string> {const result: Record<string, string> = {};for (const row of rows) {@@ -3578,6 +3630,7 @@ function currentAiEditConfig() {supportedEffortLevels: model.supportedEffortLevels ? [...model.supportedEffortLevels] : undefined,})),apiStyle: aiEditApiStyle.value,+ customHeaders: customHeadersFromRows(),proxyEnabled: aiEditProxyEnabled.value,proxyUrl: aiEditProxyUrl.value,enableThinking: aiEditEnableThinking.value,@@ -3624,6 +3677,7 @@ function aiSelectProvider(provider: AiProvider) {aiEditModel.value = "";aiEditLegacyModels.value = [];aiEditApiStyle.value = preset.apiStyle;+ aiEditCustomHeaderRows.value = [];aiEditEnableThinking.value = true;aiEditReasoningLevel.value = "default";if (CLI_AI_PROVIDERS.has(provider)) void ensureCliMcpStatus();@@ -3659,6 +3713,7 @@ function aiEnterEditMode(configId?: string) {supportedEffortLevels: model.supportedEffortLevels ? [...model.supportedEffortLevels] : undefined,}));aiEditApiStyle.value = config.apiStyle;+ aiEditCustomHeaderRows.value = aiHeaderRowsFromConfig(config.customHeaders);aiEditProxyEnabled.value = config.proxyEnabled ?? false;aiEditProxyUrl.value = config.proxyUrl ?? "";aiEditEnableThinking.value = config.enableThinking ?? true;@@ -3690,6 +3745,7 @@ function aiEnterEditMode(configId?: string) {aiEditModel.value = "";aiEditLegacyModels.value = [];aiEditApiStyle.value = AI_PROVIDER_PRESETS["claude"].apiStyle;+ aiEditCustomHeaderRows.value = [];aiEditProxyEnabled.value = false;aiEditProxyUrl.value = "";aiEditEnableThinking.value = true;@@ -3730,6 +3786,7 @@ async function applyPendingAiConfigDeepLinkDraft() {aiEditModel.value = draft.model;aiEditLegacyModels.value = [];aiEditApiStyle.value = draft.apiStyle;+ aiEditCustomHeaderRows.value = [];if (!draft.promptForClipboardApiKey) return;@@ -3764,6 +3821,10 @@ async function aiSaveConfig() {toast(t("ai.configNameExists", { name: aiEditConfigName.value }), 3000);return;}+ if (aiHeadersValidationError.value) {+ toast(aiHeadersValidationError.value, 3000);+ return;+ }const editConfig = currentAiEditConfig();const config: AiConfigItem = {@@ -3817,6 +3878,11 @@ async function aiSetDefaultConfig(id: string) {async function aiTestConn() {if ((aiRequiresApiKey.value && !aiEditApiKey.value.trim()) || (!aiIsCliProvider.value && !aiEditEndpoint.value.trim())) return;+ if (aiHeadersValidationError.value) {+ aiTestResult.value = "error";+ aiTestError.value = aiHeadersValidationError.value;+ return;+ }if (aiCliValidationError.value) {aiTestResult.value = "error";aiTestError.value = aiCliValidationError.value;@@ -7206,6 +7272,28 @@ onUnmounted(() => {</div></div>+ <!-- Custom HTTP headers for API gateways and tenant routing. -->+ <div v-if="!aiIsCliProvider" class="grid grid-cols-3 items-start gap-3">+ <Label class="pt-2 text-right text-xs">{{ t("ai.customHeaders") }}</Label>+ <div class="col-span-2 space-y-2">+ <div class="space-y-1.5">+ <div v-for="row in aiEditCustomHeaderRows" :key="row.id" class="grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.3fr)_2rem] gap-2">+ <Input v-model="row.name" autocomplete="off" class="h-8 font-mono text-xs" :placeholder="t('ai.customHeadersNamePlaceholder')" />+ <PasswordInput v-model="row.value" autocomplete="off" class="min-w-0" inputClass="h-8 font-mono text-xs" :placeholder="t('ai.customHeadersValuePlaceholder')" />+ <Button type="button" variant="ghost" size="icon" class="h-8 w-8" :title="t('common.remove')" :aria-label="t('common.remove')" @click="removeAiCustomHeaderRow(row.id)">+ <X class="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ <Button type="button" variant="outline" size="sm" class="h-7 px-2 text-xs" @click="addAiCustomHeaderRow">+ <Plus class="mr-1 h-3.5 w-3.5" />+ {{ t("ai.customHeadersAdd") }}+ </Button>+ <p v-if="aiHeadersValidationError" class="text-[11px] text-destructive">{{ aiHeadersValidationError }}</p>+ <p v-else class="text-[11px] text-muted-foreground">{{ t("ai.customHeadersHint") }}</p>+ </div>+ </div>+<!-- CLI Path --><div v-if="aiIsCliProvider" class="grid grid-cols-3 items-start gap-3"><Label class="pt-2 text-right text-xs">{{ t("ai.cliPath", { provider: aiCliProviderLabel }) }}</Label>@@ -8191,7 +8279,7 @@ onUnmounted(() => {</template><template v-else><div class="flex min-w-0 flex-1 items-center gap-2">- <Button size="sm" variant="outline" :disabled="aiTesting || !!aiCliValidationError || (aiRequiresApiKey && !aiEditApiKey?.trim()) || (!aiIsCliProvider && !aiEditEndpoint?.trim())" @click="aiTestConn">+ <Button size="sm" variant="outline" :disabled="aiTesting || !!aiCliValidationError || !!aiHeadersValidationError || (aiRequiresApiKey && !aiEditApiKey?.trim()) || (!aiIsCliProvider && !aiEditEndpoint?.trim())" @click="aiTestConn"><Loader2 v-if="aiTesting" class="h-3 w-3 animate-spin mr-1" />{{ t("connection.test") }}</Button>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex b47bbafb13..0a34da4901 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -2714,6 +2714,15 @@ export default {proxy: "Proxy",proxyEnable: "Send AI requests through proxy",proxyUrl: "Proxy URL",+ customHeaders: "Custom Headers",+ customHeadersAdd: "Add header",+ customHeadersHint: "Extra headers are sent with model discovery, connection tests, chat, and Agent requests. Header values may be sensitive.",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "Invalid header name: {name}",+ customHeadersInvalidValue: "Invalid header value for: {name}",+ customHeadersDuplicate: "Duplicate header name: {name}",+ customHeadersReserved: "This header is managed by DBX: {name}",enableThinking: "Thinking",enableThinkingOn: "Enabled",enableThinkingOff: "Disabled",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 3619eef320..0de808e33e 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -2790,6 +2790,15 @@ export default withEnglishFallback({proxy: "Proxy",proxyEnable: "Enviar solicitudes de IA mediante proxy",proxyUrl: "URL del proxy",+ customHeaders: "Cabeceras personalizadas",+ customHeadersAdd: "Añadir cabecera",+ customHeadersHint: "Estas cabeceras se envían al descubrir modelos, probar la conexión, chatear y usar Agent. Sus valores pueden ser sensibles.",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "Nombre de cabecera no válido: {name}",+ customHeadersInvalidValue: "Valor de cabecera no válido para: {name}",+ customHeadersDuplicate: "Nombre de cabecera duplicado: {name}",+ customHeadersReserved: "DBX administra esta cabecera: {name}",enableThinking: "Razonamiento",enableThinkingOn: "Activado",enableThinkingOff: "Desactivado",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 919aa900b1..4c660d569a 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -2684,6 +2684,15 @@ export default withEnglishFallback({proxy: "Proxy",proxyEnable: "Invia richieste AI tramite proxy",proxyUrl: "URL Proxy",+ customHeaders: "Intestazioni personalizzate",+ customHeadersAdd: "Aggiungi intestazione",+ customHeadersHint: "Queste intestazioni vengono inviate durante la ricerca dei modelli, il test della connessione, la chat e le richieste Agent. I valori possono essere sensibili.",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "Nome intestazione non valido: {name}",+ customHeadersInvalidValue: "Valore intestazione non valido per: {name}",+ customHeadersDuplicate: "Nome intestazione duplicato: {name}",+ customHeadersReserved: "Questa intestazione è gestita da DBX: {name}",enableThinking: "Pensiero (Thinking)",enableThinkingOn: "Abilitato",enableThinkingOff: "Disabilitato",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 872de50486..4503593cdd 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -2823,6 +2823,15 @@ export default withEnglishFallback({proxy: "プロキシ",proxyEnable: "プロキシ経由でAIリクエストを送信",proxyUrl: "プロキシURL",+ customHeaders: "カスタムヘッダー",+ customHeadersAdd: "ヘッダーを追加",+ customHeadersHint: "モデル検出、接続テスト、チャット、Agent リクエストでこれらのヘッダーが送信されます。値には機密情報が含まれる場合があります。",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "無効なヘッダー名: {name}",+ customHeadersInvalidValue: "無効なヘッダー値: {name}",+ customHeadersDuplicate: "重複するヘッダー名: {name}",+ customHeadersReserved: "このヘッダーは DBX により管理されています: {name}",enableThinking: "思考",enableThinkingOn: "有効",enableThinkingOff: "無効",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 44f3fd1c3b..8682a328e1 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -2539,6 +2539,15 @@ export default withEnglishFallback({proxy: "프록시",proxyEnable: "프록시를 통해 AI 요청 전송",proxyUrl: "프록시 URL",+ customHeaders: "사용자 지정 헤더",+ customHeadersAdd: "헤더 추가",+ customHeadersHint: "모델 검색, 연결 테스트, 채팅 및 Agent 요청에 이 헤더가 전송됩니다. 값에는 민감한 정보가 포함될 수 있습니다.",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "잘못된 헤더 이름: {name}",+ customHeadersInvalidValue: "잘못된 헤더 값: {name}",+ customHeadersDuplicate: "중복된 헤더 이름: {name}",+ customHeadersReserved: "이 헤더는 DBX에서 관리합니다: {name}",enableThinking: "사고",enableThinkingOn: "활성화됨",enableThinkingOff: "비활성화됨",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 7c44ac3841..ac1b78cf38 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -2792,6 +2792,15 @@ export default withEnglishFallback({proxy: "Proxy",proxyEnable: "Enviar requisições de AI através do proxy",proxyUrl: "URL do Proxy",+ customHeaders: "Cabeçalhos personalizados",+ customHeadersAdd: "Adicionar cabeçalho",+ customHeadersHint: "Estes cabeçalhos são enviados na descoberta de modelos, teste de conexão, chat e solicitações do Agent. Os valores podem ser sensíveis.",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "Nome de cabeçalho inválido: {name}",+ customHeadersInvalidValue: "Valor de cabeçalho inválido para: {name}",+ customHeadersDuplicate: "Nome de cabeçalho duplicado: {name}",+ customHeadersReserved: "Este cabeçalho é gerenciado pelo DBX: {name}",anthropicMessagesHint: "APIs compatíveis com Anthropic Messages geralmente usam /v1/messages.",openAiCompatibleEndpointHint: "A maioria das APIs compatíveis com OpenAI requer o prefixo de caminho /v1.",contextWindow: "Janela de Contexto",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 57f0907d6b..3c25b7885b 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -2637,6 +2637,15 @@ export default withEnglishFallback({proxy: "代理",proxyEnable: "AI 请求通过代理发送",proxyUrl: "代理地址",+ customHeaders: "自定义请求头",+ customHeadersAdd: "添加请求头",+ customHeadersHint: "模型发现、连接测试、对话和 Agent 请求都会携带这些请求头;值可能包含敏感信息。",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "请求头名称无效:{name}",+ customHeadersInvalidValue: "请求头值无效:{name}",+ customHeadersDuplicate: "请求头名称重复:{name}",+ customHeadersReserved: "该请求头由 DBX 管理:{name}",enableThinking: "Thinking",enableThinkingOn: "已启用",enableThinkingOff: "已禁用",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex a721856806..4d0906b27f 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -2683,6 +2683,15 @@ export default withEnglishFallback({proxy: "代理伺服器",proxyEnable: "經由代理伺服器發送 AI 請求",proxyUrl: "代理伺服器地址",+ customHeaders: "自訂請求標頭",+ customHeadersAdd: "新增請求標頭",+ customHeadersHint: "模型探索、連線測試、對話和 Agent 請求都會攜帶這些標頭;值可能包含敏感資訊。",+ customHeadersNamePlaceholder: "X-Tenant-ID",+ customHeadersValuePlaceholder: "tenant-a",+ customHeadersInvalidName: "請求標頭名稱無效:{name}",+ customHeadersInvalidValue: "請求標頭值無效:{name}",+ customHeadersDuplicate: "請求標頭名稱重複:{name}",+ customHeadersReserved: "此請求標頭由 DBX 管理:{name}",enableThinking: "Thinking",enableThinkingOn: "已啟用",enableThinkingOff: "已停用",diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.tsindex ec040bd296..8f2dd87dd8 100644--- a/apps/desktop/src/stores/settingsStore.ts+++ b/apps/desktop/src/stores/settingsStore.ts@@ -383,6 +383,17 @@ export function normalizeAiEnv(value: unknown): Record<string, string> {return result;}+export function normalizeAiHeaders(value: unknown): Record<string, string> {+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ const result: Record<string, string> = {};+ for (const [rawName, rawValue] of Object.entries(value as Record<string, unknown>)) {+ const name = rawName.trim();+ if (!name) continue;+ result[name] = rawValue == null ? "" : String(rawValue);+ }+ return result;+}+export function normalizeAiConfig(config: Partial<AiConfig> | null | undefined): AiConfig {const provider = config?.provider && config.provider in AI_PROVIDER_PRESETS ? config.provider : inferAiProviderFromConfig(config);return {@@ -391,6 +402,7 @@ export function normalizeAiConfig(config: Partial<AiConfig> | null | undefined):provider,apiKey: (config?.apiKey ?? "").trim(),apiStyle: config?.apiStyle ?? defaultConfigs[provider].apiStyle,+ customHeaders: normalizeAiHeaders(config?.customHeaders),authMethod: config?.authMethod ?? defaultConfigs[provider].authMethod,proxyEnabled: !!config?.proxyEnabled,proxyUrl: config?.proxyUrl ?? "",diff --git a/apps/desktop/src/types/ai.ts b/apps/desktop/src/types/ai.tsindex 6c9efcf47a..faab9ce2b9 100644--- a/apps/desktop/src/types/ai.ts+++ b/apps/desktop/src/types/ai.ts@@ -36,6 +36,8 @@ export interface AiConfig {model: string;models?: AiConfiguredModel[];apiStyle: AiApiStyle;+ /** Additional HTTP headers sent to API-based AI providers. */+ customHeaders?: Record<string, string>;proxyEnabled?: boolean;proxyUrl?: string;enableThinking?: boolean;diff --git a/crates/dbx-core/src/ai.rs b/crates/dbx-core/src/ai.rsindex 4198d78922..8119629e58 100644--- a/crates/dbx-core/src/ai.rs+++ b/crates/dbx-core/src/ai.rs@@ -1,6 +1,6 @@use crate::token_usage::TokenUsage;use futures::StreamExt;-use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};+use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE};use serde::{Deserialize, Serialize};use serde_json::json;use std::collections::{HashMap, HashSet};@@ -371,6 +371,10 @@ pub struct AiConfig {pub models: Vec<AiModelListItem>,#[serde(default)]pub api_style: AiApiStyle,+ /// Additional headers attached to every API-backed AI request. Values can+ /// contain gateway credentials, so callers must never log this map.+ #[serde(default)]+ pub custom_headers: HashMap<String, String>,#[serde(default)]pub proxy_enabled: bool,#[serde(default)]@@ -1591,6 +1595,7 @@ pub fn maybe_bearer_headers(config: &AiConfig) -> Result<HeaderMap, String> {if !api_key.is_empty() {headers.insert(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|e| e.to_string())?);}+ append_custom_headers(&mut headers, config)?;Ok(headers)}@@ -1612,6 +1617,36 @@ pub fn claude_headers(config: &AiConfig) -> Result<HeaderMap, String> {}}headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));+ append_custom_headers(&mut headers, config)?;+ Ok(headers)+}++/// Adds user-supplied gateway headers after DBX's provider headers. This+/// intentionally lets an explicit `Authorization` value replace the provider+/// default, while protecting HTTP framing and JSON content semantics.+fn append_custom_headers(headers: &mut HeaderMap, config: &AiConfig) -> Result<(), String> {+ const RESERVED: &[&str] =+ &["host", "content-length", "content-type", "connection", "transfer-encoding", "proxy-authorization"];+ let mut seen = HashSet::new();+ for (raw_name, raw_value) in &config.custom_headers {+ let name = HeaderName::from_bytes(raw_name.trim().as_bytes())+ .map_err(|_| format!("Invalid AI custom header name: {raw_name}"))?;+ if RESERVED.iter().any(|reserved| name.as_str().eq_ignore_ascii_case(reserved)) {+ return Err(format!("Invalid AI custom header name: {raw_name} (reserved by DBX)"));+ }+ if !seen.insert(name.clone()) {+ return Err(format!("Duplicate AI custom header name: {raw_name}"));+ }+ let value = HeaderValue::from_str(raw_value)+ .map_err(|error| format!("Invalid AI custom header value for {raw_name}: {error}"))?;+ headers.insert(name, value);+ }+ Ok(())+}++fn custom_headers(config: &AiConfig) -> Result<HeaderMap, String> {+ let mut headers = HeaderMap::new();+ append_custom_headers(&mut headers, config)?;Ok(headers)}@@ -1812,7 +1847,10 @@ async fn list_gemini_models(client: &reqwest::Client, config: &AiConfig) -> Resulet mut models = Vec::new();loop {- let mut request = client.get(&endpoint).query(&[("key", config.api_key.as_str()), ("pageSize", "1000")]);+ let mut request = client+ .get(&endpoint)+ .query(&[("key", config.api_key.as_str()), ("pageSize", "1000")])+ .headers(custom_headers(config)?);if let Some(token) = page_token.as_deref() {request = request.query(&[("pageToken", token)]);}@@ -2209,6 +2247,7 @@ pub async fn call_gemini(client: &reqwest::Client, request: AiCompletionRequest).post(resolve_endpoint(&request.config)).query(&[("key", normalized_api_key(&request.config))]).header(CONTENT_TYPE, "application/json")+ .headers(custom_headers(&request.config)?).json(&body).send().await@@ -2688,6 +2727,7 @@ pub async fn test_connection_core(config: &AiConfig) -> Result<AiTestConnectionRlet res = client.post(&gemini_ep).header(CONTENT_TYPE, "application/json")+ .headers(custom_headers(&config_inner)?).query(&[("key", api_key.as_str()), ("alt", "sse")]).json(&json!({"contents": [{ "parts": [{ "text": TEST_PROMPT }], "role": "user" }],@@ -3433,6 +3473,7 @@ async fn stream_gemini(let endpoint = resolve_gemini_stream_endpoint(&request.config);let api_key = normalized_api_key(&request.config).to_string();+ let headers = custom_headers(&request.config)?;let config = request.config.clone();let emitted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));@@ -3440,6 +3481,7 @@ async fn stream_gemini(let body = body.clone();let endpoint = endpoint.clone();let api_key = api_key.clone();+ let headers = headers.clone();let session_id = session_id.to_string();let emitted = emitted.clone();async move {@@ -3447,6 +3489,7 @@ async fn stream_gemini(.post(&endpoint).query(&[("key", api_key.as_str()), ("alt", "sse")]).header(CONTENT_TYPE, "application/json")+ .headers(headers).json(&body).send().await@@ -4278,6 +4321,7 @@ async fn stream_gemini_with_tools(let endpoint = resolve_gemini_stream_endpoint(&request.config);let api_key = normalized_api_key(&request.config).to_string();+ let headers = custom_headers(&request.config)?;let config = request.config.clone();let emitted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));@@ -4285,6 +4329,7 @@ async fn stream_gemini_with_tools(let body = body.clone();let endpoint = endpoint.clone();let api_key = api_key.clone();+ let headers = headers.clone();let session_id = session_id.to_string();let emitted = emitted.clone();async move {@@ -4292,6 +4337,7 @@ async fn stream_gemini_with_tools(.post(&endpoint).query(&[("key", api_key.as_str()), ("alt", "sse")]).header(CONTENT_TYPE, "application/json")+ .headers(headers).json(&body).send().await@@ -4490,7 +4536,8 @@ mod tests {AiAuthMethod, AiCapabilitySource, AiChatSelectionState, AiCompletionRequest, AiConfig, AiEffortCapability,AiEffortOption, AiEffortSelection, AiInlineImage, AiMessage, AiModelInfo, AiProvider, AiReasoningLevel,MiniMaxStreamDelta, MiniMaxStreamState, MiniMaxTextAccumulator, StreamToolEvent, StreamingToolCallAccumulator,- ToolCallRef, AUTHORIZATION, CLAUDE_DEFAULT_SYSTEM, MINIMAX_REASONING_DETAILS_PAYLOAD_KEY, TEST_PROMPT,+ ToolCallRef, AUTHORIZATION, CLAUDE_DEFAULT_SYSTEM, CONTENT_TYPE, MINIMAX_REASONING_DETAILS_PAYLOAD_KEY,+ TEST_PROMPT,};#[test]@@ -4758,6 +4805,7 @@ mod tests {model: "claude-sonnet-4-6[1m]".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5420,6 +5468,7 @@ mod tests {model: "gpt-4o".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: true,proxy_url: "not a proxy url".to_string(),enable_thinking: true,@@ -5460,6 +5509,7 @@ mod tests {model: "gpt-4o".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: true,proxy_url: "127.0.0.1:7890".to_string(),enable_thinking: true,@@ -5498,6 +5548,7 @@ mod tests {model: "gpt-4o".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: true,proxy_url: "not a proxy url".to_string(),enable_thinking: true,@@ -5536,6 +5587,7 @@ mod tests {model: "gemini-1.5-pro".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5578,6 +5630,7 @@ mod tests {model: "llama3.1".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5617,6 +5670,7 @@ mod tests {model: "local-model".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5675,6 +5729,7 @@ mod tests {model: String::new(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5709,6 +5764,7 @@ mod tests {model: String::new(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5746,6 +5802,7 @@ mod tests {model: "claude-sonnet-4-20250514".to_string(),models: Vec::new(),api_style: AiApiStyle::AnthropicMessages,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5835,6 +5892,7 @@ mod tests {model: "MiniMax-M3".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5894,6 +5952,7 @@ mod tests {model: "test-model".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5967,6 +6026,7 @@ mod tests {model: "gpt-5.6-luna".to_string(),models: Vec::new(),api_style: AiApiStyle::Responses,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -5997,6 +6057,7 @@ mod tests {let completions = AiConfig {endpoint: "https://api.openai.com/v1/responses".to_string(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),..config};assert_eq!(resolve_endpoint(&completions), "https://api.openai.com/v1/chat/completions");@@ -6012,6 +6073,7 @@ mod tests {model: "claude-sonnet-4-20250514".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -6058,6 +6120,34 @@ mod tests {assert_eq!(unauthenticated_headers.get("anthropic-version").unwrap(), "2023-06-01");}+ #[test]+ fn custom_ai_headers_are_merged_and_protect_http_framing() {+ let mut config = test_config(AiProvider::OpenaiCompatible);+ config.api_key = "provider-key".to_string();+ config.custom_headers = HashMap::from([+ ("X-GoModel-User-Path".to_string(), "/dbx-assistant".to_string()),+ ("Authorization".to_string(), "Bearer gateway-token".to_string()),+ ]);++ let headers = maybe_bearer_headers(&config).unwrap();+ assert_eq!(headers.get("x-gomodel-user-path").unwrap(), "/dbx-assistant");+ assert_eq!(headers.get(AUTHORIZATION).unwrap(), "Bearer gateway-token");+ assert_eq!(headers.get(CONTENT_TYPE).unwrap(), "application/json");++ config.custom_headers = HashMap::from([("Content-Length".to_string(), "0".to_string())]);+ assert!(maybe_bearer_headers(&config).unwrap_err().contains("reserved by DBX"));++ config.custom_headers =+ HashMap::from([("X-Tenant".to_string(), "one".to_string()), ("x-tenant".to_string(), "two".to_string())]);+ assert!(maybe_bearer_headers(&config).unwrap_err().contains("Duplicate AI custom header name"));++ config.custom_headers = HashMap::from([("bad header".to_string(), "value".to_string())]);+ assert!(maybe_bearer_headers(&config).unwrap_err().contains("Invalid AI custom header name"));++ config.custom_headers = HashMap::from([("X-Test".to_string(), "bad\r\nvalue".to_string())]);+ assert!(maybe_bearer_headers(&config).unwrap_err().contains("Invalid AI custom header value"));+ }+#[test]fn claude_system_prompt_substitutes_default_when_empty() {// Empty or whitespace-only prompts must fall back to a non-empty value,@@ -6137,6 +6227,7 @@ mod tests {model: String::new(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6179,6 +6270,7 @@ mod tests {model: "qwen3:0.6b".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6270,6 +6362,7 @@ mod tests {model: String::new(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6544,6 +6637,7 @@ mod tests {model: "gpt-5.5".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -6765,6 +6859,7 @@ mod tests {model: "kimi-k2.5".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6812,6 +6907,7 @@ mod tests {model: "gpt-5".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6865,6 +6961,7 @@ mod tests {model: "qwen3".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -6912,6 +7009,7 @@ mod tests {model: "MiniMax-M3".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -7303,6 +7401,7 @@ mod tests {model: "qwen3".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,@@ -7377,6 +7476,7 @@ mod tests {model: "local-model".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -7446,6 +7546,7 @@ mod tests {model: "deepseek-r1:14b".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,diff --git a/crates/dbx-core/src/ai_claude_code_cli.rs b/crates/dbx-core/src/ai_claude_code_cli.rsindex 5aa2db0e49..6cd0f444cb 100644--- a/crates/dbx-core/src/ai_claude_code_cli.rs+++ b/crates/dbx-core/src/ai_claude_code_cli.rs@@ -568,6 +568,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_codebuddy_cli.rs b/crates/dbx-core/src/ai_codebuddy_cli.rsindex 7a41e803bb..fe752fb90d 100644--- a/crates/dbx-core/src/ai_codebuddy_cli.rs+++ b/crates/dbx-core/src/ai_codebuddy_cli.rs@@ -923,6 +923,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_codex_cli.rs b/crates/dbx-core/src/ai_codex_cli.rsindex f0eeac59b2..d16818427a 100644--- a/crates/dbx-core/src/ai_codex_cli.rs+++ b/crates/dbx-core/src/ai_codex_cli.rs@@ -1114,6 +1114,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_cursor_cli.rs b/crates/dbx-core/src/ai_cursor_cli.rsindex 735697a8f7..d49cef3a70 100644--- a/crates/dbx-core/src/ai_cursor_cli.rs+++ b/crates/dbx-core/src/ai_cursor_cli.rs@@ -405,6 +405,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_effort.rs b/crates/dbx-core/src/ai_effort.rsindex d1665c99fa..8a03a6fbe9 100644--- a/crates/dbx-core/src/ai_effort.rs+++ b/crates/dbx-core/src/ai_effort.rs@@ -423,6 +423,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_grok_cli.rs b/crates/dbx-core/src/ai_grok_cli.rsindex 21c8befd53..60e48a8ae8 100644--- a/crates/dbx-core/src/ai_grok_cli.rs+++ b/crates/dbx-core/src/ai_grok_cli.rs@@ -785,6 +785,7 @@ mod tests {model: "default".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_opencode_cli.rs b/crates/dbx-core/src/ai_opencode_cli.rsindex 6cca558baf..0ace5290c0 100644--- a/crates/dbx-core/src/ai_opencode_cli.rs+++ b/crates/dbx-core/src/ai_opencode_cli.rs@@ -451,6 +451,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_pi_agent_cli.rs b/crates/dbx-core/src/ai_pi_agent_cli.rsindex 23b57fb843..2a8c45db1e 100644--- a/crates/dbx-core/src/ai_pi_agent_cli.rs+++ b/crates/dbx-core/src/ai_pi_agent_cli.rs@@ -859,6 +859,7 @@ mod tests {model: "openai-codex/gpt-5.4".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/ai_qoder_cli.rs b/crates/dbx-core/src/ai_qoder_cli.rsindex 3ae89e7347..b4ce8c96f0 100644--- a/crates/dbx-core/src/ai_qoder_cli.rs+++ b/crates/dbx-core/src/ai_qoder_cli.rs@@ -527,6 +527,7 @@ mod tests {model: model.to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rsindex 59da1fafda..a34d48b851 100644--- a/crates/dbx-core/src/cloud_sync.rs+++ b/crates/dbx-core/src/cloud_sync.rs@@ -1634,6 +1634,7 @@ mod tests {model: "gpt-4o-mini".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rsindex 68f9e01196..122f0ba65a 100644--- a/crates/dbx-core/src/storage.rs+++ b/crates/dbx-core/src/storage.rs@@ -7239,6 +7239,7 @@ mod tests {model: "gpt-4o".to_string(),models: Vec::new(),api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,diff --git a/crates/dbx-web/src/routes/ai.rs b/crates/dbx-web/src/routes/ai.rsindex 3e72c4f69a..f6fb110861 100644--- a/crates/dbx-web/src/routes/ai.rs+++ b/crates/dbx-web/src/routes/ai.rs@@ -521,6 +521,7 @@ mod tests {model: "test".to_string(),models: vec![],api_style: AiApiStyle::Completions,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: true,@@ -627,6 +628,7 @@ mod tests {model: "claude-sonnet-4".to_string(),models: vec![],api_style: AiApiStyle::AnthropicMessages,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,diff --git a/docs/content/docs/ai-assistant.cn.mdx b/docs/content/docs/ai-assistant.cn.mdxindex d02e68a999..c2ece02c84 100644--- a/docs/content/docs/ai-assistant.cn.mdx+++ b/docs/content/docs/ai-assistant.cn.mdx@@ -24,7 +24,7 @@ DBX 内置以下配置预设:- Anthropic Compatible- Custom-兼容或自定义配置可以设置端点、模型、API 风格、认证方式、代理和上下文窗口。API 风格包括 OpenAI 风格 completions、Responses API 和 Anthropic Messages。供应商支持时,DBX 会读取模型列表并过滤掉不适合对话/Agent 的模型。+兼容或自定义配置可以设置端点、模型、API 风格、认证方式、代理、上下文窗口和额外 HTTP 请求头。API 风格包括 OpenAI 风格 completions、Responses API 和 Anthropic Messages。供应商支持时,DBX 会读取模型列表并过滤掉不适合对话/Agent 的模型。### 本地 CLI Agent@@ -54,7 +54,7 @@ Desktop 还可以直接调用已安装并登录的:<Step>### 配置认证和推理参数- API 模式填写 API Key、认证方式、端点和代理。支持的模型可以选择 effort、reasoning 或 thinking;具体选项来自供应商能力,而不是对所有模型统一显示。+ API 模式填写 API Key、认证方式、端点、代理和自定义 HTTP 请求头。请求头可用于网关认证或租户路由,例如 `X-GoModel-User-Path: /dbx-assistant`;模型发现、连接测试、对话和 Agent 请求都会携带它们。支持的模型可以选择 effort、reasoning 或 thinking;具体选项来自供应商能力,而不是对所有模型统一显示。</Step><Step>@@ -65,7 +65,7 @@ Desktop 还可以直接调用已安装并登录的:</Step></Steps>-API Key、CLI 环境变量和自定义端点可能具有敏感性。不要把设置截图、导出的配置或调试日志发送到不可信位置。+API Key、自定义请求头的值、CLI 环境变量和自定义端点可能具有敏感性。不要把设置截图、导出的配置或调试日志发送到不可信位置。## Ask 和 Agentdiff --git a/docs/content/docs/ai-assistant.mdx b/docs/content/docs/ai-assistant.mdxindex bee992cae0..67c8de6564 100644--- a/docs/content/docs/ai-assistant.mdx+++ b/docs/content/docs/ai-assistant.mdx@@ -24,7 +24,7 @@ DBX includes presets for:- Anthropic Compatible- Custom-Compatible and custom configurations can set the endpoint, model, API style, authentication method, proxy, and context window. API styles include OpenAI-style completions, the Responses API, and Anthropic Messages. When supported, DBX discovers models and filters out endpoints that are not suitable for assistant or Agent use.+Compatible and custom configurations can set the endpoint, model, API style, authentication method, proxy, context window, and extra HTTP headers. API styles include OpenAI-style completions, the Responses API, and Anthropic Messages. When supported, DBX discovers models and filters out endpoints that are not suitable for assistant or Agent use.### Local CLI Agents@@ -54,7 +54,7 @@ You can configure the executable path and additional environment variables. CLI<Step>### Configure Authentication and Reasoning- API modes accept an API key, auth method, endpoint, and proxy. Supported models expose effort, reasoning, or thinking controls based on provider capabilities rather than one universal setting.+ API modes accept an API key, auth method, endpoint, proxy, and custom HTTP headers. Use headers for gateway authentication or tenant routing, for example `X-GoModel-User-Path: /dbx-assistant`; they are sent for model discovery, connection tests, chat, and Agent requests. Supported models expose effort, reasoning, or thinking controls based on provider capabilities rather than one universal setting.</Step><Step>@@ -65,7 +65,7 @@ You can configure the executable path and additional environment variables. CLI</Step></Steps>-API keys, CLI environment variables, and custom endpoints may be sensitive. Do not share configuration screenshots, exports, or debug logs with untrusted parties.+API keys, custom header values, CLI environment variables, and custom endpoints may be sensitive. Do not share configuration screenshots, exports, or debug logs with untrusted parties.## Ask and Agentdiff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rsindex 7ccf3eda8b..041a1010a9 100644--- a/src-tauri/src/commands/ai.rs+++ b/src-tauri/src/commands/ai.rs@@ -665,6 +665,7 @@ mod tests {model: model.to_string(),models: vec![],api_style: AiApiStyle::AnthropicMessages,+ custom_headers: Default::default(),proxy_enabled: false,proxy_url: String::new(),enable_thinking: false,