From 71cfdcb33e2b5644bf2f2e4d9e351a8d96d68f89 Mon Sep 17 00:00:00 2001 From: Zyy Date: Sat, 28 Nov 2026 22:51:01 +0800 Subject: [PATCH] feat(settings): add provider-scoped prompt rewrite rules Co-authored-by: Codex --- .../gateway-admin/src/model/settings.rs | 1 + .../tests/use_case/accounts/mod.rs | 1 + .../tests/use_case/freeze_recovery.rs | 1 + .../tests/use_case/observability/mod.rs | 1 + .../tests/use_case/service_contract.rs | 14 ++- .../gateway-admin/tests/use_case/settings.rs | 1 + .../crates/gateway-api/src/admin/settings.rs | 3 + backend/crates/gateway-api/tests/admin/mod.rs | 1 + .../gateway-api/tests/admin/settings.rs | 13 ++ .../gateway-core/src/engine/coordinator.rs | 1 + backend/crates/gateway-core/src/engine/mod.rs | 33 +++++ .../gateway-core/src/engine/prompt_rewrite.rs | 25 ++++ backend/crates/gateway-core/src/operation.rs | 17 +++ .../crates/gateway-core/src/routing/mod.rs | 9 ++ .../gateway-core/src/routing/snapshot.rs | 2 + .../gateway-core/src/settings/compiled.rs | 12 ++ .../crates/gateway-core/src/settings/mod.rs | 1 + .../src/settings/prompt_rewrite.rs | 106 ++++++++++++++++ .../gateway-core/src/settings/values.rs | 12 ++ .../crates/gateway-core/tests/operation.rs | 26 ++++ .../gateway-core/tests/routing/snapshot.rs | 57 +++++++++ .../gateway-plugin/sdk/docs/capabilities.md | 2 +- .../sdk/src/call/services/settings.rs | 11 ++ backend/crates/gateway-protocol/Cargo.toml | 2 +- .../crates/gateway-protocol/src/genai/mod.rs | 2 +- .../gateway-protocol/src/genai/tokens.rs | 26 +++- backend/crates/gateway-protocol/src/lib.rs | 3 + .../src/prompt_rewrite/mod.rs | 115 ++++++++++++++++++ .../src/prompt_rewrite/wire.rs | 44 +++++++ .../crates/gateway-protocol/src/request.rs | 4 +- backend/crates/gateway-protocol/tests/main.rs | 1 + .../tests/prompt_rewrite/mod.rs | 43 +++++++ .../tests/prompt_rewrite/wire.rs | 50 ++++++++ .../crates/gateway-protocol/tests/request.rs | 4 + .../crates/gateway-store/src/admin_adapter.rs | 1 + .../src/postgres/runtime_settings.rs | 9 +- .../gateway-store/src/postgres/snapshot.rs | 5 +- .../tests/postgres/runtime_settings.rs | 33 +++++ .../antigravity/src/provider/count.rs | 10 +- .../antigravity/src/provider/execution.rs | 11 +- .../antigravity/src/transport/client.rs | 16 ++- .../antigravity/src/transport/request.rs | 13 +- .../antigravity/tests/provider/execution.rs | 29 +++-- .../antigravity/tests/transport/count.rs | 25 +++- .../openai/src/provider/messages/count.rs | 1 + .../tests/provider/contract/messages/mod.rs | 33 +++-- .../xai/tests/provider/contract/mod.rs | 21 +++- backend/migrations/.frozen-sha256 | 1 + .../migrations/0050_prompt_rewrite_rules.sql | 3 + docs/api.md | 13 +- docs/architecture.md | 6 +- frontend/src/api/modules/settings/index.ts | 7 ++ frontend/src/components/ProviderSelect.vue | 6 +- frontend/src/i18n/locales/en/settings.json | 12 +- .../src/i18n/locales/zh-Hans/settings.json | 12 +- .../src/i18n/locales/zh-Hant/settings.json | 12 +- .../AntigravityRequestProfileEditor.vue | 32 +---- .../antigravity/request-profile/profile.ts | 2 - .../components/PromptRewriteRulesCard.vue | 88 ++++++++++++++ .../settings/composables/useSettingsForm.ts | 5 +- frontend/src/views/settings/index.vue | 2 + 61 files changed, 950 insertions(+), 102 deletions(-) create mode 100644 backend/crates/gateway-core/src/engine/prompt_rewrite.rs create mode 100644 backend/crates/gateway-core/src/settings/prompt_rewrite.rs create mode 100644 backend/crates/gateway-protocol/src/prompt_rewrite/mod.rs create mode 100644 backend/crates/gateway-protocol/src/prompt_rewrite/wire.rs create mode 100644 backend/crates/gateway-protocol/tests/prompt_rewrite/mod.rs create mode 100644 backend/crates/gateway-protocol/tests/prompt_rewrite/wire.rs create mode 100644 backend/migrations/0050_prompt_rewrite_rules.sql create mode 100644 frontend/src/views/settings/components/PromptRewriteRulesCard.vue diff --git a/backend/crates/gateway-admin/src/model/settings.rs b/backend/crates/gateway-admin/src/model/settings.rs index b7d24238f..9e05be5c9 100644 --- a/backend/crates/gateway-admin/src/model/settings.rs +++ b/backend/crates/gateway-admin/src/model/settings.rs @@ -71,6 +71,7 @@ pub struct RuntimeSettingsValues { pub usage_retention_days: u32, pub ops_event_retention_days: u32, pub audit_retention_days: u32, + pub prompt_rewrite_rules: Vec, pub account_error_protection: gateway_core::account::AccountErrorProtection, pub account_warmup_enabled: bool, pub account_warmup_cron: String, diff --git a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs index 4fe73eb16..c26f537ba 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs @@ -1229,6 +1229,7 @@ impl SettingsStore for StaticSettingsStore { usage_retention_days: 30, ops_event_retention_days: 30, audit_retention_days: 30, + prompt_rewrite_rules: Vec::new(), account_error_protection: gateway_core::account::AccountErrorProtection::default(), account_warmup_enabled: false, account_warmup_cron: "0 8 * * *".to_owned(), diff --git a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs index db3524337..95788d352 100644 --- a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs +++ b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs @@ -62,6 +62,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings { usage_retention_days: 31, ops_event_retention_days: 30, audit_retention_days: 90, + prompt_rewrite_rules: Vec::new(), account_error_protection: gateway_core::account::AccountErrorProtection { enabled, probe_enabled, diff --git a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs index e2d08e64b..e988f9e1b 100644 --- a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs @@ -366,6 +366,7 @@ impl SettingsStore for FixtureSettingsStore { usage_retention_days: 31, ops_event_retention_days: 30, audit_retention_days: 30, + prompt_rewrite_rules: Vec::new(), account_error_protection: gateway_core::account::AccountErrorProtection::default(), account_warmup_enabled: false, account_warmup_cron: "0 8 * * *".to_owned(), diff --git a/backend/crates/gateway-admin/tests/use_case/service_contract.rs b/backend/crates/gateway-admin/tests/use_case/service_contract.rs index bccadb59a..7e8e8cbc6 100644 --- a/backend/crates/gateway-admin/tests/use_case/service_contract.rs +++ b/backend/crates/gateway-admin/tests/use_case/service_contract.rs @@ -56,7 +56,9 @@ impl VisitMut for WireTypes { } let last = path.path.segments.last().unwrap().clone(); *ty = match last.ident.to_string().as_str() { - "DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" => parse_quote!(String), + "DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" | "ProviderKind" => { + parse_quote!(String) + } "Value" => parse_quote!(serde_json::Value), "OpaqueProviderData" => parse_quote!(serde_json::Map), _ => Type::Path(syn::TypePath { @@ -80,6 +82,7 @@ fn contract_type(mut item: Item, name: &str) -> Item { | "ReplaceRuntimeSettings" | "AdminApiKeyMutation" | "RegeneratedAdminApiKey" + | "PromptRewriteRule" | "CodexPrivacyPolicy" | "PrivacyRule" | "PrivacyStep" @@ -113,6 +116,11 @@ fn contract_type(mut item: Item, name: &str) -> Item { if let Some(fields) = fields { for field in fields { field.vis = parse_quote!(pub); + // 非空前缀由宿主在接收设置时校验,SDK 只描述字符串合同 + if name == "PromptRewriteRule" && field.ident.as_ref().is_some_and(|id| id == "pattern") + { + field.attrs.retain(|attr| !attr.path().is_ident("serde")); + } } } if let Item::Enum(item) = &mut item { @@ -225,6 +233,10 @@ fn sdk_settings_contract_matches_host_declarations() { "AccountErrorOperator", ][..], ), + ( + "../gateway-core/src/settings/prompt_rewrite.rs", + &["PromptRewriteRule"][..], + ), ( "../gateway-core/src/settings/websocket.rs", &["OpenAiWebSocketPoolSettings"][..], diff --git a/backend/crates/gateway-admin/tests/use_case/settings.rs b/backend/crates/gateway-admin/tests/use_case/settings.rs index 62fd73a8e..2cc795484 100644 --- a/backend/crates/gateway-admin/tests/use_case/settings.rs +++ b/backend/crates/gateway-admin/tests/use_case/settings.rs @@ -376,6 +376,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() { usage_retention_days: 31, ops_event_retention_days: 30, audit_retention_days: 30, + prompt_rewrite_rules: Vec::new(), account_error_protection: gateway_core::account::AccountErrorProtection::default(), account_warmup_enabled: false, diff --git a/backend/crates/gateway-api/src/admin/settings.rs b/backend/crates/gateway-api/src/admin/settings.rs index 9b5f11e79..1f3915cef 100644 --- a/backend/crates/gateway-api/src/admin/settings.rs +++ b/backend/crates/gateway-api/src/admin/settings.rs @@ -62,6 +62,7 @@ pub struct RuntimeSettingsFields { pub usage_retention_days: u64, pub ops_event_retention_days: u64, pub audit_retention_days: u64, + pub prompt_rewrite_rules: Vec, pub account_error_protection: gateway_core::account::AccountErrorProtection, pub account_warmup_enabled: bool, pub account_warmup_cron: String, @@ -744,6 +745,7 @@ impl RuntimeSettingsFields { .map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?, audit_retention_days: u32::try_from(self.audit_retention_days) .map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?, + prompt_rewrite_rules: self.prompt_rewrite_rules, account_error_protection: self.account_error_protection, account_warmup_enabled: self.account_warmup_enabled, account_warmup_cron: self.account_warmup_cron, @@ -787,6 +789,7 @@ impl From for RuntimeSett usage_retention_days: u64::from(settings.usage_retention_days), ops_event_retention_days: u64::from(settings.ops_event_retention_days), audit_retention_days: u64::from(settings.audit_retention_days), + prompt_rewrite_rules: settings.prompt_rewrite_rules, account_error_protection: settings.account_error_protection, account_warmup_enabled: settings.account_warmup_enabled, account_warmup_cron: settings.account_warmup_cron, diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index 6f249b17a..4c027a495 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -2016,6 +2016,7 @@ fn test_runtime_settings() -> RuntimeSettings { usage_retention_days: 31, ops_event_retention_days: 30, audit_retention_days: 90, + prompt_rewrite_rules: Vec::new(), account_error_protection: Default::default(), account_warmup_enabled: false, account_warmup_cron: "0 8 * * *".to_owned(), diff --git a/backend/crates/gateway-api/tests/admin/settings.rs b/backend/crates/gateway-api/tests/admin/settings.rs index 0578c69a6..84879d992 100644 --- a/backend/crates/gateway-api/tests/admin/settings.rs +++ b/backend/crates/gateway-api/tests/admin/settings.rs @@ -106,6 +106,7 @@ fn update_body() -> Value { "usageRetentionDays": 31, "opsEventRetentionDays": 31, "auditRetentionDays": 91, + "promptRewriteRules": [], "accountErrorProtection": gateway_core::account::AccountErrorProtection::default(), "accountWarmupEnabled": false, "accountWarmupCron": "0 8 * * *", @@ -289,6 +290,18 @@ async fn error_protection_rules_round_trip_and_invalid_policy_does_not_replace_t ); } +#[test] +fn prompt_rewrite_rejects_unknown_scope_fields_and_empty_prefixes() { + let mut body = update_body(); + for rule in [ + json!({"pattern":"prefix", "replacement":"", "unknownField":["xai"]}), + json!({"pattern":"", "replacement":""}), + ] { + body["promptRewriteRules"] = json!([rule]); + assert!(serde_json::from_value::(body.clone()).is_err()); + } +} + #[test] fn error_protection_requires_an_explicit_policy_in_settings_replacement() { let mut missing = update_body(); diff --git a/backend/crates/gateway-core/src/engine/coordinator.rs b/backend/crates/gateway-core/src/engine/coordinator.rs index f90f2eeed..0ae9a7961 100644 --- a/backend/crates/gateway-core/src/engine/coordinator.rs +++ b/backend/crates/gateway-core/src/engine/coordinator.rs @@ -1201,6 +1201,7 @@ where .with_response_control(self.response_control.clone()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) .with_fast_mode(self.plan.fast_mode()) + .with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider())) .with_pricing(self.plan.pricing()) .with_request_location(self.plan.request_location().cloned()) .with_openai_websocket_pool(*self.plan.openai_websocket_pool()) diff --git a/backend/crates/gateway-core/src/engine/mod.rs b/backend/crates/gateway-core/src/engine/mod.rs index e5c82e727..b941c0068 100644 --- a/backend/crates/gateway-core/src/engine/mod.rs +++ b/backend/crates/gateway-core/src/engine/mod.rs @@ -16,6 +16,7 @@ pub mod nested; pub mod observation; pub mod policy; pub mod probe; +mod prompt_rewrite; pub mod provider; pub mod response_control; pub mod upstream_adapter; @@ -324,6 +325,7 @@ pub struct RequestAttemptContext { request_body_limit: Option, lease_metadata: Option>, response_control: Option, + prompt_rewrite_rules: Option>, pricing: Arc, request_profile: Option, fast_mode: FastMode, @@ -396,6 +398,15 @@ impl RequestAttemptContext { self } + #[must_use] + pub fn with_prompt_rewrite_rules( + mut self, + rules: Option>, + ) -> Self { + self.prompt_rewrite_rules = rules; + self + } + #[must_use] pub fn with_pricing(mut self, pricing: Arc) -> Self { self.pricing = pricing; @@ -463,6 +474,7 @@ impl RequestAttemptContext { request_id, client_api_key_ref, request_profile: None, + prompt_rewrite_rules: None, pricing: Arc::default(), fast_mode: FastMode::Default, openai_websocket_pool: Default::default(), @@ -832,6 +844,21 @@ impl AttemptContext { self.request.extension_scope() } + /// 计数由 Provider 解开入站封套后在现有正文上应用同一份规则 + pub fn rewrite_count_prompt( + &self, + protocol: &str, + body: &mut serde_json::Map, + ) { + if let Some(rules) = &self.request.prompt_rewrite_rules + && let Some(edit) = gateway_protocol::prompt_rewrite::plan(protocol, body, |text| { + rules.replace_prefix(text) + }) + { + edit.apply(body); + } + } + /// 在已选账号并持有其 lease 后,以 owned terminal 执行本次 retry 的中间件链 /// /// terminal 返回的 stream 仍须保持 cold;中间件不能取得 credential、发送状态、 @@ -860,6 +887,12 @@ impl AttemptContext { } else { terminal }; + let terminal = match (&operation, &self.request.prompt_rewrite_rules) { + (crate::operation::Operation::Generate(_), Some(rules)) => { + prompt_rewrite::wrap(terminal, rules) + } + _ => terminal, + }; // 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写 let terminal: provider::ProviderMiddlewareTerminal = if let Some(protection) = self.request.account_error_protection.clone() { diff --git a/backend/crates/gateway-core/src/engine/prompt_rewrite.rs b/backend/crates/gateway-core/src/engine/prompt_rewrite.rs new file mode 100644 index 000000000..d597c3882 --- /dev/null +++ b/backend/crates/gateway-core/src/engine/prompt_rewrite.rs @@ -0,0 +1,25 @@ +//! 在 attempt 中间件提交后应用所选平台的生成规则 + +use super::provider::ProviderMiddlewareTerminal; +use crate::{operation::Operation, settings::prompt_rewrite::ProviderPromptRules}; +use std::sync::Arc; + +pub(super) fn wrap( + terminal: ProviderMiddlewareTerminal, + rules: &Arc, +) -> ProviderMiddlewareTerminal { + let rules = Arc::clone(rules); + Box::new(move |mut operation, headers| { + if let Operation::Generate(request) = &mut operation { + let payload = request.protocol_payload(); + if let Some(edit) = + gateway_protocol::prompt_rewrite::plan(payload.protocol(), payload.body(), |text| { + rules.replace_prefix(text) + }) + { + request.apply_prompt_edit(edit); + } + } + terminal(operation, headers) + }) +} diff --git a/backend/crates/gateway-core/src/operation.rs b/backend/crates/gateway-core/src/operation.rs index a3ec64d28..95713bd87 100644 --- a/backend/crates/gateway-core/src/operation.rs +++ b/backend/crates/gateway-core/src/operation.rs @@ -462,6 +462,23 @@ impl ClientTurn { } impl GenerateRequest { + /// 只在命中后对共享请求执行写时复制,重试持有的原请求仍可独立使用 + pub(crate) fn apply_prompt_edit(&mut self, edit: gateway_protocol::prompt_rewrite::PromptEdit) { + let wire = match self.protocol_payload().raw_json_body() { + Some(body) => { + let Some(updated) = edit.wire(body) else { + return; + }; + Some(Bytes::from(updated)) + } + None => None, + }; + let payload = Arc::make_mut(&mut self.payload); + edit.apply(&mut payload.protocol_payload.body); + payload.protocol_payload.raw_json_body = wire; + // 只编辑字符串内容,能力、角色与工具结构仍使用已有的 wire_facts + } + /// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源 #[must_use] pub fn source_protocol(&self) -> &str { diff --git a/backend/crates/gateway-core/src/routing/mod.rs b/backend/crates/gateway-core/src/routing/mod.rs index 53e335f27..71908bdd8 100644 --- a/backend/crates/gateway-core/src/routing/mod.rs +++ b/backend/crates/gateway-core/src/routing/mod.rs @@ -714,6 +714,7 @@ impl ProviderCandidate { /// 一次请求冻结的 Provider 尝试顺序 #[derive(Debug, Clone)] pub struct RoutingPlan { + prompt_rewrite: Arc, account_error_protection: Arc, account_error_protection_revision: u64, request_body_limit: usize, @@ -732,6 +733,14 @@ pub struct RoutingPlan { } impl RoutingPlan { + #[must_use] + pub fn prompt_rewrite_rules( + &self, + provider: &ProviderKind, + ) -> Option> { + self.prompt_rewrite.for_provider(provider) + } + #[must_use] pub const fn account_error_protection_revision(&self) -> u64 { self.account_error_protection_revision diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index e9f2e1568..844380e0a 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -2060,6 +2060,7 @@ impl RuntimeSnapshot { self.settings.values.max_retry_after_seconds, )), config_revision: self.revision, + prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite), pricing: Arc::clone(&self.settings.values.pricing), openai_websocket_pool: *self.settings.values.openai_websocket_pool(), openai_request_settings: self.settings.values.openai_request_settings().clone(), @@ -2153,6 +2154,7 @@ impl RuntimeSnapshot { self.settings.values.max_retry_after_seconds, )), config_revision: self.revision, + prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite), pricing: Arc::clone(&self.settings.values.pricing), openai_websocket_pool: *self.settings.values.openai_websocket_pool(), openai_request_settings: self.settings.values.openai_request_settings().clone(), diff --git a/backend/crates/gateway-core/src/settings/compiled.rs b/backend/crates/gateway-core/src/settings/compiled.rs index 34c7d1117..b29954ca2 100644 --- a/backend/crates/gateway-core/src/settings/compiled.rs +++ b/backend/crates/gateway-core/src/settings/compiled.rs @@ -13,6 +13,7 @@ use crate::{ #[derive(Debug, Clone)] pub(crate) struct CompiledSettings { pub(crate) values: SettingsValues, + pub(crate) prompt_rewrite: std::sync::Arc, pub(crate) account_error_protection: std::sync::Arc, pub(crate) privacy: Option>, @@ -40,6 +41,16 @@ impl CompiledSettings { .account_error_protection .validate() .map_err(|_| InvalidSettings)?; + let prompt_rewrite = previous + .filter(|prior| prior.values.prompt_rewrite_rules == settings.prompt_rewrite_rules) + .map_or_else( + || { + std::sync::Arc::new(super::prompt_rewrite::CompiledPromptRewrite::new( + std::sync::Arc::clone(&settings.prompt_rewrite_rules), + )) + }, + |prior| prior.prompt_rewrite.clone(), + ); let account_error_protection = previous .filter(|previous| { previous.values.account_error_protection == settings.account_error_protection @@ -130,6 +141,7 @@ impl CompiledSettings { } } Ok(Self { + prompt_rewrite, account_error_protection, account_selection_policy, client_queue_policy, diff --git a/backend/crates/gateway-core/src/settings/mod.rs b/backend/crates/gateway-core/src/settings/mod.rs index 56929992b..f3b63f66c 100644 --- a/backend/crates/gateway-core/src/settings/mod.rs +++ b/backend/crates/gateway-core/src/settings/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod compiled; mod openai; pub mod privacy; +pub mod prompt_rewrite; pub mod request_profiles; mod values; mod websocket; diff --git a/backend/crates/gateway-core/src/settings/prompt_rewrite.rs b/backend/crates/gateway-core/src/settings/prompt_rewrite.rs new file mode 100644 index 000000000..9b4e0fd8d --- /dev/null +++ b/backend/crates/gateway-core/src/settings/prompt_rewrite.rs @@ -0,0 +1,106 @@ +//! 按目标上游索引规则,共享配置原文,按配置顺序匹配前缀 + +use crate::identity::ProviderKind; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt, + sync::Arc, +}; + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PromptRewriteRule { + #[serde(default)] + providers: BTreeSet, + #[serde(deserialize_with = "nonempty_pattern")] + pattern: String, + replacement: String, +} + +impl fmt::Debug for PromptRewriteRule { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PromptRewriteRule") + .field("providers", &self.providers) + .finish_non_exhaustive() + } +} + +fn nonempty_pattern<'de, D: serde::Deserializer<'de>>(de: D) -> Result { + let pattern = String::deserialize(de)?; + if pattern.is_empty() { + return Err(serde::de::Error::custom("匹配文本不能为空")); + } + Ok(pattern) +} + +#[derive(Debug)] +pub struct ProviderPromptRules { + rules: Arc<[PromptRewriteRule]>, + global: Arc>, + scoped: BTreeSet, +} + +impl ProviderPromptRules { + pub fn replace_prefix(&self, text: &str) -> Option { + let (rule, suffix) = self + .global + .union(&self.scoped) + .map(|&index| &self.rules[index]) + .find_map(|rule| { + text.strip_prefix(&rule.pattern) + .map(|suffix| (rule, suffix)) + })?; + if rule.pattern == rule.replacement { + return None; + } + let mut updated = String::with_capacity(rule.replacement.len() + suffix.len()); + updated.push_str(&rule.replacement); + updated.push_str(suffix); + Some(updated) + } +} + +#[derive(Debug, Default)] +pub struct CompiledPromptRewrite { + all: Option>, + by_provider: BTreeMap>, +} + +impl CompiledPromptRewrite { + pub fn new(rules: Arc<[PromptRewriteRule]>) -> Self { + let mut global = BTreeSet::new(); + let mut scoped = BTreeMap::<_, BTreeSet<_>>::new(); + for (index, rule) in rules.iter().enumerate() { + if rule.providers.is_empty() { + global.insert(index); + } else { + for provider in &rule.providers { + scoped.entry(provider).or_default().insert(index); + } + } + } + let global = Arc::new(global); + let selection = |scoped| { + Arc::new(ProviderPromptRules { + rules: Arc::clone(&rules), + global: Arc::clone(&global), + scoped, + }) + }; + Self { + all: (!global.is_empty()).then(|| selection(BTreeSet::new())), + by_provider: scoped + .into_iter() + .map(|(id, indices)| (id.clone(), selection(indices))) + .collect(), + } + } + + pub fn for_provider(&self, provider: &ProviderKind) -> Option> { + self.by_provider + .get(provider) + .or(self.all.as_ref()) + .cloned() + } +} diff --git a/backend/crates/gateway-core/src/settings/values.rs b/backend/crates/gateway-core/src/settings/values.rs index 823a989d0..174cf565f 100644 --- a/backend/crates/gateway-core/src/settings/values.rs +++ b/backend/crates/gateway-core/src/settings/values.rs @@ -8,6 +8,8 @@ use crate::identity::ProviderKind; #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct SettingsValues { + #[serde(default)] + pub(crate) prompt_rewrite_rules: Arc<[super::prompt_rewrite::PromptRewriteRule]>, #[serde(default)] pub(crate) account_error_protection: crate::account::AccountErrorProtection, #[serde(skip, default = "initial_protection_revision")] @@ -45,6 +47,15 @@ fn initial_protection_revision() -> u64 { } impl SettingsValues { + #[must_use] + pub fn with_prompt_rewrite_rules( + mut self, + rules: Vec, + ) -> Self { + self.prompt_rewrite_rules = rules.into(); + self + } + #[must_use] pub const fn with_account_error_protection_revision(mut self, revision: u64) -> Self { self.account_error_protection_revision = revision; @@ -222,6 +233,7 @@ impl SettingsValues { min_codex_cli_version: Option, ) -> Self { Self { + prompt_rewrite_rules: Default::default(), account_error_protection: Default::default(), account_error_protection_revision: 1, request_profiles: Arc::default(), diff --git a/backend/crates/gateway-core/tests/operation.rs b/backend/crates/gateway-core/tests/operation.rs index 7055b75c3..fe38b9dc5 100644 --- a/backend/crates/gateway-core/tests/operation.rs +++ b/backend/crates/gateway-core/tests/operation.rs @@ -437,3 +437,29 @@ fn chat_source_survives_the_one_authorized_wire_translation() { .is_err() ); } + +#[test] +fn unmatched_prompt_prefixes_do_not_allocate_for_large_histories() { + use gateway_core::{identity::ProviderKind, settings::prompt_rewrite::CompiledPromptRewrite}; + use gateway_protocol::prompt_rewrite::plan; + let body = serde_json::json!({"instructions": "Custom instructions", "input": "x".repeat(1024 * 1024)}); + let body = body.as_object().unwrap(); + let rules = CompiledPromptRewrite::new( + serde_json::from_value(json!([{ + "pattern":"Unknown", "replacement":"Changed" + }])) + .unwrap(), + ) + .for_provider(&ProviderKind::new("openai").unwrap()) + .unwrap(); + let stats = allocation_counter::measure(|| { + for _ in 0..1000 { + assert!( + plan("openai", std::hint::black_box(body), |text| rules + .replace_prefix(text)) + .is_none() + ); + } + }); + assert_eq!(stats.count_total, 0); +} diff --git a/backend/crates/gateway-core/tests/routing/snapshot.rs b/backend/crates/gateway-core/tests/routing/snapshot.rs index d9ceb5270..a847bfe72 100644 --- a/backend/crates/gateway-core/tests/routing/snapshot.rs +++ b/backend/crates/gateway-core/tests/routing/snapshot.rs @@ -1817,6 +1817,63 @@ fn withdrawn_provider_keeps_accounts_without_becoming_a_route_or_expanding_group } } +#[test] +fn prompt_rules_are_selected_once_by_upstream_and_keep_global_order() { + let snapshot = super::snapshot(); + let plan_for = |rules| { + let configured = snapshot + .with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules)) + .unwrap(); + configured + .plan( + &PublicModelId::new("gpt-5.4").unwrap(), + &super::operation(), + configured.all_account_scope(), + &Default::default(), + ) + .unwrap() + }; + let openai = ProviderKind::new("openai").unwrap(); + let agy = ProviderKind::new("antigravity").unwrap(); + let xai = ProviderKind::new("xai").unwrap(); + let scoped = |targets, prefix| { + serde_json::from_value( + serde_json::json!({"providers": targets, "pattern": prefix, "replacement": ""}), + ) + .unwrap() + }; + let only_agy = plan_for(vec![scoped(vec!["antigravity"], "example"); 20]); + assert!(only_agy.prompt_rewrite_rules(&openai).is_none()); + let selected = only_agy.prompt_rewrite_rules(&agy).unwrap(); + assert_eq!( + selected.replace_prefix("example suffix").as_deref(), + Some(" suffix") + ); + assert!(Arc::ptr_eq( + &selected, + &only_agy.prompt_rewrite_rules(&agy).unwrap() + )); + + let mixed = plan_for(vec![ + scoped(vec![], "shared first"), + scoped(vec!["xai", "antigravity"], "shared"), + scoped(vec![], "sh"), + ]); + for provider in [&agy, &xai] { + let rules = mixed.prompt_rewrite_rules(provider).unwrap(); + assert_eq!(rules.replace_prefix("shared first!").as_deref(), Some("!")); + assert_eq!( + rules.replace_prefix("shared second").as_deref(), + Some(" second") + ); + } + let global = mixed.prompt_rewrite_rules(&openai).unwrap(); + assert_eq!( + global.replace_prefix("shared second").as_deref(), + Some("ared second") + ); +} + #[test] fn routing_plans_share_frozen_pricing_after_a_new_snapshot_is_published() { use gateway_core::{metering::PricingOverrides, runtime::RuntimeSnapshotHandle}; diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index c0f410cd3..479dc95ed 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与 `Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令; `Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。 -每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool` 和 `reset_credit_on_low_weekly_quota`。 +每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。清空提示词改写规则时提交空数组,范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。 版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务 `accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、 diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs index acd67665f..2ee5faebe 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs @@ -57,6 +57,14 @@ pub enum AccountErrorOperator { Equals, Contains, } +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PromptRewriteRule { + #[serde(default)] + pub providers: BTreeSet, + pub pattern: String, + pub replacement: String, +} #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OpenAiWebSocketPoolSettings { @@ -188,6 +196,7 @@ pub struct RuntimeSettings { pub usage_retention_days: u32, pub ops_event_retention_days: u32, pub audit_retention_days: u32, + pub prompt_rewrite_rules: Vec, pub account_error_protection: AccountErrorProtection, pub account_warmup_enabled: bool, pub account_warmup_cron: String, @@ -230,6 +239,7 @@ pub struct ReplaceRuntimeSettings { pub usage_retention_days: u32, pub ops_event_retention_days: u32, pub audit_retention_days: u32, + pub prompt_rewrite_rules: Vec, pub account_error_protection: AccountErrorProtection, pub account_warmup_enabled: bool, pub account_warmup_cron: String, @@ -444,6 +454,7 @@ impl From for ReplaceRuntimeSettings { usage_retention_days: settings.usage_retention_days, ops_event_retention_days: settings.ops_event_retention_days, audit_retention_days: settings.audit_retention_days, + prompt_rewrite_rules: settings.prompt_rewrite_rules, account_error_protection: settings.account_error_protection, account_warmup_enabled: settings.account_warmup_enabled, account_warmup_cron: settings.account_warmup_cron, diff --git a/backend/crates/gateway-protocol/Cargo.toml b/backend/crates/gateway-protocol/Cargo.toml index 09a6e134c..9f22c4528 100644 --- a/backend/crates/gateway-protocol/Cargo.toml +++ b/backend/crates/gateway-protocol/Cargo.toml @@ -18,7 +18,7 @@ http = "1.5.0" httpdate = "1.0.3" memchr = "2.8.3" serde = { version = "1.0.228", features = ["derive"] } -serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] } +serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order", "raw_value"] } thiserror = "2.0.18" uuid = { version = "1.23.3", features = ["v4"] } diff --git a/backend/crates/gateway-protocol/src/genai/mod.rs b/backend/crates/gateway-protocol/src/genai/mod.rs index d1148f590..3c4a9e2ef 100644 --- a/backend/crates/gateway-protocol/src/genai/mod.rs +++ b/backend/crates/gateway-protocol/src/genai/mod.rs @@ -14,4 +14,4 @@ pub use response::{ pub const GENAI_PROTOCOL: &str = "genai"; mod tokens; -pub use tokens::{CountTokensError, count_tokens_request}; +pub use tokens::{CountTokensError, count_tokens_request, into_count_tokens_request}; diff --git a/backend/crates/gateway-protocol/src/genai/tokens.rs b/backend/crates/gateway-protocol/src/genai/tokens.rs index 67711310c..a1ee44bb9 100644 --- a/backend/crates/gateway-protocol/src/genai/tokens.rs +++ b/backend/crates/gateway-protocol/src/genai/tokens.rs @@ -8,15 +8,31 @@ use thiserror::Error; #[error("generateContentRequest must be a JSON object.")] pub struct CountTokensError; +fn wrapped_field(request: &Map) -> Option<&'static str> { + ["generateContentRequest", "generate_content_request"] + .into_iter() + .find(|key| request.contains_key(*key)) +} + /// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数 pub fn count_tokens_request( request: &Map, ) -> Result<&Map, CountTokensError> { - match request - .get("generateContentRequest") - .or_else(|| request.get("generate_content_request")) - { - Some(value) => value.as_object().ok_or(CountTokensError), + match wrapped_field(request) { + Some(key) => request[key].as_object().ok_or(CountTokensError), + None => Ok(request), + } +} + +/// 取出计数正文供上游适配,无需复制历史和工具 +pub fn into_count_tokens_request( + mut request: Map, +) -> Result, CountTokensError> { + match wrapped_field(&request) { + Some(key) => match request.remove(key) { + Some(Value::Object(body)) => Ok(body), + _ => Err(CountTokensError), + }, None => Ok(request), } } diff --git a/backend/crates/gateway-protocol/src/lib.rs b/backend/crates/gateway-protocol/src/lib.rs index 91c117e7a..fa2363028 100644 --- a/backend/crates/gateway-protocol/src/lib.rs +++ b/backend/crates/gateway-protocol/src/lib.rs @@ -24,3 +24,6 @@ pub mod peer; /// Chat Completions 直接转换 pub mod chat_completions; + +/// 原生协议与 Chat 的系统指令定位及局部替换 +pub mod prompt_rewrite; diff --git a/backend/crates/gateway-protocol/src/prompt_rewrite/mod.rs b/backend/crates/gateway-protocol/src/prompt_rewrite/mod.rs new file mode 100644 index 000000000..5260fea42 --- /dev/null +++ b/backend/crates/gateway-protocol/src/prompt_rewrite/mod.rs @@ -0,0 +1,115 @@ +//! 定位生成正文的首条系统指令,同时维护已解析正文和原始 JSON + +mod wire; + +use serde_json::{Map, Value}; + +type Path = &'static [&'static str]; + +/// 已定位的文本字段及替换结果 +pub struct PromptEdit { + content: Path, + tail: Path, + text: String, +} + +/// 未命中时仅借用系统文本,不复制会话历史 +pub fn plan( + protocol: &str, + body: &Map, + replace: impl FnOnce(&str) -> Option, +) -> Option { + use crate::{ + anthropic::ANTHROPIC_PROTOCOL, chat_completions::CHAT_PROTOCOL, genai::GENAI_PROTOCOL, + openai::OPENAI_PROTOCOL, + }; + let (content, value, types): (Path, _, &[&str]) = match protocol { + OPENAI_PROTOCOL | CHAT_PROTOCOL => { + if let Some(value) = body.get("instructions").filter(|v| !v.is_null()) { + (&["instructions"], value, &["text", "input_text"]) + } else { + let path: Path = if protocol == CHAT_PROTOCOL { + &["messages", "0", "content"] + } else { + &["input", "0", "content"] + }; + let first = body.get(path[0])?.get(0)?; + if !matches!(first.get("role")?.as_str()?, "system" | "developer") + || first + .get("type") + .is_some_and(|v| v.as_str() != Some("message")) + { + return None; + } + (path, first.get("content")?, &["text", "input_text"]) + } + } + ANTHROPIC_PROTOCOL => (&["system"], body.get("system")?, &["text"]), + GENAI_PROTOCOL => { + let path: Path = if body.contains_key("systemInstruction") { + &["systemInstruction", "parts", "0", "text"] + } else { + &["system_instruction", "parts", "0", "text"] + }; + let value = body.get(path[0])?.get("parts")?.get(0)?.get("text")?; + return Some(PromptEdit { + content: path, + tail: &[], + text: replace(value.as_str()?)?, + }); + } + _ => return None, + }; + let (tail, text): (Path, _) = if let Some(parts) = value.as_array() { + let first = parts.first()?; + if !types.contains(&first.get("type")?.as_str()?) { + return None; + } + (&["0", "text"], first.get("text")?.as_str()?) + } else { + (&[], value.as_str()?) + }; + Some(PromptEdit { + content, + tail, + text: replace(text)?, + }) +} + +impl PromptEdit { + /// 将编辑应用于定位时使用的正文 + pub fn apply(self, body: &mut Map) { + let Some(mut field) = body.get_mut(self.content[0]) else { + return; + }; + for &key in self.content[1..].iter().chain(self.tail) { + let Some(child) = (if key == "0" { + field.get_mut(0) + } else { + field.get_mut(key) + }) else { + return; + }; + field = child; + } + *field = Value::String(self.text); + } + + /// 只编码目标字符串,保留其他字段的原始字节 + pub fn wire(&self, body: &[u8]) -> Option> { + let mut raw = serde_json::from_slice(body).ok()?; + for &key in self.content.iter().chain(self.tail) { + raw = if key == "0" { + wire::first(raw)? + } else { + wire::field(raw, key)? + }; + } + let start = raw.get().as_ptr() as usize - body.as_ptr() as usize; + let mut out = Vec::with_capacity(body.len() - raw.get().len() + self.text.len() + 2); + out.extend_from_slice(&body[..start]); + serde_json::to_writer(&mut out, &self.text).ok()?; + out.extend_from_slice(&body[start + raw.get().len()..]); + Some(out) + } +} diff --git a/backend/crates/gateway-protocol/src/prompt_rewrite/wire.rs b/backend/crates/gateway-protocol/src/prompt_rewrite/wire.rs new file mode 100644 index 000000000..3517961fd --- /dev/null +++ b/backend/crates/gateway-protocol/src/prompt_rewrite/wire.rs @@ -0,0 +1,44 @@ +//! 只借用路径命中的 JSON 字段,跳过无关值,不展开工具或历史 + +use serde::{ + Deserialize, Deserializer, + de::{IgnoredAny, MapAccess, Visitor}, +}; +use serde_json::value::RawValue; +use std::{borrow::Cow, fmt}; + +#[derive(Deserialize)] +struct Text<'a>(#[serde(borrow)] Cow<'a, str>); + +pub(super) fn first(raw: &RawValue) -> Option<&RawValue> { + let array = raw.get().strip_prefix('[')?; + serde_json::Deserializer::from_str(array) + .into_iter::<&RawValue>() + .next()? + .ok() +} + +pub(super) fn field<'a>(raw: &'a RawValue, name: &str) -> Option<&'a RawValue> { + struct Field<'a>(&'a str); + impl<'de> Visitor<'de> for Field<'_> { + type Value = Option<&'de RawValue>; + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a JSON object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut found = None; + while let Some(key) = map.next_key::>()? { + if key.0 == self.0 { + found = Some(map.next_value()?); + } else { + map.next_value::()?; + } + } + Ok(found) + } + } + serde_json::Deserializer::from_str(raw.get()) + .deserialize_map(Field(name)) + .ok() + .flatten() +} diff --git a/backend/crates/gateway-protocol/src/request.rs b/backend/crates/gateway-protocol/src/request.rs index f41b0d72b..8ce18ed98 100644 --- a/backend/crates/gateway-protocol/src/request.rs +++ b/backend/crates/gateway-protocol/src/request.rs @@ -32,9 +32,7 @@ pub fn token_count_observation( context: &Map, ) -> RequestObservation { let body = if protocol == GENAI_PROTOCOL { - body.get("generateContentRequest") - .and_then(Value::as_object) - .unwrap_or(body) + genai::count_tokens_request(body).unwrap_or(body) } else { body }; diff --git a/backend/crates/gateway-protocol/tests/main.rs b/backend/crates/gateway-protocol/tests/main.rs index 1acbda99e..19bb13527 100644 --- a/backend/crates/gateway-protocol/tests/main.rs +++ b/backend/crates/gateway-protocol/tests/main.rs @@ -4,6 +4,7 @@ mod anthropic; mod genai; mod http; mod openai; +mod prompt_rewrite; mod request; mod chat_completions; diff --git a/backend/crates/gateway-protocol/tests/prompt_rewrite/mod.rs b/backend/crates/gateway-protocol/tests/prompt_rewrite/mod.rs new file mode 100644 index 000000000..3fa136d19 --- /dev/null +++ b/backend/crates/gateway-protocol/tests/prompt_rewrite/mod.rs @@ -0,0 +1,43 @@ +//! 各协议的系统指令位置、首条命中与其余 wire 字节保留 + +use gateway_protocol::prompt_rewrite::plan; +mod wire; + +#[test] +fn unmatched_quoted_and_unknown_content_passes_through() { + for (protocol, body) in [ + ( + "openai", + r#"{"instructions":"quote: abc","input":[{"role":"system","content":"abc"}]}"#, + ), + ( + "openai", + r#"{"input":[{"type":"function_call","role":"system","content":"abc"}]}"#, + ), + ( + "chat_completions", + r#"{"messages":[{"role":"user","content":"abc"},{"role":"developer","content":"abc"}]}"#, + ), + ( + "genai", + r#"{"contents":[{"role":"user","parts":[{"text":"abc"}]}]}"#, + ), + ( + "genai", + r#"{"systemInstruction":{"parts":[{"text":"untouched"}]},"generateContentRequest":{"systemInstruction":{"parts":[{"text":"abc"}]}}}"#, + ), + ( + "anthropic", + r#"{"system":[{"type":"custom","text":"abc"}]}"#, + ), + ("other", r#"{"instructions":"abc"}"#), + ] { + let body = serde_json::from_str(body).unwrap(); + assert!( + plan(protocol, &body, |text| text + .strip_prefix("abc") + .map(str::to_owned)) + .is_none() + ); + } +} diff --git a/backend/crates/gateway-protocol/tests/prompt_rewrite/wire.rs b/backend/crates/gateway-protocol/tests/prompt_rewrite/wire.rs new file mode 100644 index 000000000..1cf54466a --- /dev/null +++ b/backend/crates/gateway-protocol/tests/prompt_rewrite/wire.rs @@ -0,0 +1,50 @@ +//! 各协议的系统指令位置、首条命中与其余 wire 字节保留 + +use gateway_protocol::prompt_rewrite::plan; +use serde_json::Map; + +#[test] +fn rewrites_only_the_authoritative_text_and_preserves_wire_bytes() { + for (protocol, instruction) in [ + ( + "chat_completions", + r#""messages":[{"role":"system","content":"First\n规则"},{"role":"user","content":"First\n规则"}]"#, + ), + ( + "openai", + r#""instructions":"First\n规则","input":[{"role":"developer","content":"First\n规则"}]"#, + ), + ( + "openai", + r#""input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":"First\n规则","extra":7}]}]"#, + ), + ("anthropic", r#""system":"First\n规则""#), + ( + "anthropic", + r#""system":[{"type":"text","text":"First\n规则","cache_control":{"type":"ephemeral"}},{"type":"text","text":"First\n规则"}]"#, + ), + ( + "genai", + r#""systemInstruction":{"parts":[{"text":"First\n规则"},{"text":"First\n规则"}]}"#, + ), + ( + "genai", + r#""system_instruction":{"parts":[{"text":"First\n规则"}]}"#, + ), + ] { + let body = format!( + r#"{{"unknown":1e+08, {instruction}, "unknown":12345678901234567890123456789}}"# + ); + let parsed: Map<_, _> = serde_json::from_str(&body).unwrap(); + let edit = plan(protocol, &parsed, |text| { + text.strip_prefix("First\n") + .map(|suffix| format!("Changed\n{suffix}")) + }) + .unwrap(); + let wire = edit.wire(body.as_bytes()).unwrap(); + let mut edited = parsed; + edit.apply(&mut edited); + assert_eq!(edited, serde_json::from_slice::>(&wire).unwrap()); + assert_eq!(wire, body.replacen("First", "Changed", 1).as_bytes()); + } +} diff --git a/backend/crates/gateway-protocol/tests/request.rs b/backend/crates/gateway-protocol/tests/request.rs index 67d53d620..d2c42ddc8 100644 --- a/backend/crates/gateway-protocol/tests/request.rs +++ b/backend/crates/gateway-protocol/tests/request.rs @@ -21,6 +21,10 @@ fn token_count_observation_uses_the_nested_generation_request() { serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}), None, ), + ( + serde_json::json!({"generate_content_request":{"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}}), + Some("high"), + ), ] { let observation = gateway_protocol::request::token_count_observation( "genai", diff --git a/backend/crates/gateway-store/src/admin_adapter.rs b/backend/crates/gateway-store/src/admin_adapter.rs index 6f2b217ca..194067228 100644 --- a/backend/crates/gateway-store/src/admin_adapter.rs +++ b/backend/crates/gateway-store/src/admin_adapter.rs @@ -120,6 +120,7 @@ impl SettingsStore for AdminSettingsStoreAdapter { "min_codex_desktop_version".to_owned(), "min_codex_cli_version".to_owned(), "retention".to_owned(), + "prompt_rewrite_rules_json".to_owned(), "account_error_protection".to_owned(), ], ), diff --git a/backend/crates/gateway-store/src/postgres/runtime_settings.rs b/backend/crates/gateway-store/src/postgres/runtime_settings.rs index 74d00f262..80fecc2ba 100644 --- a/backend/crates/gateway-store/src/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/src/postgres/runtime_settings.rs @@ -156,7 +156,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days, audit_retention_days, min_codex_desktop_version, min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, - account_error_protection_json, account_error_protection_revision, + prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision, account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", ) @@ -359,7 +359,7 @@ pub(crate) async fn load_runtime_settings_in_transaction( rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days, audit_retention_days, min_codex_desktop_version, min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, - account_error_protection_json, account_error_protection_revision, + prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision, account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", ) @@ -446,6 +446,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( quota_reset_window_weights_json = $35, openai_request_settings_json = $36, openai_websocket_pool_json = $37, + prompt_rewrite_rules_json = $38, updated_at = now() where id = 1 returning config_revision", @@ -495,6 +496,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( .bind(sqlx::types::Json(update.values.quota_reset_window_weights)) .bind(sqlx::types::Json(&update.values.openai_request_settings)) .bind(sqlx::types::Json(&update.values.openai_websocket_pool)) + .bind(sqlx::types::Json(&update.values.prompt_rewrite_rules)) .fetch_optional(&mut **transaction) .await .map_err(|source| postgres_unavailable("update runtime settings in transaction", source))? @@ -596,6 +598,8 @@ struct RuntimeSettingsRow { session_affinity_ttl_hours: i64, responses_max_decompressed_body_bytes: i64, account_error_protection_revision: i64, + prompt_rewrite_rules_json: + sqlx::types::Json>, account_error_protection_json: sqlx::types::Json, account_warmup_enabled: bool, account_warmup_cron: String, @@ -667,6 +671,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult, config_revision: i64, account_error_protection_revision: i64, + prompt_rewrite_rules_json: + sqlx::types::Json>, account_error_protection_json: sqlx::types::Json, max_concurrent_per_account: i64, smart_scheduling_json: sqlx::types::Json, @@ -257,7 +259,7 @@ async fn load_settings( transaction: &mut Transaction<'_, Postgres>, ) -> StoreResult<(Revision, SettingsValues)> { let row = sqlx::query_as::<_, SnapshotSettingsRow>( - "select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1", + "select config_revision, prompt_rewrite_rules_json, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1", ) .fetch_optional(&mut **transaction) .await @@ -306,6 +308,7 @@ async fn load_settings( }) .with_request_location(row.request_location_json.0, row.request_location_enabled) .with_codex_privacy_policy(row.codex_privacy_policy_json.0) + .with_prompt_rewrite_rules(row.prompt_rewrite_rules_json.0) .with_account_error_protection(row.account_error_protection_json.0) .with_account_error_protection_revision(to_u64(row.account_error_protection_revision)?) .with_concurrency_queues( diff --git a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs index b7d66e2a0..3710618cf 100644 --- a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs @@ -48,6 +48,7 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin usage_retention_days: 31, ops_event_retention_days: 30, audit_retention_days: 90, + prompt_rewrite_rules: Vec::new(), account_error_protection: enabled_protection(), account_warmup_enabled: false, account_warmup_cron: "0 8 * * *".to_owned(), @@ -65,6 +66,38 @@ fn runtime_settings_keep_account_rotation_global() { assert!(settings.validate().is_ok()); } +#[tokio::test] +async fn prompt_rewrite_order_and_scope_round_trip_into_the_runtime_snapshot() { + use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository}; + let Some(database) = TestDatabase::create("prompt_rewrite").await else { + return; + }; + let repository = PgRuntimeSettingsRepository::new(database.pool.clone()); + let before = repository.load_runtime_settings().await.unwrap(); + assert!(before.values.prompt_rewrite_rules.is_empty()); + let expected = serde_json::json!([ + {"providers":["antigravity","xai"],"pattern":"example","replacement":"first"}, + {"providers":[],"pattern":"example","replacement":"second"} + ]); + let mut update = settings_with_margin(300); + update.values.prompt_rewrite_rules = serde_json::from_value(expected.clone()).unwrap(); + repository.update_runtime_settings(update).await.unwrap(); + let after = repository.load_runtime_settings().await.unwrap(); + assert_eq!( + serde_json::to_value(after.values.prompt_rewrite_rules).unwrap(), + expected + ); + let snapshot = PgRuntimeSnapshotRepository::new(database.pool.clone()) + .load_runtime_snapshot() + .await + .unwrap(); + assert_eq!( + serde_json::to_value(snapshot.settings).unwrap()["prompt_rewrite_rules"], + expected + ); + database.close().await; +} + #[tokio::test] async fn privacy_policy_defaults_off_and_round_trips_in_snapshot() { use gateway_core::settings::privacy::*; diff --git a/backend/crates/providers/antigravity/src/provider/count.rs b/backend/crates/providers/antigravity/src/provider/count.rs index eb319d5af..52820380f 100644 --- a/backend/crates/providers/antigravity/src/provider/count.rs +++ b/backend/crates/providers/antigravity/src/provider/count.rs @@ -2,16 +2,17 @@ use crate::transport::{sent, unsent}; use gateway_core::{ - engine::provider::NativeResponseTranslator, + engine::{AttemptContext, provider::NativeResponseTranslator}, error::{ProviderError, ProviderErrorKind}, event::ProtocolWireEvent, operation::Operation, }; -use gateway_protocol::genai::{GENAI_PROTOCOL, count_tokens_request}; +use gateway_protocol::genai::{GENAI_PROTOCOL, into_count_tokens_request}; use serde_json::{Map, Value}; pub(super) fn prepare( operation: Operation, + context: &AttemptContext, ) -> Result<(Operation, Option), ProviderError> { let Operation::CountTokens(request) = &operation else { return Err(unsent(ProviderErrorKind::Unsupported)); @@ -22,9 +23,10 @@ pub(super) fn prepare( } let body: Map = serde_json::from_slice(request.payload().body()) .map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?; - let body = count_tokens_request(&body) + let mut body = into_count_tokens_request(body) .map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?; - let bytes = serde_json::to_vec(body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; + context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body); + let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; let translated = source == "token-count"; let operation = if translated { operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()) diff --git a/backend/crates/providers/antigravity/src/provider/execution.rs b/backend/crates/providers/antigravity/src/provider/execution.rs index a4217705c..ce6aa5754 100644 --- a/backend/crates/providers/antigravity/src/provider/execution.rs +++ b/backend/crates/providers/antigravity/src/provider/execution.rs @@ -94,7 +94,7 @@ impl AntigravityProvider { return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection.")); } let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) { - let (operation, translator) = super::count::prepare(operation)?; + let (operation, translator) = super::count::prepare(operation, &terminal_context)?; (operation, None, translator) } else { let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref())?; @@ -114,6 +114,7 @@ impl AntigravityProvider { _ => return Err(unsent(Kind::Unsupported)), }; let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?; + let translated_chat = translator.is_some(); let events = async_stream::try_stream! { if cancellation.is_cancelled() { Err(unsent(Kind::Cancelled))?; @@ -138,7 +139,13 @@ impl AntigravityProvider { // 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号 Project::Discover => resource.account_info(token).await?.project, }; - let mode = if search { crate::transport::GenerateMode::WebSearch } else { crate::transport::GenerateMode::from(stream) }; + let mode = if search { + crate::transport::GenerateMode::WebSearch + } else if translated_chat { + crate::transport::GenerateMode::Chat { stream } + } else { + crate::transport::GenerateMode::from(stream) + }; resource.generate(&project, model.as_str(), token, &body, mode, &headers).await } => response, }; diff --git a/backend/crates/providers/antigravity/src/transport/client.rs b/backend/crates/providers/antigravity/src/transport/client.rs index 697fa1e4e..af3353d7f 100644 --- a/backend/crates/providers/antigravity/src/transport/client.rs +++ b/backend/crates/providers/antigravity/src/transport/client.rs @@ -100,6 +100,7 @@ pub(crate) enum GenerateMode { Json, Stream, WebSearch, + Chat { stream: bool }, } impl From for GenerateMode { @@ -229,13 +230,16 @@ impl CloudCodeClient { enabled_credit_types: Option<[&'static str; 1]>, request: &'a RawValue, } - let instruction = if mode == GenerateMode::WebSearch { - *SEARCH_INSTRUCTION - } else { - &self.system_instruction + let instruction = match mode { + GenerateMode::WebSearch => Some(*SEARCH_INSTRUCTION), + GenerateMode::Chat { .. } => None, + GenerateMode::Json | GenerateMode::Stream => Some(self.system_instruction.as_ref()), }; let request = super::request::request_body(body, instruction, false)?; - let (send, media) = if mode == GenerateMode::Stream { + let (send, media) = if matches!( + mode, + GenerateMode::Stream | GenerateMode::Chat { stream: true } + ) { ( self.post("streamGenerateContent", token) .query(&[("alt", "sse")]), @@ -277,7 +281,7 @@ impl CloudCodeClient { headers: &[MiddlewareHeader], ) -> Result { // Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段 - let request = super::request::request_body(body, &self.system_instruction, true)?; + let request = super::request::request_body(body, Some(&self.system_instruction), true)?; #[derive(Serialize)] struct Envelope<'a> { request: &'a RawValue, diff --git a/backend/crates/providers/antigravity/src/transport/request.rs b/backend/crates/providers/antigravity/src/transport/request.rs index 4c787efbc..83ee1f5cf 100644 --- a/backend/crates/providers/antigravity/src/transport/request.rs +++ b/backend/crates/providers/antigravity/src/transport/request.rs @@ -11,16 +11,19 @@ use gateway_core::error::{ProviderError, ProviderErrorKind}; pub(super) fn request_body( body: &[u8], - instruction: &RawValue, + instruction: Option<&RawValue>, count: bool, ) -> Result, ProviderError> { let rewrite = || { let raw: &RawValue = serde_json::from_slice(body)?; - let instruction = prepend_system_prompt(raw, instruction)?; + let instruction = instruction + .map(|prompt| prepend_system_prompt(raw, prompt)) + .transpose()?; edit_object( raw, |name, value| { - if matches!(name, "systemInstruction" | "system_instruction") + if (instruction.is_some() + && matches!(name, "systemInstruction" | "system_instruction")) || (count && matches!( name, @@ -60,7 +63,9 @@ pub(super) fn request_body( } Ok(Edit::Keep) }, - Some(("systemInstruction", &instruction)), + instruction + .as_deref() + .map(|value| ("systemInstruction", value)), ) }; rewrite().map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error)) diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index 050bf3b7d..619187d24 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -717,13 +717,28 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease() ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone()) .unwrap(), )); - let mut profile = crate::profile::ClientProfile::from_frozen(&frozen_profile()).unwrap(); - profile.system_prompt = "Frozen AGY prompt".into(); + let selection = Selection { + system_prompt: Some("Frozen AGY prompt".into()), + ..Default::default() + }; + let profile = fixture + .provider + .resolve_request_profile(&selection.configuration()) + .unwrap(); let request_context = RequestAttemptContext::new( ModelRequestId::new("req_chat").unwrap(), ClientApiKeyId::new("key_fixture").unwrap(), ) - .with_request_profile(Some(profile.frozen())) + .with_request_profile(Some(profile)) + .with_prompt_rewrite_rules(if streaming { + gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new( + serde_json::from_value(json!([{"pattern":"Preserve","replacement":"Apply"}])) + .unwrap(), + ) + .for_provider(&ProviderKind::new("antigravity").unwrap()) + } else { + None + }) .with_middleware( None, Default::default(), @@ -786,12 +801,8 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease() let body: serde_json::Value = serde_json::from_slice(&sent.last().unwrap().body).unwrap(); assert!(body["request"].get("input").is_none()); assert_eq!( - body["request"]["systemInstruction"]["parts"][0]["text"], - "Frozen AGY prompt" - ); - assert_eq!( - body["request"]["systemInstruction"]["parts"][1]["text"], - "Preserve the caller's project rules." + body["request"]["systemInstruction"]["parts"], + json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}]) ); assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100); assert_eq!( diff --git a/backend/crates/providers/antigravity/tests/transport/count.rs b/backend/crates/providers/antigravity/tests/transport/count.rs index 858971f4d..0763a6a4b 100644 --- a/backend/crates/providers/antigravity/tests/transport/count.rs +++ b/backend/crates/providers/antigravity/tests/transport/count.rs @@ -45,6 +45,19 @@ async fn released(fixture: &Fixture) { #[tokio::test] async fn native_and_provider_count_share_identity_and_never_generate_usage() { + use gateway_core::{ + engine::{ModelRequestId, RequestAttemptContext}, + identity::ProviderKind, + policy::ClientApiKeyId, + settings::prompt_rewrite::CompiledPromptRewrite, + }; + let rules = CompiledPromptRewrite::new( + serde_json::from_value(json!([ + {"pattern":"client", "replacement":"client updated"} + ])) + .unwrap(), + ) + .for_provider(&ProviderKind::new("antigravity").unwrap()); for (protocol, body, expected) in [ ( "genai", @@ -73,7 +86,15 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() { .clone() .execute( counted(protocol, body), - context(profile(), CancellationToken::new()), + crate::support::context_with_request( + RequestAttemptContext::new( + ModelRequestId::new("req_count").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ) + .with_request_profile(Some(profile())) + .with_prompt_rewrite_rules(rules.clone()), + CancellationToken::new(), + ), ) .await .unwrap(); @@ -116,7 +137,7 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() { ); assert_eq!( sent["request"]["systemInstruction"]["parts"][1]["text"], - "client identity" + "client updated identity" ); assert_eq!(sent["request"]["contents"][0]["parts"][0]["text"], "hello"); assert_eq!( diff --git a/backend/crates/providers/openai/src/provider/messages/count.rs b/backend/crates/providers/openai/src/provider/messages/count.rs index cbb541bba..5cb571d5b 100644 --- a/backend/crates/providers/openai/src/provider/messages/count.rs +++ b/backend/crates/providers/openai/src/provider/messages/count.rs @@ -56,6 +56,7 @@ impl CodexProvider { let mut body: Map = serde_json::from_slice(count.payload().body()) .map_err(|_| invalid_request())?; + terminal_context.rewrite_count_prompt(ANTHROPIC_PROTOCOL, &mut body); // 通用 Provider 计数入口的模型来自路径,正文仍使用 Messages 输入合同 body.insert("model".to_owned(), Value::String(model.as_str().to_owned())); gateway_protocol::anthropic::validate_count_request(&body) diff --git a/backend/crates/providers/openai/tests/provider/contract/messages/mod.rs b/backend/crates/providers/openai/tests/provider/contract/messages/mod.rs index 1778090d8..bae187e9f 100644 --- a/backend/crates/providers/openai/tests/provider/contract/messages/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/messages/mod.rs @@ -391,21 +391,38 @@ async fn chat_service_tiers_follow_the_selected_responses_upstream() { #[tokio::test] async fn custom_messages_count_locally_without_billable_usage() { - for (target, source) in [ - (ApiKeyProtocol::Messages, "anthropic"), - (ApiKeyProtocol::Messages, "token-count"), + let rules = gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new( + serde_json::from_value(json!([{"pattern":"repeated prefix", "replacement":""}])).unwrap(), + ) + .for_provider(&ProviderKind::new("openai").unwrap()); + let mut baseline = None; + for (source, configured, system) in [ + ("anthropic", None, "rule"), + ("anthropic", rules.clone(), "repeated prefixrule"), + ("token-count", rules, "repeated prefixrule"), ] { let server = MockServer::start().await; let store = Arc::new(MemoryAccountStore::default()); - seed(&store, &server, target).await; - let body = Bytes::from_static(br#"{"messages":[{"role":"user","content":"hello world"}]}"#); + seed(&store, &server, ApiKeyProtocol::Messages).await; + let body = serde_json::to_vec( + &json!({"system":system,"messages":[{"role":"user","content":"hello world"}]}), + ) + .unwrap() + .into(); let operation = Operation::CountTokens(TokenCountRequest::from_raw_json( RawJsonPayload::new(source, body).unwrap(), )); let mut stream = provider(&store) .execute( planned_request("openai", operation), - context("req_messages_count", CancellationToken::new()), + context_for_request( + RequestAttemptContext::new( + ModelRequestId::new("req_messages_count").unwrap(), + ClientApiKeyId::new("key_openai_contract").unwrap(), + ) + .with_prompt_rewrite_rules(configured), + CancellationToken::new(), + ), ) .await .unwrap(); @@ -422,7 +439,9 @@ async fn custom_messages_count_locally_without_billable_usage() { count = body.get("input_tokens").and_then(Value::as_u64); } } - assert!(count.is_some_and(|count| count > 0)); + let count = count.unwrap(); + assert!(count > 0); + assert_eq!(count, *baseline.get_or_insert(count)); assert!(server.received_requests().await.unwrap().is_empty()); } } diff --git a/backend/crates/providers/xai/tests/provider/contract/mod.rs b/backend/crates/providers/xai/tests/provider/contract/mod.rs index 0c1bcc5e2..554679254 100644 --- a/backend/crates/providers/xai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/xai/tests/provider/contract/mod.rs @@ -2864,7 +2864,14 @@ async fn configured_request_profile_reaches_inference_headers() { ModelRequestId::new("req_profile").unwrap(), ClientApiKeyId::new("key_profile").unwrap(), ) - .with_request_profile(Some(resolved)), + .with_request_profile(Some(resolved)) + .with_prompt_rewrite_rules( + gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new( + serde_json::from_value(json!([{"pattern":"Old", "replacement":"Updated"}])) + .unwrap(), + ) + .for_provider(&ProviderKind::new("xai").unwrap()), + ), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(30), selection_policy(), @@ -2872,14 +2879,24 @@ async fn configured_request_profile_reaches_inference_headers() { None, CancellationToken::new(), ); + let payload = ProtocolPayload::from_json_bytes( + "openai", + bytes::Bytes::from_static( + br#"{"model":"client-model","instructions":"Old rule","input":"hello"}"#, + ), + ) + .unwrap(); + let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); let events = provider - .execute(provider_request("xai"), context) + .execute(provider_request_with_operation("xai", operation), context) .await .unwrap() .collect::>() .await; assert!(events.iter().all(Result::is_ok)); let requests = transport.requests.lock().unwrap(); + let sent: Value = serde_json::from_slice(requests[0].body()).unwrap(); + assert_eq!(sent["instructions"], "Updated rule"); let headers = requests[0].headers(); let header = |name| { std::str::from_utf8( diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index ede219001..f20e18834 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -47,3 +47,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a 98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql 709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql 44a24ba1bab7630881b4eeac66806231d3a7040dd72a99b0475e1a0f20cfc540 0049_client_key_validity_and_proxy_test_targets.sql +c62495a0aff26b149381370fe1eea656091ab8d9d7d55aee27be4f56d5885fd3 0050_prompt_rewrite_rules.sql diff --git a/backend/migrations/0050_prompt_rewrite_rules.sql b/backend/migrations/0050_prompt_rewrite_rules.sql new file mode 100644 index 000000000..7dfd52783 --- /dev/null +++ b/backend/migrations/0050_prompt_rewrite_rules.sql @@ -0,0 +1,3 @@ +ALTER TABLE runtime_settings + ADD COLUMN prompt_rewrite_rules_json jsonb NOT NULL DEFAULT '[]'::jsonb + CHECK (jsonb_typeof(prompt_rewrite_rules_json) = 'array'); diff --git a/docs/api.md b/docs/api.md index 2b16d6bbd..63d6f126a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -270,7 +270,7 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的 CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 OAuth 账号与冻结画像生成。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters) -Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加配置的提示词,保留客户端原有 parts 及系统指令的其他字段,并移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建 +Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加画像提示词。普通 Chat 转换只发送调用方系统指令及其配置的改写结果。网关移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建 同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文 @@ -1820,7 +1820,7 @@ OAuth start 使用: Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravity`,Key 可用 `providerRequestProfileOverrides.antigravity` 覆盖。配置使用 `client`(`desktop` 或 `cli`)、`platform`(`macos`、`linux` 或 `windows`)、`versionMode`、`clientVersion` 和 `arch`。`arch: null` 使用预设架构:macOS 为 `arm64`,Linux 与 Windows 为 `amd64`;也可显式选择 `arm64` 或 `amd64` -`systemPrompt` 可在 AGY 设置中编辑,省略、`null` 或空白值使用内置默认,最长 16 KiB。默认取自已核对的 AGY CLI 1.5.15 身份模板,不包含客户端专属工具和工作区模板;选项接口返回 `defaultSystemPrompt` 与 `systemPromptSource`,客户端版本轮询不会改写它。提示词随请求画像一起冻结,原生和转换入口均将它放在客户端系统指令之前。客户端的全局规则、项目规则、工具说明及其他系统指令保持原样;未提供客户端系统指令时只使用配置提示词 +AGY 请求画像的 `systemPrompt` 最长 16 KiB,省略、`null` 或空白值使用内置默认。选项接口通过 `defaultSystemPrompt` 和 `systemPromptSource` 返回 AGY CLI 1.5.15 身份模板及其来源。原生生成与计数在客户端系统指令之前加入画像提示词。普通 Chat 转发只应用[提示词改写规则](#提示词改写) 自动版本示例: @@ -2344,6 +2344,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly | 用途 | 字段 | | --- | --- | | 并发控制版本 | `configRevision` | +| [提示词改写](#提示词改写) | `promptRewriteRules` | | [客户端身份](#provider-客户端身份) | `providerRequestProfiles` | | [请求位置](#请求位置) | `requestLocationEnabled`、`requestLocation` | | [OpenAI 请求设置](#openai-请求设置) | `openaiRequestSettings` | @@ -2716,6 +2717,14 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI 及所有人工单价与倍率保持不变。选中的已同步模型若不再出现在来源价目中,则移除其来源层,恢复内置价格; 没有内置价目的模型变为未配置 +### 提示词改写 + +更新通用设置时须提交有序数组 `promptRewriteRules`,初始值为 `[]`。每条包含适用上游 `providers`、非空字面前缀 `pattern` 和替换文本 `replacement`。省略 `providers` 或使用空数组代表全部上游,指定多个平台时共用同一条规则。匹配与替换文本可含换行,空替换文本删除前缀 + +设置快照按目标上游索引规则,公共规则和限定平台的规则均按原始顺序生效,仅替换首个匹配前缀。上游没有适用规则时直接转发。API Key 使用同一套通用规则 + +Chat 和 Responses 优先取显式 `instructions`。否则只检查 `messages[0]` 或 `input[0]`,角色为 `system` 或 `developer` 时才匹配。Messages 取 `system`,GenAI 取 `systemInstruction` 或 `system_instruction`。分块内容仅在第一块为文本时改写该块。输入计数使用相同规则,GenAI 完整计数封套以其内层生成请求为准 + ### Provider 客户端身份 `providerRequestProfiles` 是按 Provider ID 索引的通用配置对象,最多 256 项、每项最多 64 KiB。 diff --git a/docs/architecture.md b/docs/architecture.md index b512d0498..9498d0201 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -398,7 +398,7 @@ views/<页面>/ 账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。OpenAI 的 API Key、OAuth 传输与逐条 token 导入归 `providers/openai/accounts`,Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置 -运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置 +运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载提示词改写、调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置 全局配置和 Key 覆盖共用 `components/request-profile/index.vue` 的身份编辑流程,各 Provider 在 `providers//request-profile/` 解释自己的配置字段。定价页按查询接口返回的档位编辑 @@ -513,6 +513,8 @@ Core 独占路由、重试、交付事实与结算;Provider 独占上游身份 API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。 Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果 +运行设置快照共享提示词改写规则原文,按配置顺序索引全局规则和各上游规则。路由计划冻结快照,每次尝试只取所选平台的适用规则。attempt 中间件提交后,协议层定位系统文本,Core 匹配前缀。生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串。计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则 + 原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。 内置转换只能从 Chat 来源调用;显式插件仍按现有能力声明与中间件合同运行。 字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt) @@ -598,7 +600,7 @@ GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigrav Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。 `provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实, -并将冻结画像的提示词前置到客户端系统指令,保留客户端规则、工具说明和工作区上下文。默认提示和可编辑配置归 Provider 的 `profile`,纯协议层不持有 AGY 身份规则 +原生生成与计数前置冻结画像的系统提示,普通 Chat 使用转换后的系统指令 Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属 diff --git a/frontend/src/api/modules/settings/index.ts b/frontend/src/api/modules/settings/index.ts index 8cbe7b3be..2778635c5 100644 --- a/frontend/src/api/modules/settings/index.ts +++ b/frontend/src/api/modules/settings/index.ts @@ -52,6 +52,12 @@ export interface OpenAiWebSocketPoolSettings { streamIdleTimeoutMs: number } +export interface PromptRewriteRule { + providers: string[] + pattern: string + replacement: string +} + export interface RuntimeSettings { openaiWebsocketPool: OpenAiWebSocketPoolSettings configRevision: number @@ -91,6 +97,7 @@ export interface RuntimeSettings { usageRetentionDays: number opsEventRetentionDays: number auditRetentionDays: number + promptRewriteRules: PromptRewriteRule[] accountErrorProtection: AccountErrorProtection accountWarmupEnabled: boolean accountWarmupCron: string diff --git a/frontend/src/components/ProviderSelect.vue b/frontend/src/components/ProviderSelect.vue index b27db9f43..069f5529b 100644 --- a/frontend/src/components/ProviderSelect.vue +++ b/frontend/src/components/ProviderSelect.vue @@ -7,7 +7,7 @@ import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/cat const props = withDefaults(defineProps<{ providers?: readonly Value[] - leadingOption?: SegmentedOption + leadingOption?: SegmentedOption | SegmentedOption[] display?: 'icon' | 'label' size?: 'small' | 'default' | 'large' disabled?: boolean @@ -19,9 +19,7 @@ const props = withDefaults(defineProps<{ const provider = defineModel({ required: true }) const { t } = useI18n({ useScope: 'global' }) const options = computed(() => [ - ...(props.leadingOption - ? [props.leadingOption] - : []), + ...[props.leadingOption ?? []].flat(), ...(props.providers ?? PROVIDER_IDS).map(value => ({ value, label: formatProviderLabel(value), diff --git a/frontend/src/i18n/locales/en/settings.json b/frontend/src/i18n/locales/en/settings.json index 5c3ae039f..1dcc285c3 100644 --- a/frontend/src/i18n/locales/en/settings.json +++ b/frontend/src/i18n/locales/en/settings.json @@ -1,9 +1,15 @@ { "settings": { + "promptRewrite": { + "title": "Prompt rewriting", + "description": "Replace the first matching system instruction prefix in rule order. Leave the replacement empty to remove the prefix.", + "empty": "No rewrite rules", + "providers": "Upstream platforms", + "matchPrefix": "Match prefix", + "replacement": "Replacement text", + "required": "Enter a prefix to match" + }, "clientProfile": { - "systemPrompt": "System prompt", - "systemPromptHint": "Prepended to client system instructions · Default from {source}", - "restoreSystemPrompt": "Restore default", "userAgent": "User agent", "clientIdentitySource": "Client identity source", "globalConfiguration": "Global configuration", diff --git a/frontend/src/i18n/locales/zh-Hans/settings.json b/frontend/src/i18n/locales/zh-Hans/settings.json index 1c231e825..3358e550d 100644 --- a/frontend/src/i18n/locales/zh-Hans/settings.json +++ b/frontend/src/i18n/locales/zh-Hans/settings.json @@ -1,9 +1,15 @@ { "settings": { + "promptRewrite": { + "title": "提示词改写", + "description": "按顺序匹配系统指令的前缀,首条命中后替换。替换文本留空可删除前缀", + "empty": "暂无改写规则", + "providers": "适用上游", + "matchPrefix": "匹配前缀", + "replacement": "替换文本", + "required": "请输入匹配前缀" + }, "clientProfile": { - "systemPrompt": "系统提示词", - "systemPromptHint": "前置系统提示,保留客户端指令,默认来自 {source}", - "restoreSystemPrompt": "恢复默认", "userAgent": "用户代理", "clientIdentitySource": "客户端身份来源", "globalConfiguration": "全局配置", diff --git a/frontend/src/i18n/locales/zh-Hant/settings.json b/frontend/src/i18n/locales/zh-Hant/settings.json index c2d3d6612..a18675353 100644 --- a/frontend/src/i18n/locales/zh-Hant/settings.json +++ b/frontend/src/i18n/locales/zh-Hant/settings.json @@ -1,9 +1,15 @@ { "settings": { + "promptRewrite": { + "title": "提示詞改寫", + "description": "依序比對系統指令的前綴,替換首個符合的前綴。替換文字留空可刪除前綴", + "empty": "暫無改寫規則", + "providers": "適用上游", + "matchPrefix": "比對前綴", + "replacement": "替換文字", + "required": "請輸入比對前綴" + }, "clientProfile": { - "systemPrompt": "系統提示詞", - "systemPromptHint": "前置系統提示,保留客戶端指令,預設來自 {source}", - "restoreSystemPrompt": "恢復預設", "userAgent": "用戶代理", "clientIdentitySource": "客戶端身份來源", "globalConfiguration": "全局配置", diff --git a/frontend/src/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue b/frontend/src/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue index 089e39bfb..d7a957f80 100644 --- a/frontend/src/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue +++ b/frontend/src/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue @@ -1,10 +1,9 @@ diff --git a/frontend/src/providers/antigravity/request-profile/profile.ts b/frontend/src/providers/antigravity/request-profile/profile.ts index ea5e986c0..fa2909b2c 100644 --- a/frontend/src/providers/antigravity/request-profile/profile.ts +++ b/frontend/src/providers/antigravity/request-profile/profile.ts @@ -10,8 +10,6 @@ export interface ProfileSelection { } export interface ProfileOptions { - defaultSystemPrompt: string - systemPromptSource: string defaults: ProfileSelection presets: { configuration: ProfileSelection diff --git a/frontend/src/views/settings/components/PromptRewriteRulesCard.vue b/frontend/src/views/settings/components/PromptRewriteRulesCard.vue new file mode 100644 index 000000000..6cdfce4e0 --- /dev/null +++ b/frontend/src/views/settings/components/PromptRewriteRulesCard.vue @@ -0,0 +1,88 @@ + + + diff --git a/frontend/src/views/settings/composables/useSettingsForm.ts b/frontend/src/views/settings/composables/useSettingsForm.ts index 68dd952a9..abf73cb72 100644 --- a/frontend/src/views/settings/composables/useSettingsForm.ts +++ b/frontend/src/views/settings/composables/useSettingsForm.ts @@ -1,6 +1,6 @@ import type { ProtectionDraft } from '../components/error-protection/policy' import type { rotationOptions } from '../constants' -import type { AccountAffinity, CodexPrivacyPolicy, OpenAiRequestCountry, ProviderRequestProfiles, ResetWindowWeights, SmartSchedulingConfig } from '@/api' +import type { AccountAffinity, CodexPrivacyPolicy, OpenAiRequestCountry, PromptRewriteRule, ProviderRequestProfiles, ResetWindowWeights, SmartSchedulingConfig } from '@/api' import { cloneDeep, isEqual } from 'es-toolkit' import { computed, reactive, ref, shallowRef } from 'vue' import { detectRequestLocation, getSettings, updateSettings } from '@/api' @@ -76,6 +76,7 @@ export function useSettingsForm() { opsEventRetentionDays: 30, auditRetentionDays: 90, + promptRewriteRules: [] as PromptRewriteRule[], accountErrorProtection: { enabled: false, rules: [], @@ -180,6 +181,7 @@ export function useSettingsForm() { form.usageRetentionDays = data.usageRetentionDays form.opsEventRetentionDays = data.opsEventRetentionDays form.auditRetentionDays = data.auditRetentionDays + form.promptRewriteRules = cloneDeep(data.promptRewriteRules ?? []) form.accountErrorProtection = { ...cloneDeep(data.accountErrorProtection), probeModel: data.accountErrorProtection.probeModel ?? '', @@ -332,6 +334,7 @@ export function useSettingsForm() { usageRetentionDays: usageRetentionDays!, opsEventRetentionDays: form.opsEventRetentionDays, auditRetentionDays: form.auditRetentionDays, + promptRewriteRules: form.promptRewriteRules, accountErrorProtection: { ...cloneDeep(form.accountErrorProtection), threshold: form.accountErrorProtection.threshold!, diff --git a/frontend/src/views/settings/index.vue b/frontend/src/views/settings/index.vue index f5c9c16ee..053926477 100644 --- a/frontend/src/views/settings/index.vue +++ b/frontend/src/views/settings/index.vue @@ -22,6 +22,7 @@ import ModelAliasesCard from './components/ModelAliasesCard.vue' import OpenAiRequestCard from './components/OpenAiRequestCard.vue' import PricingSection from './components/pricing/index.vue' import PrivacyPolicyCard from './components/privacy/index.vue' +import PromptRewriteRulesCard from './components/PromptRewriteRulesCard.vue' import RequestHistoryCard from './components/RequestHistoryCard.vue' import RequestLocationCard from './components/RequestLocationCard.vue' import RequestProfileCard from './components/RequestProfileCard.vue' @@ -252,6 +253,7 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) => /> +