fix(antigravity): repair IDs for same-name parallel tools (#849)

Pair ID-less calls and results by tool name and GenAI ordering when
counts match. Preserve ambiguous groups and existing raw JSON fields.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
authored and GitHub committed 2026-12-04 21:21:02 +08:00
1 parent 8d4b0496e2
commit 6bf182677a
3 files changed
+110 -53

No files matched your search

@@ -1,4 +1,4 @@
//! 为 Claude 原生生成补齐能唯一配对的工具 ID,保留其余原始 JSON 字节
//! 按 GenAI 工具关联规则为 Claude 原生生成补齐 ID,保留其余原始 JSON 字节
use std::{borrow::Cow, collections::BTreeMap};
@@ -83,15 +83,14 @@ fn tools<'a>(content: &Content<'a>) -> Option<Vec<Tool<'a>>> {
}
#[derive(Default)]
struct Pair {
call: Option<usize>,
response: Option<usize>,
ambiguous: bool,
struct ToolGroup<'a> {
calls: Vec<&'a Tool<'a>>,
responses: Vec<&'a Tool<'a>>,
}
pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::Error> {
// AGY CLI 1.5.20 的 convertToVertexV1 清空两侧 ID,见 #807
// https://github.com/zyycn/codex-proxy-rs/issues/807
// AGY CLI / ACP 1.5.24 的 Gateway/GenAI 路径仍清空两侧 ID,见 #807、#848
// https://github.com/zyycn/codex-proxy-rs/issues/848
// 客户端恢复保留 ID 后移除此补偿;不为格式错误或有歧义的历史猜测关联
let Ok(request) = serde_json::from_str::<Request<'_>>(body.get()) else {
return Ok(body);
@@ -118,48 +117,62 @@ pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::E
}
let calls = &turns[turn];
let responses = &turns[turn + 1];
let mut pairs = BTreeMap::<&str, Pair>::new();
for (index, call) in calls.iter().enumerate() {
let pair = pairs.entry(&call.name).or_default();
pair.ambiguous |= pair.call.replace(index).is_some();
let mut groups = BTreeMap::<&str, ToolGroup<'_>>::new();
for call in calls {
groups.entry(&call.name).or_default().calls.push(call);
}
for (index, response) in responses.iter().enumerate() {
let pair = pairs.entry(&response.name).or_default();
pair.ambiguous |= pair.response.replace(index).is_some();
for response in responses {
groups
.entry(&response.name)
.or_default()
.responses
.push(response);
}
for pair in pairs.values().filter(|pair| !pair.ambiguous) {
let (Some(call), Some(response)) = (pair.call, pair.response) else {
for group in groups.values() {
if group.calls.len() != group.responses.len() {
continue;
};
let (call, response) = (&calls[call], &responses[response]);
let id = match (call.id.as_deref(), response.id.as_deref()) {
(Some(_), Some(_)) => continue,
(Some(id), None) | (None, Some(id)) => {
if ids.get(id) != Some(&1) {
continue;
}
id.to_owned()
}
(None, None) => {
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
while ids.contains_key(id.as_str()) {
id.push('_');
}
id
}
};
ids.insert(Cow::Owned(id.clone()), 2);
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
for tool in [call, response]
.into_iter()
.filter(|tool| tool.id.is_none())
}
// GenAI 无 ID 时按同名出现顺序配对;混有 ID 时可能按 ID 重排,不能套用顺序
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tools/function-calling#parallel_function_calling
if group.calls.len() > 1
&& group
.calls
.iter()
.chain(&group.responses)
.any(|tool| tool.id.is_some())
{
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
+ tool.raw.get().len()
- 1;
insertions.insert(end, insertion.clone());
continue;
}
for (call, response) in group.calls.iter().zip(&group.responses) {
let id = match (call.id.as_deref(), response.id.as_deref()) {
(Some(_), Some(_)) => continue,
(Some(id), None) | (None, Some(id)) => {
if ids.get(id) != Some(&1) {
continue;
}
id.to_owned()
}
(None, None) => {
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
while ids.contains_key(id.as_str()) {
id.push('_');
}
id
}
};
ids.insert(Cow::Owned(id.clone()), 2);
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
for tool in [call, response]
.into_iter()
.filter(|tool| tool.id.is_none())
{
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
+ tool.raw.get().len()
- 1;
insertions.insert(end, insertion.clone());
}
}
}
}
@@ -71,9 +71,9 @@ fn history(calls: Vec<Value>, responses: Vec<Value>) -> Value {
}
#[tokio::test]
async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
async fn missing_ids_pair_by_name_and_parallel_order_without_reencoding_business_fields() {
let (server, client) = client().await;
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}}]}]"#;
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}},{"text":"next"},{"functionCall":{"name":"lookup","args":{"key":"third"}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}},{"text":"next"},{"function_response":{"name":"lookup","response":{"output":"third"}}}]}]"#;
let body = format!(r#"{{"contents":{contents},"unknown":1e+09,"unknown":2}}"#);
for mode in [GenerateMode::Json, GenerateMode::Stream] {
let outgoing = generate(&server, &client, &body, "claude-opus-5-5-medium", mode).await;
@@ -84,8 +84,17 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
let second = value["contents"][0]["parts"][2]["function_call"]["id"]
.as_str()
.unwrap();
let third = value["contents"][0]["parts"][4]["functionCall"]["id"]
.as_str()
.unwrap();
assert!(!first.is_empty());
assert_ne!(first, second);
assert_ne!(first, third);
assert_ne!(second, third);
assert_eq!(
value["contents"][1]["parts"][3]["function_response"]["id"],
third
);
assert_eq!(
value["contents"][1]["parts"][1]["functionResponse"]["id"],
first
@@ -97,7 +106,8 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
let restored = outgoing
.get()
.replace(&format!(",\"id\":\"{first}\""), "")
.replace(&format!(",\"id\":\"{second}\""), "");
.replace(&format!(",\"id\":\"{second}\""), "")
.replace(&format!(",\"id\":\"{third}\""), "");
assert!(restored.contains(contents));
assert!(restored.contains(r#""unknown":1e+09,"unknown":2"#));
assert!(
@@ -116,11 +126,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
call("run", None),
call("read", Some("existing-call")),
call("lookup", None),
call("run", None),
],
vec![
response("lookup", Some("existing-result")),
response("read", None),
response("run", None),
response("run", None),
],
);
let first = generate(
@@ -147,6 +159,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
first_value["contents"][0]["parts"][2]["functionCall"]["id"],
"existing-result"
);
let parallel_id = &first_value["contents"][0]["parts"][3]["functionCall"]["id"];
assert!(parallel_id.as_str().is_some_and(|id| !id.is_empty()));
assert_ne!(parallel_id, id);
assert_eq!(
first_value["contents"][1]["parts"][3]["functionResponse"]["id"],
*parallel_id
);
let retry = generate(
&server,
&client,
@@ -185,8 +204,12 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
// 客户端已有的 ID 即使占用补偿命名空间,也不能和新配对共用
let collision = history(
vec![call("run", None), call("read", Some(id))],
vec![response("run", None), response("read", Some(id))],
vec![call("run", None), call("read", Some(id)), call("run", None)],
vec![
response("run", None),
response("read", Some(id)),
response("run", None),
],
);
let collision = generate(
&server,
@@ -213,12 +236,28 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
let mut cases = vec![
history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", None)],
vec![response("run", None)],
),
history(
vec![call("run", None)],
vec![response("run", None), response("run", None)],
),
history(
vec![call("run", Some("a")), call("run", None)],
vec![response("run", None), response("run", None)],
),
history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", Some("b"))],
),
history(
vec![call("run", Some("a")), call("run", None)],
vec![response("run", None), response("run", Some("a"))],
),
history(
vec![call("run", Some("a")), call("run", Some("b"))],
vec![response("run", Some("b")), response("run", Some("a"))],
),
history(vec![call("run", None)], vec![response("other", None)]),
history(
vec![call("run", Some("a"))],
@@ -257,7 +296,10 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
#[tokio::test]
async fn compatibility_is_limited_to_native_claude_generation() {
let (server, client) = client().await;
let body = history(vec![call("run", None)], vec![response("run", None)]);
let body = history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", None)],
);
for (model, mode) in [
("gemini-4-hydrogen", GenerateMode::Json),
(
+3 -1
View File
@@ -276,7 +276,9 @@ CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加画像提示词。普通 Chat 转换只发送调用方系统指令及其配置的改写结果。网关移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
Claude 原生生成兼容缺失工具 ID 的历史:仅在相邻 `model`/`user` 轮次中,调用和结果的工具名各自唯一时补齐缺失的 `id`。一侧已有 ID 时沿用该 ID;两侧均缺失时生成确定性配对 ID,并避开正文已有 ID。已有字段、参数、结果和思考签名保持原样;同名并行调用、孤立结果、ID 冲突或格式错误不猜测配对,继续由上游校验。该兼容不作用于 Gemini、Chat 转换、独立搜索或输入计数
Claude 原生生成在相邻 `model`/`user` 轮次中补齐缺失的工具 `id`,按工具名配对。同名调用和结果各只有一个时,一侧已有 ID 就沿用,两侧均缺失时生成确定性配对 ID。同名并行调用要求调用与结果数量一致、两侧全部缺失 ID,按各自的出现顺序配对,遵循 [GenAI 并行函数调用规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tools/function-calling#parallel_function_calling)
生成的 ID 避开正文已有 ID,工具参数、结果、思考签名及已有字段保留原始表达。同名并行历史混有 ID、数量不匹配、孤立结果、ID 冲突或格式错误时保留原样,由上游校验。该兼容只适用于 Claude 原生生成
原生响应的思考签名保持上游原值,不添加网关标记。Claude/Gemini 生成根据已知原生封套识别来源,只移除可识别的异家族签名及对应思考内容,保留普通文本、工具调用和结果。导入 Gemini 的工具历史中,各轮首个工具调用缺少签名时使用官方 `skip_thought_signature_validator` 占位