mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
fix(openai): 保留 Codex ExternalMessage namespace 并禁止 OAuth 误提升 id 为 call_id
- stripOpenAIResponsesInputNamespacesWithOptions 在非 compact、非摊平的 OpenAI OAuth/API Key 转发上保留 standalone ExternalMessage(无 call_id 且带 name+namespace 的 function_call_output)的 namespace,单次遍历防重复键走私(0 allocs/op) - filterCodexInputWithOptions 不再将 standalone ExternalMessage 的 id 提升为 call_id,避免 OAuth HTTP 路径孤儿清理误删或 WSv2 路径伪造 call_id - removeOpenAIResponsesRejectedNamespaceAtIndex 同步支持反应式剥离上游显式拒绝的 ExternalMessage input[N].namespace
This commit is contained in:
1 parent
d29660bfd7
commit
6a8fca6b4e
8 files changed
+416
-15
No files matched your search
@@ -1790,20 +1790,22 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an
|
||||
}
|
||||
|
||||
if isCodexToolCallItemType(typ) {
|
||||
callID, ok := m["call_id"].(string)
|
||||
if !ok || strings.TrimSpace(callID) == "" {
|
||||
if id, ok := m["id"].(string); ok && strings.TrimSpace(id) != "" {
|
||||
callID = id
|
||||
ensureCopy()
|
||||
newItem["call_id"] = callID
|
||||
if !isCodexExternalMessageOutputMap(m, typ) {
|
||||
callID, ok := m["call_id"].(string)
|
||||
if !ok || strings.TrimSpace(callID) == "" {
|
||||
if id, ok := m["id"].(string); ok && strings.TrimSpace(id) != "" {
|
||||
callID = id
|
||||
ensureCopy()
|
||||
newItem["call_id"] = callID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if callID != "" {
|
||||
fixedCallID := fixCallIDPrefix(callID)
|
||||
if fixedCallID != callID {
|
||||
ensureCopy()
|
||||
newItem["call_id"] = fixedCallID
|
||||
if callID != "" {
|
||||
fixedCallID := fixCallIDPrefix(callID)
|
||||
if fixedCallID != callID {
|
||||
ensureCopy()
|
||||
newItem["call_id"] = fixedCallID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1852,6 +1854,24 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an
|
||||
return filtered
|
||||
}
|
||||
|
||||
// isCodexExternalMessageOutputMap 识别 Codex ExternalMessage 形态的 standalone
|
||||
// function_call_output(无 call_id 或空白 call_id,且带有非空字符串 name)。
|
||||
// 这类项不是工具调用回执,不能把其 id 提升为 call_id,否则 OAuth 路径的孤儿清理会把它静默丢弃,
|
||||
// WSv2 路径也会因伪造出无对应 function_call 的 call_id 触发上游 400。
|
||||
func isCodexExternalMessageOutputMap(item map[string]any, typ string) bool {
|
||||
if !strings.EqualFold(strings.TrimSpace(typ), "function_call_output") {
|
||||
return false
|
||||
}
|
||||
if callIDVal, exists := item["call_id"]; exists {
|
||||
callID, ok := callIDVal.(string)
|
||||
if !ok || strings.TrimSpace(callID) != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
name, ok := item["name"].(string)
|
||||
return ok && strings.TrimSpace(name) != ""
|
||||
}
|
||||
|
||||
func isCodexToolCallItemType(typ string) bool {
|
||||
switch typ {
|
||||
case "function_call",
|
||||
|
||||
@@ -129,7 +129,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
keepToolCallNamespaces := shouldKeepOpenAIResponsesToolCallNamespaces(
|
||||
account, wsDecision.Transport, passthroughEnabled, compactPath, body,
|
||||
)
|
||||
body, err = stripOpenAIResponsesInputNamespaces(body, keepToolCallNamespaces)
|
||||
keepExternalMessageNamespaces := shouldKeepOpenAIResponsesExternalMessageNamespaces(
|
||||
account, wsDecision.Transport, passthroughEnabled, compactPath,
|
||||
)
|
||||
body, err = stripOpenAIResponsesInputNamespacesWithOptions(body, openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: keepToolCallNamespaces,
|
||||
keepExternalMessageNamespaces: keepExternalMessageNamespaces,
|
||||
})
|
||||
if err != nil {
|
||||
setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
|
||||
|
||||
@@ -164,10 +164,85 @@ var openAIResponsesToolCallItemTypes = map[string]bool{
|
||||
"mcp_tool_call": true,
|
||||
}
|
||||
|
||||
// shouldKeepOpenAIResponsesExternalMessageNamespaces 判定清理 input 残留 namespace 时
|
||||
// 是否保留 Codex ExternalMessage(无 call_id、带 name 与 namespace 的 function_call_output)
|
||||
// 上的 namespace。
|
||||
//
|
||||
// Codex 0.167+ 使用此类 standalone function_call_output 传递外部上下文(如 agent.*、
|
||||
// codex_app.automation_update 等)。非 compact 且未开启摊平的 OAuth / API Key 转发
|
||||
// 若把该字段剥离,兼容 Codex 协议的上游会将其误判为 "named result without namespace"
|
||||
// 并直接 400;而标准 Responses API 本身同样会拒绝无 call_id 的 function_call_output,
|
||||
// 因此在非 compact、非摊平路径上保留该字段不会增加回归风险。
|
||||
func shouldKeepOpenAIResponsesExternalMessageNamespaces(
|
||||
account *Account,
|
||||
transport OpenAIUpstreamTransport,
|
||||
passthroughEnabled bool,
|
||||
compactPath bool,
|
||||
) bool {
|
||||
if account == nil || compactPath {
|
||||
return false
|
||||
}
|
||||
if account.IsOpenAIApiKey() {
|
||||
return true
|
||||
}
|
||||
if !account.IsOpenAIOAuthLike() {
|
||||
return false
|
||||
}
|
||||
return !shouldFlattenOpenAIResponsesNamespaces(account, transport, passthroughEnabled, compactPath)
|
||||
}
|
||||
|
||||
func isOpenAIResponsesToolCallItemType(itemType string) bool {
|
||||
return openAIResponsesToolCallItemTypes[strings.ToLower(strings.TrimSpace(itemType))]
|
||||
}
|
||||
|
||||
// isCodexExternalMessageOutputItem 识别 Codex ExternalMessage 形态的 standalone
|
||||
// function_call_output(缺失或空白 call_id,且同时带有非空字符串 name 与 namespace)。
|
||||
// 单次遍历 item 同时校验重复键:任意关键字段(type/call_id/name/namespace)重复或类型非字符串
|
||||
// 一律返回 false,避免 gjson 首键语义与上游尾键语义不一致导致走私。
|
||||
func isCodexExternalMessageOutputItem(item gjson.Result) bool {
|
||||
if !item.IsObject() {
|
||||
return false
|
||||
}
|
||||
var (
|
||||
typeCount, callIDCount, nameCount, nsCount int
|
||||
validType, validName, validNS bool
|
||||
invalidCallID bool
|
||||
)
|
||||
item.ForEach(func(key, val gjson.Result) bool {
|
||||
switch key.String() {
|
||||
case "type":
|
||||
typeCount++
|
||||
if typeCount > 1 || val.Type != gjson.String {
|
||||
return false
|
||||
}
|
||||
validType = strings.EqualFold(strings.TrimSpace(val.String()), "function_call_output")
|
||||
case "call_id":
|
||||
callIDCount++
|
||||
if callIDCount > 1 || val.Type != gjson.String || strings.TrimSpace(val.String()) != "" {
|
||||
invalidCallID = true
|
||||
return false
|
||||
}
|
||||
case "name":
|
||||
nameCount++
|
||||
if nameCount > 1 || val.Type != gjson.String {
|
||||
return false
|
||||
}
|
||||
validName = strings.TrimSpace(val.String()) != ""
|
||||
case "namespace":
|
||||
nsCount++
|
||||
if nsCount > 1 || val.Type != gjson.String {
|
||||
return false
|
||||
}
|
||||
validNS = strings.TrimSpace(val.String()) != ""
|
||||
}
|
||||
return true
|
||||
})
|
||||
return typeCount == 1 && validType &&
|
||||
callIDCount <= 1 && !invalidCallID &&
|
||||
nameCount == 1 && validName &&
|
||||
nsCount == 1 && validNS
|
||||
}
|
||||
|
||||
func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, error) {
|
||||
if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
|
||||
return body, nil
|
||||
@@ -191,6 +266,11 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro
|
||||
return rebuilt, nil
|
||||
}
|
||||
|
||||
type openAIResponsesInputNamespaceStripOptions struct {
|
||||
keepToolCallNamespaces bool
|
||||
keepExternalMessageNamespaces bool
|
||||
}
|
||||
|
||||
// stripOpenAIResponsesInputNamespaces removes namespace only from direct input
|
||||
// array items. Namespace declarations and nested namespace fields are left
|
||||
// untouched. Rebuilding the input array once keeps this linear for long
|
||||
@@ -204,6 +284,12 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro
|
||||
// namespace,让 Codex 调用能按上游要求原样回传;判定见
|
||||
// shouldKeepOpenAIResponsesToolCallNamespaces。
|
||||
func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) {
|
||||
return stripOpenAIResponsesInputNamespacesWithOptions(body, openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: keepToolCallNamespaces,
|
||||
})
|
||||
}
|
||||
|
||||
func stripOpenAIResponsesInputNamespacesWithOptions(body []byte, opts openAIResponsesInputNamespaceStripOptions) ([]byte, error) {
|
||||
if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
|
||||
return body, nil
|
||||
}
|
||||
@@ -223,7 +309,8 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo
|
||||
var stripErr error
|
||||
input.ForEach(func(_, item gjson.Result) bool {
|
||||
if !item.IsObject() || !item.Get("namespace").Exists() ||
|
||||
(keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) {
|
||||
(opts.keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) ||
|
||||
(opts.keepExternalMessageNamespaces && isCodexExternalMessageOutputItem(item)) {
|
||||
return true
|
||||
}
|
||||
itemBody, err := sjson.Delete(item.Raw, "namespace")
|
||||
|
||||
@@ -64,3 +64,27 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
|
||||
func BenchmarkStripOpenAIResponsesInputNamespacesLegacy(b *testing.B) {
|
||||
benchmarkStripOpenAIResponsesInputNamespaces(b, "legacy", legacyStripOpenAIResponsesInputNamespaces)
|
||||
}
|
||||
|
||||
func BenchmarkStripOpenAIResponsesInputNamespacesKeepExternalMessage(b *testing.B) {
|
||||
body := []byte(`{"tools":[{"type":"function","name":"exec"}],"input":[` +
|
||||
`{"type":"function_call_output","id":"fco_1","namespace":"agent","name":"browser_tabs","output":"` + strings.Repeat("x", 1<<20) + `"},` +
|
||||
`{"type":"message","role":"user","content":"hi"}]}`)
|
||||
opts := openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: false,
|
||||
keepExternalMessageNamespaces: true,
|
||||
}
|
||||
out, err := stripOpenAIResponsesInputNamespacesWithOptions(body, opts)
|
||||
if err != nil || !bytes.Equal(body, out) {
|
||||
b.Fatalf("expected no-op preservation, err=%v", err)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
out, err = stripOpenAIResponsesInputNamespacesWithOptions(body, opts)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
runtime.KeepAlive(out)
|
||||
}
|
||||
}
|
||||
@@ -208,3 +208,130 @@ func TestOpenAIGatewayService_ForwardClearsStaleNamespaceNames(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, openAIResponsesNamespaceNames(c))
|
||||
}
|
||||
|
||||
// API Key 转发 Codex 请求时,即使顶层 tools 没有 type:"namespace" 声明,
|
||||
// 也必须保留 Codex ExternalMessage(无 call_id、带 name+namespace 的 function_call_output)
|
||||
// 上的 namespace,避免兼容上游报 "named result without namespace" 400;
|
||||
// 同时仍清理普通带 call_id 输出项和 message 上的残留 namespace。
|
||||
func TestOpenAIGatewayService_APIKeyPreservesCodexExternalMessageNamespace(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"gpt-6.1-sol",
|
||||
"stream":false,
|
||||
"tools":[{"type":"function","name":"exec","parameters":{"type":"object"}}],
|
||||
"input":[
|
||||
{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","namespace":"leftover","name":"exec","output":"ok"},
|
||||
{"type":"function_call_output","id":"fco_ext_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"},
|
||||
{"type":"function_call_output","id":"fco_ext_2","namespace":"codex_app","name":"automation_update","output":"<heartbeat/>"},
|
||||
{"type":"message","role":"user","namespace":"leftover","content":[{"type":"input_text","text":"hello"}]}
|
||||
]
|
||||
}`)
|
||||
upstream := &httpUpstreamRecorder{responses: []*http.Response{
|
||||
newOpenAIRejectedFieldTestResponse(http.StatusOK, namespaceForwardOKResponse),
|
||||
}}
|
||||
c := newOpenAIRejectedFieldTestContext(body)
|
||||
|
||||
result, err := newOpenAIRejectedFieldTestService(upstream).Forward(
|
||||
context.Background(), c, newOpenAIRejectedFieldTestAccount(), body,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
forwarded := upstream.bodies[0]
|
||||
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.1.namespace").Exists(), "带 call_id 的普通输出项仍应清理残留 namespace")
|
||||
require.Equal(t, "agent", gjson.GetBytes(forwarded, "input.2.namespace").String(), "agent ExternalMessage 必须保留 namespace")
|
||||
require.Equal(t, "codex_app", gjson.GetBytes(forwarded, "input.3.namespace").String(), "codex_app ExternalMessage 必须保留 namespace")
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.4.namespace").Exists(), "普通 message 仍应清理残留 namespace")
|
||||
}
|
||||
|
||||
// OAuth 非 compact、非摊平转发时,必须保留 Codex ExternalMessage(含 id)的原生形态与 namespace,
|
||||
// 不得把 id 提升为 call_id 导致孤儿清理将其静默丢弃。
|
||||
func TestOpenAIGatewayService_OAuthPreservesCodexExternalMessageNamespace(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.6-terra",
|
||||
"stream":false,
|
||||
"instructions":"test",
|
||||
"input":[
|
||||
{"type":"function_call_output","id":"fco_ext_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"},
|
||||
{"type":"message","role":"user","namespace":"leftover","content":[{"type":"input_text","text":"hi"}]}
|
||||
]
|
||||
}`)
|
||||
upstream := &httpUpstreamRecorder{responses: []*http.Response{
|
||||
newOpenAIRejectedFieldTestResponse(http.StatusOK, namespaceForwardOKResponse),
|
||||
}}
|
||||
c := newOpenAIRejectedFieldTestContext(body)
|
||||
|
||||
result, err := newOpenAIRejectedFieldTestService(upstream).Forward(
|
||||
context.Background(), c, newOpenAIOAuthNamespaceTestAccount(), body,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
forwarded := upstream.bodies[0]
|
||||
|
||||
require.Len(t, gjson.GetBytes(forwarded, "input").Array(), 2, "ExternalMessage 不得被孤儿清理静默丢弃")
|
||||
require.Equal(t, "function_call_output", gjson.GetBytes(forwarded, "input.0.type").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(forwarded, "input.0.namespace").String())
|
||||
require.Equal(t, "browser_tabs", gjson.GetBytes(forwarded, "input.0.name").String())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.0.call_id").Exists(), "不得把 ExternalMessage 的 id 伪造为 call_id")
|
||||
require.Equal(t, "message", gjson.GetBytes(forwarded, "input.1.type").String())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.1.namespace").Exists())
|
||||
}
|
||||
|
||||
// compact 与 flatten 模式下仍全量剥离 ExternalMessage 的 namespace,同时保留该项本身(不伪造 call_id、不静默丢弃)。
|
||||
func TestOpenAIGatewayService_CompactAndFlattenStillStripExternalMessageNamespace(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.6-terra",
|
||||
"stream":false,
|
||||
"instructions":"test",
|
||||
"input":[
|
||||
{"type":"function_call_output","id":"fco_ext_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"}
|
||||
]
|
||||
}`)
|
||||
|
||||
t.Run("oauth_compact", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{responses: []*http.Response{
|
||||
newOpenAIRejectedFieldTestResponse(http.StatusOK, namespaceForwardOKResponse),
|
||||
}}
|
||||
c := newOpenAIRejectedFieldTestContext(body)
|
||||
c.Request.URL.Path = "/v1/responses/compact"
|
||||
|
||||
result, err := newOpenAIRejectedFieldTestService(upstream).Forward(
|
||||
context.Background(), c, newOpenAIOAuthNamespaceTestAccount(), body,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
forwarded := upstream.bodies[0]
|
||||
require.Len(t, gjson.GetBytes(forwarded, "input").Array(), 1)
|
||||
require.Equal(t, "function_call_output", gjson.GetBytes(forwarded, "input.0.type").String())
|
||||
require.Equal(t, "browser_tabs", gjson.GetBytes(forwarded, "input.0.name").String())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.0.call_id").Exists())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.0.namespace").Exists())
|
||||
})
|
||||
|
||||
t.Run("oauth_flatten", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{responses: []*http.Response{
|
||||
newOpenAIRejectedFieldTestResponse(http.StatusOK, namespaceForwardOKResponse),
|
||||
}}
|
||||
c := newOpenAIRejectedFieldTestContext(body)
|
||||
account := newOpenAIOAuthNamespaceTestAccount()
|
||||
account.Extra = map[string]any{"openai_responses_flatten_namespaces": true}
|
||||
|
||||
result, err := newOpenAIRejectedFieldTestService(upstream).Forward(
|
||||
context.Background(), c, account, body,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
forwarded := upstream.bodies[0]
|
||||
require.Len(t, gjson.GetBytes(forwarded, "input").Array(), 1)
|
||||
require.Equal(t, "function_call_output", gjson.GetBytes(forwarded, "input.0.type").String())
|
||||
require.Equal(t, "browser_tabs", gjson.GetBytes(forwarded, "input.0.name").String())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.0.call_id").Exists())
|
||||
require.False(t, gjson.GetBytes(forwarded, "input.0.namespace").Exists())
|
||||
})
|
||||
}
|
||||
@@ -281,3 +281,117 @@ func TestStripOpenAIResponsesInputNamespacesKeepsToolCallNamespaces(t *testing.T
|
||||
require.False(t, gjson.GetBytes(strippedAll, "input."+strconv.Itoa(index)+".namespace").Exists())
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldKeepOpenAIResponsesExternalMessageNamespaces(t *testing.T) {
|
||||
oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
apiKey := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
setupToken := &Account{Platform: PlatformOpenAI, Type: AccountTypeSetupToken}
|
||||
grokOAuth := &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
flattenOAuth := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Extra: map[string]any{"openai_responses_flatten_namespaces": true},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
account *Account
|
||||
transport OpenAIUpstreamTransport
|
||||
passthroughEnabled bool
|
||||
compactPath bool
|
||||
want bool
|
||||
}{
|
||||
{name: "oauth_http_keeps", account: oauth, transport: OpenAIUpstreamTransportHTTPSSE, want: true},
|
||||
{name: "oauth_http_passthrough_keeps", account: oauth, transport: OpenAIUpstreamTransportHTTPSSE, passthroughEnabled: true, want: true},
|
||||
{name: "oauth_compact_strips", account: oauth, transport: OpenAIUpstreamTransportHTTPSSE, compactPath: true, want: false},
|
||||
{name: "oauth_flatten_enabled_strips", account: flattenOAuth, transport: OpenAIUpstreamTransportHTTPSSE, want: false},
|
||||
{name: "apikey_http_keeps", account: apiKey, transport: OpenAIUpstreamTransportHTTPSSE, want: true},
|
||||
{name: "apikey_compact_strips", account: apiKey, transport: OpenAIUpstreamTransportHTTPSSE, compactPath: true, want: false},
|
||||
{name: "setup_token_keeps", account: setupToken, transport: OpenAIUpstreamTransportHTTPSSE, want: true},
|
||||
{name: "grok_oauth_strips", account: grokOAuth, transport: OpenAIUpstreamTransportHTTPSSE, want: false},
|
||||
{name: "nil_account_strips", account: nil, transport: OpenAIUpstreamTransportHTTPSSE, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, shouldKeepOpenAIResponsesExternalMessageNamespaces(
|
||||
tt.account, tt.transport, tt.passthroughEnabled, tt.compactPath,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripOpenAIResponsesInputNamespacesKeepsCodexExternalMessages(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"input":[
|
||||
{"type":"function_call_output","id":"fco_1","namespace":"codex_app","name":"automation_update","output":"<heartbeat/>"},
|
||||
{"type":"function_call_output","id":"fco_2","call_id":"","namespace":"agent","name":"browser_tabs","output":"tabs"},
|
||||
{"type":"function_call_output","id":"fco_3","call_id":" ","namespace":"agent","name":"terminal_info","output":"tty"},
|
||||
{"type":"function_call_output","call_id":"call_1","namespace":"codex_app","name":"exec","output":"ok"},
|
||||
{"type":"function_call_output","namespace":"leftover","output":"ok"},
|
||||
{"type":"function_call_output","call_id":null,"namespace":"agent","name":"browser_tabs","output":"bad"},
|
||||
{"type":"function_call_output","call_id":42,"namespace":"agent","name":"browser_tabs","output":"bad"},
|
||||
{"type":"function_call_output","namespace":"","name":"browser_tabs","output":"bad"},
|
||||
{"type":"function_call_output","namespace":"agent","name":"","output":"bad"},
|
||||
{"type":"function_call","namespace":"collaboration","name":"spawn_agent","call_id":"call_2","arguments":"{}"},
|
||||
{"type":"message","namespace":"leftover","role":"user","content":"hi"}
|
||||
]
|
||||
}`)
|
||||
|
||||
// 仅保留 ExternalMessage(模拟 API Key 未声明 namespace 工具时):
|
||||
// 前 3 个合法 ExternalMessage 保留 namespace,其余全部清理(含普通 tool output 和未声明工具的 function_call)。
|
||||
got, err := stripOpenAIResponsesInputNamespacesWithOptions(body, openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: false,
|
||||
keepExternalMessageNamespaces: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "codex_app", gjson.GetBytes(got, "input.0.namespace").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(got, "input.1.namespace").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(got, "input.2.namespace").String())
|
||||
for index := 3; index <= 10; index++ {
|
||||
require.False(t, gjson.GetBytes(got, "input."+strconv.Itoa(index)+".namespace").Exists(), "input.%d", index)
|
||||
}
|
||||
|
||||
// 同时保留工具调用项与 ExternalMessage:input.9 的 function_call 也保留 namespace。
|
||||
gotBoth, err := stripOpenAIResponsesInputNamespacesWithOptions(body, openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: true,
|
||||
keepExternalMessageNamespaces: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "codex_app", gjson.GetBytes(gotBoth, "input.0.namespace").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(gotBoth, "input.1.namespace").String())
|
||||
require.Equal(t, "agent", gjson.GetBytes(gotBoth, "input.2.namespace").String())
|
||||
require.Equal(t, "collaboration", gjson.GetBytes(gotBoth, "input.9.namespace").String())
|
||||
for _, index := range []int{3, 4, 5, 6, 7, 8, 10} {
|
||||
require.False(t, gjson.GetBytes(gotBoth, "input."+strconv.Itoa(index)+".namespace").Exists(), "input.%d", index)
|
||||
}
|
||||
|
||||
// 关闭保留(compact / flatten 模式):所有项包括 ExternalMessage 均清理。
|
||||
gotNone, err := stripOpenAIResponsesInputNamespacesWithOptions(body, openAIResponsesInputNamespaceStripOptions{})
|
||||
require.NoError(t, err)
|
||||
for index := 0; index <= 10; index++ {
|
||||
require.False(t, gjson.GetBytes(gotNone, "input."+strconv.Itoa(index)+".namespace").Exists(), "input.%d", index)
|
||||
}
|
||||
|
||||
// 重复键走私防护:任意关键字段(type/call_id/name/namespace)重复时不得豁免清理。
|
||||
smuggled := []struct {
|
||||
name string
|
||||
item string
|
||||
}{
|
||||
{"duplicate_call_id", `{"type":"function_call_output","call_id":"","call_id":"call_real","namespace":"leftover","name":"exec","output":"ok"}`},
|
||||
{"duplicate_type", `{"type":"function_call_output","type":"message","namespace":"leftover","name":"x","role":"user","content":"hi"}`},
|
||||
{"duplicate_namespace", `{"type":"function_call_output","namespace":"agent","namespace":null,"name":"browser_tabs","output":"ok"}`},
|
||||
{"duplicate_name", `{"type":"function_call_output","name":"browser_tabs","name":"","namespace":"leftover","output":"ok"}`},
|
||||
}
|
||||
for _, tc := range smuggled {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.False(t, isCodexExternalMessageOutputItem(gjson.Parse(tc.item)))
|
||||
req := []byte(`{"input":[` + tc.item + `]}`)
|
||||
stripped, err := stripOpenAIResponsesInputNamespacesWithOptions(req, openAIResponsesInputNamespaceStripOptions{
|
||||
keepToolCallNamespaces: true,
|
||||
keepExternalMessageNamespaces: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, string(req), string(stripped), "smuggled duplicate-key item must not be exempted")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -386,9 +386,14 @@ func removeOpenAIResponsesRejectedReasoningContentAtIndex(body []byte, index int
|
||||
|
||||
func removeOpenAIResponsesRejectedNamespaceAtIndex(body []byte, index int) ([]byte, string, bool, error) {
|
||||
itemPath := fmt.Sprintf("input.%d", index)
|
||||
itemType := strings.ToLower(strings.TrimSpace(gjson.GetBytes(body, itemPath+".type").String()))
|
||||
item := gjson.GetBytes(body, itemPath)
|
||||
itemType := strings.ToLower(strings.TrimSpace(item.Get("type").String()))
|
||||
switch itemType {
|
||||
case "function_call", "tool_call", "custom_tool_call", "mcp_tool_call":
|
||||
case "function_call_output":
|
||||
if !isCodexExternalMessageOutputItem(item) {
|
||||
return nil, "", false, nil
|
||||
}
|
||||
default:
|
||||
return nil, "", false, nil
|
||||
}
|
||||
|
||||
@@ -152,6 +152,24 @@ func TestNormalizeOpenAIResponsesRejectedFieldRetryBodyBindsNamespacePathToRejec
|
||||
require.False(t, gjson.GetBytes(retryBody, "input.1.namespace").Exists())
|
||||
}
|
||||
|
||||
func TestNormalizeOpenAIResponsesRejectedFieldRetryBodyStripsExternalMessageNamespace(t *testing.T) {
|
||||
body := []byte(`{"input":[{"type":"function_call_output","id":"fco_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"},{"type":"function_call_output","call_id":"call_1","namespace":"leftover","name":"exec","output":"ok"}]}`)
|
||||
responseBody := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: 'input[0].namespace'.","param":"input[0].namespace"}}`)
|
||||
|
||||
retryBody, _, changed, err := normalizeOpenAIResponsesRejectedFieldRetryBody(http.StatusBadRequest, body, responseBody)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.False(t, gjson.GetBytes(retryBody, "input.0.namespace").Exists())
|
||||
require.Equal(t, "browser_tabs", gjson.GetBytes(retryBody, "input.0.name").String())
|
||||
|
||||
// 带有效 call_id 的普通 function_call_output 不会被此反应式分支处理。
|
||||
ordinaryResp := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: 'input[1].namespace'.","param":"input[1].namespace"}}`)
|
||||
retryBody, _, changed, err = normalizeOpenAIResponsesRejectedFieldRetryBody(http.StatusBadRequest, body, ordinaryResp)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
require.Nil(t, retryBody)
|
||||
}
|
||||
|
||||
func TestNormalizeOpenAIResponsesRejectedFieldRetryBodyDoesNotTreatMaxOutputTokensSuggestionAsRejection(t *testing.T) {
|
||||
body := []byte(`{"max_tokens":4096,"max_output_tokens":2048}`)
|
||||
responseBody := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: max_tokens. Use max_output_tokens instead."}}`)
|
||||
|
||||
Reference in new issue
Block a user