From 9961ffeeb91a7ec59fdcfec572a002057073e96e Mon Sep 17 00:00:00 2001 From: Zyy Date: Thu, 26 Nov 2026 18:55:27 +0800 Subject: [PATCH] fix(antigravity): align Gemini request translation and transport Build GenAI requests directly from Responses input and preserve multimodal tool results. Select unary or streaming generation from the client transport and derive session IDs from isolated affinity keys. Honor account credit preferences in generation and scheduling, and scope connection and SSE limits to Antigravity. Co-authored-by: Codex --- .../gateway-protocol/src/anthropic/content.rs | 10 +- .../gateway-protocol/src/anthropic/mod.rs | 4 +- .../gateway-protocol/src/anthropic/request.rs | 3 +- .../gateway-protocol/src/anthropic/tools.rs | 98 ++++-- .../gateway-protocol/src/genai/messages.rs | 88 ++--- .../crates/gateway-protocol/src/genai/mod.rs | 1 + .../gateway-protocol/src/genai/parts.rs | 101 ++++++ .../gateway-protocol/src/genai/responses.rs | 324 +++++++++++++++++- .../crates/gateway-protocol/src/openai/sse.rs | 60 +++- .../gateway-protocol/tests/genai/messages.rs | 19 + .../gateway-protocol/tests/genai/responses.rs | 61 ++++ .../gateway-protocol/tests/openai/sse.rs | 22 ++ .../antigravity/src/admin/provider.rs | 1 + .../src/credential/quota/document.rs | 38 +- .../src/credential/quota/service.rs | 49 ++- .../antigravity/src/provider/affinity.rs | 11 + .../antigravity/src/provider/execution.rs | 5 +- .../antigravity/src/provider/translation.rs | 38 +- .../antigravity/src/transport/account.rs | 45 +++ .../antigravity/src/transport/client.rs | 29 +- .../antigravity/src/transport/pool.rs | 2 +- .../antigravity/src/transport/response.rs | 2 +- .../tests/credential/quota/service.rs | 69 ++++ .../antigravity/tests/provider/execution.rs | 40 ++- docs/api.md | 4 +- docs/architecture.md | 8 +- 26 files changed, 950 insertions(+), 182 deletions(-) create mode 100644 backend/crates/gateway-protocol/src/genai/parts.rs diff --git a/backend/crates/gateway-protocol/src/anthropic/content.rs b/backend/crates/gateway-protocol/src/anthropic/content.rs index 78a88c2e4..a45e5c57f 100644 --- a/backend/crates/gateway-protocol/src/anthropic/content.rs +++ b/backend/crates/gateway-protocol/src/anthropic/content.rs @@ -102,10 +102,12 @@ pub(super) fn source_url(source: &Value) -> Option { } } +pub(crate) fn split_data_url(url: &str) -> Option<(&str, &str)> { + url.strip_prefix("data:")?.split_once(";base64,") +} + fn url_source(url: &str) -> Value { - if let Some(data) = url.strip_prefix("data:") - && let Some((media_type, data)) = data.split_once(";base64,") - { + if let Some((media_type, data)) = split_data_url(url) { return json!({"type":"base64","media_type":media_type,"data":data}); } json!({"type":"url","url":url}) @@ -144,7 +146,7 @@ pub(super) fn is_anthropic_carrier(item: &Value) -> bool { .is_some_and(|carrier| carrier.starts_with(ANTHROPIC_CARRIER)) } -pub(super) fn restore_anthropic(item: &Value) -> Option { +pub(crate) fn restore_anthropic(item: &Value) -> Option { let carrier = item.get("encrypted_content")?.as_str()?; if let Some(raw) = carrier.strip_prefix(ANTHROPIC_CARRIER) { return serde_json::from_str(raw).ok(); diff --git a/backend/crates/gateway-protocol/src/anthropic/mod.rs b/backend/crates/gateway-protocol/src/anthropic/mod.rs index 2543847e5..8accdf1f5 100644 --- a/backend/crates/gateway-protocol/src/anthropic/mod.rs +++ b/backend/crates/gateway-protocol/src/anthropic/mod.rs @@ -11,8 +11,8 @@ mod thinking; mod tools; mod usage; -pub(crate) use content::GENAI_CARRIER; -pub(crate) use request::responses_to_messages_content; +pub(crate) use content::{GENAI_CARRIER, restore_anthropic, split_data_url}; +pub(crate) use tools::{ToolSet, allowed_tools}; pub use capabilities::MessagesModelCapabilities; pub use error::TranslationError; diff --git a/backend/crates/gateway-protocol/src/anthropic/request.rs b/backend/crates/gateway-protocol/src/anthropic/request.rs index fe9e29498..c939d25c9 100644 --- a/backend/crates/gateway-protocol/src/anthropic/request.rs +++ b/backend/crates/gateway-protocol/src/anthropic/request.rs @@ -324,8 +324,7 @@ pub fn responses_to_messages_request( Ok(result) } -/// 共享对话、签名与工具映射,生成参数由最终目标协议独立处理 -pub(crate) fn responses_to_messages_content( +fn responses_to_messages_content( request: &Map, hosted_search: bool, ) -> Result, TranslationError> { diff --git a/backend/crates/gateway-protocol/src/anthropic/tools.rs b/backend/crates/gateway-protocol/src/anthropic/tools.rs index 6fa32e019..5373cb919 100644 --- a/backend/crates/gateway-protocol/src/anthropic/tools.rs +++ b/backend/crates/gateway-protocol/src/anthropic/tools.rs @@ -8,7 +8,7 @@ use crate::openai::web_search; use serde_json::{Map, Value, json}; #[derive(Debug, Clone)] -pub(super) struct Tool { +pub(crate) struct Tool { pub name: String, pub namespace: Option, pub custom: bool, @@ -16,7 +16,7 @@ pub(super) struct Tool { } #[derive(Debug, Clone, Default)] -pub(super) struct ToolSet { +pub(crate) struct ToolSet { pub tools: BTreeMap>, } @@ -115,31 +115,71 @@ impl ToolSet { } } +pub(crate) fn allowed_tools(choice: &Value) -> Result, TranslationError> { + if choice["type"] != "allowed_tools" { + return Ok(None); + } + choice["tools"] + .as_array() + .filter(|tools| !tools.is_empty()) + .map(|tools| Some(tools.as_slice())) + .ok_or(TranslationError::InvalidRequest( + "Allowed tools must contain at least one tool.", + )) +} + +impl Tool<&Value> { + pub(crate) fn schema(&self) -> Value { + if self.custom { + json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]}) + } else { + self.definition + .get("parameters") + .cloned() + .unwrap_or_else(|| json!({"type":"object","properties":{}})) + } + } +} + impl<'a> ToolSet<&'a Value> { pub fn from_responses(request: &'a Map) -> Self { Self::collect(request, |tool| tool) } + pub(crate) fn declarations<'b>( + &'b self, + allowed: Option<&'b [Value]>, + ) -> impl Iterator)> { + self.tools + .iter() + .filter(move |(_, tool)| { + allowed.is_none_or(|choices| { + choices.iter().any(|choice| { + matches!(choice["type"].as_str(), Some("function" | "custom")) + && choice["type"] == tool.definition["type"] + && choice.get("name").and_then(Value::as_str) + == Some(tool.name.as_str()) + && choice.get("namespace").and_then(Value::as_str) + == tool.namespace.as_deref() + }) + }) + }) + .map(|(name, tool)| (name.as_str(), tool)) + } + fn definitions(&self, allowed: Option<&[Value]>) -> Vec { - self.tools.iter().filter(|(_, tool)| { - allowed.is_none_or(|choices| choices.iter().any(|choice| - matches!(choice["type"].as_str(), Some("function" | "custom")) - && choice["type"] == tool.definition["type"] - && choice.get("name").and_then(Value::as_str) == Some(tool.name.as_str()) - && choice.get("namespace").and_then(Value::as_str) == tool.namespace.as_deref() - )) - }).map(|(name, tool)| { - let schema = if tool.custom { - json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]}) - } else { - tool.definition.get("parameters").cloned().unwrap_or_else(|| json!({"type":"object","properties":{}})) - }; - let mut definition = json!({"name":name,"input_schema":schema}); - for field in ["description", "strict", "cache_control", "defer_loading"] { - if let Some(value) = tool.definition.get(field) { definition[field] = value.clone(); } - } - definition - }).collect() + self.declarations(allowed) + .map(|(name, tool)| { + let schema = tool.schema(); + let mut definition = json!({"name":name,"input_schema":schema}); + for field in ["description", "strict", "cache_control", "defer_loading"] { + if let Some(value) = tool.definition.get(field) { + definition[field] = value.clone(); + } + } + definition + }) + .collect() } pub fn write_messages_tools( @@ -149,20 +189,8 @@ impl<'a> ToolSet<&'a Value> { hosted_search: bool, ) -> Result<(), TranslationError> { let choice = request.get("tool_choice").unwrap_or(&Value::Null); - let restricted = choice["type"] == "allowed_tools"; - let allowed = if restricted { - Some( - choice["tools"] - .as_array() - .filter(|v| !v.is_empty()) - .ok_or(TranslationError::InvalidRequest( - "Allowed tools must contain at least one tool.", - ))? - .as_slice(), - ) - } else { - None - }; + let allowed = allowed_tools(choice)?; + let restricted = allowed.is_some(); let mut definitions = self.definitions(allowed); for tool in web_search::allowed_declarations(request) .filter(|tool| hosted_search && web_search::allows_live_access(tool)) diff --git a/backend/crates/gateway-protocol/src/genai/messages.rs b/backend/crates/gateway-protocol/src/genai/messages.rs index c1e5a91fb..96ed98c1d 100644 --- a/backend/crates/gateway-protocol/src/genai/messages.rs +++ b/backend/crates/gateway-protocol/src/genai/messages.rs @@ -1,15 +1,10 @@ //! Messages 内容到 GenAI 的纯协议映射,签名载荷只按明确来源恢复 -use crate::anthropic::{GENAI_CARRIER as SIGNATURE_PREFIX, TranslationError}; +use super::parts::{TurnParts, content, function_response, invalid}; +use crate::anthropic::TranslationError; use serde_json::{Map, Value, json}; use std::{borrow::Cow, collections::BTreeMap}; -fn invalid() -> TranslationError { - TranslationError::InvalidRequest( - "The request contains content unsupported by the GenAI adapter.", - ) -} - /// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入 pub fn messages_to_genai_request( request: &Map, @@ -58,9 +53,7 @@ pub fn messages_to_genai_request( Ok(result) } -pub(super) fn content_to_genai( - request: &Map, -) -> Result, TranslationError> { +fn content_to_genai(request: &Map) -> Result, TranslationError> { let mut result = Map::new(); if let Some(system) = request.get("system") { result.insert( @@ -89,37 +82,14 @@ pub(super) fn content_to_genai( Some("user") => "user", _ => return Err(invalid()), }; - let mut parts: Vec = Vec::new(); - let mut pending_signature = None; + let mut parts = TurnParts::default(); for block in blocks.iter() { - let mut part = match block["type"].as_str() { + let part = match block["type"].as_str() { Some("text") => json!({"text":block["text"]}), Some("image" | "document") => media(&block["source"])?, Some("thinking") => { - if let Some(raw) = block["signature"] - .as_str() - .and_then(|s| s.strip_prefix(SIGNATURE_PREFIX)) - { - let carrier: Value = serde_json::from_str(raw).map_err(|_| invalid())?; - match carrier["target"].as_str() { - Some("previous") => { - let last = parts.last_mut().ok_or_else(invalid)?; - last["thoughtSignature"] = carrier["signature"].clone(); - continue; - } - Some("next") => { - pending_signature = Some(carrier["signature"].clone()); - continue; - } - Some("thinking") => { - json!({"text":block["thinking"],"thought":true,"thoughtSignature":carrier["signature"]}) - } - _ => return Err(invalid()), - } - } else { - // 没有本协议签名的思考不作为可验证历史回放 - continue; - } + parts.thinking(block)?; + continue; } Some("redacted_thinking") => continue, Some("tool_use") => { @@ -134,44 +104,28 @@ pub(super) fn content_to_genai( Some("tool_result") => { let id = block["tool_use_id"].as_str().ok_or_else(invalid)?; let name = calls.get(id).ok_or_else(invalid)?; - let output = &block["content"]; - let mut response = - json!({"functionResponse":{"id":id,"name":name,"response":{}}}); - let key = if block["is_error"] == true { - "error" - } else { - "output" - }; - response["functionResponse"]["response"][key] = output.clone(); - response + function_response( + id, + name, + block["is_error"] == true, + &block["content"], + |block| match block["type"].as_str() { + Some("text") => Ok(json!({"text":block["text"]})), + Some("image" | "document") => media(&block["source"]), + _ => Err(invalid()), + }, + )? } _ => return Err(invalid()), }; - if part.get("thoughtSignature").is_some_and(Value::is_null) { - part.as_object_mut() - .ok_or_else(invalid)? - .remove("thoughtSignature"); - } - if let Some(signature) = pending_signature.take() { - part["thoughtSignature"] = signature; - } - // Google 为外部历史提供的兜底值;真实签名优先,Chat 等无签名合同无需服务端缓存 - // https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures - if part.get("functionCall").is_some() && part.get("thoughtSignature").is_none() { - part["thoughtSignature"] = json!("skip_thought_signature_validator"); - } parts.push(part); } - if pending_signature.is_some() { - return Err(invalid()); - } - // Chat 工具轮次可带空 content;签名已附着后再删除无内容且无签名的占位 - parts.retain(|part| part["text"] != "" || part.get("thoughtSignature").is_some()); + let parts = parts.finish()?; if !parts.is_empty() { - contents.push(json!({"role":role,"parts":parts})); + contents.push(content(role, parts)); } } - result.insert("contents".into(), json!(contents)); + result.insert("contents".into(), Value::Array(contents)); if let Some(tools) = request.get("tools").and_then(Value::as_array) { let declarations = tools .iter() diff --git a/backend/crates/gateway-protocol/src/genai/mod.rs b/backend/crates/gateway-protocol/src/genai/mod.rs index 49dc53219..7b945946f 100644 --- a/backend/crates/gateway-protocol/src/genai/mod.rs +++ b/backend/crates/gateway-protocol/src/genai/mod.rs @@ -13,6 +13,7 @@ pub use response::{ pub const GENAI_PROTOCOL: &str = "genai"; mod messages; +mod parts; mod responses; mod stream; mod tokens; diff --git a/backend/crates/gateway-protocol/src/genai/parts.rs b/backend/crates/gateway-protocol/src/genai/parts.rs new file mode 100644 index 000000000..16bc5483f --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/parts.rs @@ -0,0 +1,101 @@ +//! GenAI 轮次中的签名和多模态函数返回 +use crate::anthropic::{GENAI_CARRIER as SIGNATURE_PREFIX, TranslationError}; +use serde_json::{Map, Value, json}; + +pub(super) fn invalid() -> TranslationError { + TranslationError::InvalidRequest( + "The request contains content unsupported by the GenAI adapter.", + ) +} + +// 工具截图可能很大,组装轮次时直接移入已编码的媒体数据 +pub(super) fn content(role: &str, parts: Vec) -> Value { + Value::Object(Map::from_iter([ + ("role".into(), json!(role)), + ("parts".into(), Value::Array(parts)), + ])) +} + +#[derive(Default)] +pub(super) struct TurnParts { + parts: Vec, + pending_signature: Option, +} + +impl TurnParts { + pub(super) fn thinking(&mut self, block: &Value) -> Result<(), TranslationError> { + let Some(raw) = block["signature"] + .as_str() + .and_then(|s| s.strip_prefix(SIGNATURE_PREFIX)) + else { + // 只回放由本协议返回的思考签名 + return Ok(()); + }; + let carrier: Value = serde_json::from_str(raw).map_err(|_| invalid())?; + let signature = carrier["signature"].as_str().ok_or_else(invalid)?; + match carrier["target"].as_str() { + Some("previous") => { + self.parts.last_mut().ok_or_else(invalid)?["thoughtSignature"] = json!(signature) + } + Some("next") => self.pending_signature = Some(json!(signature)), + Some("thinking") => self.push( + json!({"text":block["thinking"],"thought":true,"thoughtSignature":signature}), + ), + _ => return Err(invalid()), + } + Ok(()) + } + pub(super) fn push(&mut self, mut part: Value) { + if let Some(signature) = self.pending_signature.take() { + part["thoughtSignature"] = signature; + } + // Google 为外部历史提供的兜底值;真实签名优先,Chat 等无签名合同无需服务端缓存 + // https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures + if part.get("functionCall").is_some() && part.get("thoughtSignature").is_none() { + part["thoughtSignature"] = json!("skip_thought_signature_validator"); + } + self.parts.push(part); + } + pub(super) fn finish(mut self) -> Result, TranslationError> { + if self.pending_signature.is_some() { + return Err(invalid()); + } + self.parts + .retain(|part| part["text"] != "" || part.get("thoughtSignature").is_some()); + Ok(self.parts) + } +} + +pub(super) fn function_response( + id: &str, + name: &str, + error: bool, + output: &Value, + parse_part: impl Fn(&Value) -> Result, +) -> Result { + let mut result = json!({"id":id,"name":name}); + let key = if error { "error" } else { "output" }; + let value = if let Some(blocks) = output.as_array() { + let mut texts = Vec::new(); + let mut media = Vec::new(); + for block in blocks { + let part = parse_part(block)?; + if let Some(text) = part.get("text").and_then(Value::as_str) { + texts.push(text.to_owned()); + } else { + media.push(part); + } + } + if !media.is_empty() { + result["parts"] = Value::Array(media); + } + Value::String(texts.join("\n")) + } else { + output.clone() + }; + result["response"] = json!({(key):value}); + Ok(Value::Object(Map::from_iter([( + "functionResponse".into(), + result, + )]))) +} diff --git a/backend/crates/gateway-protocol/src/genai/responses.rs b/backend/crates/gateway-protocol/src/genai/responses.rs index d7366c892..c2972b04c 100644 --- a/backend/crates/gateway-protocol/src/genai/responses.rs +++ b/backend/crates/gateway-protocol/src/genai/responses.rs @@ -1,7 +1,12 @@ -//! Responses 复用内容映射,生成参数直接转入 GenAI,避免继承 Messages 的默认值与限制 +//! Responses 输入、函数声明与生成参数直接映射到 GenAI -use crate::anthropic::{TranslationError, responses_to_messages_content}; +use super::parts::{TurnParts, content, function_response, invalid}; +use crate::anthropic::{ + ToolSet, TranslationError, allowed_tools, restore_anthropic, split_data_url, +}; +use crate::openai::web_search; use serde_json::{Map, Value, json}; +use std::{borrow::Cow, collections::BTreeMap}; /// 普通生成只映射函数工具,独立搜索由 Provider 按账号能力编排 pub fn responses_to_genai_request( @@ -43,8 +48,9 @@ pub fn responses_to_genai_request( format.get("schema").cloned().unwrap_or_else(|| json!({})), ); } - let content = responses_to_messages_content(request, false)?; - let mut result = super::messages::content_to_genai(&content)?; + let tools = ToolSet::from_responses(request); + let mut result = conversation(request, &tools)?; + write_tools(request, &tools, &mut result)?; result.insert("generationConfig".into(), Value::Object(generation)); Ok(result) } @@ -63,3 +69,313 @@ fn thinking_config(effort: &str) -> Option { }; Some(json!({"thinkingBudget":budget,"includeThoughts":true})) } + +fn content_part(part: &Value) -> Result { + let data = match part["type"].as_str() { + Some("text" | "input_text" | "output_text") => { + return Ok(json!({"text":part["text"].as_str().ok_or_else(invalid)?})); + } + Some("refusal") => { + return Ok(json!({"text":part["refusal"].as_str().ok_or_else(invalid)?})); + } + Some("input_image") => part["image_url"] + .as_str() + .or_else(|| part["image_url"]["url"].as_str()), + Some("input_file") => part["file_data"] + .as_str() + .or_else(|| part["file_url"].as_str()), + _ => return Err(invalid()), + } + .ok_or_else(invalid)?; + if let Some((mime, bytes)) = split_data_url(data) { + return Ok(json!({"inlineData":{"mimeType":mime,"data":bytes}})); + } + if let Some(mime) = part["mime_type"].as_str() { + return Ok(json!({"fileData":{"mimeType":mime,"fileUri":data}})); + } + Err(invalid()) +} + +fn content_parts(content: &Value) -> Result, TranslationError> { + match content { + Value::String(text) => Ok(vec![json!({"text":text})]), + Value::Array(parts) => parts.iter().map(content_part).collect(), + _ => Err(invalid()), + } +} + +fn conversation( + request: &Map, + tools: &ToolSet<&Value>, +) -> Result, TranslationError> { + let mut result = Map::new(); + let mut system = Vec::new(); + if let Some(text) = request + .get("instructions") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + { + system.push(json!({"text":text})); + } + let mut contents = Vec::new(); + let mut history = Vec::new(); + let input = match request.get("input") { + None | Some(Value::Null) => &[][..], + Some(Value::String(text)) => { + if !text.is_empty() { + contents.push(json!({"role":"user","parts":[{"text":text}]})); + } + &[] + } + Some(Value::Array(items)) => items.as_slice(), + _ => { + return Err(TranslationError::InvalidRequest( + "The input field must be a string or an array.", + )); + } + }; + for (pos, item) in input.iter().enumerate() { + let kind = item["type"].as_str().unwrap_or("message"); + let role = match kind { + "message" => match item["role"].as_str().unwrap_or("user") { + "system" | "developer" => { + let parts = content_parts(&item["content"])?; + if parts.iter().any(|part| !part["text"].is_string()) { + return Err(invalid()); + } + system.extend(parts); + continue; + } + "assistant" => "model", + "user" => "user", + _ => return Err(invalid()), + }, + "reasoning" => { + // CPR 的历史签名载荷包含完整思考块,其他来源的推理不应打断相邻轮次 + if let Some(block) = restore_anthropic(item) + && block["type"] == "thinking" + && block["signature"] + .as_str() + .is_some_and(|v| v.starts_with(crate::anthropic::GENAI_CARRIER)) + { + history.push(InputItem { + role: "model", + position: pos, + body: Cow::Owned(block), + }); + } + continue; + } + "function_call" | "custom_tool_call" => "model", + "function_call_output" | "custom_tool_call_output" => "user", + // 托管工具的历史事件不包含可回放的模型内容 + "web_search_call" => continue, + _ => return Err(invalid()), + }; + history.push(InputItem { + role, + position: pos, + body: Cow::Borrowed(item), + }); + } + let mut calls = Vec::new(); + for turn in history.chunk_by(|a, b| a.role == b.role) { + let role = turn[0].role; + let parts = if role == "model" { + model_turn(turn, tools, &mut calls)? + } else { + user_turn(turn, &mut calls)? + }; + if !parts.is_empty() { + contents.push(content(role, parts)); + } + } + if !calls.is_empty() { + contents.push(content("user", user_turn(&[], &mut calls)?)); + } + result.insert("contents".into(), Value::Array(contents)); + if !system.is_empty() { + result.insert("systemInstruction".into(), json!({"parts":system})); + } + Ok(result) +} + +struct InputItem<'a> { + role: &'static str, + position: usize, + body: Cow<'a, Value>, +} + +fn model_turn( + turn: &[InputItem<'_>], + tools: &ToolSet<&Value>, + calls: &mut Vec<(String, String)>, +) -> Result, TranslationError> { + let mut parts = TurnParts::default(); + for entry in turn { + let item = entry.body.as_ref(); + match item["type"].as_str().unwrap_or("message") { + "thinking" => parts.thinking(item)?, + "message" => { + for part in content_parts(&item["content"])? { + parts.push(part); + } + } + _ => { + let name = tools.wire_name( + item["name"].as_str().ok_or_else(invalid)?, + item["namespace"].as_str(), + ); + let id = item["call_id"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| format!("call_{}", entry.position)); + let args = if item["type"] == "custom_tool_call" { + json!({"input":item["input"].as_str().ok_or_else(invalid)?}) + } else { + serde_json::from_str::(item["arguments"].as_str().unwrap_or("{}")) + .map_err(|_| invalid())? + }; + if !args.is_object() { + return Err(invalid()); + } + parts.push(json!({"functionCall":{"id":id,"name":name,"args":args}})); + calls.push((id, name.to_owned())); + } + } + } + parts.finish() +} + +fn user_turn( + turn: &[InputItem<'_>], + calls: &mut Vec<(String, String)>, +) -> Result, TranslationError> { + let mut outputs = BTreeMap::new(); + for entry in turn { + let item = entry.body.as_ref(); + if matches!( + item["type"].as_str(), + Some("function_call_output" | "custom_tool_call_output") + ) { + outputs.insert( + item["call_id"].as_str().unwrap_or_default(), + (entry.position, item), + ); + } + } + // 同轮按调用顺序闭合,重复返回只取最后一项,迟到的结果保留为普通用户内容 + let mut parts = Vec::new(); + for (id, name) in calls.drain(..) { + let response = if let Some((_, item)) = outputs.remove(id.as_str()) { + function_response( + &id, + &name, + item["status"] == "incomplete", + &item["output"], + content_part, + )? + } else { + function_response( + &id, + &name, + true, + &json!("Tool call was interrupted before any output was recorded."), + content_part, + )? + }; + parts.push(response); + } + for entry in turn { + let item = entry.body.as_ref(); + if item["type"].as_str().unwrap_or("message") == "message" { + parts.extend( + content_parts(&item["content"])? + .into_iter() + .filter(|part| part["text"] != ""), + ); + } else if outputs + .get(item["call_id"].as_str().unwrap_or_default()) + .is_some_and(|(last, _)| *last == entry.position) + { + let output = &item["output"]; + let blocks = if output.is_array() || output.is_string() { + content_parts(output)? + } else { + vec![json!({"text":output.to_string()})] + }; + let before = parts.len(); + parts.extend( + blocks + .into_iter() + .filter(|p| p["text"].as_str().is_none_or(|s| !s.trim().is_empty())), + ); + if parts.len() == before { + parts.push(json!({"text":"Tool result was empty."})); + } + } + } + Ok(parts) +} + +fn write_tools( + request: &Map, + tools: &ToolSet<&Value>, + result: &mut Map, +) -> Result<(), TranslationError> { + let choice = request.get("tool_choice").unwrap_or(&Value::Null); + let allowed = allowed_tools(choice)?; + let mut declarations = Vec::new(); + for (name, tool) in tools.declarations(allowed) { + let schema = tool.schema(); + if !schema.is_object() { + return Err(invalid()); + } + let mut declaration = json!({"name":name,"parametersJsonSchema":schema}); + if let Some(description) = tool.definition.get("description") { + declaration["description"] = description.clone(); + } + declarations.push(declaration); + } + let kind = if allowed.is_some() { + match choice["mode"].as_str() { + Some(mode @ ("required" | "auto")) => Some(mode), + _ => return Err(invalid()), + } + } else { + choice.as_str().or_else(|| choice["type"].as_str()) + }; + if declarations.is_empty() { + if matches!(kind, Some("required" | "function" | "custom")) + || allowed.is_some_and(|a| !a.iter().all(web_search::is_search)) + { + return Err(TranslationError::InvalidRequest( + "No declared function can satisfy the tool choice.", + )); + } + return Ok(()); + } + let config = match kind { + Some("function" | "custom") => { + let (name, _) = tools + .declarations(Some(std::slice::from_ref(choice))) + .next() + .ok_or(TranslationError::InvalidRequest( + "The selected function must be declared.", + ))?; + Some(json!({"mode":"ANY","allowedFunctionNames":[name]})) + } + Some("required") => Some(json!({"mode":"ANY"})), + Some("none") => Some(json!({"mode":"NONE"})), + Some("auto") => Some(json!({"mode":"AUTO"})), + _ => None, + }; + if let Some(config) = config { + result.insert("toolConfig".into(), json!({"functionCallingConfig":config})); + } + result.insert( + "tools".into(), + json!([{"functionDeclarations":declarations}]), + ); + Ok(()) +} diff --git a/backend/crates/gateway-protocol/src/openai/sse.rs b/backend/crates/gateway-protocol/src/openai/sse.rs index aa92566fd..46341e307 100644 --- a/backend/crates/gateway-protocol/src/openai/sse.rs +++ b/backend/crates/gateway-protocol/src/openai/sse.rs @@ -73,6 +73,7 @@ pub const DONE_SSE_FRAME: &str = "data: [DONE]\n\n"; /// 用于处理任意分块边界的增量 SSE 解码器 #[derive(Debug)] pub struct SseEventDecoder { + max_bytes: usize, pending: Vec, /// `pending` 中已确认不含帧分隔符的前缀长度 /// 新数据到达时从该边界 @@ -87,16 +88,23 @@ pub struct SseEventDecoder { impl Default for SseEventDecoder { fn default() -> Self { + Self::with_max_event_bytes(MAX_SSE_EVENT_BUFFER_BYTES) + } +} + +impl SseEventDecoder { + /// 按上游合同设置单事件缓冲上限 + #[must_use] + pub fn with_max_event_bytes(max_bytes: usize) -> Self { Self { + max_bytes, pending: Vec::new(), scanned: 0, opaque_frame: false, stream_start: true, } } -} -impl SseEventDecoder { /// 返回从 `consumed` 起的下一个完整帧结束位置(含分隔符),并推进扫描边界 fn next_frame_end(&mut self, consumed: usize) -> Option { // `\r\n\r\n` 分隔符可能跨 chunk 边界,扫描起点回退 3 字节 @@ -130,15 +138,19 @@ impl SseEventDecoder { while let Some(end) = self.next_frame_end(consumed) { let frame = std::str::from_utf8(&self.pending[consumed..end]) .map_err(|error| SseError::ParseError(error.to_string()))?; - events.extend(parse_sse_events_inner(frame, self.stream_start)?); + events.extend(parse_sse_events_inner( + frame, + self.stream_start, + self.max_bytes, + )?); self.stream_start = false; consumed = end; } self.commit_consumed(consumed); - if self.pending.len() > MAX_SSE_EVENT_BUFFER_BYTES { + if self.pending.len() > self.max_bytes { return Err(SseError::BufferExceeded { - max_bytes: MAX_SSE_EVENT_BUFFER_BYTES, + max_bytes: self.max_bytes, }); } Ok(events) @@ -161,12 +173,14 @@ impl SseEventDecoder { while let Some(end) = self.next_frame_end(consumed) { let raw = self.pending[consumed..end].to_vec(); - let events = if raw.len() > MAX_SSE_EVENT_BUFFER_BYTES { + let events = if raw.len() > self.max_bytes { Vec::new() } else { std::str::from_utf8(&raw) .ok() - .and_then(|frame| parse_sse_events_inner(frame, self.stream_start).ok()) + .and_then(|frame| { + parse_sse_events_inner(frame, self.stream_start, self.max_bytes).ok() + }) .unwrap_or_default() }; self.stream_start = false; @@ -175,7 +189,7 @@ impl SseEventDecoder { } self.commit_consumed(consumed); - if self.pending.len() > MAX_SSE_EVENT_BUFFER_BYTES { + if self.pending.len() > self.max_bytes { self.opaque_frame = true; self.flush_opaque_prefix(&mut frames); } @@ -191,7 +205,7 @@ impl SseEventDecoder { let pending = std::mem::take(&mut self.pending); let frame = std::str::from_utf8(&pending) .map_err(|error| SseError::ParseError(error.to_string()))?; - let events = parse_sse_events_inner(frame, self.stream_start)?; + let events = parse_sse_events_inner(frame, self.stream_start, self.max_bytes)?; self.stream_start = false; Ok(events) } @@ -206,12 +220,14 @@ impl SseEventDecoder { return Vec::new(); } let raw = std::mem::take(&mut self.pending); - let events = if self.opaque_frame || raw.len() > MAX_SSE_EVENT_BUFFER_BYTES { + let events = if self.opaque_frame || raw.len() > self.max_bytes { Vec::new() } else { std::str::from_utf8(&raw) .ok() - .and_then(|frame| parse_sse_events_inner(frame, self.stream_start).ok()) + .and_then(|frame| { + parse_sse_events_inner(frame, self.stream_start, self.max_bytes).ok() + }) .unwrap_or_default() }; self.stream_start = false; @@ -430,10 +446,14 @@ impl EventBuilder { /// 解析 SSE 事件流 pub fn parse_sse_events(input: &str) -> Result, SseError> { - parse_sse_events_inner(input, true) + parse_sse_events_inner(input, true, MAX_SSE_EVENT_BUFFER_BYTES) } -fn parse_sse_events_inner(input: &str, strip_leading_bom: bool) -> Result, SseError> { +fn parse_sse_events_inner( + input: &str, + strip_leading_bom: bool, + max_bytes: usize, +) -> Result, SseError> { let mut events = Vec::new(); let mut builder = EventBuilder::default(); let mut saw_sse_syntax = false; @@ -453,7 +473,7 @@ fn parse_sse_events_inner(input: &str, strip_leading_bom: bool) -> Result bool { sse_field_value_is_single_line(value) && !value.contains('\0') } -fn track_event_buffer_bytes(current_bytes: &mut usize, line: &str) -> Result<(), SseError> { +fn track_event_buffer_bytes( + current_bytes: &mut usize, + line: &str, + max_bytes: usize, +) -> Result<(), SseError> { let line_separator_bytes = usize::from(*current_bytes != 0); *current_bytes = current_bytes .saturating_add(line_separator_bytes) .saturating_add(line.len()); - if *current_bytes > MAX_SSE_EVENT_BUFFER_BYTES { - return Err(SseError::BufferExceeded { - max_bytes: MAX_SSE_EVENT_BUFFER_BYTES, - }); + if *current_bytes > max_bytes { + return Err(SseError::BufferExceeded { max_bytes }); } Ok(()) } diff --git a/backend/crates/gateway-protocol/tests/genai/messages.rs b/backend/crates/gateway-protocol/tests/genai/messages.rs index cfec6db94..d56aa23b9 100644 --- a/backend/crates/gateway-protocol/tests/genai/messages.rs +++ b/backend/crates/gateway-protocol/tests/genai/messages.rs @@ -228,3 +228,22 @@ fn empty_client_placeholders_do_not_change_message_roles_or_system_content() { let invalid = json!({"messages":[{"role":"system","content":"instructions"}]}); assert!(messages_to_genai_request(invalid.as_object().unwrap()).is_err()); } + +#[test] +fn messages_tool_result_documents_use_native_response_parts() { + let request = json!({"messages":[ + {"role":"assistant","content":[{"type":"tool_use","name":"read","id":"c","input":{}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"c","content":[ + {"type":"document","source":{"type":"text","data":"caption"}}, + {"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}} + ]}]} + ]}); + let body = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + body["contents"][1]["parts"][0], + json!({"functionResponse":{ + "name":"read","id":"c","response":{"output":"caption"}, + "parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}] + }}) + ); +} diff --git a/backend/crates/gateway-protocol/tests/genai/responses.rs b/backend/crates/gateway-protocol/tests/genai/responses.rs index 949a3d1ef..15fd20cd0 100644 --- a/backend/crates/gateway-protocol/tests/genai/responses.rs +++ b/backend/crates/gateway-protocol/tests/genai/responses.rs @@ -110,3 +110,64 @@ fn content_and_json_schema_preserve_their_target_representation() { json!({"responseMimeType":"application/json","responseSchema":request["text"]["format"]["schema"]}) ); } + +#[test] +fn parallel_tool_results_keep_call_order_and_native_media() { + let request = json!({"input":[ + {"type":"custom_tool_call","call_id":"a","name":"display","namespace":"screen","input":"shot"}, + {"type":"function_call","call_id":"b","name":"lookup","arguments":"{}"}, + {"type":"function_call_output","call_id":"b","output":{"value":2}}, + {"type":"custom_tool_call_output","call_id":"a","output":"stale"}, + {"type":"custom_tool_call_output","call_id":"a","status":"incomplete","output":[ + {"type":"input_text","text":"captured"}, + {"type":"input_image","image_url":"data:image/png;base64,AA=="}, + {"type":"input_file","file_data":"data:application/pdf;base64,AQ=="} + ]} + ], "tools":[{"type":"namespace","name":"screen","tools":[{"type":"custom","name":"display"}]}], + "tool_choice":{"type":"custom","name":"display","namespace":"screen"}}); + let body = responses_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"], + json!(["screen__display"]) + ); + assert_eq!( + body["contents"][1]["parts"], + json!([ + {"functionResponse":{"id":"a","name":"screen__display","response":{"error":"captured"},"parts":[ + {"inlineData":{"mimeType":"image/png","data":"AA=="}},{"inlineData":{"mimeType":"application/pdf","data":"AQ=="}} + ]}}, + {"functionResponse":{"id":"b","name":"lookup","response":{"output":{"value":2}}}} + ]) + ); +} + +#[test] +fn late_tool_results_remain_in_user_order_and_do_not_close_earlier_turns() { + let request = json!({"input":[ + {"type":"function_call","name":"tool","call_id":"a","arguments":"{}"}, + {"role":"user","content":"continue"}, + {"role":"assistant","content":"ok"}, + {"role":"user","content":"before"}, + {"type":"reasoning","summary":[],"encrypted_content":"opaque-other-model"}, + {"type":"function_call_output","call_id":"a","output":[{"type":"input_text","text":"late"}]}, + {"role":"user","content":"after"} + ]}); + let body = responses_to_genai_request(request.as_object().unwrap()).unwrap(); + assert!(body["contents"][1]["parts"][0]["functionResponse"]["response"]["error"].is_string()); + assert_eq!( + body["contents"][3]["parts"], + json!([{"text":"before"},{"text":"late"},{"text":"after"}]) + ); +} + +#[test] +fn named_tool_selection_requires_the_declared_type_and_namespace() { + let function = json!({"type":"function","name":"read"}); + for choice in [ + json!({"type":"function","name":"read","namespace":"missing"}), + json!({"type":"custom","name":"read"}), + ] { + let request = json!({"input":"read","tools":[function],"tool_choice":choice}); + assert!(responses_to_genai_request(request.as_object().unwrap()).is_err()); + } +} diff --git a/backend/crates/gateway-protocol/tests/openai/sse.rs b/backend/crates/gateway-protocol/tests/openai/sse.rs index fbbf43b01..005782d08 100644 --- a/backend/crates/gateway-protocol/tests/openai/sse.rs +++ b/backend/crates/gateway-protocol/tests/openai/sse.rs @@ -553,3 +553,25 @@ fn frame_end_should_support_lf_and_crlf_boundaries() { [Some(11), Some(13), None, Some(11), Some(13)] ); } + +#[test] +fn upstream_event_limit_applies_to_complete_and_fragmented_data() { + for chunks in [ + vec![&b"data: abc\n\n"[..]], + vec![&b"data: "[..], &b"abc\n\n"[..]], + ] { + let mut small = SseEventDecoder::with_max_event_bytes(8); + let mut exact = SseEventDecoder::with_max_event_bytes(9); + for chunk in &chunks[..chunks.len() - 1] { + assert!(small.push(chunk).unwrap().is_empty()); + assert!(exact.push(chunk).unwrap().is_empty()); + } + let last = chunks.last().unwrap(); + assert!(matches!( + small.push(last), + Err(SseError::BufferExceeded { max_bytes: 8 }) + )); + assert_eq!(exact.push(last).unwrap()[0].data, "abc"); + assert_eq!(exact.push(b"data: def\n\n").unwrap()[0].data, "def"); + } +} diff --git a/backend/crates/providers/antigravity/src/admin/provider.rs b/backend/crates/providers/antigravity/src/admin/provider.rs index f70039110..617eaa87c 100644 --- a/backend/crates/providers/antigravity/src/admin/provider.rs +++ b/backend/crates/providers/antigravity/src/admin/provider.rs @@ -72,6 +72,7 @@ impl ProviderAdmin for AntigravityAdmin { credential_export: oauth, quota: oauth, quota_refresh: oauth, + quota_credits: oauth, ..Default::default() } } diff --git a/backend/crates/providers/antigravity/src/credential/quota/document.rs b/backend/crates/providers/antigravity/src/credential/quota/document.rs index f33099728..b4c5de7b2 100644 --- a/backend/crates/providers/antigravity/src/credential/quota/document.rs +++ b/backend/crates/providers/antigravity/src/credential/quota/document.rs @@ -2,11 +2,11 @@ use crate::transport::{ Catalog, - account::{ModelQuota, QuotaGroup, QuotaSummary, Tier}, + account::{Credit, ModelQuota, QuotaGroup, QuotaSummary, Tier}, }; use chrono::{DateTime, Utc}; use gateway_admin::model::provider_credentials::{ - ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution, + ProviderQuota, ProviderQuotaCredits, ProviderQuotaWindow, QuotaLocalUsageAttribution, }; use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState}; use serde::{Deserialize, Serialize}; @@ -95,9 +95,30 @@ impl ModelQuota { } impl Document { + fn credit(&self) -> Option<&Credit> { + self.tier + .as_ref()? + .available_credits + .iter() + .find(|c| c.is_google_one()) + } + + pub(super) fn access_with_credits( + &self, + state: QuotaState, + enabled: bool, + observed: SystemTime, + ) -> QuotaState { + if enabled && state.is_exhausted() && self.credit().is_some_and(Credit::usable) { + QuotaState::credits_only(observed, state.reset_at()) + } else { + state + } + } pub(super) fn model_observation( &self, model: &str, + use_credits: bool, observed_at: SystemTime, now: SystemTime, ) -> Option { @@ -119,7 +140,10 @@ impl Document { } else { QuotaState::allowed(observed_at) }; - Some(gateway_admin::ports::provider::ProviderPeerModelQuota { state, valid_until }) + Some(gateway_admin::ports::provider::ProviderPeerModelQuota { + state: self.access_with_credits(state, use_credits, observed_at), + valid_until, + }) } pub(super) fn plan_type(&self) -> Option { self.tier @@ -159,6 +183,7 @@ impl Document { pub(super) fn model_signals( &self, model: &str, + use_credits: bool, observed: SystemTime, now: SystemTime, ) -> (bool, Option) { @@ -172,7 +197,7 @@ impl Document { let remaining = quota.remaining(); let reset = quota.reset_time.map(SystemTime::from); ( - remaining == Some(0.0), + remaining == Some(0.0) && !(use_credits && self.credit().is_some_and(Credit::usable)), Some(AccountQuotaSignals::new( reset, remaining.map(|v| (v * 10_000.0).round() as u64), @@ -220,6 +245,11 @@ impl Document { } } ProviderQuota { + credits: self.credit().map(|credit| ProviderQuotaCredits { + has_credits: credit.usable(), + unlimited: false, + balance: credit.balance().map(|v| v.to_string()), + }), limit_reached: self.access(observed).is_exhausted(), plan_type: self.plan_type(), observed_at: Some(DateTime::::from(observed)), diff --git a/backend/crates/providers/antigravity/src/credential/quota/service.rs b/backend/crates/providers/antigravity/src/credential/quota/service.rs index e2cf62eff..5498ec0e5 100644 --- a/backend/crates/providers/antigravity/src/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/src/credential/quota/service.rs @@ -49,7 +49,7 @@ impl QuotaService { let authorized: BTreeMap<_, _> = accounts .iter() .filter(|a| a.provider_kind == self.kind && a.authentication_kind == "oauth") - .map(|a| (a.id.as_str(), a.credential_revision.get())) + .map(|a| (a.id.as_str(), a)) .collect(); let ids = authorized .keys() @@ -72,9 +72,12 @@ impl QuotaService { let now = SystemTime::now(); for (owners, catalog) in catalogs { for owner in owners { - if authorized.get(owner.account_id.as_str()) != Some(&owner.revision.get()) { + let Some(account) = authorized + .get(owner.account_id.as_str()) + .filter(|a| a.credential_revision.get() == owner.revision.get()) + else { continue; - } + }; let observation = quotas .get(&owner.account_id) .filter(|q| q.expected_revision == owner.revision); @@ -83,9 +86,14 @@ impl QuotaService { .models .keys() .map(|model| { - let quota = observation - .zip(document.as_ref()) - .and_then(|(o, d)| d.model_observation(model, o.observed_at, now)); + let quota = observation.zip(document.as_ref()).and_then(|(o, d)| { + d.model_observation( + model, + account.auto_use_quota_credits, + o.observed_at, + now, + ) + }); (model.clone(), quota) }) .collect(); @@ -201,7 +209,11 @@ impl QuotaService { ), plan_type: plan.clone(), observed_at, - state: doc.access(observed_at), + state: doc.access_with_credits( + doc.access(observed_at), + current.account.auto_use_quota_credits(), + observed_at, + ), }; if self .accounts @@ -230,18 +242,25 @@ impl QuotaService { model: &str, ) -> Result)>, ProviderAdminError> { - let revisions: BTreeMap<_, _> = accounts - .iter() - .map(|a| (a.id().clone(), a.revision())) - .collect(); - let ids: Vec<_> = revisions.keys().cloned().collect(); + let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect(); + let ids: Vec<_> = owners.keys().cloned().collect(); let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?; let now = SystemTime::now(); observations .into_iter() - .filter(|o| revisions.get(&o.account_id) == Some(&o.expected_revision)) - .map(|o| { - let result = parse(&o)?.model_signals(model, o.observed_at, now); + .filter_map(|o| { + owners + .get(&o.account_id) + .filter(|a| a.revision() == o.expected_revision) + .map(|account| (o, account)) + }) + .map(|(o, account)| { + let result = parse(&o)?.model_signals( + model, + account.auto_use_quota_credits(), + o.observed_at, + now, + ); Ok((o.account_id, result)) }) .collect() diff --git a/backend/crates/providers/antigravity/src/provider/affinity.rs b/backend/crates/providers/antigravity/src/provider/affinity.rs index c31a159bc..e1ad46565 100644 --- a/backend/crates/providers/antigravity/src/provider/affinity.rs +++ b/backend/crates/providers/antigravity/src/provider/affinity.rs @@ -52,6 +52,17 @@ pub(super) fn session_key( ProviderSessionAffinityKey::try_new(hex::encode(hash.finalize())).ok() } +// AGY 使用 FNV-1a 64 位有符号十进制串,网关从隔离后的会话键派生 +pub(super) fn upstream_session_id(key: &ProviderSessionAffinityKey) -> String { + let hash = key + .expose_to_store() + .bytes() + .fold(0xcbf29ce484222325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3) + }); + (hash as i64).to_string() +} + fn header(context: &Map, name: &str) -> Option { context .get("headers") diff --git a/backend/crates/providers/antigravity/src/provider/execution.rs b/backend/crates/providers/antigravity/src/provider/execution.rs index 0b722ca63..c3f362556 100644 --- a/backend/crates/providers/antigravity/src/provider/execution.rs +++ b/backend/crates/providers/antigravity/src/provider/execution.rs @@ -89,7 +89,8 @@ impl AntigravityProvider { .and_then(|models| models.get(model.as_str())), ); // AGY 没有可跨轮引用的响应,Responses WS 客户端可在新连接上直接发送完整输入 - let reconnect_websocket = ctx.client_transport() == ClientTransport::WebSocket + let transport = ctx.client_transport(); + let reconnect_websocket = transport == ClientTransport::WebSocket && request.operation().protocol() == gateway_protocol::openai::OPENAI_PROTOCOL; ctx.execute_middleware( request.operation().clone(), @@ -100,7 +101,7 @@ impl AntigravityProvider { if operation.requires_web_search() != search { return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection.")); } - let (operation, translator) = super::translation::prepare(operation)?; + let (operation, translator) = super::translation::prepare(operation, transport, affinity.as_ref())?; let headers = crate::transport::request_headers(&operation, headers, selected.account_switch); if operation.protocol() != GENAI_PROTOCOL { return Err(unsent(Kind::Unsupported)); diff --git a/backend/crates/providers/antigravity/src/provider/translation.rs b/backend/crates/providers/antigravity/src/provider/translation.rs index 139aebc6e..023cfe54e 100644 --- a/backend/crates/providers/antigravity/src/provider/translation.rs +++ b/backend/crates/providers/antigravity/src/provider/translation.rs @@ -4,11 +4,13 @@ use crate::transport::{sent, unsent}; use gateway_core::{ engine::{ ModelRequestId, + execution::ClientTransport, provider::{LocalWebSocketPrewarm, NativeResponseTranslator}, }, error::{ClientVisibleUpstreamError, ProviderError, ProviderErrorKind}, event::ProtocolWireEvent, operation::{Operation, ProtocolPayload}, + provider_ports::ProviderSessionAffinityKey, upstream::UpstreamSendState, }; use gateway_protocol::{ @@ -100,6 +102,8 @@ pub(super) fn validate_request_mode(operation: &Operation) -> Result<(), Provide pub(super) fn prepare( operation: Operation, + transport: ClientTransport, + affinity: Option<&ProviderSessionAffinityKey>, ) -> Result<(Operation, Option), ProviderError> { if matches!(operation, Operation::CountTokens(_)) { return prepare_count(operation); @@ -124,7 +128,7 @@ pub(super) fn prepare( } else { None }; - let body = if let Some(tool) = search { + let mut body = if let Some(tool) = search { super::web_search::request(original, tool)? } else { if source == OPENAI_PROTOCOL { @@ -134,6 +138,12 @@ pub(super) fn prepare( } .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))? }; + if let Some(session) = affinity { + body.insert( + "sessionId".into(), + json!(super::affinity::upstream_session_id(session)), + ); + } let model = original .get("model") .and_then(Value::as_str) @@ -149,8 +159,16 @@ pub(super) fn prepare( })) }; let mut context = payload.context().clone(); - // Desktop 搜索使用完整 JSON,编码路径保留增量交付 - context.insert("stream".into(), json!(search.is_none())); + // HTTP 和 WS 的交付模式在入口已确定,内部探测默认保留首输出观测 + let stream = match transport { + ClientTransport::HttpJson => false, + ClientTransport::HttpSse | ClientTransport::WebSocket => true, + ClientTransport::InternalProbe | ClientTransport::InternalPlugin => original + .get("stream") + .and_then(Value::as_bool) + .unwrap_or(true), + }; + context.insert("stream".into(), json!(search.is_none() && stream)); let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; let operation = operation .replace_protocol_wire(None, context) @@ -222,13 +240,13 @@ impl NativeResponseTranslator for Translator { if let Self::Search(search) = self { return search.translate(event); } + let value = match event.raw_json_body() { + Some(raw) => Cow::Owned( + serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?, + ), + None => Cow::Borrowed(event.data()), + }; let Self::Generate(translator) = self else { - let value = match event.raw_json_body() { - Some(raw) => Cow::Owned( - serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?, - ), - None => Cow::Borrowed(event.data()), - }; let body = if self.target_protocol() == ANTHROPIC_PROTOCOL { gateway_protocol::genai::count_tokens_to_messages(&value) .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))? @@ -242,7 +260,7 @@ impl NativeResponseTranslator for Translator { }; let events = translator .genai - .push(event.data()) + .push(&value) .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?; translator.events(events) } diff --git a/backend/crates/providers/antigravity/src/transport/account.rs b/backend/crates/providers/antigravity/src/transport/account.rs index 5262dfc24..9b91888d4 100644 --- a/backend/crates/providers/antigravity/src/transport/account.rs +++ b/backend/crates/providers/antigravity/src/transport/account.rs @@ -19,6 +19,49 @@ pub(crate) struct Tier { pub(crate) id: String, #[serde(default)] pub(crate) name: String, + #[serde( + default, + rename = "availableCredits", + skip_serializing_if = "Vec::is_empty" + )] + pub(crate) available_credits: Vec, +} + +pub(crate) const GOOGLE_ONE_AI: &str = "GOOGLE_ONE_AI"; + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Credit { + #[serde(default)] + credit_type: serde_json::Value, + #[serde(default)] + credit_amount: serde_json::Value, + #[serde(default)] + minimum_credit_amount_for_usage: serde_json::Value, +} + +impl Credit { + pub(crate) fn is_google_one(&self) -> bool { + self.credit_type == GOOGLE_ONE_AI || self.credit_type.as_u64() == Some(1) + } + // protobuf 的 int64 通常编码成十进制字符串 + fn amount(value: &serde_json::Value) -> Option { + let amount = value.as_i64().or_else(|| value.as_str()?.parse().ok())?; + u64::try_from(amount).ok() + } + pub(crate) fn balance(&self) -> Option { + Self::amount(&self.credit_amount) + } + pub(crate) fn usable(&self) -> bool { + let minimum = if self.minimum_credit_amount_for_usage.is_null() { + Some(0) + } else { + Self::amount(&self.minimum_credit_amount_for_usage) + }; + self.balance() + .zip(minimum) + .is_some_and(|(balance, minimum)| balance > 0 && balance >= minimum) + } } #[derive(Clone, Serialize, Deserialize)] @@ -56,6 +99,7 @@ impl CloudCodeClient { pub(crate) async fn account_info(&self, token: &str) -> Result { let info: AccountInfo = control( self.post("loadCodeAssist", token) + .timeout(std::time::Duration::from_secs(15)) .json(&json!({"metadata":{}})), token, ) @@ -75,6 +119,7 @@ impl CloudCodeClient { ) -> Result { control( self.post("retrieveUserQuotaSummary", token) + .timeout(std::time::Duration::from_secs(15)) .json(&json!({"project":project})), token, ) diff --git a/backend/crates/providers/antigravity/src/transport/client.rs b/backend/crates/providers/antigravity/src/transport/client.rs index c2552023b..7ac644f31 100644 --- a/backend/crates/providers/antigravity/src/transport/client.rs +++ b/backend/crates/providers/antigravity/src/transport/client.rs @@ -19,6 +19,7 @@ static SEARCH_INSTRUCTION: std::sync::LazyLock<&RawValue> = std::sync::LazyLock: serde_json::from_str(r#"{"parts":[{"text":"Search the web for the query and return a concise answer grounded in the sources."}]}"#).expect("valid static search instruction") }); +const GENERATION_TIMEOUT: Duration = Duration::from_secs(600); const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024; #[derive(Serialize, Deserialize)] @@ -66,6 +67,7 @@ pub(crate) struct CloudCodeClient { client: Client, origin: Url, system_instruction: Box, + use_quota_credits: bool, } impl CloudCodeClient { @@ -74,7 +76,7 @@ impl CloudCodeClient { proxy: Option<&OutboundProxy>, profile: &ClientProfile, ) -> Result { - Self::with_client(origin, Self::build_client(proxy, profile)?, profile) + Self::with_client(origin, Self::build_client(proxy, profile)?, profile, false) } pub(super) fn build_client( @@ -87,6 +89,8 @@ impl CloudCodeClient { .use_rustls_tls() .http1_only() .http1_title_case_headers() + .pool_max_idle_per_host(100) + .read_timeout(GENERATION_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .retry(reqwest::retry::never()) .user_agent(profile.user_agent()) @@ -100,10 +104,12 @@ impl CloudCodeClient { origin: &Url, client: Client, profile: &ClientProfile, + use_quota_credits: bool, ) -> Result { Ok(Self { client, origin: origin.clone(), + use_quota_credits, system_instruction: RawValue::from_string( json!({"parts":[{"text":profile.system_prompt}]}).to_string(), ) @@ -140,6 +146,7 @@ impl CloudCodeClient { } let models: Models = control( self.post("fetchAvailableModels", token) + .timeout(Duration::from_secs(20)) .json(&json!({"project":project})), token, ) @@ -174,6 +181,8 @@ impl CloudCodeClient { model: &'a str, #[serde(rename = "requestType", skip_serializing_if = "Option::is_none")] request_type: Option<&'static str>, + #[serde(rename = "enabledCreditTypes", skip_serializing_if = "Option::is_none")] + enabled_credit_types: Option<[&'static str; 1]>, request: BTreeMap, } let instruction = if mode == GenerateMode::WebSearch { @@ -189,13 +198,20 @@ impl CloudCodeClient { "text/event-stream", ) } else { - (self.post("generateContent", token), "application/json") + ( + self.post("generateContent", token) + .timeout(GENERATION_TIMEOUT), + "application/json", + ) }; self.send( send.json(&Envelope { project, model, request_type: (mode == GenerateMode::WebSearch).then_some("web_search"), + enabled_credit_types: self + .use_quota_credits + .then_some([super::account::GOOGLE_ONE_AI]), request, }), token, @@ -227,6 +243,7 @@ impl CloudCodeClient { } self.send( self.post("countTokens", token) + .timeout(GENERATION_TIMEOUT) .json(&json!({"request":request})), token, headers, @@ -284,13 +301,7 @@ pub(super) async fn control( token: &str, ) -> Result { let mut response = successful( - super::response::decode( - request - .timeout(Duration::from_secs(15)) - .send() - .await - .map_err(network)?, - ), + super::response::decode(request.send().await.map_err(network)?), token, ) .await?; diff --git a/backend/crates/providers/antigravity/src/transport/pool.rs b/backend/crates/providers/antigravity/src/transport/pool.rs index 084397bed..717f754ff 100644 --- a/backend/crates/providers/antigravity/src/transport/pool.rs +++ b/backend/crates/providers/antigravity/src/transport/pool.rs @@ -59,6 +59,6 @@ impl ClientPool { } drop(clients); // 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值 - CloudCodeClient::with_client(origin, client, profile) + CloudCodeClient::with_client(origin, client, profile, account.auto_use_quota_credits()) } } diff --git a/backend/crates/providers/antigravity/src/transport/response.rs b/backend/crates/providers/antigravity/src/transport/response.rs index 8e58de03d..b389a67da 100644 --- a/backend/crates/providers/antigravity/src/transport/response.rs +++ b/backend/crates/providers/antigravity/src/transport/response.rs @@ -76,7 +76,7 @@ pub(crate) fn events( let observation = ProviderResponseObservation::new( UpstreamTransport::new("http").map_err(|_| sent(Kind::ProviderInfrastructureUnavailable))?, ).with_status_code(response.status().as_u16()); - let mut decoder = SseEventDecoder::default(); + let mut decoder = SseEventDecoder::with_max_event_bytes(256 * 1024 * 1024); let mut json_body = Vec::new(); let mut observed = GenerateContentObservation::default(); let mut started = None; diff --git a/backend/crates/providers/antigravity/tests/credential/quota/service.rs b/backend/crates/providers/antigravity/tests/credential/quota/service.rs index 4eb7c18b4..93ffed203 100644 --- a/backend/crates/providers/antigravity/tests/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/tests/credential/quota/service.rs @@ -423,3 +423,72 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() { .is_empty() ); } + +#[tokio::test] +async fn google_one_credits_require_opt_in_and_sufficient_balance() { + use crate::support::{context, request}; + use futures::TryStreamExt; + use gateway_core::engine::provider::Provider; + for (balance, usable) in [("9", false), ("10", true)] { + let server = MockServer::start().await; + Mock::given(path("/v1internal:loadCodeAssist")).respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "cloudaicompanionProject":"p","paidTier":{"id":"g1-pro-tier","availableCredits":[ + {"creditType":"GOOGLE_ONE_AI","creditAmount":balance,"minimumCreditAmountForUsage":"10"}]} + }))).mount(&server).await; + Mock::given(path("/v1internal:fetchAvailableModels")).respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "models":{"fixture-model":{"displayName":"Gemini","quotaInfo":{"remainingFraction":0,"resetTime":"2099-01-01T00:00:00Z"}}} + }))).mount(&server).await; + Mock::given(path("/v1internal:retrieveUserQuotaSummary")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"groups":[]}))) + .mount(&server) + .await; + Mock::given(path("/v1internal:generateContent")).and(wiremock::matchers::body_partial_json(json!({"enabledCreditTypes":["GOOGLE_ONE_AI"]}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}))) + .expect(u64::from(usable)).mount(&server).await; + let fixture = Fixture::new(&server.uri()); + let primary = fixture.store.primary(); + for enabled in [false, true, false] { + let account = { + let mut loaded = primary.loaded.lock().unwrap(); + loaded.account = loaded.account.clone().with_auto_use_quota_credits(enabled); + loaded.account.clone() + }; + fixture.quota.refresh(account.id()).await.unwrap(); + let credits = fixture + .quota + .read(account.id()) + .await + .unwrap() + .credits + .unwrap(); + assert_eq!(credits.balance.as_deref(), Some(balance)); + assert_eq!(credits.has_credits, usable); + let (blocked, _) = fixture + .quota + .scheduling(std::slice::from_ref(&account), "fixture-model") + .await + .unwrap() + .remove(account.id()) + .unwrap(); + assert_eq!(blocked, !(enabled && usable)); + let result = fixture + .provider + .clone() + .execute( + request(false), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await; + if enabled && usable { + result.unwrap().try_collect::>().await.unwrap(); + } else { + assert!(result.is_err()); + } + } + } +} diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index a77920e57..b8557bbac 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -325,12 +325,20 @@ async fn model_group_menu_routes_responses_and_native_generation_to_declared_mem released(&fixture).await; } Mock::given(path("/v1internal:streamGenerateContent")) - .and(body_partial_json(json!({"model":"gemini-4-hydrogen-high","request":{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]}]}}))) + .and(body_partial_json(json!({"model":"gemini-4-hydrogen-high","request":{"contents":[ + {"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]}, + {"role":"model","parts":[{"functionCall":{"name":"capture","id":"c","args":{}}}]}, + {"role":"user","parts":[{"functionResponse":{"name":"capture","id":"c","response":{"output":"ok"},"parts":[{"inlineData":{"mimeType":"image/png","data":"AQ=="}}]}}]} + ]}}))) .respond_with(ResponseTemplate::new(200).set_body_raw( "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}}\n\n", "text/event-stream", )).expect(1).mount(&upstream).await; - let body = json!({"model":group.upstream_model().as_str(),"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}],"reasoning":{"effort":"high"}}); + let body = json!({"model":group.upstream_model().as_str(),"input":[ + {"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}, + {"type":"function_call","name":"capture","call_id":"c","arguments":"{}"}, + {"type":"function_call_output","call_id":"c","output":[{"type":"input_text","text":"ok"},{"type":"input_image","image_url":"data:image/png;base64,AQ=="}]} + ],"reasoning":{"effort":"high"}}); let operation = Operation::Generate(GenerateRequest::from_protocol_payload( ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(), )); @@ -735,10 +743,21 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() { "data: {\"response\":{\"responseId\":\"r\",\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n", "data: {\"response\":{\"usageMetadata\":{\"promptTokenCount\":7,\"candidatesTokenCount\":2}}}\n\n" ),"text/event-stream")).expect(3).mount(&upstream).await; - let responses = json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8,"tools":[{"type":"function","name":"pwd","parameters":{"type":"object"}}],"tool_choice":"required","text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}); + Mock::given(method("POST")).and(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{ + "responseId":"r", "candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}], + "usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":2} + }}))).expect(2).mount(&upstream).await; + let responses = json!({"model":"fixture-model","client_metadata":{"session_id":"same-conversation"},"input":"hello","max_output_tokens":100,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8,"tools":[{"type":"function","name":"pwd","parameters":{"type":"object"}}],"tool_choice":"required","text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}); for (protocol, transport, body) in [ ("openai", ClientTransport::WebSocket, responses.clone()), + ("openai", ClientTransport::HttpJson, responses.clone()), ("openai", ClientTransport::HttpSse, responses), + ( + "anthropic", + ClientTransport::HttpJson, + json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"max_tokens":100}), + ), ( "anthropic", ClientTransport::HttpSse, @@ -794,6 +813,21 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() { ); let sent = upstream.received_requests().await.unwrap(); let body: serde_json::Value = serde_json::from_slice(&sent.last().unwrap().body).unwrap(); + let http_json = transport == ClientTransport::HttpJson; + assert_eq!( + sent.last().unwrap().url.path(), + if http_json { + "/v1internal:generateContent" + } else { + "/v1internal:streamGenerateContent" + } + ); + if protocol == "openai" { + assert_eq!(body["request"]["sessionId"], "-6977519665959570574"); + } else { + assert!(body["request"].get("sessionId").is_none()); + } + assert!(body.get("enabledCreditTypes").is_none()); assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100); assert_eq!( body["request"]["systemInstruction"]["parts"][0]["text"], diff --git a/docs/api.md b/docs/api.md index 351d76172..ae94d29e6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1388,6 +1388,8 @@ OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `PO - 开启后,上游确认 `hasCredits=true` 或 `unlimited=true` 且没有支出限制时,允许靠点数继续请求;余额数字本身不能证明可用 - 对已耗尽账号开启时复查额度;关闭时立即撤销仅靠点数的放行 +Antigravity OAuth 账号开启后,生成请求携带 `enabledCreditTypes: ["GOOGLE_ONE_AI"]`。套餐额度耗尽时,调度同时检查 Google 返回的点数余额和最低使用门槛。计数调用不使用点数 + 点数不解除凭据错误、停用或冷却,也不触发对已被上游拒绝请求的重发 账号名称是本地显示信息,与账号 ID、上游邮箱和凭据独立。编辑接口的可选 `name` 省略或为 `null` 时保留原值; @@ -2540,7 +2542,7 @@ Guardian 以 `subagent_kind` 或 `client_metadata.x-openai-subagent` 值 `guardi - `strict` 优先同一账号,启用账号排队时等待繁忙的绑定账号,关闭排队、绑定失效或允许换号时重新绑定 Antigravity 原生 GenAI 请求使用 `X-Http-Session-Id`,缺失时使用 `X-Session-Id`;这些头只作为会话标识 -Responses 和 Messages 转入 Antigravity 时分别复用 Codex 逻辑会话和 Claude Code 会话解析,在转换前按 Client Key、模型及入站协议隔离绑定 +Responses 和 Messages 转入 Antigravity 时分别复用 Codex 逻辑会话和 Claude Code 会话解析,在转换前按 Client Key、模型及入站协议隔离绑定,发给 Google 的 `sessionId` 从该绑定键派生 无显式会话及计数请求不建立绑定。账号资格失效后按调度策略重选,凭据、额度、模型目录和权限仍由 Antigravity 检查 xAI 沿用自身显式会话及对话开头的识别规则,按 Client Key 和模型隔离绑定 diff --git a/docs/architecture.md b/docs/architecture.md index 2705ffd61..8b0a0c4d3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -580,13 +580,15 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模 GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 和 Messages 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算 -Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用 Messages 的内容与工具映射,生成参数直接映射到 GenAI,不继承 Messages 的默认值与模型限制;Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则 +Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 与 Messages 各自构造 GenAI 请求,共用签名回放和多模态工具结果编码。Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则 Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属 推理 HTTP 客户端按账号、凭据版本、代理和 UA 隔离,最多缓存 64 项并按最近使用淘汰;在途请求持有独立客户端引用,令牌、项目和系统指令不随连接池缓存 -Antigravity 的 Cloud Code 传输固定使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间 +Antigravity 的 Cloud Code 传输按下游生成模式选择普通 JSON 或 SSE。HTTP 非流式调用使用 `generateContent`,SSE 和 WebSocket 使用 `streamGenerateContent`,独立搜索使用普通 JSON + +Cloud Code 连接使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间 跨协议响应在 Core 的响应中间件阶段之间转换。转换器在正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态。转换状态随单次流释放,不增加账号级签名缓存或对话副本 @@ -790,7 +792,7 @@ OpenAI 与 Antigravity 的内置 `round_robin` 在最高可调度权重层按账 分配游标只读,取得租约后通过共享准入接口推进;有会话认领时,游标和绑定原子提交,冲突先释放租约再重选 亲和命中、保留主绑定的临时分流、固定账号和插件显式选号不消耗轮询位置;插件委托仍参与内置轮询 -Antigravity 在转换前识别 GenAI 会话头及正文 `sessionId`/`session_id`(头优先)、Codex 逻辑会话和 Claude Code 会话,绑定按 Client Key、模型和入站协议隔离 +Antigravity 在转换前识别 GenAI 会话头及正文 `sessionId`/`session_id`(头优先)、Codex 逻辑会话和 Claude Code 会话,绑定按 Client Key、模型和入站协议隔离。转换请求从绑定键派生 Cloud Code 的 `sessionId` xAI 继续从自身请求身份派生模型级亲和键,共用版本绑定及 TTL;上游 session ID 和推理重放身份仍由传输模块持有 两者的优先模式在容量分流时保留合格的主绑定,绑定不再满足当前资格时迁移;严格模式等待繁忙主账号,关闭排队或资格失效时允许重选 原生固定账号请求不改写已有主绑定,诊断请求和没有亲和键的请求不访问绑定存储