mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
Merge pull request #1029 from buddhism5080/fix/xai-function-parameters-root
fix: lift Build function parameter root unions for xAI grammar
This commit is contained in:
9 files changed
+1085
-83
No files matched your search
@@ -153,6 +153,21 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa
|
||||
failure.SpendingLimitBlocked = isPaidQuotaExhaustion(metadataText)
|
||||
failure.CredentialRejected = !failure.QuotaExhausted && containsAny(metadataText, "authentication", "unauthorized", "invalid token", "token expired")
|
||||
failure.AccountScoped = failure.AccountBlocked || failure.PermanentAccountDenial || failure.QuotaExhausted || failure.CredentialRejected || isAccountScopedForbidden(metadataText)
|
||||
case http.StatusBadRequest:
|
||||
if isRequestScopedForbidden(upstreamCode, metadataText) {
|
||||
failure.Code = "invalid_argument"
|
||||
failure.RequestScopedForbidden = true
|
||||
if upstreamMessage != "" {
|
||||
failure.PublicMessage = upstreamMessage
|
||||
} else {
|
||||
failure.PublicMessage = "请求参数无效"
|
||||
}
|
||||
break
|
||||
}
|
||||
failure.Code = "upstream_error"
|
||||
if upstreamMessage != "" {
|
||||
failure.PublicMessage = upstreamMessage
|
||||
}
|
||||
case http.StatusTooManyRequests:
|
||||
failure.Code = "upstream_rate_limited"
|
||||
failure.PublicMessage = "上游请求频率受限"
|
||||
@@ -163,8 +178,16 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa
|
||||
failure.ModelQuotaExhausted = isModelQuotaExhaustion(metadataText)
|
||||
failure.QuotaExhausted = failure.FreeQuotaExhausted || isPaidQuotaExhaustion(metadataText)
|
||||
default:
|
||||
failure.Code = "upstream_server_error"
|
||||
failure.PublicMessage = "上游服务暂时异常"
|
||||
if status >= 400 && status < 500 {
|
||||
failure.Code = "upstream_error"
|
||||
failure.PublicMessage = "上游拒绝了该请求"
|
||||
if upstreamMessage != "" {
|
||||
failure.PublicMessage = upstreamMessage
|
||||
}
|
||||
} else {
|
||||
failure.Code = "upstream_server_error"
|
||||
failure.PublicMessage = "上游服务暂时异常"
|
||||
}
|
||||
}
|
||||
fingerprintPart := normalizeFailureCode(firstNonEmptyFailure(upstreamCode, upstreamType, upstreamMessage))
|
||||
if fingerprintPart == "" {
|
||||
@@ -174,6 +197,17 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa
|
||||
return failure
|
||||
}
|
||||
|
||||
// ClassifyUpstreamHTTPError maps an upstream HTTP error body to a client-facing
|
||||
// error code and message. Request-scoped 400s (invalid-argument) keep the
|
||||
// upstream text so the client can see the tool name.
|
||||
func ClassifyUpstreamHTTPError(status int, body []byte) (string, string) {
|
||||
failure := newHTTPUpstreamFailure(status, body, 0, "")
|
||||
if failure == nil {
|
||||
return "upstream_error", "上游服务返回错误"
|
||||
}
|
||||
return failure.Code, failure.PublicMessage
|
||||
}
|
||||
|
||||
func newTransportUpstreamFailure(err error, accountID uint64, accountName string) *UpstreamFailure {
|
||||
code, message := "upstream_network_error", "连接上游服务失败"
|
||||
status := http.StatusBadGateway
|
||||
|
||||
@@ -126,6 +126,11 @@ func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) {
|
||||
name: "invalid argument code", body: `{"code":"invalid-argument","error":"unsupported request field"}`,
|
||||
requestScopedForbidden: true, upstreamCode: "invalid-argument",
|
||||
},
|
||||
{
|
||||
name: "400 tool schema union", status: http.StatusBadRequest,
|
||||
body: `{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}`,
|
||||
requestScopedForbidden: true, upstreamCode: "invalid-argument",
|
||||
},
|
||||
{
|
||||
name: "request-level access denied sentence", body: `{"code":"operation-denied","error":"Access denied because this operation is unavailable under ZDR"}`,
|
||||
requestScopedForbidden: true, upstreamCode: "operation-denied",
|
||||
@@ -160,6 +165,24 @@ func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyUpstreamHTTPErrorInvalidArgument(t *testing.T) {
|
||||
code, message := ClassifyUpstreamHTTPError(http.StatusBadRequest, []byte(`{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}`))
|
||||
if code != "invalid_argument" || !strings.Contains(message, "mcp__codex_app__automation_update") {
|
||||
t.Fatalf("code=%q message=%q", code, message)
|
||||
}
|
||||
failure := newHTTPUpstreamFailure(http.StatusBadRequest, []byte(`{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type"}`), 42, "build")
|
||||
if !failure.RequestScopedForbidden || failure.AccountScoped || failure.Code != "invalid_argument" {
|
||||
t.Fatalf("failure = %#v", failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyUpstreamHTTPErrorKeepsOther4xxMessage(t *testing.T) {
|
||||
code, message := ClassifyUpstreamHTTPError(http.StatusNotFound, []byte(`{"error":{"code":"not_found","message":"requested response is missing"}}`))
|
||||
if code != "upstream_error" || message != "requested response is missing" {
|
||||
t.Fatalf("code=%q message=%q", code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPUpstreamFailureClassifiesDPoPRequirementAsSystemic(t *testing.T) {
|
||||
failure := newHTTPUpstreamFailure(http.StatusForbidden, []byte(`{"code":"unauthorized:dpop-required","error":"DPoP proof required but was not verified."}`), 42, "console")
|
||||
if failure.AccountScoped || failure.CredentialRejected || !failure.RequestScopedForbidden {
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootLiftsNestedUnionRefs(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"ID": map[string]any{"type": "string"},
|
||||
"View": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"view"}, "type": "string"}, "id": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "id"}, "additionalProperties": false},
|
||||
"Create": map[string]any{"oneOf": []any{
|
||||
map[string]any{"$ref": "#/$defs/CreateCron"},
|
||||
map[string]any{"$ref": "#/$defs/CreateHB"},
|
||||
}},
|
||||
"CreateCron": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"create"}, "type": "string"}, "kind": map[string]any{"enum": []any{"cron"}, "type": "string"}, "name": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "kind", "name"}, "additionalProperties": false},
|
||||
"CreateHB": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"create"}, "type": "string"}, "kind": map[string]any{"enum": []any{"heartbeat"}, "type": "string"}, "name": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "kind", "name"}, "additionalProperties": false},
|
||||
"Delete": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"delete"}, "type": "string"}, "id": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "id"}, "additionalProperties": false},
|
||||
},
|
||||
"type": "object",
|
||||
"properties": map[string]any{},
|
||||
"oneOf": []any{
|
||||
map[string]any{"$ref": "#/$defs/View"},
|
||||
map[string]any{"$ref": "#/$defs/Create"},
|
||||
map[string]any{"$ref": "#/$defs/Delete"},
|
||||
},
|
||||
}
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, ok := normalized.(map[string]any)
|
||||
if !ok || !changed {
|
||||
t.Fatalf("normalized=%#v changed=%v", normalized, changed)
|
||||
}
|
||||
if _, exists := out["$ref"]; exists {
|
||||
t.Fatalf("root still has $ref: %#v", out)
|
||||
}
|
||||
branches, _ := out["oneOf"].([]any)
|
||||
if out["type"] != nil || len(branches) != 4 {
|
||||
t.Fatalf("want root oneOf[4] without type wrapper, got %#v", out)
|
||||
}
|
||||
for i, raw := range branches {
|
||||
branch, _ := raw.(map[string]any)
|
||||
if branch["type"] != "object" {
|
||||
t.Fatalf("branch[%d] type=%v %#v", i, branch["type"], branch)
|
||||
}
|
||||
if _, exists := branch["oneOf"]; exists {
|
||||
t.Fatalf("branch[%d] still nested oneOf: %#v", i, branch)
|
||||
}
|
||||
if _, exists := branch["$ref"]; exists {
|
||||
t.Fatalf("branch[%d] still $ref: %#v", i, branch)
|
||||
}
|
||||
props, _ := branch["properties"].(map[string]any)
|
||||
if id, ok := props["id"].(map[string]any); ok {
|
||||
if id["$ref"] != "#/$defs/ID" {
|
||||
t.Fatalf("property $ref was inlined: %#v", id)
|
||||
}
|
||||
}
|
||||
if name, ok := props["name"].(map[string]any); ok {
|
||||
if name["$ref"] != "#/$defs/ID" {
|
||||
t.Fatalf("property $ref was inlined: %#v", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
defs, _ := out["$defs"].(map[string]any)
|
||||
if _, ok := defs["ID"]; !ok {
|
||||
t.Fatalf("$defs.ID dropped: %#v", defs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootKeepsNestedPropertyUnion(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"value": map[string]any{
|
||||
"anyOf": []any{map[string]any{"type": "string"}, map[string]any{"type": "null"}},
|
||||
}},
|
||||
}
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
value := out["properties"].(map[string]any)["value"].(map[string]any)
|
||||
if changed || value["anyOf"] == nil {
|
||||
t.Fatalf("nested anyOf was rewritten: %#v changed=%v", out, changed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootLiftsOneOfNestedAnyOf(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"oneOf": []any{
|
||||
map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"kind": map[string]any{"const": "a"}},
|
||||
"required": []any{"kind"},
|
||||
},
|
||||
map[string]any{"anyOf": []any{
|
||||
map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"kind": map[string]any{"const": "b"}},
|
||||
"required": []any{"kind"},
|
||||
},
|
||||
map[string]any{"type": "null"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
branches, _ := out["oneOf"].([]any)
|
||||
if !changed || len(branches) != 2 {
|
||||
t.Fatalf("want 2 object leaves, got %#v", out)
|
||||
}
|
||||
for i, raw := range branches {
|
||||
if raw.(map[string]any)["type"] != "object" {
|
||||
t.Fatalf("branch[%d]=%#v", i, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootFollowsBareRootRef(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"Args": map[string]any{"oneOf": []any{
|
||||
map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "view"}}, "required": []any{"mode"}},
|
||||
map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "create"}}, "required": []any{"mode"}},
|
||||
}},
|
||||
},
|
||||
"$ref": "#/$defs/Args",
|
||||
}
|
||||
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
branches, _ := out["oneOf"].([]any)
|
||||
if !changed || len(branches) != 2 || out["$ref"] != nil {
|
||||
t.Fatalf("normalized=%#v changed=%v", out, changed)
|
||||
}
|
||||
for index, raw := range branches {
|
||||
branch, _ := raw.(map[string]any)
|
||||
if branch["type"] != "object" || branch["$ref"] != nil {
|
||||
t.Fatalf("branch[%d]=%#v", index, branch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootPreservesUnionSiblingConstraints(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"Read": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "read"}}, "required": []any{"mode"}},
|
||||
"Write": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "write"}}, "required": []any{"mode"}},
|
||||
},
|
||||
"type": "object",
|
||||
"properties": map[string]any{"tenant": map[string]any{"type": "string"}},
|
||||
"required": []any{"tenant"},
|
||||
"additionalProperties": false,
|
||||
"oneOf": []any{
|
||||
map[string]any{"$ref": "#/$defs/Read"},
|
||||
map[string]any{"$ref": "#/$defs/Write"},
|
||||
},
|
||||
}
|
||||
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
branches, _ := out["oneOf"].([]any)
|
||||
if !changed || len(branches) != 2 {
|
||||
t.Fatalf("normalized=%#v changed=%v", out, changed)
|
||||
}
|
||||
for index, raw := range branches {
|
||||
branch := raw.(map[string]any)
|
||||
allOf, _ := branch["allOf"].([]any)
|
||||
if branch["type"] != "object" || len(allOf) != 2 {
|
||||
t.Fatalf("branch[%d]=%#v", index, branch)
|
||||
}
|
||||
common := allOf[0].(map[string]any)
|
||||
if common["additionalProperties"] != false || len(common["required"].([]any)) != 1 {
|
||||
t.Fatalf("branch[%d] lost common constraints: %#v", index, branch)
|
||||
}
|
||||
if _, ok := common["properties"].(map[string]any)["tenant"]; !ok {
|
||||
t.Fatalf("branch[%d] lost tenant property: %#v", index, branch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootPreservesAnyOf(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"A": map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}},
|
||||
"B": map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}},
|
||||
},
|
||||
"anyOf": []any{
|
||||
map[string]any{"$ref": "#/$defs/A"},
|
||||
map[string]any{"$ref": "#/$defs/B"},
|
||||
},
|
||||
}
|
||||
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
if !changed || len(out["anyOf"].([]any)) != 2 || out["oneOf"] != nil {
|
||||
t.Fatalf("normalized=%#v changed=%v", out, changed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootRejectsUnsafeNestedUnionFlatten(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"oneOf": []any{
|
||||
map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}},
|
||||
map[string]any{"oneOf": []any{
|
||||
map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}},
|
||||
map[string]any{"type": "object", "properties": map[string]any{"c": map[string]any{"type": "string"}}},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
if _, _, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters"); err == nil {
|
||||
t.Fatal("overlapping nested oneOf should fail locally instead of changing semantics")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootKeepsDefinitionForSubpathRef(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"Config": map[string]any{"type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}}},
|
||||
"Args": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"id": map[string]any{"$ref": "#/$defs/Config/properties/id"}},
|
||||
},
|
||||
},
|
||||
"$ref": "#/$defs/Args",
|
||||
}
|
||||
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
defs, _ := out["$defs"].(map[string]any)
|
||||
if !changed || defs["Config"] == nil || defs["Config/properties/id"] != nil {
|
||||
t.Fatalf("normalized=%#v changed=%v", out, changed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootRejectsIllegalRootWithToolName(t *testing.T) {
|
||||
_, _, err := normalizeBuildFunctionParametersRootForTool(
|
||||
map[string]any{"type": "string"},
|
||||
"tools[0].parameters",
|
||||
"mcp__codex_app__automation_update",
|
||||
)
|
||||
requestErr, ok := err.(*responsesRequestError)
|
||||
if !ok || !strings.Contains(requestErr.Message, "mcp__codex_app__automation_update") {
|
||||
t.Fatalf("error=%#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeResponsesRequestIllegalFunctionRootNamesTool(t *testing.T) {
|
||||
_, _, err := normalizeResponsesRequest([]byte(`{
|
||||
"model":"public",
|
||||
"input":"hello",
|
||||
"tools":[{"type":"function","name":"mcp__codex_app__automation_update","parameters":{"type":"string"}}]
|
||||
}`), "grok-4.5")
|
||||
requestErr, ok := err.(*responsesRequestError)
|
||||
if !ok || requestErr.Param != "tools[0].parameters" || !strings.Contains(requestErr.Message, "mcp__codex_app__automation_update") {
|
||||
t.Fatalf("error=%#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootRejectsRootCycle(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"Loop": map[string]any{"$ref": "#/$defs/Loop"},
|
||||
},
|
||||
"oneOf": []any{map[string]any{"$ref": "#/$defs/Loop"}},
|
||||
}
|
||||
_, _, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
requestErr, ok := err.(*responsesRequestError)
|
||||
if !ok || requestErr.Param != "tools[0].parameters" {
|
||||
t.Fatalf("error = %#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildFunctionParametersRootKeepsPropertyCycle(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"$defs": map[string]any{
|
||||
"Node": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"child": map[string]any{"$ref": "#/$defs/Node"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"root": map[string]any{"$ref": "#/$defs/Node"},
|
||||
},
|
||||
}
|
||||
normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := normalized.(map[string]any)
|
||||
if changed {
|
||||
t.Fatalf("property cycle should not rewrite root: %#v", out)
|
||||
}
|
||||
root := out["properties"].(map[string]any)["root"].(map[string]any)
|
||||
if root["$ref"] != "#/$defs/Node" {
|
||||
t.Fatalf("property $ref rewritten: %#v", root)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeResponsesRequestLiftsAutomationUpdateStyleUnion(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"public","input":"hello",
|
||||
"tools":[{"type":"function","name":"mcp__codex_app__automation_update","parameters":{
|
||||
"$defs":{
|
||||
"ID":{"type":"string"},
|
||||
"View":{"type":"object","properties":{"mode":{"enum":["view"],"type":"string"},"id":{"$ref":"#/$defs/ID"}},"required":["mode","id"]},
|
||||
"Create":{"oneOf":[
|
||||
{"type":"object","properties":{"mode":{"enum":["create"],"type":"string"},"name":{"$ref":"#/$defs/ID"}},"required":["mode","name"]}
|
||||
]}
|
||||
},
|
||||
"type":"object",
|
||||
"properties":{},
|
||||
"oneOf":[{"$ref":"#/$defs/View"},{"$ref":"#/$defs/Create"}]
|
||||
}}]
|
||||
}`)
|
||||
normalized, compatibility, err := normalizeResponsesRequest(body, "grok-4.5")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") {
|
||||
t.Fatalf("compatibility = %#v", compatibility)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(normalized, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any)
|
||||
branches, _ := parameters["oneOf"].([]any)
|
||||
if len(branches) != 2 {
|
||||
t.Fatalf("upstream parameters = %#v", parameters)
|
||||
}
|
||||
visible := compatibility.visibleTools[0].(map[string]any)["parameters"].(map[string]any)
|
||||
if _, ok := visible["$defs"]; !ok {
|
||||
t.Fatalf("visible schema lost $defs: %#v", visible)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package cli
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -172,14 +173,14 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
|
||||
}
|
||||
converted := cloneJSONObject(tool)
|
||||
if parameters, exists := converted["parameters"]; exists {
|
||||
normalized, changed, normalizeErr := normalizeBuildFunctionParametersRoot(parameters, param+".parameters")
|
||||
normalized, changed, normalizeErr := normalizeBuildFunctionParametersRootForTool(parameters, param+".parameters", name)
|
||||
if normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
}
|
||||
if changed {
|
||||
converted["parameters"] = normalized
|
||||
c.changed = true
|
||||
c.addWarning("function_parameters_nullable_root_normalized")
|
||||
c.addWarning("function_parameters_root_normalized")
|
||||
}
|
||||
}
|
||||
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
|
||||
@@ -273,85 +274,460 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeBuildFunctionParametersRoot removes root-level nullability from function schemas.
|
||||
// Build requires the parameter root to be an object, while Codex can emit `object | null`
|
||||
// for tools with an optional argument object. Nested nullable fields remain untouched.
|
||||
const maxRootUnionDepth = 32
|
||||
const maxRootUnionLeaves = 32
|
||||
|
||||
type buildFunctionParametersRootContext struct {
|
||||
param string
|
||||
toolName string
|
||||
}
|
||||
|
||||
type rootObjectLeafCollector struct {
|
||||
doc map[string]any
|
||||
context buildFunctionParametersRootContext
|
||||
leaves []map[string]any
|
||||
rootUnionKeyword string
|
||||
requiresDisjoint bool
|
||||
changed bool
|
||||
}
|
||||
|
||||
// NormalizeBuildFunctionParametersRoot rewrites a function parameters schema so
|
||||
// Grok Build can compile it: the root is an object, or a root union of object
|
||||
// leaves. Nested oneOf/anyOf at the root are lifted; $ref inside properties
|
||||
// and recursive property $ref are left alone.
|
||||
func NormalizeBuildFunctionParametersRoot(value any, param, toolName string) (any, bool, error) {
|
||||
return normalizeBuildFunctionParametersRootForTool(value, param, toolName)
|
||||
}
|
||||
|
||||
// normalizeBuildFunctionParametersRoot removes root-level nullability from function schemas
|
||||
// and lifts nested root unions. Nested nullable fields remain untouched.
|
||||
func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, error) {
|
||||
return normalizeBuildFunctionParametersRootForTool(value, param, "")
|
||||
}
|
||||
|
||||
func normalizeBuildFunctionParametersRootForTool(value any, param, toolName string) (any, bool, error) {
|
||||
schema, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return value, false, nil
|
||||
return nil, false, invalidBuildFunctionParametersRoot(buildFunctionParametersRootContext{param: param, toolName: toolName})
|
||||
}
|
||||
normalized := cloneJSONObject(schema)
|
||||
changed := false
|
||||
doc := cloneJSONObject(schema)
|
||||
context := buildFunctionParametersRootContext{param: param, toolName: toolName}
|
||||
collector := rootObjectLeafCollector{doc: doc, context: context}
|
||||
if err := collector.walk(doc, nil, nil, 0, 0); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if len(collector.leaves) == 0 {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(context)
|
||||
}
|
||||
if collector.requiresDisjoint && !rootObjectLeavesPairwiseDisjoint(collector.leaves, doc) {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(context)
|
||||
}
|
||||
if !collector.changed {
|
||||
return doc, false, nil
|
||||
}
|
||||
var out map[string]any
|
||||
if len(collector.leaves) == 1 {
|
||||
out = collector.leaves[0]
|
||||
} else {
|
||||
if collector.rootUnionKeyword == "" {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(context)
|
||||
}
|
||||
branches := make([]any, len(collector.leaves))
|
||||
for i, leaf := range collector.leaves {
|
||||
branches[i] = leaf
|
||||
}
|
||||
out = map[string]any{collector.rootUnionKeyword: branches}
|
||||
}
|
||||
delete(out, "$defs")
|
||||
if defs := referencedDefs(out, doc); len(defs) > 0 {
|
||||
out["$defs"] = defs
|
||||
}
|
||||
return out, !reflect.DeepEqual(out, schema), nil
|
||||
}
|
||||
|
||||
if rawTypes, ok := normalized["type"].([]any); ok {
|
||||
filtered, removedNull := withoutNullSchemaTypes(rawTypes)
|
||||
if removedNull {
|
||||
changed = true
|
||||
switch len(filtered) {
|
||||
case 0:
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
case 1:
|
||||
if filtered[0] != "object" {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
}
|
||||
normalized["type"] = "object"
|
||||
default:
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
func (c *rootObjectLeafCollector) walk(node any, constraints []map[string]any, seen map[string]struct{}, depth, unionDepth int) error {
|
||||
if depth > maxRootUnionDepth || len(c.leaves) > maxRootUnionLeaves {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
schema, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if ref, ok := schema["$ref"].(string); ok {
|
||||
if !strings.HasPrefix(ref, "#/") {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if _, loop := seen[ref]; loop {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
resolved, ok := resolveLocalSchemaRef(c.doc, ref)
|
||||
if !ok {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
sibling, siblingErr := rootSchemaSiblingConstraint(schema, "$ref")
|
||||
if siblingErr != nil {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if len(sibling) > 0 {
|
||||
constraints = append(cloneRootConstraints(constraints), sibling)
|
||||
}
|
||||
next := cloneRefSeen(seen)
|
||||
next[ref] = struct{}{}
|
||||
c.changed = true
|
||||
return c.walk(resolved, constraints, next, depth+1, unionDepth)
|
||||
}
|
||||
normalized, nullOnly, typeChanged := normalizeRootObjectType(schema)
|
||||
if nullOnly {
|
||||
c.changed = true
|
||||
return nil
|
||||
}
|
||||
if typeChanged {
|
||||
c.changed = true
|
||||
}
|
||||
keyword, branches, unionErr := rootUnion(normalized)
|
||||
if unionErr != nil {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if keyword != "" {
|
||||
if c.rootUnionKeyword == "" {
|
||||
c.rootUnionKeyword = keyword
|
||||
} else {
|
||||
c.changed = true
|
||||
if c.rootUnionKeyword == "oneOf" || keyword != c.rootUnionKeyword {
|
||||
c.requiresDisjoint = true
|
||||
}
|
||||
}
|
||||
sibling, siblingErr := rootSchemaSiblingConstraint(normalized, keyword)
|
||||
if siblingErr != nil {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if len(sibling) > 0 {
|
||||
constraints = append(cloneRootConstraints(constraints), sibling)
|
||||
}
|
||||
for _, branch := range branches {
|
||||
if err := c.walk(branch, constraints, cloneRefSeen(seen), depth+1, unionDepth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if unionDepth == 0 && c.rootUnionKeyword != "" {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
if !isObjectRootSchema(normalized, c.doc, nil) {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
leaf := cloneJSONObject(normalized)
|
||||
if leaf["type"] != "object" {
|
||||
leaf["type"] = "object"
|
||||
c.changed = true
|
||||
}
|
||||
delete(leaf, "$defs")
|
||||
leaf = applyRootConstraints(leaf, constraints)
|
||||
c.leaves = append(c.leaves, leaf)
|
||||
if len(c.leaves) > maxRootUnionLeaves {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, keyword := range []string{"anyOf", "oneOf"} {
|
||||
rawBranches, exists := normalized[keyword]
|
||||
func rootUnion(schema map[string]any) (string, []any, error) {
|
||||
var keyword string
|
||||
var branches []any
|
||||
for _, candidate := range []string{"anyOf", "oneOf"} {
|
||||
raw, exists := schema[candidate]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
branches, ok := rawBranches.([]any)
|
||||
if !ok {
|
||||
continue
|
||||
if keyword != "" {
|
||||
return "", nil, fmt.Errorf("multiple root unions")
|
||||
}
|
||||
filtered := make([]any, 0, len(branches))
|
||||
removedNull := false
|
||||
for _, rawBranch := range branches {
|
||||
if isNullOnlySchema(rawBranch) {
|
||||
removedNull = true
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, rawBranch)
|
||||
parsed, ok := raw.([]any)
|
||||
if !ok || len(parsed) == 0 {
|
||||
return "", nil, fmt.Errorf("invalid root union")
|
||||
}
|
||||
if !removedNull {
|
||||
continue
|
||||
}
|
||||
changed = true
|
||||
if len(filtered) == 0 {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
}
|
||||
if len(filtered) == 1 {
|
||||
branch, ok := filtered[0].(map[string]any)
|
||||
if !ok || !isObjectRootSchema(branch, normalized, nil) {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
}
|
||||
if len(normalized) == 1 {
|
||||
normalized = cloneJSONObject(branch)
|
||||
normalized["type"] = "object"
|
||||
continue
|
||||
}
|
||||
normalized[keyword] = cloneJSONArray(filtered)
|
||||
normalized["type"] = "object"
|
||||
continue
|
||||
}
|
||||
for _, rawBranch := range filtered {
|
||||
branch, ok := rawBranch.(map[string]any)
|
||||
if !ok || !isObjectRootSchema(branch, normalized, nil) {
|
||||
return nil, false, invalidBuildFunctionParametersRoot(param)
|
||||
}
|
||||
}
|
||||
normalized[keyword] = cloneJSONArray(filtered)
|
||||
normalized["type"] = "object"
|
||||
keyword, branches = candidate, parsed
|
||||
}
|
||||
return keyword, branches, nil
|
||||
}
|
||||
|
||||
return normalized, changed, nil
|
||||
func normalizeRootObjectType(schema map[string]any) (map[string]any, bool, bool) {
|
||||
out := cloneJSONObject(schema)
|
||||
rawTypes, isArray := out["type"].([]any)
|
||||
if !isArray {
|
||||
return out, out["type"] == "null", false
|
||||
}
|
||||
filtered, removedNull := withoutNullSchemaTypes(rawTypes)
|
||||
if len(filtered) == 0 {
|
||||
return out, true, removedNull
|
||||
}
|
||||
for _, value := range filtered {
|
||||
if value != "object" {
|
||||
return out, false, false
|
||||
}
|
||||
}
|
||||
out["type"] = "object"
|
||||
return out, false, true
|
||||
}
|
||||
|
||||
func rootSchemaSiblingConstraint(schema map[string]any, excluded string) (map[string]any, error) {
|
||||
constraint := make(map[string]any)
|
||||
for key, value := range schema {
|
||||
switch key {
|
||||
case excluded, "$defs":
|
||||
continue
|
||||
case "anyOf", "oneOf":
|
||||
return nil, fmt.Errorf("multiple root expressions")
|
||||
case "type":
|
||||
if value == "object" {
|
||||
continue
|
||||
}
|
||||
case "properties":
|
||||
if properties, ok := value.(map[string]any); ok && len(properties) == 0 {
|
||||
continue
|
||||
}
|
||||
case "required":
|
||||
if required, ok := value.([]any); ok && len(required) == 0 {
|
||||
continue
|
||||
}
|
||||
case "additionalProperties":
|
||||
if allowed, ok := value.(bool); ok && allowed {
|
||||
continue
|
||||
}
|
||||
}
|
||||
constraint[key] = cloneJSONValue(value)
|
||||
}
|
||||
return constraint, nil
|
||||
}
|
||||
|
||||
func cloneRootConstraints(constraints []map[string]any) []map[string]any {
|
||||
return append([]map[string]any(nil), constraints...)
|
||||
}
|
||||
|
||||
func applyRootConstraints(leaf map[string]any, constraints []map[string]any) map[string]any {
|
||||
if len(constraints) == 0 {
|
||||
return leaf
|
||||
}
|
||||
allOf := make([]any, 0, len(constraints))
|
||||
for _, constraint := range constraints {
|
||||
if len(constraint) > 0 {
|
||||
allOf = append(allOf, cloneJSONObject(constraint))
|
||||
}
|
||||
}
|
||||
allOf = append(allOf, leaf)
|
||||
return map[string]any{"type": "object", "allOf": allOf}
|
||||
}
|
||||
|
||||
func cloneRefSeen(seen map[string]struct{}) map[string]struct{} {
|
||||
out := make(map[string]struct{}, len(seen))
|
||||
for key, value := range seen {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func rootObjectLeavesPairwiseDisjoint(leaves []map[string]any, doc map[string]any) bool {
|
||||
for i := 0; i < len(leaves); i++ {
|
||||
for j := i + 1; j < len(leaves); j++ {
|
||||
if !rootObjectSchemasDisjoint(leaves[i], leaves[j], doc) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type rootObjectSchemaFacts struct {
|
||||
required map[string]struct{}
|
||||
values map[string]map[string]struct{}
|
||||
}
|
||||
|
||||
func rootObjectSchemasDisjoint(left, right map[string]any, doc map[string]any) bool {
|
||||
leftFacts := collectRootObjectSchemaFacts(left, doc, nil)
|
||||
rightFacts := collectRootObjectSchemaFacts(right, doc, nil)
|
||||
for property := range leftFacts.required {
|
||||
if _, required := rightFacts.required[property]; !required {
|
||||
continue
|
||||
}
|
||||
leftValues, leftKnown := leftFacts.values[property]
|
||||
rightValues, rightKnown := rightFacts.values[property]
|
||||
if leftKnown && rightKnown && finiteValueSetsDisjoint(leftValues, rightValues) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func collectRootObjectSchemaFacts(schema map[string]any, doc map[string]any, seen map[string]struct{}) rootObjectSchemaFacts {
|
||||
facts := rootObjectSchemaFacts{required: map[string]struct{}{}, values: map[string]map[string]struct{}{}}
|
||||
collectRootObjectSchemaFactsInto(schema, doc, seen, &facts)
|
||||
return facts
|
||||
}
|
||||
|
||||
func collectRootObjectSchemaFactsInto(schema map[string]any, doc map[string]any, seen map[string]struct{}, facts *rootObjectSchemaFacts) {
|
||||
if ref, ok := schema["$ref"].(string); ok {
|
||||
if _, loop := seen[ref]; !loop {
|
||||
if resolved, resolvedOK := resolveLocalSchemaRef(doc, ref); resolvedOK {
|
||||
next := cloneRefSeen(seen)
|
||||
next[ref] = struct{}{}
|
||||
collectRootObjectSchemaFactsInto(resolved, doc, next, facts)
|
||||
}
|
||||
}
|
||||
}
|
||||
if required, ok := schema["required"].([]any); ok {
|
||||
for _, raw := range required {
|
||||
if property, ok := raw.(string); ok {
|
||||
facts.required[property] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
if properties, ok := schema["properties"].(map[string]any); ok {
|
||||
for property, raw := range properties {
|
||||
propertySchema, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
values, known := finiteSchemaValues(propertySchema, doc, nil)
|
||||
if !known {
|
||||
continue
|
||||
}
|
||||
if existing, exists := facts.values[property]; exists {
|
||||
facts.values[property] = intersectFiniteValueSets(existing, values)
|
||||
} else {
|
||||
facts.values[property] = values
|
||||
}
|
||||
}
|
||||
}
|
||||
if allOf, ok := schema["allOf"].([]any); ok {
|
||||
for _, raw := range allOf {
|
||||
if part, ok := raw.(map[string]any); ok {
|
||||
collectRootObjectSchemaFactsInto(part, doc, cloneRefSeen(seen), facts)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func finiteSchemaValues(schema map[string]any, doc map[string]any, seen map[string]struct{}) (map[string]struct{}, bool) {
|
||||
if ref, ok := schema["$ref"].(string); ok {
|
||||
if _, loop := seen[ref]; loop {
|
||||
return nil, false
|
||||
}
|
||||
resolved, resolvedOK := resolveLocalSchemaRef(doc, ref)
|
||||
if !resolvedOK {
|
||||
return nil, false
|
||||
}
|
||||
next := cloneRefSeen(seen)
|
||||
next[ref] = struct{}{}
|
||||
return finiteSchemaValues(resolved, doc, next)
|
||||
}
|
||||
if value, exists := schema["const"]; exists {
|
||||
key, ok := finiteSchemaValueKey(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return map[string]struct{}{key: {}}, true
|
||||
}
|
||||
if values, ok := schema["enum"].([]any); ok {
|
||||
result := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
key, valid := finiteSchemaValueKey(value)
|
||||
if !valid {
|
||||
return nil, false
|
||||
}
|
||||
result[key] = struct{}{}
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func finiteSchemaValueKey(value any) (string, bool) {
|
||||
switch value.(type) {
|
||||
case nil, bool, float64, string:
|
||||
raw, err := json.Marshal(value)
|
||||
return string(raw), err == nil
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func finiteValueSetsDisjoint(left, right map[string]struct{}) bool {
|
||||
for value := range left {
|
||||
if _, exists := right[value]; exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func intersectFiniteValueSets(left, right map[string]struct{}) map[string]struct{} {
|
||||
intersection := make(map[string]struct{})
|
||||
for value := range left {
|
||||
if _, exists := right[value]; exists {
|
||||
intersection[value] = struct{}{}
|
||||
}
|
||||
}
|
||||
return intersection
|
||||
}
|
||||
|
||||
func referencedDefs(node any, doc map[string]any) map[string]any {
|
||||
rawDefs, _ := doc["$defs"].(map[string]any)
|
||||
if len(rawDefs) == 0 {
|
||||
return nil
|
||||
}
|
||||
needed := map[string]struct{}{}
|
||||
collectDefRefs(node, needed)
|
||||
changed := true
|
||||
for changed {
|
||||
changed = false
|
||||
for name := range needed {
|
||||
extra := map[string]struct{}{}
|
||||
collectDefRefs(rawDefs[name], extra)
|
||||
for key := range extra {
|
||||
if _, exists := needed[key]; !exists {
|
||||
needed[key] = struct{}{}
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(needed) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]any, len(needed))
|
||||
for name := range needed {
|
||||
if def, ok := rawDefs[name]; ok {
|
||||
out[name] = cloneJSONValue(def)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func collectDefRefs(node any, needed map[string]struct{}) {
|
||||
switch typed := node.(type) {
|
||||
case map[string]any:
|
||||
if ref, ok := typed["$ref"].(string); ok && strings.HasPrefix(ref, "#/$defs/") {
|
||||
if name, nameOK := rootDefinitionName(ref); nameOK {
|
||||
needed[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, value := range typed {
|
||||
collectDefRefs(value, needed)
|
||||
}
|
||||
case []any:
|
||||
for _, value := range typed {
|
||||
collectDefRefs(value, needed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rootDefinitionName(ref string) (string, bool) {
|
||||
tail := strings.TrimPrefix(ref, "#/$defs/")
|
||||
if tail == ref || tail == "" {
|
||||
return "", false
|
||||
}
|
||||
encoded := strings.SplitN(tail, "/", 2)[0]
|
||||
return strings.ReplaceAll(strings.ReplaceAll(encoded, "~1", "/"), "~0", "~"), true
|
||||
}
|
||||
|
||||
func withoutNullSchemaTypes(types []any) ([]any, bool) {
|
||||
@@ -447,10 +823,14 @@ func resolveLocalSchemaRef(root map[string]any, ref string) (map[string]any, boo
|
||||
return resolved, ok
|
||||
}
|
||||
|
||||
func invalidBuildFunctionParametersRoot(param string) error {
|
||||
func invalidBuildFunctionParametersRoot(context buildFunctionParametersRootContext) error {
|
||||
message := context.param + " 顶层必须是非 nullable 的 object schema"
|
||||
if context.toolName != "" {
|
||||
message = fmt.Sprintf("工具 %s 的 %s 顶层必须是非 nullable 的 object schema", context.toolName, context.param)
|
||||
}
|
||||
return &responsesRequestError{
|
||||
Message: param + " 顶层必须是非 nullable 的 object schema",
|
||||
Param: param,
|
||||
Message: message,
|
||||
Param: context.param,
|
||||
Code: "invalid_parameter",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +279,7 @@ func TestNormalizeResponsesRequestRemovesNullableFunctionParameterRoot(t *testin
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_nullable_root_normalized") {
|
||||
if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") {
|
||||
t.Fatalf("compatibility = %#v", compatibility)
|
||||
}
|
||||
var payload map[string]any
|
||||
@@ -328,7 +328,7 @@ func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_nullable_root_normalized") {
|
||||
if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") {
|
||||
t.Fatalf("compatibility = %#v", compatibility)
|
||||
}
|
||||
var payload map[string]any
|
||||
@@ -336,12 +336,12 @@ func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing
|
||||
t.Fatal(err)
|
||||
}
|
||||
parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any)
|
||||
if parameters["type"] != "object" {
|
||||
if parameters["type"] != "object" || parameters["anyOf"] != nil {
|
||||
t.Fatalf("upstream parameters = %#v", parameters)
|
||||
}
|
||||
branches := parameters["anyOf"].([]any)
|
||||
if len(branches) != 1 || branches[0].(map[string]any)["$ref"] != "#/$defs/Args" {
|
||||
t.Fatalf("upstream branches = %#v", branches)
|
||||
properties := parameters["properties"].(map[string]any)
|
||||
if properties["query"].(map[string]any)["type"] != "string" {
|
||||
t.Fatalf("upstream properties = %#v", properties)
|
||||
}
|
||||
visibleParameters := compatibility.visibleTools[0].(map[string]any)["parameters"].(map[string]any)
|
||||
visibleBranches := visibleParameters["anyOf"].([]any)
|
||||
@@ -381,6 +381,15 @@ func TestNormalizeBuildFunctionParametersRootVariants(t *testing.T) {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "single object type array",
|
||||
schema: map[string]any{"type": []any{"object"}, "properties": map[string]any{}},
|
||||
check: func(t *testing.T, normalized map[string]any, changed bool) {
|
||||
if !changed || normalized["type"] != "object" {
|
||||
t.Fatalf("normalized=%#v changed=%v", normalized, changed)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oneOf",
|
||||
schema: map[string]any{"oneOf": []any{
|
||||
|
||||
@@ -336,6 +336,59 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRequestLiftsFunctionParameterUnion(t *testing.T) {
|
||||
spec, ok := Resolve("grok-4.3")
|
||||
if !ok {
|
||||
t.Fatal("grok-4.3 missing")
|
||||
}
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"input":"hello",
|
||||
"tools":[{"type":"function","name":"automation_update","parameters":{
|
||||
"$defs":{
|
||||
"View":{"type":"object","properties":{"mode":{"enum":["view"],"type":"string"}},"required":["mode"]},
|
||||
"Create":{"oneOf":[{"type":"object","properties":{"mode":{"enum":["create"],"type":"string"}},"required":["mode"]}]}
|
||||
},
|
||||
"type":"object",
|
||||
"properties":{},
|
||||
"oneOf":[{"$ref":"#/$defs/View"},{"$ref":"#/$defs/Create"}]
|
||||
}}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any)
|
||||
branches, _ := parameters["oneOf"].([]any)
|
||||
if len(branches) != 2 {
|
||||
t.Fatalf("parameters = %#v", parameters)
|
||||
}
|
||||
for i, raw := range branches {
|
||||
branch, _ := raw.(map[string]any)
|
||||
if branch["type"] != "object" || branch["$ref"] != nil || branch["oneOf"] != nil {
|
||||
t.Fatalf("branch[%d] = %#v", i, branch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRequestIllegalFunctionRootNamesTool(t *testing.T) {
|
||||
spec, ok := Resolve("grok-4.3")
|
||||
if !ok {
|
||||
t.Fatal("grok-4.3 missing")
|
||||
}
|
||||
_, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"input":"hello",
|
||||
"tools":[{"type":"function","name":"automation_update","parameters":{"type":"string"}}]
|
||||
}`), spec)
|
||||
if err == nil || !strings.Contains(err.Error(), "automation_update") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) {
|
||||
spec, ok := Resolve("grok-4.3")
|
||||
if !ok {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/cli"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -46,7 +47,10 @@ func normalizeRequestWithMetadata(body []byte, spec ModelSpec, metadata *provide
|
||||
normalizeReasoning(payload, spec)
|
||||
updateConsoleReasoningMetadata(payload, spec, requestedEffort, metadata)
|
||||
ensureReasoningInclude(payload)
|
||||
retainedClientTools := normalizeConsoleTools(payload)
|
||||
retainedClientTools, err := normalizeConsoleTools(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalizeConsoleToolChoice(payload, retainedClientTools)
|
||||
return json.Marshal(payload)
|
||||
}
|
||||
@@ -241,18 +245,18 @@ func ensureReasoningInclude(payload map[string]any) {
|
||||
payload["include"] = result
|
||||
}
|
||||
|
||||
func normalizeConsoleTools(payload map[string]any) bool {
|
||||
func normalizeConsoleTools(payload map[string]any) (bool, error) {
|
||||
value, exists := payload["tools"]
|
||||
if !exists || value == nil {
|
||||
delete(payload, "tools")
|
||||
delete(payload, "tool_choice")
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
tools, ok := value.([]any)
|
||||
if !ok {
|
||||
delete(payload, "tools")
|
||||
delete(payload, "tool_choice")
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
hasClientViewImage := hasConsoleFunctionTool(tools, "view_image")
|
||||
result := make([]any, 0, len(tools))
|
||||
@@ -315,6 +319,14 @@ func normalizeConsoleTools(payload map[string]any) bool {
|
||||
clean := map[string]any{"type": "function", "name": strings.TrimSpace(name)}
|
||||
for _, field := range []string{"description", "parameters", "strict"} {
|
||||
if fieldValue, exists := tool[field]; exists {
|
||||
if field == "parameters" {
|
||||
normalized, _, err := cli.NormalizeBuildFunctionParametersRoot(fieldValue, "tools.parameters", strings.TrimSpace(name))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
clean[field] = normalized
|
||||
continue
|
||||
}
|
||||
clean[field] = fieldValue
|
||||
}
|
||||
}
|
||||
@@ -331,10 +343,10 @@ func normalizeConsoleTools(payload map[string]any) bool {
|
||||
if len(result) == 0 {
|
||||
delete(payload, "tools")
|
||||
delete(payload, "tool_choice")
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
payload["tools"] = result
|
||||
return retainedClientTools
|
||||
return retainedClientTools, nil
|
||||
}
|
||||
|
||||
func hasConsoleFunctionTool(tools []any, target string) bool {
|
||||
|
||||
@@ -1292,10 +1292,30 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
return
|
||||
}
|
||||
copyHeaders(c.Writer.Header(), result.Header)
|
||||
c.Status(result.StatusCode)
|
||||
if result.StatusCode >= 400 {
|
||||
errorCode = "upstream_error"
|
||||
if stream && !isEventStreamContentType(result.Header.Get("Content-Type")) {
|
||||
raw, readErr := io.ReadAll(io.LimitReader(result.Body, maxJSONResponseTransferBytes+1))
|
||||
if readErr != nil {
|
||||
if anthropic {
|
||||
writeAnthropicError(c, http.StatusBadGateway, "api_error", "读取上游错误响应失败", "upstream_error")
|
||||
} else {
|
||||
writeOpenAIError(c, http.StatusBadGateway, "upstream_error", "读取上游错误响应失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
c.Writer.Header().Del("Content-Length")
|
||||
code, message := gateway.ClassifyUpstreamHTTPError(result.StatusCode, raw)
|
||||
errorCode = code
|
||||
if anthropic {
|
||||
writeAnthropicError(c, result.StatusCode, anthropicUpstreamHTTPErrorType(result.StatusCode), message, errorCode)
|
||||
} else {
|
||||
writeOpenAIError(c, result.StatusCode, errorCode, message)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status(result.StatusCode)
|
||||
var err error
|
||||
if stream {
|
||||
metadata, copyErr := copyStreamWithFallbackModel(c.Writer, result.Body, protocol, result.MarkFirstToken, fallbackModel)
|
||||
@@ -1312,6 +1332,21 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
}
|
||||
}
|
||||
|
||||
func anthropicUpstreamHTTPErrorType(status int) string {
|
||||
switch status {
|
||||
case http.StatusBadRequest, http.StatusConflict, http.StatusUnprocessableEntity:
|
||||
return "invalid_request_error"
|
||||
case http.StatusNotFound:
|
||||
return "not_found_error"
|
||||
case http.StatusTooManyRequests:
|
||||
return "rate_limit_error"
|
||||
case http.StatusRequestTimeout, http.StatusGatewayTimeout:
|
||||
return "timeout_error"
|
||||
default:
|
||||
return "api_error"
|
||||
}
|
||||
}
|
||||
|
||||
func classifyCopyError(ctx context.Context, err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
@@ -2232,6 +2267,11 @@ func copyHeaders(destination, source http.Header) {
|
||||
}
|
||||
}
|
||||
|
||||
func isEventStreamContentType(value string) bool {
|
||||
mediaType, _, err := mime.ParseMediaType(value)
|
||||
return err == nil && strings.EqualFold(mediaType, "text/event-stream")
|
||||
}
|
||||
|
||||
func writeOpenAIError(c *gin.Context, status int, code, message string) {
|
||||
errorType := "invalid_request_error"
|
||||
switch {
|
||||
|
||||
@@ -1644,6 +1644,98 @@ func TestWriteResultUpstreamCutStaysUpstreamInterrupted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteProtocolResultMapsJSONInvalidArgumentWithoutCopyStream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
body := `{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}`
|
||||
var finalCode string
|
||||
recorded := false
|
||||
result := &gateway.Result{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Status: "400 Bad Request",
|
||||
Header: http.Header{"Content-Type": {"application/json"}, "Content-Length": {fmt.Sprintf("%d", len(body))}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
RecordStreamFailure: func(gateway.StreamFailureDiagnostic) {
|
||||
recorded = true
|
||||
},
|
||||
Finalize: func(_ gateway.Usage, _, code string) {
|
||||
finalCode = code
|
||||
},
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
handler.writeResponsesResult(c, result, true, "")
|
||||
})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != http.StatusBadRequest || recorded || finalCode != "invalid_argument" {
|
||||
t.Fatalf("status=%d recorded=%v final=%q body=%s", recorder.Code, recorded, finalCode, recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "mcp__codex_app__automation_update") || strings.Contains(recorder.Body.String(), "upstream_stream_incomplete") {
|
||||
t.Fatalf("body=%s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteProtocolResultAnthropicJSONReadFailureKeepsAnthropicShape(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
var finalCode string
|
||||
result := &gateway.Result{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Status: "400 Bad Request",
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(&chunkErrorReader{data: []byte(`{"error":"partial"}`)}),
|
||||
Finalize: func(_ gateway.Usage, _, code string) {
|
||||
finalCode = code
|
||||
},
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
handler.writeAnthropicResult(c, result, true)
|
||||
})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
|
||||
var payload struct {
|
||||
Type string `json:"type"`
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recorder.Code != http.StatusBadGateway || payload.Type != "error" || payload.Error.Type != "api_error" || payload.Error.Code != "upstream_error" || finalCode != "upstream_error" {
|
||||
t.Fatalf("status=%d payload=%#v final=%q body=%s", recorder.Code, payload, finalCode, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteProtocolResultDoesNotRemapOtherJSON4xxAsServerError(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
body := `{"error":{"code":"not_found","message":"requested response is missing"}}`
|
||||
var finalCode string
|
||||
result := &gateway.Result{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Status: "404 Not Found",
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Finalize: func(_ gateway.Usage, _, code string) {
|
||||
finalCode = code
|
||||
},
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
handler.writeResponsesResult(c, result, true, "")
|
||||
})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != http.StatusNotFound || finalCode != "upstream_error" || !strings.Contains(recorder.Body.String(), "requested response is missing") {
|
||||
t.Fatalf("status=%d final=%q body=%s", recorder.Code, finalCode, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteResultOutputLoopFinalizesDistinctCode(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
|
||||
Reference in new issue
Block a user