From 5249ec2247e7de9af505582e50a6a9ddeda8e6d0 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:38:37 +0800 Subject: [PATCH 1/5] Preserve reasoning history with upstream capabilities --- crates/tw-config/src/lib.rs | 10 +- crates/tw-config/src/model_specs.rs | 15 + crates/tw-config/tests/manual/schema.rs | 30 ++ crates/tw-control/src/resources.rs | 14 +- crates/tw-control/tests/model_specs.rs | 42 ++ crates/tw-dialect/src/bedrock/response.rs | 2 +- crates/tw-dialect/src/bedrock/stream.rs | 11 +- crates/tw-dialect/src/chat/request.rs | 119 ++++-- crates/tw-dialect/src/chat/response.rs | 86 ++-- crates/tw-dialect/src/chat/stream.rs | 92 +++-- crates/tw-dialect/src/convert.rs | 73 +++- crates/tw-dialect/src/history.rs | 320 +++++++++++++++ crates/tw-dialect/src/ir.rs | 6 +- crates/tw-dialect/src/lib.rs | 1 + crates/tw-dialect/src/written.rs | 24 +- crates/tw-dialect/tests/reasoning_history.rs | 399 +++++++++++++++++++ crates/tw-gateway/src/oauth.rs | 12 +- crates/tw-gateway/src/server/pipeline/hop.rs | 67 +++- crates/tw-gateway/src/translate.rs | 109 ++++- crates/tw-gateway/tests/conversion.rs | 108 +++++ docs/config.md | 3 + docs/config.zh-CN.md | 3 + 22 files changed, 1393 insertions(+), 153 deletions(-) create mode 100644 crates/tw-dialect/src/history.rs create mode 100644 crates/tw-dialect/tests/reasoning_history.rs diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 1194db73..995eea0c 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -39,7 +39,7 @@ pub use aliases::{Alias, Aliases}; pub use credential::{CredentialError, Header, Headers, Secret, SecretResolveError, auth_header}; pub use init::{generate_control_key, generate_initial, generate_key}; pub use limits::{KeyLimit, LimitMeasure, LimitPer, UsageLimit}; -pub use model_specs::{ModelSpec, ResolvedSpec, Sourced, SpecSource}; +pub use model_specs::{ModelSpec, ReasoningHistory, ResolvedSpec, Sourced, SpecSource}; pub use plugins::Plugin; pub use proxy::{DIRECT, OnProxyFail, Proxy, ProxyKind, SYSTEM}; pub use validate::ValidationError; @@ -192,6 +192,8 @@ impl Default for Provider { aws: None, protocol: None, forward_client_identity: false, + reasoning_history: ReasoningHistory::Auto, + reasoning_history_group: None, proxy: default_proxy(), on_proxy_fail: OnProxyFail::default(), models: Vec::new(), @@ -776,6 +778,12 @@ pub fn parse_duration_secs(s: &str) -> Option { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Provider { + /// Request-side history format; model_specs can override it per model. + #[serde(default, skip_serializing_if = "is_default")] + pub reasoning_history: ReasoningHistory, + /// Explicitly share signed Chat history between compatible upstream identities. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_history_group: Option, pub name: String, pub base_url: String, /// API 密钥,按接口协议放进它认的请求头。可以写 `${ENV}`。**不做 keychain。** diff --git a/crates/tw-config/src/model_specs.rs b/crates/tw-config/src/model_specs.rs index 1a0a2e19..47347c4c 100644 --- a/crates/tw-config/src/model_specs.rs +++ b/crates/tw-config/src/model_specs.rs @@ -19,10 +19,25 @@ use serde::{Deserialize, Serialize}; use crate::{Config, Provider}; +/// Request-side reasoning-history capability. Independent of the API protocol. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ReasoningHistory { + #[default] + Auto, + ReasoningContent, + Reasoning, + ContentBlocks, + Disabled, +} + /// `providers[].model_specs` 的一项。每项都可选,但至少写一项(校验管)。 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ModelSpec { + /// Override this model's request-side reasoning-history format. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_history: Option, /// 一次最多输入多少 token,也就是上下文窗口 #[serde(default, skip_serializing_if = "Option::is_none")] pub context_window: Option, diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index f442d607..6e6e5b23 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -33,6 +33,9 @@ const fn row(name: &'static str, kind: Kind, def: Def, doc: T2) -> Row { fn protocols() -> Vec<&'static str> { super::fields::() } +fn reasoning_histories() -> Vec<&'static str> { + super::fields::() +} fn billings() -> Vec<&'static str> { super::fields::() } @@ -650,6 +653,24 @@ pub fn sections() -> Vec
{ "上游的接口格式。不写:官方地址按 `base_url` 识别(Bedrock 的推理地址是 `bedrock`),其余按 `anthropic` 处理。", ), ), + row( + "reasoning_history", + Kind::Enum(reasoning_histories), + Def::Is("auto"), + t( + "Request-side Chat reasoning history: auto uses verified endpoint defaults, otherwise keeps native content blocks for the same source and the existing reasoning_content field convention. Select reasoning-content, reasoning, content-blocks, or disabled for a compatible gateway. Model-specific settings take precedence. Signed history cannot cross an incompatible source or format.", + "Chat 请求的思考历史格式:auto 使用已验证的端点默认值,其余同来源保留原生内容块和既有的 reasoning_content 字段惯例。兼容网关可显式选择 reasoning-content、reasoning、content-blocks 或 disabled。模型级设置优先。带签名的历史不发送到来源或格式不兼容的上游。", + ), + ), + row( + "reasoning_history_group", + Kind::Str, + Def::Unset, + t( + "Explicit compatibility group for signed Chat history. Unset: isolated by upstream, model and configured credentials. Only share a group when the backends accept each other's signatures; blank is treated as unset.", + "带签名的 Chat 历史的显式兼容组。不写时按上游、模型及配置凭据隔离;只有确认后端相互接受签名时才共享组。空白视为未设置。", + ), + ), row( "forward_client_identity", Kind::Bool, @@ -783,6 +804,15 @@ pub fn sections() -> Vec
{ // 每项都可选,至少写一项由校验管 ty: checked!(ModelSpec, "{}"), rows: vec![ + row( + "reasoning_history", + Kind::Enum(reasoning_histories), + Def::Unset, + t( + "Override this model's request-side reasoning-history format. Unset: use the upstream setting. This is independent of whether the model can reason.", + "覆盖这个模型的请求侧思考历史格式。不写时遵从上游设置;与模型会不会推理是两项独立能力。", + ), + ), row( "context_window", Kind::Int, diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index efebc619..0e08316f 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -164,19 +164,27 @@ async fn set_model_spec( Json(req): Json, ) -> Result, Fail> { let model = req.model.trim(); - let spec = tw_config::ModelSpec { + let mut spec = tw_config::ModelSpec { context_window: req.context_window, max_output_tokens: req.max_output_tokens, reasoning: req.reasoning, image_input: req.image_input, + ..Default::default() }; - let spec = (!spec.is_empty()).then_some(spec); let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { if !cfg.providers.iter().any(|p| p.name == req.provider) { return Err(not_found("upstream", &req.provider)); } + // The UI edits the four public specifications, not the advanced history override. + spec.reasoning_history = cfg + .providers + .iter() + .find(|p| p.name == req.provider) + .and_then(|p| p.model_specs.get(model)) + .and_then(|s| s.reasoning_history); + let spec = (!spec.is_empty()).then_some(spec); tw_config::check_model_spec(&req.provider, model, spec.as_ref()) .map_err(|e| invalid(e.msg()))?; Ok(edit::set_model_spec( @@ -543,6 +551,8 @@ fn to_provider( aws, protocol: input.protocol.map(Into::into), forward_client_identity: input.forward_client_identity, + reasoning_history: existing.map(|e| e.reasoning_history).unwrap_or_default(), + reasoning_history_group: existing.and_then(|e| e.reasoning_history_group.clone()), models: input .models .iter() diff --git a/crates/tw-control/tests/model_specs.rs b/crates/tw-control/tests/model_specs.rs index 6f87d0bb..92b34f4c 100644 --- a/crates/tw-control/tests/model_specs.rs +++ b/crates/tw-control/tests/model_specs.rs @@ -354,3 +354,45 @@ async fn specs_stay_with_their_upstream_through_edits_renames_and_deletes() { assert_eq!(st, StatusCode::OK, "{v}"); assert!(!b.file().contains("model_specs"), "{}", b.file()); } + +#[tokio::test] +async fn editing_public_specs_and_provider_forms_preserves_history_capabilities() { + let up = upstream().await; + let b = bed(&config( + up, + " reasoning_history: content-blocks\n reasoning_history_group: shared\n model_specs:\n custom: { context_window: 32000, reasoning_history: reasoning }\n", + "", + )); + let (st, result) = call( + &b.app, + "PUT", + "/provider-model-spec", + json!({"provider":"relay","model":"custom","context_window":64000}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{result}"); + let cfg = tw_config::try_parse(&b.file()).unwrap(); + assert_eq!( + cfg.providers[0].model_specs["custom"].context_window, + Some(64000) + ); + assert_eq!( + cfg.providers[0].model_specs["custom"].reasoning_history, + Some(tw_config::ReasoningHistory::Reasoning) + ); + let (st,result)=call(&b.app,"PUT","/providers/relay",json!({"provider":{"name":"renamed","base_url":format!("http://{up}"),"key":"sk-good","protocol":"openai-chat"}})).await; + assert_eq!(st, StatusCode::OK, "{result}"); + let cfg = tw_config::try_parse(&b.file()).unwrap(); + assert_eq!( + cfg.providers[0].reasoning_history, + tw_config::ReasoningHistory::ContentBlocks + ); + assert_eq!( + cfg.providers[0].reasoning_history_group.as_deref(), + Some("shared") + ); + assert_eq!( + cfg.providers[0].model_specs["custom"].reasoning_history, + Some(tw_config::ReasoningHistory::Reasoning) + ); +} diff --git a/crates/tw-dialect/src/bedrock/response.rs b/crates/tw-dialect/src/bedrock/response.rs index 8e40c5b5..5e344257 100644 --- a/crates/tw-dialect/src/bedrock/response.rs +++ b/crates/tw-dialect/src/bedrock/response.rs @@ -165,7 +165,7 @@ pub fn encode_response(r: &Response, _s: &Session) -> Value { "reasoningContent": { "reasoningText": { "text": th.text, - "signature": sig.as_ref().map(|s| s.value.clone()).unwrap_or_default(), + "signature": sig.as_ref().map(|s| s.carried_in(Vendor::Anthropic)).unwrap_or_else(unsigned_marker), }, }, })), diff --git a/crates/tw-dialect/src/bedrock/stream.rs b/crates/tw-dialect/src/bedrock/stream.rs index 6420f42f..e56f49a3 100644 --- a/crates/tw-dialect/src/bedrock/stream.rs +++ b/crates/tw-dialect/src/bedrock/stream.rs @@ -109,11 +109,10 @@ impl Parser { self.begin(i, BlockKind::Thinking, out); out.push(Event::Delta { index: i, - delta: Delta::Signature(Signature { - vendor: Vendor::Anthropic, - value: s.to_string(), - redacted: false, - }), + delta: Delta::Signature( + Signature::read(s, Vendor::Anthropic) + .unwrap_or_else(|| Signature::new(Vendor::Anthropic, s)), + ), }); } if let Some(s) = r.get("redactedContent").and_then(Value::as_str) { @@ -247,7 +246,7 @@ impl Writer { json!({ "reasoningContent": { "redactedContent": s.value } }) } Delta::Signature(s) => { - json!({ "reasoningContent": { "signature": s.value } }) + json!({ "reasoningContent": { "signature": s.carried_in(Vendor::Anthropic) } }) } Delta::ToolInput(t) => json!({ "toolUse": { "input": t } }), }; diff --git a/crates/tw-dialect/src/chat/request.rs b/crates/tw-dialect/src/chat/request.rs index 6a749440..4169c0f1 100644 --- a/crates/tw-dialect/src/chat/request.rs +++ b/crates/tw-dialect/src/chat/request.rs @@ -2,6 +2,7 @@ use serde_json::{Map, Value, json}; +use crate::history::{ChatHistory, HistoryFormat, HistoryTarget}; use crate::ir::*; use crate::think; @@ -255,25 +256,33 @@ fn user_parts(content: &Value, dropped: &mut Dropped) -> Vec { fn assistant_parts(m: &Value, dropped: &mut Dropped) -> Vec { let mut parts = Vec::new(); - // DeepSeek 等实现的推理字段,不在 OpenAI 的定义里。DeepSeek 叫 reasoning_content, - // OpenRouter、vLLM 叫 reasoning - if let Some(t) = str_of(m, "reasoning_content") - .or_else(|| str_of(m, "reasoning")) - .filter(|t| !t.is_empty()) - { - parts.push(Part::Thinking(Thinking { - text: t.to_string(), - signature: Some(Signature::new(Vendor::Chat, "")), - })); - } - match m.get("content") { - Some(Value::String(s)) if !s.is_empty() => parts.push(Part::Text(s.clone())), - Some(Value::Array(items)) => parts.extend(items.iter().filter_map(|p| { - str_of(p, "text") - .or_else(|| str_of(p, "refusal")) - .map(|t| Part::Text(t.to_string())) - })), - _ => {} + for (key, format) in [ + ("reasoning_content", HistoryFormat::ReasoningContent), + ("reasoning", HistoryFormat::Reasoning), + ] { + if let Some(t) = str_of(m, key).filter(|t| !t.is_empty()) { + parts.push(Part::Thinking(Thinking { + text: t.to_string(), + signature: Some(ChatHistory::field(format).signature()), + })); + break; + } + } + let content = &m["content"]; + if let Some(items) = content.as_array() { + for item in items { + if str_of(item, "type") == Some("thinking") { + for block in super::response::content_blocks(&json!([item])) { + if let Block::Thinking(thinking) = block { + parts.push(Part::Thinking(thinking)); + } + } + } else if let Some(text) = str_of(item, "text").or_else(|| str_of(item, "refusal")) { + parts.push(Part::Text(text.to_string())); + } + } + } else if let Some(text) = content.as_str().filter(|t| !t.is_empty()) { + parts.push(Part::Text(text.to_string())); } for c in arr_of(m, "tool_calls") { let call = match str_of(c, "type") { @@ -302,6 +311,15 @@ fn assistant_parts(m: &Value, dropped: &mut Dropped) -> Vec { /// 中间表示 → 发给 Chat 上游的请求。 pub fn encode_request(r: &Request, t: &Target, dropped: &mut Dropped) -> Value { + encode_request_with_history(r, t, &HistoryTarget::default(), dropped) +} + +pub fn encode_request_with_history( + r: &Request, + t: &Target, + history: &HistoryTarget, + dropped: &mut Dropped, +) -> Value { // 对话中途的系统消息写成带标记的用户消息(见 `fold_system_turns`) let folded = fold_system_turns(r); let r = folded.as_ref(); @@ -319,7 +337,7 @@ pub fn encode_request(r: &Request, t: &Target, dropped: &mut Dropped) -> Value { match m.role { Role::User | Role::System => user_messages(m, dropped, &mut messages), Role::Assistant => { - if let Some(a) = assistant_message(m, dropped) { + if let Some(a) = assistant_message(m, history, dropped) { messages.push(a); } } @@ -519,39 +537,58 @@ fn merge_assistant_turns(messages: &[Message]) -> Vec { out } -fn assistant_message(m: &Message, dropped: &mut Dropped) -> Option { +fn assistant_message(m: &Message, target: &HistoryTarget, dropped: &mut Dropped) -> Option { let mut texts = Vec::new(); - let mut reasoning = Vec::new(); + let mut content = Vec::new(); + let mut fields: std::collections::BTreeMap<&str, Vec<&str>> = Default::default(); let mut calls = Vec::new(); + let mut typed = false; for p in &m.parts { match p { - Part::Text(s) if !s.is_empty() => texts.push(s.as_str()), + Part::Text(s) if !s.is_empty() => { + texts.push(s.as_str()); + content.push(json!({"type": "text", "text": s})); + } Part::ToolCall(c) => calls.push(json!({ - "id": c.id, - "type": "function", + "id": c.id, "type": "function", "function": { "name": c.name, "arguments": c.input.to_json_text() }, })), - // 只写回 Chat 上游自己给的推理:DeepSeek 在工具调用的那几轮要它原样带回; - // 别家签发的写过去没有意义,而且 OpenAI 自己的接口不认 reasoning_content - Part::Thinking(th) => match &th.signature { - Some(s) if s.vendor == Vendor::Chat && !th.text.is_empty() => { - reasoning.push(th.text.as_str()) + Part::Thinking(th) => { + let Some(history) = th.signature.as_ref().and_then(ChatHistory::read) else { + dropped.feature(Feature::ReasoningHistory); + continue; + }; + if !history.compatible(target) { + dropped.feature(Feature::ReasoningHistory); + continue; } - Some(s) if s.vendor == Vendor::Chat => {} - _ => dropped.feature(Feature::ReasoningHistory), - }, + match history.format_for(target) { + HistoryFormat::ContentBlocks => { + typed = true; + content.push(history.block.unwrap_or_else(|| json!({"type": "thinking", "thinking": [{"type": "text", "text": th.text}]}))); + } + HistoryFormat::ReasoningContent | HistoryFormat::Reasoning => { + if !th.text.is_empty() { + let key = if history.format_for(target) == HistoryFormat::Reasoning { + "reasoning" + } else { + "reasoning_content" + }; + fields.entry(key).or_default().push(th.text.as_str()); + } + } + _ => dropped.feature(Feature::ReasoningHistory), + } + } _ => {} } } - if texts.is_empty() && calls.is_empty() { + if texts.is_empty() && calls.is_empty() && !typed && fields.is_empty() { return None; } - let mut msg = json!({ - "role": "assistant", - "content": if texts.is_empty() { Value::Null } else { json!(texts.join("\n")) }, - }); - if !reasoning.is_empty() { - msg["reasoning_content"] = json!(reasoning.join("\n\n")); + let mut msg = json!({ "role": "assistant", "content": if typed { Value::Array(content) } else if texts.is_empty() { Value::Null } else { json!(texts.join("\n")) } }); + for (key, reasoning) in fields { + msg[key] = json!(reasoning.join("\n\n")); } if !calls.is_empty() { msg["tool_calls"] = Value::Array(calls); @@ -690,7 +727,7 @@ mod tests { r.messages[0].parts[0], Part::Thinking(Thinking { text: "想".into(), - signature: Some(Signature::new(Vendor::Chat, "")), + signature: Some(ChatHistory::field(HistoryFormat::Reasoning).signature()), }) ); } diff --git a/crates/tw-dialect/src/chat/response.rs b/crates/tw-dialect/src/chat/response.rs index 96ba6305..00e69401 100644 --- a/crates/tw-dialect/src/chat/response.rs +++ b/crates/tw-dialect/src/chat/response.rs @@ -1,5 +1,6 @@ //! OpenAI Chat Completions 整包响应 ⇄ 中间表示。 +use crate::history::{ChatHistory, HistoryFormat}; use serde_json::{Value, json}; use crate::convert::Session; @@ -57,32 +58,38 @@ pub fn usage_json(u: &Usage) -> Value { /// Chat 兼容端点的正文:标准字符串,或 Mistral 的有序内容块。 /// 只读文本和显式的推理文字,引用、图片与未知块不能当作回答正文。 -pub(super) fn content_parts(v: &Value, mut emit: impl FnMut(bool, &str)) { +pub(super) fn content_blocks(v: &Value) -> Vec { if let Some(text) = v.as_str() { - if !text.is_empty() { - emit(false, text); - } - } else if let Some(parts) = v.as_array() { - for part in parts { - match str_of(part, "type") { - Some("text") => { - if let Some(text) = str_of(part, "text").filter(|t| !t.is_empty()) { - emit(false, text); - } - } - Some("thinking") => { - for thought in arr_of(part, "thinking") { - if str_of(thought, "type") == Some("text") - && let Some(text) = str_of(thought, "text").filter(|t| !t.is_empty()) - { - emit(true, text); - } - } - } - _ => {} - } - } + return if text.is_empty() { + Vec::new() + } else { + vec![Block::Text(text.to_string())] + }; } + arr(v) + .iter() + .filter_map(|part| match str_of(part, "type") { + Some("text") => str_of(part, "text") + .filter(|t| !t.is_empty()) + .map(|t| Block::Text(t.to_string())), + Some("thinking") => { + let text: String = arr_of(part, "thinking") + .iter() + .filter(|t| str_of(t, "type") == Some("text")) + .filter_map(|t| str_of(t, "text")) + .collect(); + Some(Block::Thinking(Thinking { + text, + signature: Some(ChatHistory::content(part).signature()), + })) + } + _ => None, + }) + .collect() +} + +fn arr(v: &Value) -> &[Value] { + v.as_array().map(Vec::as_slice).unwrap_or_default() } /// 上游 Chat 的整包响应 → 中间表示。 @@ -93,27 +100,20 @@ pub fn decode_response(v: &Value) -> Response { .unwrap_or(&Value::Null); let msg = choice.get("message").unwrap_or(&Value::Null); let mut blocks = Vec::new(); - // DeepSeek 叫 reasoning_content,OpenRouter、vLLM 叫 reasoning - if let Some(t) = str_of(msg, "reasoning_content") - .or_else(|| str_of(msg, "reasoning")) - .filter(|t| !t.is_empty()) - { - blocks.push(Block::Thinking(Thinking { - text: t.to_string(), - signature: Some(Signature::new(Vendor::Chat, "")), - })); + for (key, format) in [ + ("reasoning_content", HistoryFormat::ReasoningContent), + ("reasoning", HistoryFormat::Reasoning), + ] { + if let Some(t) = str_of(msg, key).filter(|t| !t.is_empty()) { + blocks.push(Block::Thinking(Thinking { + text: t.to_string(), + signature: Some(ChatHistory::field(format).signature()), + })); + break; + } } for key in ["content", "refusal"] { - content_parts(&msg[key], |thinking, text| { - blocks.push(if thinking { - Block::Thinking(Thinking { - text: text.to_string(), - signature: Some(Signature::new(Vendor::Chat, "")), - }) - } else { - Block::Text(text.to_string()) - }); - }); + blocks.extend(content_blocks(&msg[key])); } for c in arr_of(msg, "tool_calls") { let id = str_of(c, "id").unwrap_or_default().to_string(); diff --git a/crates/tw-dialect/src/chat/stream.rs b/crates/tw-dialect/src/chat/stream.rs index 32e62cd6..7b49482b 100644 --- a/crates/tw-dialect/src/chat/stream.rs +++ b/crates/tw-dialect/src/chat/stream.rs @@ -9,10 +9,11 @@ use std::collections::HashMap; use serde_json::{Value, json}; use super::response::{ - completion_id, content_parts, finish_reason, stop_reason, usage, usage_json, + completion_id, content_blocks, finish_reason, stop_reason, usage, usage_json, }; use crate::convert::Session; use crate::frame::{self, Frame}; +use crate::history::{ChatHistory, HistoryFormat}; use crate::ir::*; // ───────────────────────────────────────────────────────── 解析 @@ -20,13 +21,14 @@ use crate::ir::*; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Open { Text, - Thinking, + Thinking(HistoryFormat), /// OpenAI 的工具调用序号 Tool(u64), } #[derive(Debug, Default)] pub struct Parser { + history: Option, started: bool, open: Option<(usize, Open)>, /// 已经开过的工具调用:OpenAI 的序号 → 块 @@ -71,33 +73,60 @@ impl Parser { }; let delta = choice.get("delta").unwrap_or(&Value::Null); - // DeepSeek 叫 reasoning_content,OpenRouter、vLLM 叫 reasoning - if let Some(t) = str_of(delta, "reasoning_content") - .or_else(|| str_of(delta, "reasoning")) - .filter(|t| !t.is_empty()) - { - let index = self.ensure(Open::Thinking, None, out); - out.push(Event::Delta { - index, - delta: Delta::Thinking(t.to_string()), - }); - } - for key in ["content", "refusal"] { - content_parts(&delta[key], |thinking, text| { - let index = self.ensure( - if thinking { Open::Thinking } else { Open::Text }, - None, - out, - ); + for (key, format) in [ + ("reasoning_content", HistoryFormat::ReasoningContent), + ("reasoning", HistoryFormat::Reasoning), + ] { + if let Some(t) = str_of(delta, key).filter(|t| !t.is_empty()) { + let index = self.ensure(Open::Thinking(format), None, out); + self.history + .get_or_insert_with(|| ChatHistory::field(format)); out.push(Event::Delta { index, - delta: if thinking { - Delta::Thinking(text.to_string()) - } else { - Delta::Text(text.to_string()) - }, + delta: Delta::Thinking(t.to_string()), }); - }); + break; + } + } + for key in ["content", "refusal"] { + for block in content_blocks(&delta[key]) { + match block { + Block::Text(text) => { + let index = self.ensure(Open::Text, None, out); + out.push(Event::Delta { + index, + delta: Delta::Text(text), + }); + } + Block::Thinking(th) => { + let index = + self.ensure(Open::Thinking(HistoryFormat::ContentBlocks), None, out); + if let Some(history) = th.signature.as_ref().and_then(ChatHistory::read) { + match &mut self.history { + Some(current) => current.append(history), + None => self.history = Some(history), + } + } + if !th.text.is_empty() { + out.push(Event::Delta { + index, + delta: Delta::Thinking(th.text), + }); + } + if self + .history + .as_ref() + .and_then(|h| h.block.as_ref()) + .and_then(|b| b.get("closed")) + .and_then(Value::as_bool) + == Some(true) + { + self.close(out); + } + } + _ => {} + } + } } for c in arr_of(delta, "tool_calls") { let k = u64_of(c, "index").unwrap_or(0); @@ -154,11 +183,16 @@ impl Parser { fn close(&mut self, out: &mut Vec) { if let Some((index, o)) = self.open.take() { - // 推理块结束时打上 Chat 的厂商:下一轮认得出该原样写回 reasoning_content - if o == Open::Thinking { + // 记住原生回放结构,下一轮由目标的请求能力决定写法 + if let Open::Thinking(format) = o { out.push(Event::Delta { index, - delta: Delta::Signature(Signature::new(Vendor::Chat, "")), + delta: Delta::Signature( + self.history + .take() + .unwrap_or_else(|| ChatHistory::field(format)) + .signature(), + ), }); } out.push(Event::BlockStop { index }); diff --git a/crates/tw-dialect/src/convert.rs b/crates/tw-dialect/src/convert.rs index 2d8abd98..3efa22c1 100644 --- a/crates/tw-dialect/src/convert.rs +++ b/crates/tw-dialect/src/convert.rs @@ -15,6 +15,7 @@ use std::collections::{HashMap, HashSet}; use serde_json::Value; use crate::frame::{self, Frame}; +use crate::history::HistoryTarget; use crate::ir::*; use crate::{anthropic, bedrock, chat, gemini, responses}; @@ -28,6 +29,9 @@ pub struct Prepared { pub query: Option, /// 客户端请求里转不过去、被丢掉的字段 pub dropped: Vec, + /// Do not send this request when true: signed reasoning cannot be replayed + /// to the selected upstream. A router may try another compatible target. + pub incompatible_history: bool, pub session: Session, } @@ -87,6 +91,13 @@ pub fn decode( impl Decoded { /// 中间表示 → 发给某种格式上游的请求。 pub fn encode(&self, target: &Target) -> Prepared { + self.encode_with_history(target, &HistoryTarget::default()) + } + + /// Encode with an explicitly resolved request-history capability and source. + /// The original `Target` and `encode` API remain compatible with callers + /// that do not configure route-specific history capabilities. + pub fn encode_with_history(&self, target: &Target, history: &HistoryTarget) -> Prepared { let mut dropped = self.dropped.clone(); let request = &self.request; let (body, path, query) = match target.dialect { @@ -96,7 +107,7 @@ impl Decoded { None, ), Dialect::Chat => ( - chat::encode_request(request, target, &mut dropped), + chat::request::encode_request_with_history(request, target, history, &mut dropped), "/v1/chat/completions".to_string(), None, ), @@ -139,7 +150,21 @@ impl Decoded { path, query, dropped: dropped.into_vec(), - session: Session::new(self.client, target.dialect, request, self.shape.clone()), + incompatible_history: crate::history::incompatible( + request, + history, + target.dialect == Dialect::Chat, + ), + session: { + let mut session = + Session::new(self.client, target.dialect, request, self.shape.clone()); + session.history_origin = if target.dialect == Dialect::Chat { + history.origin.clone() + } else { + None + }; + session + }, } } } @@ -151,13 +176,22 @@ impl Decoded { /// 这种格式里长什么样」只该有一个答案 —— 手写的那一份迟早和转发时真正发出去的 /// 不一样,而那时「转发正常、测速失败」查起来毫无头绪。 pub fn encode(request: &Request, target: &Target) -> Prepared { + encode_with_history(request, target, &HistoryTarget::default()) +} + +/// Encode a constructed request with route-specific history capabilities. +pub fn encode_with_history( + request: &Request, + target: &Target, + history: &HistoryTarget, +) -> Prepared { Decoded { client: target.dialect, request: request.clone(), dropped: Dropped::new(target.dialect), shape: ClientShape::default(), } - .encode(target) + .encode_with_history(target, history) } /// 客户端请求 → 上游请求,一步到位。 @@ -167,10 +201,22 @@ pub fn prepare( path: &str, query: Option<&str>, target: &Target, +) -> Result { + prepare_with_history(client, body, path, query, target, &HistoryTarget::default()) +} + +/// Decode and encode with route-specific history capabilities. +pub fn prepare_with_history( + client: Dialect, + body: &[u8], + path: &str, + query: Option<&str>, + target: &Target, + history: &HistoryTarget, ) -> Result { let v: Value = serde_json::from_slice(body) .map_err(|_| Rejection("The request body is not valid JSON.".into()))?; - Ok(decode(client, &v, path, query)?.encode(target)) + Ok(decode(client, &v, path, query)?.encode_with_history(target, history)) } /// `/model/anthropic.claude-sonnet-4-v1:0/converse-stream` → (模型, 是否流式) @@ -202,6 +248,7 @@ fn gemini_path(path: &str) -> Option<(String, bool)> { /// 一次请求转换之后,写响应时要用的东西。 #[derive(Debug, Clone, PartialEq)] pub struct Session { + history_origin: Option, pub client: Dialect, pub upstream: Dialect, /// 客户端请求的模型名。上游响应里没写模型时用它 @@ -224,6 +271,7 @@ impl Session { shape: ClientShape, ) -> Session { Session { + history_origin: None, client, upstream, model: r.model.clone(), @@ -372,6 +420,11 @@ impl Session { chat::text_calls::rewrite(r, &self.tools); } for b in &mut r.blocks { + if let Block::Thinking(th) = b + && let Some(signature) = th.signature.as_mut() + { + crate::history::ChatHistory::stamp(signature, self.history_origin.as_deref()); + } if let Block::ToolCall(c) = b && self.is_freeform(&c.name) && let ToolInput::Json(v) = &c.input @@ -384,6 +437,7 @@ impl Session { #[cfg(test)] pub(crate) fn for_test(client: Dialect, upstream: Dialect) -> Session { Session { + history_origin: None, client, upstream, model: "m".into(), @@ -610,6 +664,7 @@ impl Writer { /// - **没有参数的函数调用**:有的上游一个参数片段都不发,补一个 `{}`,否则客户端解析 /// 空串会失败 struct Normalizer { + history_origin: Option, text_calls: Option, freeform: HashSet, /// 上游把自由格式的输入包成 JSON(除 Responses 以外都是) @@ -622,6 +677,7 @@ struct Normalizer { impl Normalizer { fn new(s: &Session) -> Normalizer { Normalizer { + history_origin: s.history_origin.clone(), text_calls: (s.upstream == Dialect::Chat && !s.tools.is_empty()) .then(|| chat::text_calls::Stage::new(s.tools.clone())), freeform: s.freeform.clone(), @@ -641,7 +697,14 @@ impl Normalizer { } } - fn apply_one(&mut self, e: Event, out: &mut Vec) { + fn apply_one(&mut self, mut e: Event, out: &mut Vec) { + if let Event::Delta { + delta: Delta::Signature(signature), + .. + } = &mut e + { + crate::history::ChatHistory::stamp(signature, self.history_origin.as_deref()); + } match &e { Event::BlockStart { index, diff --git a/crates/tw-dialect/src/history.rs b/crates/tw-dialect/src/history.rs new file mode 100644 index 00000000..44e6340e --- /dev/null +++ b/crates/tw-dialect/src/history.rs @@ -0,0 +1,320 @@ +//! Chat-compatible APIs share an envelope, not a reasoning-history schema. +//! +//! Keep the replay format and native thinking block in the existing signature +//! carrier. Old `tw1.ch.` histories remain readable. The target's capability +//! decides what can be replayed; opaque signatures never change formats or +//! cross a known source boundary. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::ir::{Part, Request, Signature, Vendor}; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum HistoryFormat { + #[default] + Auto, + ReasoningContent, + Reasoning, + ContentBlocks, + Disabled, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HistoryTarget { + pub format: HistoryFormat, + /// An upstream/credential compatibility group, never an API key. + pub origin: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChatHistory { + version: u8, + pub format: HistoryFormat, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub block: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub origin: Option, +} + +impl ChatHistory { + pub fn field(format: HistoryFormat) -> Self { + Self { + version: 1, + format, + block: None, + origin: None, + } + } + + pub fn content(block: &Value) -> Self { + // Replay request fields only, not response-only metadata. + let mut native = json!({"type": "thinking", "thinking": block.get("thinking").filter(|v| v.is_array()).cloned().unwrap_or_else(|| json!([]))}); + if let Some(signature) = block.get("signature").and_then(Value::as_str) { + native["signature"] = json!(signature); + } + if let Some(closed) = block.get("closed").and_then(Value::as_bool) { + native["closed"] = json!(closed); + } + Self { + block: Some(native), + ..Self::field(HistoryFormat::ContentBlocks) + } + } + + pub fn read(signature: &Signature) -> Option { + if signature.vendor != Vendor::Chat { + return None; + } + if signature.value.is_empty() { + return Some(Self::field(HistoryFormat::ReasoningContent)); + } + let history: Self = serde_json::from_str(&signature.value).ok()?; + let valid_block = match history.format { + HistoryFormat::ContentBlocks => history.block.as_ref().is_some_and(|b| { + b.get("type").and_then(Value::as_str) == Some("thinking") + && b.get("thinking").is_some_and(Value::is_array) + }), + _ => history.block.is_none(), + }; + (history.version == 1 + && valid_block + && matches!( + history.format, + HistoryFormat::ReasoningContent + | HistoryFormat::Reasoning + | HistoryFormat::ContentBlocks + )) + .then_some(history) + } + + pub fn signature(&self) -> Signature { + if self.format == HistoryFormat::ReasoningContent + && self.block.is_none() + && self.origin.is_none() + { + return Signature::new(Vendor::Chat, ""); + } + Signature::new( + Vendor::Chat, + serde_json::to_string(self).expect("reasoning history is JSON"), + ) + } + + pub fn opaque(&self) -> bool { + self.block + .as_ref() + .and_then(|b| b.get("signature")) + .and_then(Value::as_str) + .is_some_and(|s| !s.is_empty()) + } + + /// A stream carries fragments of a native block, not complete messages. + pub fn append(&mut self, next: Self) { + let (Some(block), Some(next)) = (&mut self.block, next.block) else { + return; + }; + if let Some(parts) = next.get("thinking").and_then(Value::as_array) { + let items = block["thinking"] + .as_array_mut() + .expect("native thinking is an array"); + for part in parts { + if let Some(text) = part.get("text").and_then(Value::as_str) + && part.get("type").and_then(Value::as_str) == Some("text") + && part.as_object().is_some_and(|o| o.len() == 2) + && let Some(last) = items.last_mut() + && last.get("type").and_then(Value::as_str) == Some("text") + && last.as_object().is_some_and(|o| o.len() == 2) + && let Some(Value::String(previous)) = last.get_mut("text") + { + previous.push_str(text); + continue; + } + items.push(part.clone()); + } + } + for key in ["signature", "closed"] { + if let Some(value) = next.get(key) { + block[key] = value.clone(); + } + } + } + + pub fn format_for(&self, target: &HistoryTarget) -> HistoryFormat { + match target.format { + // A carried native shape belongs to its source. Switching to an + // unknown upstream does not establish request-field compatibility. + HistoryFormat::Auto if self.origin.is_some() && self.origin != target.origin => { + HistoryFormat::Disabled + } + // A response's `reasoning` string does not establish that the + // request accepts the same field. Keep the existing compatible + // request convention unless a capability explicitly selects it. + HistoryFormat::Auto if self.format == HistoryFormat::Reasoning => { + HistoryFormat::ReasoningContent + } + HistoryFormat::Auto => self.format, + format => format, + } + } + + pub fn compatible(&self, target: &HistoryTarget) -> bool { + !self.opaque() + || (self.format_for(target) == self.format + && (self.origin.is_none() || self.origin == target.origin)) + } + + pub fn stamp(signature: &mut Signature, origin: Option<&str>) { + if let Some(origin) = origin + && let Some(mut history) = Self::read(signature) + { + history.origin = Some(origin.to_string()); + *signature = history.signature(); + } + } +} + +pub fn incompatible(request: &Request, target: &HistoryTarget, chat: bool) -> bool { + request.messages.iter().flat_map(|m| &m.parts).any(|part| { + let Part::Thinking(thinking) = part else { + return false; + }; + thinking.signature.as_ref().is_some_and(|signature| { + if signature.vendor != Vendor::Chat { + return false; + } + match ChatHistory::read(signature) { + Some(history) => history.opaque() && (!chat || !history.compatible(target)), + None => !signature.value.is_empty(), + } + }) + }) +} + +/// Apply an explicit capability to a native Chat request without round-tripping +/// unrelated fields through the IR. Auto leaves native requests byte-for-byte. +pub fn shape_chat(body: &[u8], format: HistoryFormat) -> Option> { + if format == HistoryFormat::Auto + || ![ + b"reasoning_content".as_slice(), + b"\"reasoning\"", + b"\"thinking\"", + b"\\u", + ] + .iter() + .any(|needle| memchr::memmem::find(body, needle).is_some()) + { + return None; + } + let mut request: Value = serde_json::from_slice(body).ok()?; + let original = request.clone(); + let mut changed = false; + let messages = request.get_mut("messages")?.as_array_mut()?; + let mut empty_messages = Vec::new(); + for (index, message) in messages.iter_mut().enumerate() { + let mut message_changed = false; + if message.get("role").and_then(Value::as_str) != Some("assistant") { + continue; + } + let Some(object) = message.as_object_mut() else { + continue; + }; + let mut thoughts = Vec::new(); + for key in ["reasoning_content", "reasoning"] { + if let Some(value) = object.remove(key) { + changed = true; + message_changed = true; + if let Some(text) = value.as_str().filter(|s| !s.is_empty()) { + thoughts.push(text.to_string()); + } + } + } + let content = object.get("content").cloned().unwrap_or(Value::Null); + let mut blocks = match &content { + Value::Array(parts) => parts.clone(), + Value::String(text) if !text.is_empty() => vec![json!({"type": "text", "text": text})], + _ => Vec::new(), + }; + match format { + HistoryFormat::ContentBlocks => { + if !thoughts.is_empty() { + blocks.insert(0, json!({"type": "thinking", "thinking": [{"type": "text", "text": thoughts.join("\n\n")}]})); + object.insert("content".into(), json!(blocks)); + } + } + HistoryFormat::Reasoning + | HistoryFormat::ReasoningContent + | HistoryFormat::Disabled => { + let before = blocks.len(); + blocks.retain(|block| { + if block.get("type").and_then(Value::as_str) != Some("thinking") { + return true; + } + if let Some(parts) = block.get("thinking").and_then(Value::as_array) { + thoughts.push( + parts + .iter() + .filter(|p| p.get("type").and_then(Value::as_str) == Some("text")) + .filter_map(|p| p.get("text").and_then(Value::as_str)) + .collect::(), + ); + } + false + }); + if before != blocks.len() { + changed = true; + message_changed = true; + object.insert( + "content".into(), + if blocks.is_empty() { + Value::Null + } else { + json!(blocks) + }, + ); + } + if format != HistoryFormat::Disabled && !thoughts.is_empty() { + object.insert( + if format == HistoryFormat::Reasoning { + "reasoning" + } else { + "reasoning_content" + } + .into(), + json!(thoughts.join("\n\n")), + ); + } + } + HistoryFormat::Auto => {} + } + let empty_content = object.get("content").is_none_or(|v| { + v.is_null() || v.as_str() == Some("") || v.as_array().is_some_and(Vec::is_empty) + }); + let has_other_content = [ + "tool_calls", + "function_call", + "audio", + "refusal", + "reasoning_content", + "reasoning", + ] + .iter() + .any(|key| { + object.get(*key).is_some_and(|v| { + !v.is_null() && v.as_str() != Some("") && !v.as_array().is_some_and(Vec::is_empty) + }) + }); + if message_changed && empty_content && !has_other_content { + empty_messages.push(index); + } + } + let mut index = 0; + messages.retain(|_| { + let keep = !empty_messages.contains(&index); + index += 1; + keep + }); + (changed && request != original).then(|| request.to_string().into_bytes()) +} diff --git a/crates/tw-dialect/src/ir.rs b/crates/tw-dialect/src/ir.rs index 1084dc63..c7ae4247 100644 --- a/crates/tw-dialect/src/ir.rs +++ b/crates/tw-dialect/src/ir.rs @@ -428,9 +428,9 @@ pub enum Vendor { Anthropic, OpenAi, Google, - /// Chat 格式的上游(DeepSeek 等)的 `reasoning_content`。它们不签名,`value` 为空; - /// 打上厂商只为了下一轮认得出这段推理该原样写回 `reasoning_content` —— DeepSeek - /// 在工具调用的那几轮要求带回来,而 OpenAI 自己的 Chat 接口不认这个字段 + /// Chat-compatible reasoning history. Empty values are legacy + /// `reasoning_content`; newer carriers retain the wire format, native blocks + /// and source identity (see `history::ChatHistory`). Chat, } diff --git a/crates/tw-dialect/src/lib.rs b/crates/tw-dialect/src/lib.rs index 4f306000..2d5bb140 100644 --- a/crates/tw-dialect/src/lib.rs +++ b/crates/tw-dialect/src/lib.rs @@ -22,6 +22,7 @@ pub mod convert; pub mod frame; pub mod gemini; pub mod harness; +pub mod history; pub mod ir; pub mod official; pub mod params; diff --git a/crates/tw-dialect/src/written.rs b/crates/tw-dialect/src/written.rs index 6eb5d081..eb8b3aa0 100644 --- a/crates/tw-dialect/src/written.rs +++ b/crates/tw-dialect/src/written.rs @@ -362,7 +362,7 @@ fn chat(c: &mut Collect, v: &Value) { }); } -/// 字符串,或者各块的 `text`、`refusal` +/// 字符串,或者正文、拒答和原生思考块里的文字。签名仍是协议元数据。 fn chat_content(c: &mut Collect, content: &Value, in_tool_result: bool) { match content { Value::String(_) => c.here(content, in_tool_result), @@ -371,6 +371,15 @@ fn chat_content(c: &mut Collect, content: &Value, in_tool_result: bool) { c.index(i, |c| match str_of(p, "type").unwrap_or("") { "text" => c.field(p, "text", in_tool_result), "refusal" => c.field(p, "refusal", in_tool_result), + "thinking" => c.key("thinking", |c| { + for (j, thought) in each(p, "thinking") { + c.index(j, |c| { + if str_of(thought, "type") == Some("text") { + c.field(thought, "text", in_tool_result); + } + }); + } + }), _ => {} }); } @@ -760,6 +769,19 @@ mod tests { ); } + #[test] + fn chat_native_thinking_is_written_text_but_signatures_and_unknown_blocks_are_not() { + let body = json!({"messages":[{"role":"assistant","content":[ + {"type":"thinking","thinking":[{"type":"text","text":"thought"},{"type":"reference","text":"reference metadata"}],"signature":"opaque signature","closed":true}, + {"type":"text","text":"answer"}, + {"type":"unknown","text":"unknown metadata"} + ]}]}); + assert_eq!( + found(Shape::Generate(Dialect::Chat), &body), + sorted(["thought", "answer"]) + ); + } + #[test] fn gemini_reads_both_spellings_and_skips_signatures() { let body = json!({ diff --git a/crates/tw-dialect/tests/reasoning_history.rs b/crates/tw-dialect/tests/reasoning_history.rs new file mode 100644 index 00000000..3a2ae5c1 --- /dev/null +++ b/crates/tw-dialect/tests/reasoning_history.rs @@ -0,0 +1,399 @@ +//! Reasoning histories must survive real client carriers, not just a text decode. +use serde_json::{Value, json}; +use tw_dialect::{ + convert, + history::{ChatHistory, HistoryFormat as F, HistoryTarget}, + ir::*, +}; + +fn target(format: F, origin: &str) -> (Target, HistoryTarget) { + ( + Target { + dialect: Dialect::Chat, + official: false, + default_max_tokens: 8192, + }, + HistoryTarget { + format, + origin: Some(origin.into()), + }, + ) +} + +fn prepare( + client: Dialect, + body: &[u8], + path: &str, + query: Option<&str>, + target: &(Target, HistoryTarget), +) -> Result { + convert::prepare_with_history(client, body, path, query, &target.0, &target.1) +} + +fn encode(request: &Request, target: &(Target, HistoryTarget)) -> convert::Prepared { + convert::encode_with_history(request, &target.0, &target.1) +} + +fn initial(client: Dialect, stream: bool) -> (Value, &'static str) { + match client { + Dialect::Anthropic => ( + json!({"model":"m","max_tokens":1024,"stream":stream,"messages":[{"role":"user","content":"hi"}]}), + "/v1/messages", + ), + Dialect::Responses => ( + json!({"model":"m","stream":stream,"input":[{"role":"user","content":"hi"}]}), + "/v1/responses", + ), + Dialect::Gemini => ( + json!({"contents":[{"role":"user","parts":[{"text":"hi"}]}]}), + if stream { + "/v1beta/models/m:streamGenerateContent" + } else { + "/v1beta/models/m:generateContent" + }, + ), + Dialect::Bedrock => ( + json!({"messages":[{"role":"user","content":[{"text":"hi"}]}]}), + if stream { + "/model/m/converse-stream" + } else { + "/model/m/converse" + }, + ), + _ => unreachable!(), + } +} + +fn followup(client: Dialect, mut request: Value, reply: &Value) -> Value { + match client { + Dialect::Anthropic => { + request["messages"].as_array_mut().unwrap().extend([ + json!({"role":"assistant","content":reply["content"]}), + json!({"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"done"}]}), + ]); + } + Dialect::Responses => { + request["input"] + .as_array_mut() + .unwrap() + .extend(reply["output"].as_array().unwrap().clone()); + request["input"] + .as_array_mut() + .unwrap() + .push(json!({"type":"function_call_output","call_id":"call_1","output":"done"})); + } + Dialect::Gemini => { + request["contents"].as_array_mut().unwrap().extend([ + reply["candidates"][0]["content"].clone(), + json!({"role":"user","parts":[{"functionResponse":{"id":"call_1","name":"f","response":{"result":"done"}}}]}), + ]); + } + Dialect::Bedrock => { + request["messages"].as_array_mut().unwrap().extend([ + reply["output"]["message"].clone(), + json!({"role":"user","content":[{"toolResult":{"toolUseId":"call_1","content":[{"text":"done"}]}}]}), + ]); + } + _ => unreachable!(), + } + request +} + +fn content() -> Value { + json!([ + {"type":"thinking","thinking":[{"type":"text","text":"first thought"}],"signature":"opaque.one","closed":true}, + {"type":"text","text":"first answer"}, + {"type":"thinking","thinking":[{"type":"text","text":"second thought"}],"signature":"opaque.two","closed":true}, + {"type":"text","text":"second answer"} + ]) +} + +fn tool() -> Value { + json!({"id":"call_1","type":"function","function":{"name":"f","arguments":"{}"}}) +} +fn response(native: Value) -> Value { + json!({"id":"r","model":"m","choices":[{"message":{"role":"assistant","content":native,"tool_calls":[tool()]},"finish_reason":"tool_calls"}]}) +} + +fn check_next(client: Dialect, request: Value, path: &str, reply: Value, wanted: Value) { + let next = followup(client, request, &reply); + let prepared = prepare( + client, + next.to_string().as_bytes(), + path, + Some("alt=sse"), + &target(F::Auto, "source"), + ) + .unwrap(); + assert!(!prepared.incompatible_history, "{client:?}: {next}"); + let sent: Value = serde_json::from_slice(&prepared.body).unwrap(); + let assistant = sent["messages"] + .as_array() + .unwrap() + .iter() + .find(|m| m["role"] == "assistant") + .unwrap(); + assert_eq!(assistant["content"], wanted, "{client:?}"); + assert!(assistant.get("reasoning_content").is_none(), "{assistant}"); + assert!(assistant.get("reasoning").is_none(), "{assistant}"); + assert_eq!(assistant["tool_calls"][0], tool()); +} + +#[test] +fn native_blocks_and_signatures_roundtrip_through_every_signed_client_carrier() { + for client in [ + Dialect::Anthropic, + Dialect::Responses, + Dialect::Gemini, + Dialect::Bedrock, + ] { + let (request, path) = initial(client, false); + let prepared = prepare( + client, + request.to_string().as_bytes(), + path, + None, + &target(F::Auto, "source"), + ) + .unwrap(); + let reply: Value = serde_json::from_slice( + &prepared + .session + .response(response(content()).to_string().as_bytes()) + .unwrap(), + ) + .unwrap(); + check_next(client, request, path, reply, content()); + } +} + +fn frame(delta: Value) -> String { + format!( + "data: {}\n\n", + json!({"id":"r","model":"m","choices":[{"delta":delta,"finish_reason":null}]}) + ) +} + +#[test] +fn streamed_blocks_keep_signature_only_fragments_without_buffering_the_answer() { + for client in [ + Dialect::Anthropic, + Dialect::Responses, + Dialect::Gemini, + Dialect::Bedrock, + ] { + for chunk in [1, 13, 4096] { + let (request, path) = initial(client, true); + let prepared = prepare( + client, + request.to_string().as_bytes(), + path, + Some("alt=sse"), + &target(F::Auto, "source"), + ) + .unwrap(); + let mut stream = prepared.session.stream(); + let mut output = Vec::new(); + let fragments = [ + json!({"content":[{"type":"thinking","thinking":[{"type":"text","text":"first "}]}]}), + json!({"content":[{"type":"thinking","thinking":[{"type":"text","text":"thought"}]}]}), + json!({"content":[{"type":"thinking","thinking":[],"signature":"opaque.one","closed":true}]}), + json!({"content":[{"type":"text","text":"first answer"}]}), + json!({"content":[{"type":"thinking","thinking":[{"type":"text","text":"second thought"}],"signature":"opaque.two","closed":true}]}), + json!({"content":[{"type":"text","text":"second answer"}]}), + json!({"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"f","arguments":"{}"}}]}), + ]; + for (i, fragment) in fragments.into_iter().enumerate() { + for bytes in frame(fragment).as_bytes().chunks(chunk) { + output.extend(stream.process(bytes)); + } + if i == 3 || (i == 0 && client != Dialect::Gemini) { + let expected = if i == 3 { "first answer" } else { "first " }; + assert!( + String::from_utf8_lossy(&output).contains(expected), + "{client:?} must emit actual content before the upstream finishes" + ); + } + } + output.extend(stream.process(b"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n")); + output.extend(stream.finish()); + // Consume exactly what a streaming client received, through its native parser. + let mut own = target(F::Auto, "unused"); + own.0.dialect = client; + let consumer = prepare( + client, + request.to_string().as_bytes(), + path, + Some("alt=sse"), + &own, + ) + .unwrap(); + let mut collector = consumer.session.collector(); + for bytes in output.chunks(chunk) { + collector.process(bytes); + } + let reply: Value = serde_json::from_slice(&collector.finish().unwrap()).unwrap(); + check_next(client, request, path, reply, content()); + } + } +} + +#[test] +fn explicit_capabilities_repair_old_histories_and_preserve_distinct_field_names() { + let request = json!({"model":"m","input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"old thought"}],"encrypted_content":"tw1.ch."},{"role":"assistant","content":"answer"}]}); + for (format, key) in [ + (F::ReasoningContent, "reasoning_content"), + (F::Reasoning, "reasoning"), + (F::ContentBlocks, "content"), + (F::Disabled, "none"), + ] { + let prepared = prepare( + Dialect::Responses, + request.to_string().as_bytes(), + "/v1/responses", + None, + &target(format, "source"), + ) + .unwrap(); + let sent: Value = serde_json::from_slice(&prepared.body).unwrap(); + let message = &sent["messages"][0]; + if key == "content" { + assert_eq!(message["content"][0]["type"], "thinking"); + assert_eq!(message["content"][0]["thinking"][0]["text"], "old thought"); + } else if key != "none" { + assert_eq!(message[key], "old thought"); + } else { + assert!(message.get("reasoning_content").is_none()); + assert!(!prepared.dropped.is_empty()); + } + } +} + +#[test] +fn signed_history_is_rejected_before_incompatible_replay() { + let mut history = ChatHistory::content(&content()[0]); + history.origin = Some("source".into()); + let mut request = Request { + model: "m".into(), + messages: vec![Message { + role: Role::Assistant, + parts: vec![ + Part::Thinking(Thinking { + text: "first thought".into(), + signature: Some(history.signature()), + }), + Part::Text("answer".into()), + ], + }], + ..Default::default() + }; + for target in [ + target(F::ContentBlocks, "other"), + target(F::ReasoningContent, "source"), + target(F::Disabled, "source"), + ] { + assert!(encode(&request, &target).incompatible_history); + } + assert!(!encode(&request, &target(F::ContentBlocks, "source")).incompatible_history); + // Unsigned source history can be omitted with the normal dropped-feature diagnostic. + history + .block + .as_mut() + .unwrap() + .as_object_mut() + .unwrap() + .remove("signature"); + if let Part::Thinking(th) = &mut request.messages[0].parts[0] { + th.signature = Some(history.signature()); + } + let prepared = encode(&request, &target(F::Auto, "other")); + assert!(!prepared.incompatible_history); + assert!(!prepared.dropped.is_empty()); +} + +#[test] +fn native_requests_keep_unrelated_fields_and_avoid_unnecessary_reserialization() { + let body=br#"{ "model":"m", "custom":{"keep":true}, "messages":[{"role":"assistant","content":"answer","reasoning_content":"thought","custom":42}] }"#; + assert!(tw_dialect::history::shape_chat(body, F::Auto).is_none()); + assert!(tw_dialect::history::shape_chat(body, F::ReasoningContent).is_none()); + let native = tw_dialect::history::shape_chat(body, F::ContentBlocks).unwrap(); + let sent: Value = serde_json::from_slice(&native).unwrap(); + assert_eq!(sent["custom"]["keep"], true); + assert_eq!(sent["messages"][0]["custom"], 42); + assert_eq!(sent["messages"][0]["content"][0]["type"], "thinking"); + assert!(sent["messages"][0].get("reasoning_content").is_none()); +} + +#[test] +fn signature_only_native_blocks_remain_replayable() { + let native = + json!([{"type":"thinking","thinking":[],"signature":"opaque.empty","closed":true}]); + for client in [ + Dialect::Anthropic, + Dialect::Responses, + Dialect::Gemini, + Dialect::Bedrock, + ] { + let (request, path) = initial(client, false); + let prepared = prepare( + client, + request.to_string().as_bytes(), + path, + None, + &target(F::Auto, "source"), + ) + .unwrap(); + let reply: Value = serde_json::from_slice( + &prepared + .session + .response(response(native.clone()).to_string().as_bytes()) + .unwrap(), + ) + .unwrap(); + check_next(client, request, path, reply, native.clone()); + } +} + +#[test] +fn a_response_reasoning_field_does_not_guess_a_new_request_capability() { + let decoded=convert::decode(Dialect::Chat,&json!({"model":"m","messages":[{"role":"assistant","content":"answer","reasoning":"thought"}]}),"/v1/chat/completions",None).unwrap(); + let sent: Value = + serde_json::from_slice(&encode(&decoded.request, &target(F::Auto, "source")).body).unwrap(); + assert_eq!(sent["messages"][0]["reasoning_content"], "thought"); + assert!(sent["messages"][0].get("reasoning").is_none()); + let sent: Value = + serde_json::from_slice(&encode(&decoded.request, &target(F::Reasoning, "source")).body) + .unwrap(); + assert_eq!(sent["messages"][0]["reasoning"], "thought"); +} + +#[test] +fn disabling_native_history_never_leaves_an_empty_assistant_turn() { + let native = json!({"model":"m","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":[{"type":"text","text":"only thought"}]}]},{"role":"assistant","content":null,"reasoning_content":"tool thought","tool_calls":[tool()]},{"role":"user","content":"next"}]}); + let sent: Value = serde_json::from_slice( + &tw_dialect::history::shape_chat(native.to_string().as_bytes(), F::Disabled).unwrap(), + ) + .unwrap(); + assert_eq!(sent["messages"].as_array().unwrap().len(), 2); + assert!(sent["messages"][0]["content"].is_null()); + assert_eq!(sent["messages"][0]["tool_calls"][0], tool()); + assert_eq!(sent["messages"][1]["role"], "user"); +} + +#[test] +fn assistant_content_arrays_still_keep_refusals_and_legacy_text_chunks() { + let request = json!({"model":"m","messages":[{"role":"assistant","content":[{"type":"text","text":"first"},{"type":"refusal","refusal":"refused"},{"text":"legacy"}]}]}); + let decoded = convert::decode(Dialect::Chat, &request, "/v1/chat/completions", None).unwrap(); + let text: Vec<_> = decoded.request.messages[0] + .parts + .iter() + .filter_map(|p| { + if let Part::Text(t) = p { + Some(t.as_str()) + } else { + None + } + }) + .collect(); + assert_eq!(text, ["first", "refused", "legacy"]); +} diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index 623f4a0b..73ec8f67 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -762,6 +762,12 @@ async fn exchange(cfg: &OAuth, refresh: &str, http: &reqwest::Client) -> Result< mod tests { use super::*; + fn direct_client() -> reqwest::Client { + // These tests require a direct loopback connection refusal, regardless + // of the developer machine's native system proxy settings. + reqwest::Client::builder().no_proxy().build().unwrap() + } + fn cfg(endpoint: &str) -> OAuth { OAuth { access: None, @@ -780,7 +786,7 @@ mod tests { let c = Cache::new(); let mut o = cfg("http://127.0.0.1:1/nope"); o.access = Some("a-existing".into()); - let http = reqwest::Client::new(); + let http = direct_client(); let got = tokio::runtime::Runtime::new() .unwrap() .block_on(c.token("p", &o, &http)) @@ -792,7 +798,7 @@ mod tests { #[test] fn a_configured_access_token_is_used_until_its_lead_time_then_renewed() { let rt = tokio::runtime::Runtime::new().unwrap(); - let http = reqwest::Client::new(); + let http = direct_client(); let at = |secs: i64| { (chrono::Utc::now() + chrono::Duration::seconds(secs)) .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) @@ -863,7 +869,7 @@ mod tests { // **没有退避,一个坏掉的 token 端点会被每个请求敲一次。** let c = Cache::new(); let o = cfg("http://127.0.0.1:1/nope"); - let http = reqwest::Client::new(); + let http = direct_client(); let rt = tokio::runtime::Runtime::new().unwrap(); let first = rt.block_on(c.token("p", &o, &http)).unwrap_err(); assert!(matches!(first, OauthError::Http { .. }), "{first}"); diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 1598b930..75d24a96 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -2069,9 +2069,32 @@ fn prepare( id: u64, ) -> Result { let generates = reading.generates; - // 方言互转。**同格式时是 None,这一整段零成本** let client_dialect = req.api.map(|a| a.dialect()); let target = crate::translate::plan(req.api, generates, provider.effective_protocol()); + let model = effective_set + .model + .as_deref() + .unwrap_or(&reading.facts.model); + let history_target = crate::translate::history_target(provider, model); + if generates + && asked.decoded.is_some_and(|decoded| { + decoded.as_ref().is_ok_and(|d| { + tw_dialect::history::incompatible( + &d.request, + &history_target, + target.or(client_dialect) == Some(tw_dialect::ir::Dialect::Chat), + ) + }) + }) + { + return Err(GatewayError::new( + crate::error::Source::Request, + msg!( + "gw.convert.reasoning_history_incompatible", upstream = provider.name.clone() => + "Signed reasoning history cannot be replayed to upstream `{upstream}`: its source or request format is incompatible." + ), + )); + } let chatgpt = generates && provider.effective_protocol() == Some(tw_config::Protocol::Chatgpt); // DeepSeek Harness 的扩展只有 DeepSeek 官方认。**发给它时一个字节都不改**。 // 不止生成请求:数 token 这样的请求一样带着它的头,也可能带着会话日志 @@ -2088,11 +2111,13 @@ fn prepare( // 参数改写。**只在这里动 body,而且只动被点名的那几个字段** —— // 出站直通说过任何 body 改写都可能是缓存杀手,所以这是 // 一个用户显式要求的例外,不是默认行为。 - let model = effective_set - .model - .as_deref() - .unwrap_or(&reading.facts.model); let out = forward::apply_set(asked.body, effective_set, client_dialect, model); + let history_shape = (generates + && client_dialect == Some(tw_dialect::ir::Dialect::Chat)) + .then(|| tw_dialect::history::shape_chat(&out, history_target.format)) + .flatten(); + let history_changed = history_shape.is_some(); + let out = history_shape.map(Bytes::from).unwrap_or(out); if let (Some(tw_dialect::ir::Dialect::Gemini), Some(m)) = (client_dialect, &effective_set.model) { @@ -2110,12 +2135,17 @@ fn prepare( // DeepSeek Harness 发给别家:去掉只有 DeepSeek 认的扩展。**去掉了什么要说**, // 和转换丢了字段一样记在这一跳上 let mut dropped = Vec::new(); + if history_changed + && history_target.format == tw_dialect::history::HistoryFormat::Disabled + { + dropped.push("messages.reasoning_content".into()); + } let out = match client_dialect .filter(|_| harness && !to_deepseek) .and_then(|d| tw_dialect::harness::clean(d, &out)) { Some(c) => { - dropped = c.dropped; + dropped.extend(c.dropped); Bytes::from(c.body) } None => out, @@ -2136,8 +2166,8 @@ fn prepare( .and_then(|d| crate::egress::strip_body_identity(d, &out)) .unwrap_or(out) }; - reshaped = !dropped.is_empty(); - if let Some(d) = client_dialect.filter(|_| !dropped.is_empty()) { + reshaped = history_changed || !dropped.is_empty(); + if let Some(d) = client_dialect.filter(|_| reshaped) { let same = crate::wire::dialect(d); state.bus.emit(tw_api::Event::Translated { id, @@ -2194,15 +2224,18 @@ fn prepare( } else { None }; - let p = d.encode(&tw_dialect::ir::Target { - dialect, - official: tw_dialect::official::is_official_host(&provider.base_url), - default_max_tokens: crate::translate::default_max_tokens( - &state.pricing.load(), - provider, - &d.request.model, - ), - }); + let p = d.encode_with_history( + &tw_dialect::ir::Target { + dialect, + official: tw_dialect::official::is_official_host(&provider.base_url), + default_max_tokens: crate::translate::default_max_tokens( + &state.pricing.load(), + provider, + &d.request.model, + ), + }, + &history_target, + ); // 请求强制要用的工具发不过去:这一跳不发,换下一家(见 `unsendable_tool`) if let Some(err) = unsendable_tool(&d.request, &p.dropped, &provider.name) { return Err(err); diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index 93116ca7..60df97c2 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -1,7 +1,7 @@ //! 方言互转在管线上的接线。 //! //! **只在客户端格式和上游协议不同、而且调的是生成回答时才醒过来。**同格式那条路 -//! 一个字节都不碰(例外有两个:去掉转换写出去的推理签名,见 +//! 默认不改正文(另外遵从显式的思考历史能力;其余例外有两个:去掉转换写出去的推理签名,见 //! [`tw_dialect::convert::strip_carried`];DeepSeek Harness 发给 DeepSeek 以外的上游时 //! 去掉它的扩展,见 [`tw_dialect::harness`])。转换本身在 `tw-dialect` 里,这里只管 //! 三个接缝: @@ -27,6 +27,71 @@ pub fn dialect_of(p: Protocol) -> Dialect { } } +/// Resolve capabilities independently of the shared Chat API envelope. Exact +/// endpoint defaults are conveniences; relays can override them per model. +pub fn history_target( + provider: &tw_config::Provider, + model: &str, +) -> tw_dialect::history::HistoryTarget { + use tw_config::ReasoningHistory as C; + use tw_dialect::history::{HistoryFormat as F, HistoryTarget}; + let configured = provider + .model_specs + .get(model) + .and_then(|s| s.reasoning_history) + .unwrap_or(provider.reasoning_history); + let format = match configured { + C::ReasoningContent => F::ReasoningContent, + C::Reasoning => F::Reasoning, + C::ContentBlocks => F::ContentBlocks, + C::Disabled => F::Disabled, + C::Auto => match reqwest::Url::parse(&provider.base_url) + .ok() + .and_then(|u| u.host_str().map(str::to_ascii_lowercase)) + .as_deref() + { + Some("api.mistral.ai") => F::ContentBlocks, + Some("api.deepseek.com") => F::ReasoningContent, + Some("api.openai.com") => F::Disabled, + _ => F::Auto, + }, + }; + let mut identity = blake3::Hasher::new(); + let mut add = |value: &str| { + identity.update(&(value.len() as u64).to_le_bytes()); + identity.update(value.as_bytes()); + }; + if let Some(group) = provider + .reasoning_history_group + .as_deref() + .map(str::trim) + .filter(|g| !g.is_empty()) + { + add(group); + } else { + add(&provider.name); + add(&provider.base_url); + // A credential change cannot silently reuse another account's signature. + if let Some(key) = provider.key.as_ref().and_then(|k| k.resolve().ok()) { + add(&key); + } + if let Some(oauth) = &provider.oauth { + add(&oauth.refresh); + } + for header in provider.headers.iter() { + add(&header.name.to_ascii_lowercase()); + if let Ok(value) = header.value.resolve() { + add(&value); + } + } + } + add(model); + HistoryTarget { + format, + origin: Some(identity.finalize().to_hex().to_string()), + } +} + /// 这一跳转成哪种格式。`None` 是直通。 pub fn plan( api: Option, @@ -124,6 +189,48 @@ pub fn default_max_tokens( mod tests { use super::*; + #[test] + fn history_capabilities_are_per_route_and_per_model_not_model_name_guesses() { + use tw_config::ReasoningHistory as C; + use tw_dialect::history::HistoryFormat as F; + let mut provider = tw_config::Provider { + name: "relay".into(), + base_url: "https://api.mistral.ai/v1".into(), + ..Default::default() + }; + assert_eq!( + history_target(&provider, "anything").format, + F::ContentBlocks + ); + provider.base_url = "https://relay.example/api.mistral.ai".into(); + assert_eq!( + history_target(&provider, "mistral-thinking").format, + F::Auto + ); + provider.reasoning_history = C::Disabled; + provider.model_specs.insert( + "custom".into(), + tw_config::ModelSpec { + reasoning_history: Some(C::Reasoning), + ..Default::default() + }, + ); + assert_eq!(history_target(&provider, "custom").format, F::Reasoning); + assert_eq!( + history_target(&provider, "custom-other").format, + F::Disabled + ); + let original = history_target(&provider, "custom").origin; + provider.key = Some("new-account".into()); + assert_ne!(history_target(&provider, "custom").origin, original); + provider.reasoning_history_group = Some("verified-compatible".into()); + let shared = history_target(&provider, "custom").origin; + provider.name = "other".into(); + provider.key = Some("other-account".into()); + assert_eq!(history_target(&provider, "custom").origin, shared); + assert_ne!(history_target(&provider, "custom-other").origin, shared); + } + #[test] fn same_format_and_non_generating_calls_are_passthrough() { let messages = ClientApi::of_path("/v1/messages"); diff --git a/crates/tw-gateway/tests/conversion.rs b/crates/tw-gateway/tests/conversion.rs index 98a2d5a9..13e3c0f0 100644 --- a/crates/tw-gateway/tests/conversion.rs +++ b/crates/tw-gateway/tests/conversion.rs @@ -1156,3 +1156,111 @@ async fn a_tag_with_a_name_the_request_did_not_define_stays_text() { assert_eq!(v["content"][0]["type"], "text"); assert_eq!(v["stop_reason"], "end_turn"); } + +#[tokio::test] +async fn native_reasoning_history_survives_a_real_multiturn_gateway_roundtrip() { + let native = json!([ + {"type":"thinking","thinking":[{"type":"text","text":"check the tool"}],"signature":"opaque-signature","closed":true}, + {"type":"text","text":"checking"} + ]); + let reply = json!({"choices":[{"message":{"content":native,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"f","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}).to_string(); + let (up, seen) = upstream(200, "application/json", reply).await; + let mut p = provider(up, Protocol::OpenaiChat); + p.reasoning_history = tw_config::ReasoningHistory::ContentBlocks; + let (gw, _) = gateway(p.clone(), SecurityMode::Observe).await; + let initial = json!({"model":"custom-model","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"tools":[{"name":"f","input_schema":{"type":"object"}}]}); + let (status, _, reply) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + initial.clone(), + ) + .await; + assert_eq!(status, 200, "{reply}"); + let reply: Value = serde_json::from_str(&reply).unwrap(); + let mut next = initial.clone(); + next["messages"].as_array_mut().unwrap().extend([ + json!({"role":"assistant","content":reply["content"]}), + json!({"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"done"}]}), + ]); + let (status, _, body) = post(gw, "/v1/messages", &[("x-api-key", "tw-k")], next.clone()).await; + assert_eq!(status, 200, "{body}"); + let sent: Value = serde_json::from_slice(&seen.lock().unwrap().body).unwrap(); + assert_eq!(sent["messages"][1]["content"], native); + assert!(sent["messages"][1].get("reasoning_content").is_none()); + assert_eq!(sent["messages"][1]["tool_calls"][0]["id"], "call_1"); + + // Changing credentials must stop a signed replay before an upstream request. + let previous = seen.lock().unwrap().body.clone(); + p.key = Some("another-account".into()); + let (other, _) = gateway(p, SecurityMode::Observe).await; + let (status, _, body) = post(other, "/v1/messages", &[("x-api-key", "tw-k")], next).await; + assert_ne!(status, 200, "{body}"); + assert!(body.contains("incompatible"), "{body}"); + assert_eq!(seen.lock().unwrap().body, previous); +} + +#[tokio::test] +async fn explicit_history_capabilities_also_apply_to_native_chat_requests() { + for format in [ + tw_config::ReasoningHistory::ContentBlocks, + tw_config::ReasoningHistory::Disabled, + ] { + let (up, seen) = upstream( + 200, + "application/json", + r#"{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}"#.into(), + ) + .await; + let mut p = provider(up, Protocol::OpenaiChat); + p.reasoning_history = format; + let (gw, _) = gateway(p, SecurityMode::Observe).await; + let (status,_,body)=post(gw,"/v1/chat/completions",&[("authorization","Bearer tw-k")],json!({"model":"custom-model","custom_field":42,"messages":[{"role":"assistant","content":"answer","reasoning_content":"thought"},{"role":"user","content":"next"}]})).await; + assert_eq!(status, 200, "{body}"); + let sent: Value = serde_json::from_slice(&seen.lock().unwrap().body).unwrap(); + assert_eq!(sent["custom_field"], 42); + assert!(sent["messages"][0].get("reasoning_content").is_none()); + if format == tw_config::ReasoningHistory::ContentBlocks { + assert_eq!( + sent["messages"][0]["content"][0]["thinking"][0]["text"], + "thought" + ); + } else { + assert_eq!(sent["messages"][0]["content"], "answer"); + } + } +} + +#[tokio::test] +async fn native_history_capabilities_keep_reasoning_text_inside_outbound_redaction() { + let secret = format!("ghp_{}", "a".repeat(36)); + for native in [false, true] { + let (up, seen) = upstream( + 200, + "application/json", + json!({"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}).to_string(), + ) + .await; + let mut p = provider(up, Protocol::OpenaiChat); + p.reasoning_history = tw_config::ReasoningHistory::ContentBlocks; + let (gw, _) = gateway(p, SecurityMode::Enforce).await; + let thought = format!("remember {secret}"); + let assistant = if native { + json!({"role":"assistant","content":[{"type":"thinking","thinking":[{"type":"text","text":thought}]},{"type":"text","text":"answer"}]}) + } else { + json!({"role":"assistant","content":"answer","reasoning_content":thought}) + }; + let (status, _, body) = post(gw, "/v1/chat/completions", &[("authorization", "Bearer tw-k")], json!({"model":"m","custom_metadata":secret,"messages":[assistant,{"role":"user","content":"next"}]})).await; + assert_eq!(status, 200, "{body}"); + let sent: Value = serde_json::from_slice(&seen.lock().unwrap().body).unwrap(); + let text = sent["messages"][0]["content"][0]["thinking"][0]["text"] + .as_str() + .unwrap(); + assert!( + !text.contains(&secret), + "reasoning bypassed outbound redaction" + ); + assert!(text.contains("< Date: Wed, 11 Nov 2026 01:09:09 +0800 Subject: [PATCH 2/5] Negotiate reasoning history from verified request rejections --- Cargo.lock | 44 +- Cargo.toml | 2 +- crates/tw-api/msg-codes.txt | 1 + crates/tw-api/src/ep.rs | 3 + crates/tw-api/src/lib.rs | 59 ++- crates/tw-control/src/resources.rs | 95 ++++ crates/tw-control/tests/handover.rs | 2 +- crates/tw-control/tests/model_specs.rs | 86 +++ crates/tw-gateway/src/history_memory.rs | 488 ++++++++++++++++++ crates/tw-gateway/src/lib.rs | 1 + crates/tw-gateway/src/server/pipeline/hop.rs | 122 ++++- crates/tw-gateway/src/state.rs | 4 + crates/tw-gateway/src/translate.rs | 1 + crates/tw-gateway/tests/conversion.rs | 126 +++++ .../tw-gateway/tests/history_negotiation.rs | 236 +++++++++ docs/config.md | 21 + docs/config.zh-CN.md | 15 + release-notes/0.92.0.md | 7 + 18 files changed, 1281 insertions(+), 32 deletions(-) create mode 100644 crates/tw-gateway/src/history_memory.rs create mode 100644 crates/tw-gateway/tests/history_negotiation.rs create mode 100644 release-notes/0.92.0.md diff --git a/Cargo.lock b/Cargo.lock index 7be656f9..da02124b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3763,7 +3763,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.91.0" +version = "0.92.0" dependencies = [ "serde", "serde_json", @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.91.0" +version = "0.92.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3795,7 +3795,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.91.0" +version = "0.92.0" dependencies = [ "serde", "serde_json", @@ -3803,7 +3803,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.91.0" +version = "0.92.0" dependencies = [ "blake3", "libc", @@ -3829,7 +3829,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.91.0" +version = "0.92.0" dependencies = [ "axum", "base64 0.22.1", @@ -3875,7 +3875,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.91.0" +version = "0.92.0" dependencies = [ "memchr", "serde", @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.91.0" +version = "0.92.0" dependencies = [ "chrono", "serde", @@ -3898,7 +3898,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.91.0" +version = "0.92.0" dependencies = [ "arc-swap", "async-stream", @@ -3950,7 +3950,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.91.0" +version = "0.92.0" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3971,7 +3971,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.91.0" +version = "0.92.0" dependencies = [ "libc", "serde", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.91.0" +version = "0.92.0" dependencies = [ "serde", "serde_json", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.91.0" +version = "0.92.0" dependencies = [ "tokio", "tracing", @@ -4007,7 +4007,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.91.0" +version = "0.92.0" dependencies = [ "age", "blake3", @@ -4031,7 +4031,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.91.0" +version = "0.92.0" dependencies = [ "libc", "rand 0.10.2", @@ -4047,7 +4047,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.91.0" +version = "0.92.0" dependencies = [ "arc-swap", "flate2", @@ -4060,14 +4060,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.91.0" +version = "0.92.0" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.91.0" +version = "0.92.0" dependencies = [ "blake3", "bytes", @@ -4087,7 +4087,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.91.0" +version = "0.92.0" dependencies = [ "age", "axum", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.91.0" +version = "0.92.0" dependencies = [ "serde", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.91.0" +version = "0.92.0" dependencies = [ "libc", "notify", @@ -4135,7 +4135,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.91.0" +version = "0.92.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.91.0" +version = "0.92.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 52d6498c..7fe2ea2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.91.0" +version = "0.92.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 5cfa4c6a..9b0f3863 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -332,6 +332,7 @@ gw.content.refused gw.content.refused_invisible_message gw.content.refused_invisible_tool_result gw.convert.failed +gw.convert.reasoning_history_incompatible gw.convert.tool_unsendable gw.convert.tools_unsendable gw.count_tokens.bedrock_upstream diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index dee382fa..be020811 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -142,6 +142,9 @@ endpoints! { ProviderModels: GET "/providers/{name}/models" [name], () => api::ProviderModelsView; /// 手写一家上游的一个模型的上下文窗口、输出上限,优先于价目表;两项都空就删掉。 /// **不在 `/providers/` 底下**:写死的一段会盖住 `/providers/{name}` + ReasoningHistory: GET "/providers/{name}/reasoning-history" [name], () => api::ReasoningHistoryView; + SaveReasoningHistory: PUT "/reasoning-history", api::ReasoningHistorySave => api::ConfigWritten; + ClearReasoningHistory: DELETE "/providers/{name}/reasoning-history/cache" [name], () => api::ReasoningHistoryView; SetModelSpec: PUT "/provider-model-spec", api::ModelSpecSave => api::ConfigWritten; /// 换掉一家上游手动添加的模型(整份清单,空的就是清掉):上游能服务、却没列进清单的 /// 模型,和列出的一样算这家提供。**不在 `/providers/` 底下**,同上 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 1291675e..7a84e746 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1144,7 +1144,12 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 速度,请求记录里照记。新码:`gw.upstream.too_slow`、`config.min_speed_range`(`upstream`、 /// `field`、`value`、`min`、`max`);一键修复修得了它:速度越界删掉 `min_speed`,判定时长越界改回 /// 20。请求库 SCHEMA 不变 -pub const CONTROL_API_VERSION: u32 = 58; +/// +/// **59 起增加思考历史能力查看与覆盖,以及运行时学习缓存的清除接口。** +/// Reasoning-history capability inspection, explicit overrides, and +/// clearing of the runtime-only, 24-hour evidence cache. Existing provider and +/// model editors preserve overrides when they do not edit this setting. +pub const CONTROL_API_VERSION: u32 = 59; /// `/live` 的速度看最近多久(见 [`LiveView::tokens_per_sec`]),毫秒 pub const LIVE_RATE_WINDOW_MS: u64 = 3_000; @@ -3726,6 +3731,58 @@ pub struct ProviderInput { pub balance: Option, } +/// Explicit request-side encoding. Auto uses protocol defaults and verified +/// runtime omissions; a response field never declares request support. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "kebab-case")] +pub enum ReasoningHistory { + Auto, + ReasoningContent, + Reasoning, + ContentBlocks, + Disabled, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum HistoryField { + ReasoningContent, + Reasoning, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct HistoryObservation { + pub model: String, + pub path: String, + pub tools: bool, + pub thinking: bool, + pub omitted: Vec, + pub observed_at_ms: u64, + pub expires_at_ms: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ReasoningHistoryView { + pub provider: String, + pub format: ReasoningHistory, + pub models: std::collections::BTreeMap, + pub observations: Vec, +} + +/// Change only this override. A model's Auto inherits the upstream setting. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ReasoningHistorySave { + pub provider: String, + pub model: Option, + pub format: ReasoningHistory, + pub base_version: Option, +} + /// 一家上游的最低生成速度(配置的 `providers[].min_speed`)。 /// /// 流式回答从第一个 token 起,每秒看一次最近 `window_secs` 秒的平均生成速度(和 diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 0e08316f..72291709 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -35,6 +35,9 @@ pub fn router() -> axum::Router { .at(ep::UpdateProvider, update_provider) .at(ep::DeleteProvider, delete_provider) .at(ep::ProviderModels, provider_models) + .at(ep::ReasoningHistory, reasoning_history) + .at(ep::SaveReasoningHistory, save_reasoning_history) + .at(ep::ClearReasoningHistory, clear_reasoning_history) .at(ep::SetModelSpec, set_model_spec) .at(ep::SetManualModels, set_manual_models) .at(ep::RefreshProviderModels, refresh_models) @@ -383,6 +386,98 @@ async fn provider_models( Ok(Json(models_view(&s, p, s.gateway.models.listing(p)))) } +fn history_format(f: tw_config::ReasoningHistory) -> tw_api::ReasoningHistory { + // Both public enums use the same stable wire spellings. + serde_json::from_value(serde_json::to_value(f).expect("history format")) + .expect("history format") +} + +async fn reasoning_history( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let rt = s.gateway.runtime(); + let p = rt + .config + .providers + .iter() + .find(|p| p.name == name) + .ok_or_else(|| crate::no_such_upstream(&name))?; + Ok(Json(tw_api::ReasoningHistoryView { + provider: name.clone(), + format: history_format(p.reasoning_history), + models: p + .model_specs + .iter() + .filter_map(|(m, s)| s.reasoning_history.map(|f| (m.clone(), history_format(f)))) + .collect(), + observations: rt + .history_memory + .view(&name, tw_gateway::history_memory::now_ms()), + })) +} + +async fn clear_reasoning_history( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let rt = s.gateway.runtime(); + if !rt.config.providers.iter().any(|p| p.name == name) { + return Err(crate::no_such_upstream(&name)); + } + rt.history_memory.clear(&name); + reasoning_history(State(s), Path(name)).await +} + +async fn save_reasoning_history( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + use tw_api::ReasoningHistory as A; + use tw_config::ReasoningHistory as C; + let format = match req.format { + A::Auto => C::Auto, + A::ReasoningContent => C::ReasoningContent, + A::Reasoning => C::Reasoning, + A::ContentBlocks => C::ContentBlocks, + A::Disabled => C::Disabled, + }; + let version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { + let p = cfg + .providers + .iter() + .find(|p| p.name == req.provider) + .ok_or_else(|| not_found("upstream", &req.provider))?; + if let Some(model) = &req.model { + let mut spec = p.model_specs.get(model).cloned().unwrap_or_default(); + spec.reasoning_history = + (format != tw_config::ReasoningHistory::Auto).then_some(format); + tw_config::check_model_spec(&req.provider, model, Some(&spec)) + .map_err(|e| invalid(e.msg()))?; + Ok(edit::set_model_spec( + text, + &req.provider, + model, + (!spec.is_empty()).then_some(&spec), + )?) + } else { + let mut p = p.clone(); + p.reasoning_history = format; + Ok(edit::upsert( + text, + edit::PROVIDERS, + Some(&req.provider), + &mapping(&p)?, + )?) + } + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + /// 马上向上游重新获取模型清单。 async fn refresh_models( State(s): State, diff --git a/crates/tw-control/tests/handover.rs b/crates/tw-control/tests/handover.rs index a0e71a58..20dec39d 100644 --- a/crates/tw-control/tests/handover.rs +++ b/crates/tw-control/tests/handover.rs @@ -146,7 +146,7 @@ async fn status_reports_the_handover_phase_and_the_draining_count() { let st = status(&s).await; assert_eq!(st.handover, tw_api::HandoverState::Draining); assert_eq!(st.draining, 3); - assert_eq!(st.api_version, 58); + assert_eq!(st.api_version, tw_api::CONTROL_API_VERSION); } /// arm 之后(以及接替者正在接管时)不开始新的账号登录:回调端口不交接。(平常、排空中的 diff --git a/crates/tw-control/tests/model_specs.rs b/crates/tw-control/tests/model_specs.rs index 92b34f4c..0a719576 100644 --- a/crates/tw-control/tests/model_specs.rs +++ b/crates/tw-control/tests/model_specs.rs @@ -396,3 +396,89 @@ async fn editing_public_specs_and_provider_forms_preserves_history_capabilities( Some(tw_config::ReasoningHistory::Reasoning) ); } + +#[tokio::test] +async fn history_overrides_are_versioned_preserve_specs_and_can_be_cleared() { + let b = bed(&config( + upstream().await, + " reasoning_history: content-blocks\n model_specs:\n m: { context_window: 32000, reasoning: true }\n", + "", + )); + let path = "/providers/relay/reasoning-history"; + let (st, view) = call(&b.app, "GET", path, Value::Null).await; + assert_eq!(st, StatusCode::OK, "{view}"); + assert_eq!(view["format"], "content-blocks"); + assert_eq!(view["observations"], json!([])); + let save = + |format: &str| json!({"provider":"relay","model":"m","format":format,"base_version":null}); + let (st, _) = call( + &b.app, + "PUT", + "/reasoning-history", + save("reasoning-content"), + ) + .await; + assert_eq!(st, StatusCode::OK); + let parsed = tw_config::try_parse(&b.file()).unwrap(); + let p = &parsed.providers[0]; + assert_eq!( + p.reasoning_history, + tw_config::ReasoningHistory::ContentBlocks + ); + assert_eq!(p.model_specs["m"].context_window, Some(32000)); + assert_eq!(p.model_specs["m"].reasoning, Some(true)); + assert_eq!( + p.model_specs["m"].reasoning_history, + Some(tw_config::ReasoningHistory::ReasoningContent) + ); + // An older/public model editor must retain the advanced override. + let (st, _) = call(&b.app,"PUT","/provider-model-spec",json!({"provider":"relay","model":"m","context_window":64000,"max_output_tokens":null,"reasoning":true,"image_input":null})).await; + assert_eq!(st, StatusCode::OK); + assert_eq!( + tw_config::try_parse(&b.file()).unwrap().providers[0].model_specs["m"].reasoning_history, + Some(tw_config::ReasoningHistory::ReasoningContent) + ); + let (st, _) = call(&b.app, "PUT", "/reasoning-history", save("auto")).await; + assert_eq!(st, StatusCode::OK); + let parsed = tw_config::try_parse(&b.file()).unwrap(); + assert_eq!( + parsed.providers[0].model_specs["m"].context_window, + Some(64000) + ); + assert!( + parsed.providers[0].model_specs["m"] + .reasoning_history + .is_none() + ); + let before = b.file(); + let (st, _) = call( + &b.app, + "DELETE", + "/providers/relay/reasoning-history/cache", + Value::Null, + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!( + b.file(), + before, + "clearing runtime observations must not rewrite configuration" + ); + let (st, _) = call( + &b.app, + "PUT", + "/reasoning-history", + json!({"provider":"relay","model":null,"format":"disabled","base_version":"stale"}), + ) + .await; + assert_eq!(st, StatusCode::CONFLICT); + assert_eq!(b.file(), before); + let (st, _) = call( + &b.app, + "GET", + "/providers/missing/reasoning-history", + Value::Null, + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND); +} diff --git a/crates/tw-gateway/src/history_memory.rs b/crates/tw-gateway/src/history_memory.rs new file mode 100644 index 00000000..2644d080 --- /dev/null +++ b/crates/tw-gateway/src/history_memory.rs @@ -0,0 +1,488 @@ +//! Evidence-based Chat history adaptation. A rejected field is not evidence for +//! another encoding. Keep the original request and omit only the proven extra +//! field on a separately encoded attempt; remember it only after acceptance. + +use std::collections::HashMap; +use std::sync::Mutex; + +use serde_json::Value; +use tw_api::{HistoryField, HistoryObservation}; +use tw_dialect::ir::{Part, Request, Vendor}; + +const TTL_MS: u64 = 24 * 60 * 60 * 1000; +const MAX: usize = 1024; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Key { + provider: String, + model: String, + path: String, + identity: String, + mode: String, + tools: bool, + thinking: bool, +} + +impl Key { + pub fn of(p: &tw_config::Provider, model: &str, path: &str, body: &[u8]) -> Option { + let v: Value = serde_json::from_slice(body).ok()?; + let mode = serde_json::json!({ + "tools": v.get("tools"), "tool_choice": v.get("tool_choice"), + "thinking": v.get("thinking"), "reasoning": v.get("reasoning"), + "reasoning_effort": v.get("reasoning_effort"), + }); + // Runtime-local entries already expire on reload. Also isolate resolved + // credentials/headers in case an environment-backed value changes. + let mut identity = p.clone(); + identity.reasoning_history_group = None; + Some(Self { + provider: p.name.clone(), + model: model.into(), + path: path.into(), + identity: crate::translate::history_target(&identity, model).origin?, + mode: blake3::hash(mode.to_string().as_bytes()) + .to_hex() + .to_string(), + tools: v + .get("tools") + .and_then(Value::as_array) + .is_some_and(|a| !a.is_empty()) + || v.get("messages") + .and_then(Value::as_array) + .is_some_and(|messages| { + messages.iter().any(|m| { + m.get("tool_calls").is_some() + || m.get("role").and_then(Value::as_str) == Some("tool") + }) + }), + thinking: v.get("thinking").is_some() + || v.get("reasoning").is_some() + || v.get("reasoning_effort").is_some(), + }) + } +} + +#[derive(Clone)] +struct Entry { + fields: Vec, + at_ms: u64, +} +#[derive(Default)] +struct Inner { + entries: HashMap, + epochs: HashMap, +} +#[derive(Default)] +pub struct Cache { + inner: Mutex, +} + +#[derive(Clone)] +pub struct Policy { + pub fields: Vec, + epoch: u64, +} + +impl Cache { + pub fn policy(&self, key: &Key, now: u64) -> Policy { + let mut inner = self.inner.lock().unwrap(); + inner + .entries + .retain(|_, e| now.saturating_sub(e.at_ms) < TTL_MS); + Policy { + fields: inner + .entries + .get(key) + .map(|e| e.fields.clone()) + .unwrap_or_default(), + epoch: *inner.epochs.get(&key.provider).unwrap_or(&0), + } + } + + pub fn accepted(&self, key: Key, policy: Policy, now: u64) { + let mut inner = self.inner.lock().unwrap(); + // Clearing from the UI also cancels learning by requests in flight. + if *inner.epochs.get(&key.provider).unwrap_or(&0) != policy.epoch + || policy.fields.is_empty() + { + return; + } + if inner.entries.len() >= MAX + && !inner.entries.contains_key(&key) + && let Some(oldest) = inner + .entries + .iter() + .min_by_key(|(_, e)| e.at_ms) + .map(|(k, _)| k.clone()) + { + inner.entries.remove(&oldest); + } + inner.entries.insert( + key, + Entry { + fields: policy.fields, + at_ms: now, + }, + ); + } + + pub fn clear(&self, provider: &str) { + let mut inner = self.inner.lock().unwrap(); + inner.entries.retain(|k, _| k.provider != provider); + let epoch = inner.epochs.entry(provider.to_owned()).or_default(); + *epoch = epoch.wrapping_add(1); + } + + pub fn view(&self, provider: &str, now: u64) -> Vec { + let mut inner = self.inner.lock().unwrap(); + inner + .entries + .retain(|_, e| now.saturating_sub(e.at_ms) < TTL_MS); + let mut rows: Vec<_> = inner + .entries + .iter() + .filter(|(k, _)| k.provider == provider) + .map(|(k, e)| HistoryObservation { + model: k.model.clone(), + path: k.path.clone(), + tools: k.tools, + thinking: k.thinking, + omitted: e.fields.clone(), + observed_at_ms: e.at_ms, + expires_at_ms: e.at_ms + TTL_MS, + }) + .collect(); + rows.sort_by(|a, b| { + (&a.model, &a.path, a.tools, a.thinking, a.observed_at_ms).cmp(&( + &b.model, + &b.path, + b.tools, + b.thinking, + b.observed_at_ms, + )) + }); + rows + } +} + +pub fn automatic(p: &tw_config::Provider, model: &str) -> bool { + use tw_config::ReasoningHistory as H; + p.model_specs + .get(model) + .and_then(|s| s.reasoning_history) + .filter(|f| *f != H::Auto) + .unwrap_or(p.reasoning_history) + == H::Auto +} + +pub fn unsigned(request: &Request) -> bool { + request.messages.iter().flat_map(|m| &m.parts).all(|part| { + let Part::Thinking(t) = part else { + return true; + }; + t.signature.as_ref().is_none_or(|s| { + if s.vendor == Vendor::Chat { + tw_dialect::history::ChatHistory::read(s).is_some_and(|h| !h.opaque()) + } else { + s.value.is_empty() + } + }) + }) +} + +fn field(name: &str) -> Option { + match name { + "reasoning_content" => Some(HistoryField::ReasoningContent), + "reasoning" => Some(HistoryField::Reasoning), + _ => None, + } +} + +fn location(v: &Value) -> Option<(usize, HistoryField)> { + let loc = v.as_array()?; + let loc = if loc.first()?.as_str() == Some("body") { + &loc[1..] + } else { + loc.as_slice() + }; + if loc.first()?.as_str() != Some("messages") || !loc.get(1)?.is_u64() { + return None; + } + let index = usize::try_from(loc[1].as_u64()?).ok()?; + let field = match &loc[2..] { + [name] => field(name.as_str()?), + [role, name] if role.as_str() == Some("assistant") => field(name.as_str()?), + _ => None, + }?; + Some((index, field)) +} + +/// Only known machine-readable request validation schemas, never prose, SSE +/// errors, generic 422s, nested tool arguments, or a model's answer text. +pub fn refusal(status: u16, body: &[u8], sent: &[u8]) -> Option> { + if !matches!(status, 400 | 422) || body.len() > 64 * 1024 { + return None; + } + let v: Value = serde_json::from_slice(body).ok()?; + let errors = v + .get("detail") + .or_else(|| v.get("error").and_then(|e| e.get("detail"))) + .and_then(Value::as_array)?; + if errors.is_empty() || errors.len() > 32 { + return None; + } + let request: Value = serde_json::from_slice(sent).ok()?; + let messages = request.get("messages")?.as_array()?; + let mut fields = Vec::new(); + for e in errors { + if e.get("type").and_then(Value::as_str) != Some("extra_forbidden") { + return None; + } + let (index, f) = location(e.get("loc")?)?; + let message = messages.get(index)?; + if message.get("role").and_then(Value::as_str) != Some("assistant") { + return None; + } + let name = match f { + HistoryField::ReasoningContent => "reasoning_content", + HistoryField::Reasoning => "reasoning", + }; + if message.get(name).is_none() { + return None; + } + if !fields.contains(&f) { + fields.push(f); + } + } + Some(fields) +} + +/// Remove only explicitly rejected, unsigned assistant fields. Other history, +/// tool call IDs, results and extension fields retain their original values. +pub fn omit(body: &[u8], fields: &[HistoryField]) -> Option> { + if fields.is_empty() { + return None; + } + let mut v: Value = serde_json::from_slice(body).ok()?; + let messages = v.get_mut("messages")?.as_array_mut()?; + // Native signed blocks may not have been represented by the decoder. + if messages.iter().any(|m| { + m.get("content").and_then(Value::as_array).is_some_and(|a| { + a.iter().any(|b| { + b.get("signature") + .and_then(Value::as_str) + .is_some_and(|s| !s.is_empty()) + || b.get("type").and_then(Value::as_str) == Some("redacted_thinking") + }) + }) + }) { + return None; + } + if messages + .iter() + .filter(|m| m.get("role").and_then(Value::as_str) == Some("assistant")) + .any(|m| { + fields.iter().any(|f| { + let key = match f { + HistoryField::ReasoningContent => "reasoning_content", + HistoryField::Reasoning => "reasoning", + }; + m.get(key).is_some_and(|v| !v.is_string() && !v.is_null()) + }) + }) + { + return None; + } + let mut changed = false; + messages.retain_mut(|m| { + if m.get("role").and_then(Value::as_str) != Some("assistant") { + return true; + } + let Some(object) = m.as_object_mut() else { + return true; + }; + let mut removed = false; + for f in fields { + let key = match f { + HistoryField::ReasoningContent => "reasoning_content", + HistoryField::Reasoning => "reasoning", + }; + removed |= object.remove(key).is_some(); + } + changed |= removed; + !removed + || object.get("content").is_some_and(|c| match c { + Value::Null => false, + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + _ => true, + }) + || object + .get("tool_calls") + .and_then(Value::as_array) + .is_some_and(|a| !a.is_empty()) + || object + .keys() + .any(|k| !matches!(k.as_str(), "role" | "content" | "tool_calls")) + }); + changed.then(|| serde_json::to_vec(&v).expect("JSON history")) +} + +pub fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn only_precise_request_validation_is_evidence() { + let wire = json!({"messages": (0..4).map(|_| json!({"role":"assistant","reasoning_content":"thought","reasoning":"other"})).collect::>()}).to_string(); + let refusal = |status, body: &[u8]| super::refusal(status, body, wire.as_bytes()); + let error = |loc: Value, kind: &str| { + json!({"detail":[{"type":kind,"loc":loc,"msg":"arbitrary prose"}]}).to_string() + }; + let exact = error( + json!(["body", "messages", 3, "assistant", "reasoning_content"]), + "extra_forbidden", + ); + assert_eq!( + refusal(422, exact.as_bytes()), + Some(vec![HistoryField::ReasoningContent]) + ); + assert_eq!( + refusal(400, exact.as_bytes()), + Some(vec![HistoryField::ReasoningContent]) + ); + let wrong_role = wire.replace("assistant", "user"); + assert!(super::refusal(422, exact.as_bytes(), wrong_role.as_bytes()).is_none()); + let missing_index = json!({"messages":[]}).to_string(); + assert!(super::refusal(422, exact.as_bytes(), missing_index.as_bytes()).is_none()); + for status in [200, 401, 403, 429, 500] { + assert!(refusal(status, exact.as_bytes()).is_none()); + } + for loc in [ + json!(["body", "tools", 0, "reasoning_content"]), + json!(["body", "messages", 0, "tool_calls", 0, "reasoning_content"]), + json!(["body", "messages", 0, "user", "reasoning_content"]), + json!(["body", "messages", 0, "assistant", "max_tokens"]), + ] { + assert!(refusal(422, error(loc, "extra_forbidden").as_bytes()).is_none()); + } + assert!( + refusal( + 422, + error( + json!(["body", "messages", 0, "reasoning_content"]), + "missing" + ) + .as_bytes() + ) + .is_none() + ); + assert!( + refusal( + 422, + br#"{"error":{"message":"reasoning_content unsupported"}}"# + ) + .is_none() + ); + let mixed = json!({"detail":[{"type":"extra_forbidden","loc":["messages",0,"reasoning"]},{"type":"missing","loc":["model"]}]}).to_string(); + assert!(refusal(422, mixed.as_bytes()).is_none()); + } + + #[test] + fn omission_keeps_tools_alternate_fields_and_signed_history() { + let body = json!({"model":"m","unknown":42,"messages":[ + {"role":"assistant","content":null,"reasoning_content":"secret","reasoning":"keep","tool_calls":[{"id":"t1","type":"function","function":{"name":"f","arguments":"{}"}}]}, + {"role":"tool","tool_call_id":"t1","content":"result"}, + {"role":"user","content":"next","reasoning_content":"user extension"} + ]}); + let stripped: Value = serde_json::from_slice( + &omit( + &serde_json::to_vec(&body).unwrap(), + &[HistoryField::ReasoningContent], + ) + .unwrap(), + ) + .unwrap(); + assert!(stripped["messages"][0].get("reasoning_content").is_none()); + assert_eq!(stripped["messages"][0]["reasoning"], "keep"); + assert_eq!( + stripped["messages"][0]["tool_calls"], + body["messages"][0]["tool_calls"] + ); + assert_eq!(stripped["messages"][1], body["messages"][1]); + assert_eq!(stripped["messages"][2], body["messages"][2]); + assert_eq!(stripped["unknown"], 42); + let signed = json!({"messages":[{"role":"assistant","reasoning_content":"thought","content":[{"type":"thinking","signature":"opaque","thinking":[]}]}]}); + assert!( + omit( + signed.to_string().as_bytes(), + &[HistoryField::ReasoningContent] + ) + .is_none() + ); + } + + #[test] + fn bounded_expiring_cache_is_isolated_and_clear_cancels_inflight_learning() { + let p = tw_config::Provider { + name: "relay".into(), + base_url: "https://unknown.example/v1".into(), + ..Default::default() + }; + let key = Key::of(&p, "m", "/v1/chat/completions", br#"{}"#).unwrap(); + let cache = Cache::default(); + let mut pending = cache.policy(&key, 1); + pending.fields.push(HistoryField::ReasoningContent); + assert!(cache.view("relay", 1).is_empty()); + cache.accepted(key.clone(), pending.clone(), 2); + assert_eq!(cache.policy(&key, 3).fields, pending.fields); + for different in [ + Key::of(&p, "other", "/v1/chat/completions", br#"{}"#).unwrap(), + Key::of(&p, "m", "/chat/completions", br#"{}"#).unwrap(), + Key::of( + &p, + "m", + "/v1/chat/completions", + br#"{"tools":[{"type":"function"}]}"#, + ) + .unwrap(), + Key::of( + &p, + "m", + "/v1/chat/completions", + br#"{"reasoning_effort":"high"}"#, + ) + .unwrap(), + ] { + assert!(cache.policy(&different, 3).fields.is_empty()); + } + let mut other_p = p.clone(); + other_p.key = Some("new-account".into()); + assert_ne!( + key, + Key::of(&other_p, "m", "/v1/chat/completions", br#"{}"#).unwrap() + ); + cache.clear("relay"); + cache.accepted(key.clone(), pending, 4); + assert!(cache.view("relay", 4).is_empty()); + let mut pending = cache.policy(&key, 5); + pending.fields.push(HistoryField::Reasoning); + cache.accepted(key.clone(), pending, 5); + assert!(cache.policy(&key, 5 + TTL_MS).fields.is_empty()); + for i in 0..MAX + 1 { + let key = Key::of(&p, &format!("m{i}"), "/v1/chat/completions", br#"{}"#).unwrap(); + let mut policy = cache.policy(&key, 10); + policy.fields.push(HistoryField::Reasoning); + cache.accepted(key, policy, 10 + i as u64); + } + assert_eq!(cache.view("relay", MAX as u64 + 10).len(), MAX); + } +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 9e2c643f..47db7d00 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -34,6 +34,7 @@ pub mod guard; pub mod handover; pub mod health; pub mod hint; +pub mod history_memory; pub mod inflate; pub mod key_limits; pub mod l1; diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 75d24a96..a155fae9 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -195,6 +195,11 @@ pub(super) async fn try_upstreams<'a>( // 退避重试的账(见 `crate::retry`):最后一个失败是不是暂时的错、这一轮里暂时出错的是哪几家、 // 重试过的那几轮 let mut retries = Retries::default(); + // One request-schema repair across fields, providers and backoff rounds. + // OAuth refresh remains separate: it never changes request semantics. + let mut repair_used = false; + let mut history_trial: Option<(crate::history_memory::Key, crate::history_memory::Policy)> = + None; // 客户端收的是 SSE 流:压着开头过了时限先交响应头、发保活(见 `super::commit`)。最后一家的 // 开头只在这时为重试压着 let early = super::commit::early(state, req, reading).is_some(); @@ -622,7 +627,7 @@ pub(super) async fn try_upstreams<'a>( _ => None, }; // `hop_effort`:这一跳的推理强度改了什么(见 `adjust_effort`) - let (out, mut hop_effort) = match super::heavy(asked.body, || { + let (mut out, mut hop_effort) = match super::heavy(asked.body, || { prepare(state, req, reading, &asked, provider, &effective_set, id).map(|mut out| { let effort = adjust_effort( state, @@ -653,6 +658,48 @@ pub(super) async fn try_upstreams<'a>( } }; + // Capabilities apply to the actual routed model/API/mode. Re-encode + // from Asked on every attempt, then redact this exact outbound body. + let history_safe = reading.generates && !counting + && wire(req, &out) == Some(tw_dialect::ir::Dialect::Chat) + && crate::history_memory::automatic(provider, &sent_model) + // This protocol profile requires reasoning during thinking/tool replay. + && crate::translate::history_target(provider, &sent_model).format != tw_dialect::history::HistoryFormat::ReasoningContent + && asked.decoded.is_some_and(|d| d.as_ref().is_ok_and(|d| crate::history_memory::unsigned(&d.request))); + let history_key = history_safe + .then(|| crate::history_memory::Key::of(provider, &sent_model, &out.path, &out.body)) + .flatten(); + let history_policy = history_key.as_ref().map(|key| { + history_trial + .as_ref() + .filter(|(k, _)| k == key) + .map(|(_, p)| p.clone()) + .unwrap_or_else(|| rt.history_memory.policy(key, now_ms())) + }); + if let Some(policy) = &history_policy + && let Some(body) = crate::history_memory::omit(&out.body, &policy.fields) + { + out.body = Bytes::from(body); + out.reshaped = true; + state.bus.emit(tw_api::Event::Translated { + id, + provider: provider.name.clone(), + from: crate::wire::dialect(tw_dialect::ir::Dialect::Chat), + to: crate::wire::dialect(tw_dialect::ir::Dialect::Chat), + dropped: policy + .fields + .iter() + .map(|f| match f { + tw_api::HistoryField::ReasoningContent => { + "messages.reasoning_content".into() + } + tw_api::HistoryField::Reasoning => "messages.reasoning".into(), + }) + .collect(), + at_ms: now_ms(), + }); + } + // 出站脱敏的拦截档:换掉**这一跳真正发出去的那一份**(可能转换过 // 格式)。规则是全局的,每一跳换掉的是同一批东西;**接着原文那本账换**, // 同一个值在每一跳、在存下来的那份请求里都是同一个占位符。插件改过的一跳接着 @@ -820,8 +867,16 @@ pub(super) async fn try_upstreams<'a>( conversation: started.conversation.as_deref(), tap: &tap, }; - let (r, uncached) = - resend_uncached(state, req, provider, http, resend, r).await?; + let (r, uncached) = resend_uncached( + state, + req, + provider, + http, + resend, + r, + &mut repair_used, + ) + .await?; let resend = Resend { out: &out, body: uncached.as_ref().unwrap_or(&body), @@ -830,7 +885,8 @@ pub(super) async fn try_upstreams<'a>( conversation: started.conversation.as_deref(), tap: &tap, }; - resend_unsealed(state, req, provider, http, resend, r).await + resend_unsealed(state, req, provider, http, resend, r, &mut repair_used) + .await } Err(e) => Err(e), } @@ -918,11 +974,47 @@ pub(super) async fn try_upstreams<'a>( if !matches!(verdict, Verdict::Failed(Cause::RateLimited { .. })) { to_throttle(state, &provider.name, sent_at, verdict); } + if !repair_used && tokio::time::Instant::now() < until + && let (Some(key), Some(mut policy)) = (history_key.clone(), history_policy.clone()) + && let Some(fields) = crate::history_memory::refusal(status, &head, &body) + // Every reported field must actually be present. Do not + // "repair" a stale error or infer an alternate encoding. + && fields.iter().all(|f| crate::history_memory::omit(&body, &[*f]).is_some()) + { + for field in fields { + if !policy.fields.contains(&field) { + policy.fields.push(field); + } + } + repair_used = true; + history_trial = Some((key, policy)); + tap.said(&head); + state.note_proxy_ok(&provider.proxy); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_success(&provider.name), + ); + chain.push(hop( + &provider.name, + model.clone(), + tw_api::AttemptOutcome::Status, + status, + hop_started, + )); + // Reuse the slot, but create a real new attempt with normal + // usage accounting, plugins, conversion and redaction. + effort_hold = Some((name, slot, probe.take())); + queue.push_front(name); + continue; + } // 上游因为推理强度拒了它(见 `crate::effort_memory`):这一跳是一跳普通的 400,同一家 // 改一档(或者去掉强度)马上再发一次,是尝试链上新的一跳,接着用这一跳占着的位置。 // **一家只重发一次**,再被拒照常交给客户端。上游好好的,不算失败。记着的改法自己 // 被拒了:那一条删掉 if status == 400 + && !repair_used && reading.generates && !counting && !effort_resent.contains(&name) @@ -953,6 +1045,7 @@ pub(super) async fn try_upstreams<'a>( status, hop_started, )); + repair_used = true; effort_resent.push(name); effort_resend = Some((name, pre, fix)); effort_hold = Some((name, slot, probe.take())); @@ -1113,7 +1206,9 @@ pub(super) async fn try_upstreams<'a>( // 吞掉;等不起的没有下一家可换、也不能再试。不压的由回程按无响应超时收尾(见 `relay`) let hold = hold_of(req, reading, provider, &out, &r); let held = hold.as_ref().is_some_and(|h| { - !last + history_key.as_ref().is_some_and(|k| { + history_trial.as_ref().is_some_and(|(trial, _)| trial == k) + }) || !last || (matches!(h, Hold::Stream(..)) && tokio::time::Instant::now() < until && (early || state.throttles.wary(&provider.name))) @@ -1340,6 +1435,15 @@ pub(super) async fn try_upstreams<'a>( crate::effort_memory::now_secs(), ); } + if answered + && !unconfirmed + && let Some(key) = &history_key + && let Some((trial, policy)) = &history_trial + && trial == key + { + rt.history_memory + .accepted(key.clone(), policy.clone(), now_ms()); + } chain.push(hop( &provider.name, model.clone(), @@ -2520,12 +2624,13 @@ async fn resend_uncached( http: &reqwest::Client, resend: Resend<'_>, r: reqwest::Response, + repair_used: &mut bool, ) -> Result<(reqwest::Response, Option), SendError> { let (Some(model), Some(wire)) = (resend.out.auto_cache.as_deref(), wire(req, resend.out)) else { return Ok((r, None)); }; - if r.status() != 400 { + if *repair_used || r.status() != 400 { return Ok((r, None)); } let Some(stripped) = tw_dialect::cache::strip_marks(wire, resend.body) else { @@ -2543,6 +2648,7 @@ async fn resend_uncached( state .cache_marks .note(&provider.name, model, crate::server::now_ms()); + *repair_used = true; tracing::info!( provider = %provider.name, model = %model, @@ -2576,11 +2682,12 @@ async fn resend_unsealed( http: &reqwest::Client, resend: Resend<'_>, r: reqwest::Response, + repair_used: &mut bool, ) -> Result { let Some(wire) = wire(req, resend.out) else { return Ok(r); }; - if r.status() != 400 { + if *repair_used || r.status() != 400 { return Ok(r); } let Some((stripped, removed)) = crate::seal::strip(wire, resend.body, None) else { @@ -2600,6 +2707,7 @@ async fn resend_unsealed( .seals .note(c, &provider.name, &removed, crate::server::now_ms()); } + *repair_used = true; tracing::info!( provider = %provider.name, removed = removed.len(), diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index dd0f8de4..54267c62 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -38,6 +38,8 @@ pub struct Runtime { /// **和配置一起建、一起换**,而不是每个请求现编一次 —— 自定义规则是 /// 正则,摆在数据面上现编就是每个请求白付一次编译。 pub redact: Arc, + /// Verified request-side omissions; replaced on configuration reload. + pub history_memory: Arc, /// 出站脱敏的扫描缓存:对话历史里没变的消息不再扫(见 [`tw_guard::redact::cache`])。 /// **跟着规则一起换**:重载配置换上一份空的,旧规则下扫出来的结果不会留到新规则下 pub scan_cache: Arc, @@ -124,6 +126,7 @@ impl Runtime { clients, allow, redact: Arc::new(redact), + history_memory: Arc::new(crate::history_memory::Cache::default()), scan_cache: Arc::new(tw_guard::redact::cache::ScanCache::new()), tools: Arc::new(tools), content: Arc::new(content), @@ -142,6 +145,7 @@ impl Runtime { redact: self.redact.clone(), // 规则没变,扫过的照样作数 scan_cache: self.scan_cache.clone(), + history_memory: self.history_memory.clone(), tools: self.tools.clone(), content: self.content.clone(), answer: self.answer.clone(), diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index 60df97c2..1903aacc 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -39,6 +39,7 @@ pub fn history_target( .model_specs .get(model) .and_then(|s| s.reasoning_history) + .filter(|f| *f != C::Auto) .unwrap_or(provider.reasoning_history); let format = match configured { C::ReasoningContent => F::ReasoningContent, diff --git a/crates/tw-gateway/tests/conversion.rs b/crates/tw-gateway/tests/conversion.rs index 13e3c0f0..698548f2 100644 --- a/crates/tw-gateway/tests/conversion.rs +++ b/crates/tw-gateway/tests/conversion.rs @@ -1264,3 +1264,129 @@ async fn native_history_capabilities_keep_reasoning_text_inside_outbound_redacti assert_eq!(sent["custom_metadata"], secret); } } + +/// Unknown Chat-compatible endpoints learn from schema errors without a host +/// allowlist. The second logical request uses the verified omission immediately. +#[tokio::test] +async fn history_negotiation_is_bounded_scoped_and_redacted_on_every_attempt() { + let seen = Arc::new(Mutex::new(Vec::::new())); + let app = Router::new().fallback({ + let seen = seen.clone(); + move |body: bytes::Bytes| { + let seen = seen.clone(); + async move { + let v: Value = serde_json::from_slice(&body).unwrap(); + seen.lock().unwrap().push(v.clone()); + let rejected = v["messages"].as_array().unwrap().iter().position(|m| m.get("reasoning_content").is_some()); + let (status, reply) = if let Some(i) = rejected { + (422, json!({"detail":[{"type":"extra_forbidden","loc":["body","messages",i,"assistant","reasoning_content"],"msg":"Extra inputs are not permitted"}]})) + } else { + (200, json!({"id":"r","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"ok","reasoning_content":"thought"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2}})) + }; + axum::response::Response::builder().status(status).header("content-type","application/json").body(axum::body::Body::from(reply.to_string())).unwrap() + } + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let up = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut cfg = Config { + version: 1, + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![provider(up, Protocol::OpenaiChat)], + ..Default::default() + }; + cfg.security.redact.mode = SecurityMode::Enforce; + let state = tw_gateway::AppState::new(cfg.clone()).unwrap(); + let gw = tw_gateway::serve(state.clone(), ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + let auth = [("authorization", "Bearer tw-k")]; + let (status, _, first) = post( + gw, + "/v1/chat/completions", + &auth, + json!({"model":"m","messages":[{"role":"user","content":"first"}]}), + ) + .await; + assert_eq!(status, 200); + let first: Value = serde_json::from_str(&first).unwrap(); + let thought = first["choices"][0]["message"]["reasoning_content"].clone(); + let secret = format!("ghp_{}", "b".repeat(36)); + let request = json!({"model":"m","unknown":42,"messages":[ + {"role":"assistant","content":format!("contact {secret}"),"reasoning_content":thought,"tool_calls":[{"id":"t1","type":"function","function":{"name":"lookup","arguments":"{}"}}]}, + {"role":"tool","tool_call_id":"t1","content":format!("found {secret}")}, + {"role":"user","content":"next"} + ]}); + for expected in [3, 4] { + let (status, _, body) = post(gw, "/v1/chat/completions", &auth, request.clone()).await; + assert_eq!(status, 200, "{body}"); + assert_eq!(seen.lock().unwrap().len(), expected); + } + { + let seen = seen.lock().unwrap(); + assert_eq!(seen[1]["messages"][0]["reasoning_content"], thought); + for sent in seen.iter().skip(1) { + assert_eq!(sent["unknown"], 42); + assert_eq!(sent["messages"][0]["tool_calls"][0]["id"], "t1"); + assert_eq!(sent["messages"][1]["tool_call_id"], "t1"); + assert!(!sent.to_string().contains(&secret)); + } + assert!(seen[2]["messages"][0].get("reasoning_content").is_none()); + } + assert_eq!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .len(), + 1 + ); + state.runtime().history_memory.clear("up"); + assert_eq!( + post(gw, "/v1/chat/completions", &auth, request.clone()) + .await + .0, + 200 + ); + assert_eq!( + seen.lock().unwrap().len(), + 6, + "clear must force fresh evidence" + ); + // Explicit policy takes precedence and does not get silently repaired. + cfg.providers[0].reasoning_history = tw_config::ReasoningHistory::ReasoningContent; + state.reload(cfg).unwrap(); + assert_eq!( + post(gw, "/v1/chat/completions", &auth, request).await.0, + 422 + ); + assert_eq!(seen.lock().unwrap().len(), 7); +} + +#[tokio::test] +async fn history_rejection_does_not_guess_formats_or_loop_on_a_second_rejection() { + let error = json!({"detail":[{"type":"extra_forbidden","loc":["body","messages",0,"assistant","reasoning_content"]}]}).to_string(); + let (up, _) = upstream(422, "application/json", error).await; + let (gw, mut events) = gateway(provider(up, Protocol::OpenaiChat), SecurityMode::Observe).await; + let (status,_,_) = post(gw,"/v1/chat/completions",&[("authorization","Bearer tw-k")],json!({"model":"m","messages":[{"role":"assistant","content":"answer","reasoning_content":"thought"},{"role":"user","content":"next"}]})).await; + assert_eq!(status, 422); + let mut attempts = None; + while let Ok(event) = events.try_recv() { + if let tw_api::Event::RequestRouted { + attempts: chain, .. + } = event + { + attempts = Some(chain); + } + } + assert_eq!( + attempts.unwrap().len(), + 2, + "one logical request may negotiate only once" + ); +} diff --git a/crates/tw-gateway/tests/history_negotiation.rs b/crates/tw-gateway/tests/history_negotiation.rs new file mode 100644 index 00000000..1c797590 --- /dev/null +++ b/crates/tw-gateway/tests/history_negotiation.rs @@ -0,0 +1,236 @@ +//! Regression boundaries for request-side runtime capability negotiation. +use axum::{Router, body::Body, response::Response}; +use serde_json::{Value, json}; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use tw_config::{Client, Config, Protocol, Provider}; + +type Seen = Arc>>; +async fn upstream( + reply: impl Fn(&Value, usize) -> (u16, &'static str, String) + Send + Sync + 'static, +) -> (SocketAddr, Seen) { + let seen = Seen::default(); + let app = Router::new().fallback({ + let seen = seen.clone(); + let reply = Arc::new(reply); + move |body: bytes::Bytes| { + let seen = seen.clone(); + let reply = reply.clone(); + async move { + let v: Value = serde_json::from_slice(&body).unwrap(); + let count = { + let mut seen = seen.lock().unwrap(); + seen.push(v.clone()); + seen.len() + }; + let (status, ct, body) = reply(&v, count); + Response::builder() + .status(status) + .header("content-type", ct) + .body(Body::from(body)) + .unwrap() + } + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (addr, seen) +} +fn rejected() -> (u16, &'static str, String) { + (422,"application/json",json!({"detail":[{"type":"extra_forbidden","loc":["body","messages",0,"assistant","reasoning_content"]}]}).to_string()) +} +fn accepted() -> (u16, &'static str, String) { + ( + 200, + "application/json", + json!({"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}) + .to_string(), + ) +} +async fn gateway(ups: &[SocketAddr]) -> (SocketAddr, tw_gateway::AppState) { + let cfg = if ups.len() == 1 { + Config { + version: 1, + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![Provider { + name: "up".into(), + base_url: format!("http://{}", ups[0]), + protocol: Some(Protocol::OpenaiChat), + ..Default::default() + }], + ..Default::default() + } + } else { + serde_yaml_ng::from_str(&format!("version: 1\ndefault_route: all\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: up\n base_url: http://{}\n protocol: openai-chat\n - name: next\n base_url: http://{}\n protocol: openai-chat\ngroups:\n - name: pool\n type: fallback\n providers: [up, next]\nroutes:\n - name: all\n rules:\n - name: all\n to: pool\n",ups[0],ups[1])).unwrap() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let addr = tw_gateway::serve(state.clone(), ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + (addr, state) +} +fn request() -> Value { + json!({"model":"m","messages":[{"role":"assistant","content":"answer","reasoning_content":"thought"},{"role":"user","content":"next"}]}) +} +async fn post(gw: SocketAddr, request: &Value) -> u16 { + let r = reqwest::Client::new() + .post(format!("http://{gw}/v1/chat/completions")) + .header("authorization", "Bearer tw-k") + .json(request) + .send() + .await + .unwrap(); + let status = r.status().as_u16(); + let _ = r.bytes().await.unwrap(); + status +} + +#[tokio::test] +async fn unsuccessful_adjustment_is_not_cached() { + let (up, seen) = upstream(|_, _| rejected()).await; + let (gw, state) = gateway(&[up]).await; + for count in [2, 4] { + assert_eq!(post(gw, &request()).await, 422); + assert_eq!(seen.lock().unwrap().len(), count); + assert!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .is_empty() + ); + } +} + +#[tokio::test] +async fn signed_native_history_is_never_automatically_removed() { + let (up, seen) = upstream(|_, _| rejected()).await; + let (gw, _) = gateway(&[up]).await; + let mut v = request(); + v["messages"][0]["content"] = json!([{"type":"thinking","thinking":[{"type":"text","text":"native"}],"signature":"opaque"},{"type":"text","text":"answer"}]); + assert_eq!(post(gw, &v).await, 422); + assert_eq!(seen.lock().unwrap().len(), 1); + assert_eq!( + seen.lock().unwrap()[0]["messages"][0]["content"][0]["signature"], + "opaque" + ); +} + +#[tokio::test] +async fn later_candidates_receive_original_history_and_share_the_repair_budget() { + let (first, a) = upstream(|_, n| { + if n == 1 { + rejected() + } else { + ( + 503, + "application/json", + json!({"error":{"message":"overloaded"}}).to_string(), + ) + } + }) + .await; + let (next, b) = upstream(|_, _| rejected()).await; + let (gw, state) = gateway(&[first, next]).await; + assert_eq!(post(gw, &request()).await, 422); + assert_eq!(a.lock().unwrap().len(), 2); + assert!( + a.lock().unwrap()[1]["messages"][0] + .get("reasoning_content") + .is_none() + ); + assert_eq!( + b.lock().unwrap().len(), + 1, + "negotiation must not restart at each provider" + ); + assert_eq!( + b.lock().unwrap()[0]["messages"][0]["reasoning_content"], + "thought" + ); + assert!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .is_empty() + ); +} + +#[tokio::test] +async fn sse_errors_neither_trigger_negotiation_nor_confirm_a_trial() { + let stream_error = || { + ( + 200, + "text/event-stream", + format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({"error":{"type":"invalid_request_error","message":"reasoning_content is unsupported","code":422}}) + ), + ) + }; + let (up, seen) = upstream(move |_, n| if n == 1 { rejected() } else { stream_error() }).await; + let (gw, state) = gateway(&[up]).await; + let mut v = request(); + v["stream"] = json!(true); + assert_eq!(post(gw, &v).await, 200); + assert_eq!(seen.lock().unwrap().len(), 2); + assert!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .is_empty() + ); + assert_eq!(post(gw, &v).await, 200); + assert_eq!( + seen.lock().unwrap().len(), + 3, + "an SSE error does not initiate a repair" + ); +} + +#[tokio::test] +async fn tool_and_thinking_modes_are_independently_verified_and_reload_clears_them() { + let (up, seen) = upstream(|v, _| { + if v["messages"][0].get("reasoning_content").is_some() { + rejected() + } else { + accepted() + } + }) + .await; + let (gw, state) = gateway(&[up]).await; + let original = request(); + let mut thinking = original.clone(); + thinking["reasoning_effort"] = json!("high"); + let mut tools = original.clone(); + tools["tools"] = json!([{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{}}}}]); + for (i, v) in [original.clone(), thinking, tools].iter().enumerate() { + assert_eq!(post(gw, v).await, 200); + assert_eq!(seen.lock().unwrap().len(), (i + 1) * 2); + } + assert_eq!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .len(), + 3 + ); + state.reload((*state.config()).clone()).unwrap(); + assert!( + state + .runtime() + .history_memory + .view("up", tw_gateway::history_memory::now_ms()) + .is_empty() + ); + assert_eq!(post(gw, &original).await, 200); + assert_eq!(seen.lock().unwrap().len(), 8); +} diff --git a/docs/config.md b/docs/config.md index 7f0e17f3..d415811c 100644 --- a/docs/config.md +++ b/docs/config.md @@ -450,6 +450,27 @@ Upstreams: the APIs requests are forwarded to. | `signed_in` | `zai` \| `bigmodel` | — | Which account sign-in the `key` came from: `zai` (Z.ai) or `bigmodel` (BigModel). Signing in to the account in the desktop app writes it; replacing the key there removes it. It does not change how requests are sent. Unset: the key was written by hand. | +In `auto`, unknown Chat-compatible endpoints can also learn a narrowly scoped +omission from a structured HTTP 400/422 `extra_forbidden` validation error for +`messages[n].reasoning_content` or `messages[n].reasoning`. This does **not** +establish support for an alternate format. The gateway re-encodes from the original +history, removes only the rejected unsigned field, applies outbound redaction again, +and makes at most one request-schema repair per logical request (shared with effort, +automatic cache-breakpoint and sealed-history repairs). Explicit overrides and signed +history are never changed by this negotiation. Profiles that require reasoning +replay do not negotiate omissions. Ambiguous errors, SSE errors, timeouts and failures +after generation starts do not initiate negotiation. + +Only an accepted adjusted request is remembered. The in-memory cache is bounded +at 1,024 entries, expires after 24 hours, is isolated by upstream/resolved credentials, +model, actual API path and tool/thinking mode, and resets on configuration reload or +restart. `GET /providers/{name}/reasoning-history` shows explicit settings and verified +observations; `DELETE /providers/{name}/reasoning-history/cache` clears observations +and cancels pending learning. `PUT /reasoning-history` updates only the upstream or +model override (`provider`, optional `model`, `format`, optional `base_version`); +model `auto` removes the override and inherits the upstream setting. Ordinary upstream +and model-spec saves retain these settings. + A credential is one of four things: `key`, which goes in the header the protocol expects; `oauth`, a token obtained from a refresh token; `aws`, the access keys a Bedrock upstream signs its requests with; or `headers`, when the diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index f7a6a1fe..f8b56ef2 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -322,6 +322,21 @@ clients: | `signed_in` | `zai` \| `bigmodel` | — | `key` 来自哪一家的账号登录:`zai`(Z.ai)或 `bigmodel`(BigModel)。在桌面端登录账号时写入,在桌面端更换密钥时删除。不影响请求的发送方式。不写:密钥是手动填写的。 | +`auto` 也能从未知 Chat 兼容接口的结构化 HTTP 400/422 校验错误中学习:只识别 +`messages[n].reasoning_content` 或 `messages[n].reasoning` 的 `extra_forbidden`, +不会据此猜另一种格式。网关从原始历史重新编码,只省略明确被拒绝的普通字段,再次执行 +出站脱敏;每个逻辑请求最多修复一次,与推理强度、自动缓存断点和封存历史的修复共用预算。 +显式设置和签名历史不参与自动协商,要求回传思考历史的协议配置也不自动省略。 +含糊的报错、SSE 错误、超时或已经开始生成后的错误都不触发协商。 + +只有调整后被接受的请求才会留下学习记录。缓存只在内存中,最多 1024 条、24 小时过期, +按上游及解析后的凭据、模型、实际接口路径、工具和思考设置隔离;重载配置或重启后清空。 +`GET /providers/{name}/reasoning-history` 查看显式设置与已验证的记录, +`DELETE /providers/{name}/reasoning-history/cache` 清除记录并取消尚在途的学习。 +`PUT /reasoning-history` 只修改相应上游或模型的设置,字段为 `provider`、可选 `model`、 +`format` 和可选 `base_version`;模型级 `auto` 删除覆盖、继承上游设置。 +普通上游编辑和模型规格编辑会保留这些设置。 + 凭据有四种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`aws`,Bedrock 上游签名请求用的访问密钥;`headers`,用于上游自有的鉴权方式。`headers` 可以和其余几种同时使用,但不能再设置已经承载凭据的那个请求头。 ```yaml diff --git a/release-notes/0.92.0.md b/release-notes/0.92.0.md new file mode 100644 index 00000000..35bcbb93 --- /dev/null +++ b/release-notes/0.92.0.md @@ -0,0 +1,7 @@ +Multi-turn reasoning history is now encoded for the selected upstream's request capabilities. Native thinking blocks, ordering, signatures and source identity survive protocol conversion. Explicit upstream and model settings select `reasoning_content`, `reasoning`, native content blocks or omitted history. Incompatible signed histories are rejected before sending. + +Automatic mode can learn from precise structured HTTP 400/422 validation errors that reject an assistant history field. It omits only that rejected unsigned field, re-encodes from the original request, reapplies outbound redaction and retries once. It does not guess another format or negotiate from ambiguous errors, SSE errors or timeouts. Request-schema repairs share one budget across providers and existing effort, cache-breakpoint and sealed-history recovery paths. + +Only accepted adjustments are cached. Observations are isolated by upstream, resolved credentials, model, API and tool/thinking mode, expire after 24 hours and reset on configuration reload or restart. The control API exposes observations, cache clearing and versioned upstream/model overrides. Existing provider and model editors preserve those overrides. Required and signed history are excluded from automatic omission. + +The control-plane protocol is now 59. The request-store schema remains 28; no database migration is required. This addresses the reproduced multi-turn field rejection in ThinkWatch Lite #407. The original streaming-delay report still needs reporter confirmation or a complete capture. From ce53a96e9850120b811881eb03401545e8cfb491 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:13:58 +0800 Subject: [PATCH 3/5] Use fallible lookup for rejected history fields --- crates/tw-gateway/src/history_memory.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/tw-gateway/src/history_memory.rs b/crates/tw-gateway/src/history_memory.rs index 2644d080..c35904f2 100644 --- a/crates/tw-gateway/src/history_memory.rs +++ b/crates/tw-gateway/src/history_memory.rs @@ -247,9 +247,7 @@ pub fn refusal(status: u16, body: &[u8], sent: &[u8]) -> Option "reasoning_content", HistoryField::Reasoning => "reasoning", }; - if message.get(name).is_none() { - return None; - } + message.get(name)?; if !fields.contains(&f) { fields.push(f); } From f3539d034c2d3c4388da41b26788a135c5a7e9aa Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:25:55 +0800 Subject: [PATCH 4/5] Keep reasoning-history adaptation internal and automatic --- crates/tw-api/src/ep.rs | 3 - crates/tw-api/src/lib.rs | 59 +----------- crates/tw-control/src/resources.rs | 95 ------------------- crates/tw-control/tests/handover.rs | 2 +- crates/tw-control/tests/model_specs.rs | 86 ----------------- crates/tw-gateway/src/history_memory.rs | 61 ++++-------- crates/tw-gateway/src/server/pipeline/hop.rs | 6 +- crates/tw-gateway/tests/conversion.rs | 7 +- .../tw-gateway/tests/history_negotiation.rs | 19 ++-- docs/config.md | 8 +- docs/config.zh-CN.md | 6 +- release-notes/0.92.0.md | 4 +- 12 files changed, 39 insertions(+), 317 deletions(-) diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index be020811..dee382fa 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -142,9 +142,6 @@ endpoints! { ProviderModels: GET "/providers/{name}/models" [name], () => api::ProviderModelsView; /// 手写一家上游的一个模型的上下文窗口、输出上限,优先于价目表;两项都空就删掉。 /// **不在 `/providers/` 底下**:写死的一段会盖住 `/providers/{name}` - ReasoningHistory: GET "/providers/{name}/reasoning-history" [name], () => api::ReasoningHistoryView; - SaveReasoningHistory: PUT "/reasoning-history", api::ReasoningHistorySave => api::ConfigWritten; - ClearReasoningHistory: DELETE "/providers/{name}/reasoning-history/cache" [name], () => api::ReasoningHistoryView; SetModelSpec: PUT "/provider-model-spec", api::ModelSpecSave => api::ConfigWritten; /// 换掉一家上游手动添加的模型(整份清单,空的就是清掉):上游能服务、却没列进清单的 /// 模型,和列出的一样算这家提供。**不在 `/providers/` 底下**,同上 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 7a84e746..1291675e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1144,12 +1144,7 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 速度,请求记录里照记。新码:`gw.upstream.too_slow`、`config.min_speed_range`(`upstream`、 /// `field`、`value`、`min`、`max`);一键修复修得了它:速度越界删掉 `min_speed`,判定时长越界改回 /// 20。请求库 SCHEMA 不变 -/// -/// **59 起增加思考历史能力查看与覆盖,以及运行时学习缓存的清除接口。** -/// Reasoning-history capability inspection, explicit overrides, and -/// clearing of the runtime-only, 24-hour evidence cache. Existing provider and -/// model editors preserve overrides when they do not edit this setting. -pub const CONTROL_API_VERSION: u32 = 59; +pub const CONTROL_API_VERSION: u32 = 58; /// `/live` 的速度看最近多久(见 [`LiveView::tokens_per_sec`]),毫秒 pub const LIVE_RATE_WINDOW_MS: u64 = 3_000; @@ -3731,58 +3726,6 @@ pub struct ProviderInput { pub balance: Option, } -/// Explicit request-side encoding. Auto uses protocol defaults and verified -/// runtime omissions; a response field never declares request support. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -#[serde(rename_all = "kebab-case")] -pub enum ReasoningHistory { - Auto, - ReasoningContent, - Reasoning, - ContentBlocks, - Disabled, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -#[serde(rename_all = "snake_case")] -pub enum HistoryField { - ReasoningContent, - Reasoning, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -pub struct HistoryObservation { - pub model: String, - pub path: String, - pub tools: bool, - pub thinking: bool, - pub omitted: Vec, - pub observed_at_ms: u64, - pub expires_at_ms: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -pub struct ReasoningHistoryView { - pub provider: String, - pub format: ReasoningHistory, - pub models: std::collections::BTreeMap, - pub observations: Vec, -} - -/// Change only this override. A model's Auto inherits the upstream setting. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -pub struct ReasoningHistorySave { - pub provider: String, - pub model: Option, - pub format: ReasoningHistory, - pub base_version: Option, -} - /// 一家上游的最低生成速度(配置的 `providers[].min_speed`)。 /// /// 流式回答从第一个 token 起,每秒看一次最近 `window_secs` 秒的平均生成速度(和 diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 72291709..0e08316f 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -35,9 +35,6 @@ pub fn router() -> axum::Router { .at(ep::UpdateProvider, update_provider) .at(ep::DeleteProvider, delete_provider) .at(ep::ProviderModels, provider_models) - .at(ep::ReasoningHistory, reasoning_history) - .at(ep::SaveReasoningHistory, save_reasoning_history) - .at(ep::ClearReasoningHistory, clear_reasoning_history) .at(ep::SetModelSpec, set_model_spec) .at(ep::SetManualModels, set_manual_models) .at(ep::RefreshProviderModels, refresh_models) @@ -386,98 +383,6 @@ async fn provider_models( Ok(Json(models_view(&s, p, s.gateway.models.listing(p)))) } -fn history_format(f: tw_config::ReasoningHistory) -> tw_api::ReasoningHistory { - // Both public enums use the same stable wire spellings. - serde_json::from_value(serde_json::to_value(f).expect("history format")) - .expect("history format") -} - -async fn reasoning_history( - State(s): State, - Path(name): Path, -) -> Result, Fail> { - let rt = s.gateway.runtime(); - let p = rt - .config - .providers - .iter() - .find(|p| p.name == name) - .ok_or_else(|| crate::no_such_upstream(&name))?; - Ok(Json(tw_api::ReasoningHistoryView { - provider: name.clone(), - format: history_format(p.reasoning_history), - models: p - .model_specs - .iter() - .filter_map(|(m, s)| s.reasoning_history.map(|f| (m.clone(), history_format(f)))) - .collect(), - observations: rt - .history_memory - .view(&name, tw_gateway::history_memory::now_ms()), - })) -} - -async fn clear_reasoning_history( - State(s): State, - Path(name): Path, -) -> Result, Fail> { - let rt = s.gateway.runtime(); - if !rt.config.providers.iter().any(|p| p.name == name) { - return Err(crate::no_such_upstream(&name)); - } - rt.history_memory.clear(&name); - reasoning_history(State(s), Path(name)).await -} - -async fn save_reasoning_history( - State(s): State, - Json(req): Json, -) -> Result, Fail> { - use tw_api::ReasoningHistory as A; - use tw_config::ReasoningHistory as C; - let format = match req.format { - A::Auto => C::Auto, - A::ReasoningContent => C::ReasoningContent, - A::Reasoning => C::Reasoning, - A::ContentBlocks => C::ContentBlocks, - A::Disabled => C::Disabled, - }; - let version = s - .cfg - .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { - let p = cfg - .providers - .iter() - .find(|p| p.name == req.provider) - .ok_or_else(|| not_found("upstream", &req.provider))?; - if let Some(model) = &req.model { - let mut spec = p.model_specs.get(model).cloned().unwrap_or_default(); - spec.reasoning_history = - (format != tw_config::ReasoningHistory::Auto).then_some(format); - tw_config::check_model_spec(&req.provider, model, Some(&spec)) - .map_err(|e| invalid(e.msg()))?; - Ok(edit::set_model_spec( - text, - &req.provider, - model, - (!spec.is_empty()).then_some(&spec), - )?) - } else { - let mut p = p.clone(); - p.reasoning_history = format; - Ok(edit::upsert( - text, - edit::PROVIDERS, - Some(&req.provider), - &mapping(&p)?, - )?) - } - }) - .await - .map_err(apply_fail)?; - Ok(Json(tw_api::ConfigWritten { version })) -} - /// 马上向上游重新获取模型清单。 async fn refresh_models( State(s): State, diff --git a/crates/tw-control/tests/handover.rs b/crates/tw-control/tests/handover.rs index 20dec39d..a0e71a58 100644 --- a/crates/tw-control/tests/handover.rs +++ b/crates/tw-control/tests/handover.rs @@ -146,7 +146,7 @@ async fn status_reports_the_handover_phase_and_the_draining_count() { let st = status(&s).await; assert_eq!(st.handover, tw_api::HandoverState::Draining); assert_eq!(st.draining, 3); - assert_eq!(st.api_version, tw_api::CONTROL_API_VERSION); + assert_eq!(st.api_version, 58); } /// arm 之后(以及接替者正在接管时)不开始新的账号登录:回调端口不交接。(平常、排空中的 diff --git a/crates/tw-control/tests/model_specs.rs b/crates/tw-control/tests/model_specs.rs index 0a719576..92b34f4c 100644 --- a/crates/tw-control/tests/model_specs.rs +++ b/crates/tw-control/tests/model_specs.rs @@ -396,89 +396,3 @@ async fn editing_public_specs_and_provider_forms_preserves_history_capabilities( Some(tw_config::ReasoningHistory::Reasoning) ); } - -#[tokio::test] -async fn history_overrides_are_versioned_preserve_specs_and_can_be_cleared() { - let b = bed(&config( - upstream().await, - " reasoning_history: content-blocks\n model_specs:\n m: { context_window: 32000, reasoning: true }\n", - "", - )); - let path = "/providers/relay/reasoning-history"; - let (st, view) = call(&b.app, "GET", path, Value::Null).await; - assert_eq!(st, StatusCode::OK, "{view}"); - assert_eq!(view["format"], "content-blocks"); - assert_eq!(view["observations"], json!([])); - let save = - |format: &str| json!({"provider":"relay","model":"m","format":format,"base_version":null}); - let (st, _) = call( - &b.app, - "PUT", - "/reasoning-history", - save("reasoning-content"), - ) - .await; - assert_eq!(st, StatusCode::OK); - let parsed = tw_config::try_parse(&b.file()).unwrap(); - let p = &parsed.providers[0]; - assert_eq!( - p.reasoning_history, - tw_config::ReasoningHistory::ContentBlocks - ); - assert_eq!(p.model_specs["m"].context_window, Some(32000)); - assert_eq!(p.model_specs["m"].reasoning, Some(true)); - assert_eq!( - p.model_specs["m"].reasoning_history, - Some(tw_config::ReasoningHistory::ReasoningContent) - ); - // An older/public model editor must retain the advanced override. - let (st, _) = call(&b.app,"PUT","/provider-model-spec",json!({"provider":"relay","model":"m","context_window":64000,"max_output_tokens":null,"reasoning":true,"image_input":null})).await; - assert_eq!(st, StatusCode::OK); - assert_eq!( - tw_config::try_parse(&b.file()).unwrap().providers[0].model_specs["m"].reasoning_history, - Some(tw_config::ReasoningHistory::ReasoningContent) - ); - let (st, _) = call(&b.app, "PUT", "/reasoning-history", save("auto")).await; - assert_eq!(st, StatusCode::OK); - let parsed = tw_config::try_parse(&b.file()).unwrap(); - assert_eq!( - parsed.providers[0].model_specs["m"].context_window, - Some(64000) - ); - assert!( - parsed.providers[0].model_specs["m"] - .reasoning_history - .is_none() - ); - let before = b.file(); - let (st, _) = call( - &b.app, - "DELETE", - "/providers/relay/reasoning-history/cache", - Value::Null, - ) - .await; - assert_eq!(st, StatusCode::OK); - assert_eq!( - b.file(), - before, - "clearing runtime observations must not rewrite configuration" - ); - let (st, _) = call( - &b.app, - "PUT", - "/reasoning-history", - json!({"provider":"relay","model":null,"format":"disabled","base_version":"stale"}), - ) - .await; - assert_eq!(st, StatusCode::CONFLICT); - assert_eq!(b.file(), before); - let (st, _) = call( - &b.app, - "GET", - "/providers/missing/reasoning-history", - Value::Null, - ) - .await; - assert_eq!(st, StatusCode::NOT_FOUND); -} diff --git a/crates/tw-gateway/src/history_memory.rs b/crates/tw-gateway/src/history_memory.rs index c35904f2..ff302c8e 100644 --- a/crates/tw-gateway/src/history_memory.rs +++ b/crates/tw-gateway/src/history_memory.rs @@ -6,9 +6,14 @@ use std::collections::HashMap; use std::sync::Mutex; use serde_json::Value; -use tw_api::{HistoryField, HistoryObservation}; use tw_dialect::ir::{Part, Request, Vendor}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HistoryField { + ReasoningContent, + Reasoning, +} + const TTL_MS: u64 = 24 * 60 * 60 * 1000; const MAX: usize = 1024; @@ -70,7 +75,6 @@ struct Entry { #[derive(Default)] struct Inner { entries: HashMap, - epochs: HashMap, } #[derive(Default)] pub struct Cache { @@ -80,7 +84,6 @@ pub struct Cache { #[derive(Clone)] pub struct Policy { pub fields: Vec, - epoch: u64, } impl Cache { @@ -95,16 +98,12 @@ impl Cache { .get(key) .map(|e| e.fields.clone()) .unwrap_or_default(), - epoch: *inner.epochs.get(&key.provider).unwrap_or(&0), } } pub fn accepted(&self, key: Key, policy: Policy, now: u64) { let mut inner = self.inner.lock().unwrap(); - // Clearing from the UI also cancels learning by requests in flight. - if *inner.epochs.get(&key.provider).unwrap_or(&0) != policy.epoch - || policy.fields.is_empty() - { + if policy.fields.is_empty() { return; } if inner.entries.len() >= MAX @@ -126,42 +125,17 @@ impl Cache { ); } - pub fn clear(&self, provider: &str) { - let mut inner = self.inner.lock().unwrap(); - inner.entries.retain(|k, _| k.provider != provider); - let epoch = inner.epochs.entry(provider.to_owned()).or_default(); - *epoch = epoch.wrapping_add(1); - } - - pub fn view(&self, provider: &str, now: u64) -> Vec { + /// Internal diagnostics/tests; no control-plane endpoint or user setting. + pub fn entries_for(&self, provider: &str, now: u64) -> usize { let mut inner = self.inner.lock().unwrap(); inner .entries .retain(|_, e| now.saturating_sub(e.at_ms) < TTL_MS); - let mut rows: Vec<_> = inner + inner .entries - .iter() - .filter(|(k, _)| k.provider == provider) - .map(|(k, e)| HistoryObservation { - model: k.model.clone(), - path: k.path.clone(), - tools: k.tools, - thinking: k.thinking, - omitted: e.fields.clone(), - observed_at_ms: e.at_ms, - expires_at_ms: e.at_ms + TTL_MS, - }) - .collect(); - rows.sort_by(|a, b| { - (&a.model, &a.path, a.tools, a.thinking, a.observed_at_ms).cmp(&( - &b.model, - &b.path, - b.tools, - b.thinking, - b.observed_at_ms, - )) - }); - rows + .keys() + .filter(|k| k.provider == provider) + .count() } } @@ -429,7 +403,7 @@ mod tests { } #[test] - fn bounded_expiring_cache_is_isolated_and_clear_cancels_inflight_learning() { + fn bounded_expiring_cache_is_isolated_by_account_model_api_and_mode() { let p = tw_config::Provider { name: "relay".into(), base_url: "https://unknown.example/v1".into(), @@ -439,7 +413,7 @@ mod tests { let cache = Cache::default(); let mut pending = cache.policy(&key, 1); pending.fields.push(HistoryField::ReasoningContent); - assert!(cache.view("relay", 1).is_empty()); + assert!(cache.entries_for("relay", 1) == 0); cache.accepted(key.clone(), pending.clone(), 2); assert_eq!(cache.policy(&key, 3).fields, pending.fields); for different in [ @@ -468,9 +442,6 @@ mod tests { key, Key::of(&other_p, "m", "/v1/chat/completions", br#"{}"#).unwrap() ); - cache.clear("relay"); - cache.accepted(key.clone(), pending, 4); - assert!(cache.view("relay", 4).is_empty()); let mut pending = cache.policy(&key, 5); pending.fields.push(HistoryField::Reasoning); cache.accepted(key.clone(), pending, 5); @@ -481,6 +452,6 @@ mod tests { policy.fields.push(HistoryField::Reasoning); cache.accepted(key, policy, 10 + i as u64); } - assert_eq!(cache.view("relay", MAX as u64 + 10).len(), MAX); + assert_eq!(cache.entries_for("relay", MAX as u64 + 10), MAX); } } diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index a155fae9..795eb959 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -690,10 +690,12 @@ pub(super) async fn try_upstreams<'a>( .fields .iter() .map(|f| match f { - tw_api::HistoryField::ReasoningContent => { + crate::history_memory::HistoryField::ReasoningContent => { "messages.reasoning_content".into() } - tw_api::HistoryField::Reasoning => "messages.reasoning".into(), + crate::history_memory::HistoryField::Reasoning => { + "messages.reasoning".into() + } }) .collect(), at_ms: now_ms(), diff --git a/crates/tw-gateway/tests/conversion.rs b/crates/tw-gateway/tests/conversion.rs index 698548f2..a8cb4167 100644 --- a/crates/tw-gateway/tests/conversion.rs +++ b/crates/tw-gateway/tests/conversion.rs @@ -1342,11 +1342,10 @@ async fn history_negotiation_is_bounded_scoped_and_redacted_on_every_attempt() { state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .len(), + .entries_for("up", tw_gateway::history_memory::now_ms()), 1 ); - state.runtime().history_memory.clear("up"); + state.reload(cfg.clone()).unwrap(); assert_eq!( post(gw, "/v1/chat/completions", &auth, request.clone()) .await @@ -1356,7 +1355,7 @@ async fn history_negotiation_is_bounded_scoped_and_redacted_on_every_attempt() { assert_eq!( seen.lock().unwrap().len(), 6, - "clear must force fresh evidence" + "configuration reload must force fresh evidence" ); // Explicit policy takes precedence and does not get silently repaired. cfg.providers[0].reasoning_history = tw_config::ReasoningHistory::ReasoningContent; diff --git a/crates/tw-gateway/tests/history_negotiation.rs b/crates/tw-gateway/tests/history_negotiation.rs index 1c797590..c1e2410f 100644 --- a/crates/tw-gateway/tests/history_negotiation.rs +++ b/crates/tw-gateway/tests/history_negotiation.rs @@ -101,8 +101,8 @@ async fn unsuccessful_adjustment_is_not_cached() { state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .is_empty() + .entries_for("up", tw_gateway::history_memory::now_ms()) + == 0 ); } } @@ -157,8 +157,8 @@ async fn later_candidates_receive_original_history_and_share_the_repair_budget() state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .is_empty() + .entries_for("up", tw_gateway::history_memory::now_ms()) + == 0 ); } @@ -184,8 +184,8 @@ async fn sse_errors_neither_trigger_negotiation_nor_confirm_a_trial() { state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .is_empty() + .entries_for("up", tw_gateway::history_memory::now_ms()) + == 0 ); assert_eq!(post(gw, &v).await, 200); assert_eq!( @@ -219,8 +219,7 @@ async fn tool_and_thinking_modes_are_independently_verified_and_reload_clears_th state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .len(), + .entries_for("up", tw_gateway::history_memory::now_ms()), 3 ); state.reload((*state.config()).clone()).unwrap(); @@ -228,8 +227,8 @@ async fn tool_and_thinking_modes_are_independently_verified_and_reload_clears_th state .runtime() .history_memory - .view("up", tw_gateway::history_memory::now_ms()) - .is_empty() + .entries_for("up", tw_gateway::history_memory::now_ms()) + == 0 ); assert_eq!(post(gw, &original).await, 200); assert_eq!(seen.lock().unwrap().len(), 8); diff --git a/docs/config.md b/docs/config.md index d415811c..997242b5 100644 --- a/docs/config.md +++ b/docs/config.md @@ -464,12 +464,8 @@ after generation starts do not initiate negotiation. Only an accepted adjusted request is remembered. The in-memory cache is bounded at 1,024 entries, expires after 24 hours, is isolated by upstream/resolved credentials, model, actual API path and tool/thinking mode, and resets on configuration reload or -restart. `GET /providers/{name}/reasoning-history` shows explicit settings and verified -observations; `DELETE /providers/{name}/reasoning-history/cache` clears observations -and cancels pending learning. `PUT /reasoning-history` updates only the upstream or -model override (`provider`, optional `model`, `format`, optional `base_version`); -model `auto` removes the override and inherits the upstream setting. Ordinary upstream -and model-spec saves retain these settings. +restart. These runtime observations are internal and require no user settings. +Explicit upstream/model overrides remain available in advanced configuration. A credential is one of four things: `key`, which goes in the header the protocol expects; `oauth`, a token obtained from a refresh token; `aws`, the diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index f8b56ef2..0d2d1ab1 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -331,11 +331,7 @@ clients: 只有调整后被接受的请求才会留下学习记录。缓存只在内存中,最多 1024 条、24 小时过期, 按上游及解析后的凭据、模型、实际接口路径、工具和思考设置隔离;重载配置或重启后清空。 -`GET /providers/{name}/reasoning-history` 查看显式设置与已验证的记录, -`DELETE /providers/{name}/reasoning-history/cache` 清除记录并取消尚在途的学习。 -`PUT /reasoning-history` 只修改相应上游或模型的设置,字段为 `provider`、可选 `model`、 -`format` 和可选 `base_version`;模型级 `auto` 删除覆盖、继承上游设置。 -普通上游编辑和模型规格编辑会保留这些设置。 +学习记录完全由程序内部管理,正常使用无需额外设置。高级配置仍可显式覆盖上游或模型的历史格式。 凭据有四种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`aws`,Bedrock 上游签名请求用的访问密钥;`headers`,用于上游自有的鉴权方式。`headers` 可以和其余几种同时使用,但不能再设置已经承载凭据的那个请求头。 diff --git a/release-notes/0.92.0.md b/release-notes/0.92.0.md index 35bcbb93..54a364fc 100644 --- a/release-notes/0.92.0.md +++ b/release-notes/0.92.0.md @@ -2,6 +2,6 @@ Multi-turn reasoning history is now encoded for the selected upstream's request Automatic mode can learn from precise structured HTTP 400/422 validation errors that reject an assistant history field. It omits only that rejected unsigned field, re-encodes from the original request, reapplies outbound redaction and retries once. It does not guess another format or negotiate from ambiguous errors, SSE errors or timeouts. Request-schema repairs share one budget across providers and existing effort, cache-breakpoint and sealed-history recovery paths. -Only accepted adjustments are cached. Observations are isolated by upstream, resolved credentials, model, API and tool/thinking mode, expire after 24 hours and reset on configuration reload or restart. The control API exposes observations, cache clearing and versioned upstream/model overrides. Existing provider and model editors preserve those overrides. Required and signed history are excluded from automatic omission. +Only accepted adjustments are cached. Observations are isolated by upstream, resolved credentials, model, API and tool/thinking mode, expire after 24 hours and reset on configuration reload or restart. Learning and expiry are managed internally and require no additional UI or user configuration. Existing advanced upstream/model overrides remain authoritative and survive ordinary provider and model-spec edits. Required and signed history are excluded from automatic omission. -The control-plane protocol is now 59. The request-store schema remains 28; no database migration is required. This addresses the reproduced multi-turn field rejection in ThinkWatch Lite #407. The original streaming-delay report still needs reporter confirmation or a complete capture. +The control-plane protocol remains 58. The request-store schema remains 28; no database migration is required. This addresses the reproduced multi-turn field rejection in ThinkWatch Lite #407. The original streaming-delay report still needs reporter confirmation or a complete capture. From a00b4f6c5fc91b5cc42ad560aa519c01c30a7bc1 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:29:49 +0800 Subject: [PATCH 5/5] Learn history repairs only when applied to the accepted attempt --- crates/tw-gateway/src/server/pipeline/hop.rs | 12 ++++++ .../tw-gateway/tests/history_negotiation.rs | 43 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 795eb959..97e6f8b0 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -676,6 +676,17 @@ pub(super) async fn try_upstreams<'a>( .map(|(_, p)| p.clone()) .unwrap_or_else(|| rt.history_memory.policy(key, now_ms())) }); + // Plugins run again on a history retry and may change the request. + // Accepting a different body proves nothing about an unapplied repair. + let history_trial_applied = history_key.as_ref().is_some_and(|key| { + history_trial.as_ref().is_some_and(|(trial, policy)| { + trial == key + && policy + .fields + .iter() + .all(|field| crate::history_memory::omit(&out.body, &[*field]).is_some()) + }) + }); if let Some(policy) = &history_policy && let Some(body) = crate::history_memory::omit(&out.body, &policy.fields) { @@ -1439,6 +1450,7 @@ pub(super) async fn try_upstreams<'a>( } if answered && !unconfirmed + && history_trial_applied && let Some(key) = &history_key && let Some((trial, policy)) = &history_trial && trial == key diff --git a/crates/tw-gateway/tests/history_negotiation.rs b/crates/tw-gateway/tests/history_negotiation.rs index c1e2410f..53972ff5 100644 --- a/crates/tw-gateway/tests/history_negotiation.rs +++ b/crates/tw-gateway/tests/history_negotiation.rs @@ -233,3 +233,46 @@ async fn tool_and_thinking_modes_are_independently_verified_and_reload_clears_th assert_eq!(post(gw, &original).await, 200); assert_eq!(seen.lock().unwrap().len(), 8); } + +#[tokio::test] +async fn a_plugin_removing_history_does_not_confirm_an_unapplied_adjustment() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use tw_gateway::plugin::host::double::{self, Double}; + use tw_gateway::plugin::{Invocation, PluginSet, RequestOutcome}; + + let (up, seen) = upstream(|v, _| { + if v["messages"][0].get("reasoning_content").is_some() { + rejected() + } else { + accepted() + } + }) + .await; + let (gw, state) = gateway(&[up]).await; + let calls = AtomicUsize::new(0); + let plugin = Double::new("changing history") + .permit(&[tw_api::Permission::Messages]) + .on_request(move |mut view, _| { + if calls.fetch_add(1, Ordering::Relaxed) % 2 == 0 { + Invocation::ok(RequestOutcome::Unchanged) + } else { + view["messages"].as_array_mut().unwrap().remove(0); + Invocation::ok(RequestOutcome::Changed(view)) + } + }); + state.swap_plugins(PluginSet::new(vec![Arc::new(double::active( + "changing", plugin, + ))])); + for count in [2, 4] { + assert_eq!(post(gw, &request()).await, 200); + assert_eq!(seen.lock().unwrap().len(), count); + assert_eq!( + state + .runtime() + .history_memory + .entries_for("up", tw_gateway::history_memory::now_ms()), + 0, + "a retry that did not apply the proposed omission is not evidence" + ); + } +}