From 631a315a79a960a77253a70a2d2190249eab6d19 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:27:00 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20BPS=20?= =?UTF-8?q?=E5=BF=85=E9=80=89=E4=B8=8E=E6=8C=87=E5=AE=9A=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/basispoints/README.md | 15 +++ .../internal/service/basispoints/request.go | 15 ++- .../service/basispoints/tool_choice.go | 115 +++++++++++++++++ .../service/basispoints/tool_choice_test.go | 118 ++++++++++++++++++ .../service/basispoints/tool_repair.go | 9 +- .../basispoints/unknown_tool_repair.go | 4 +- .../service/openai_excel_bps_tools_test.go | 2 +- 7 files changed, 270 insertions(+), 8 deletions(-) create mode 100644 backend/internal/service/basispoints/tool_choice.go create mode 100644 backend/internal/service/basispoints/tool_choice_test.go diff --git a/backend/internal/service/basispoints/README.md b/backend/internal/service/basispoints/README.md index 16664e5acdc2..6fbb9a64c632 100644 --- a/backend/internal/service/basispoints/README.md +++ b/backend/internal/service/basispoints/README.md @@ -223,3 +223,18 @@ these ceilings are not throughput or memory-use guarantees. - Failure/cancellation retains usage and withholds unvalidated tools. Readers stop at cancellation without waiting for EOF, including correction and image compaction readers. This does not add a BPS WebSocket transport. + +# Required and named client tools + +`tool_choice` accepts `auto`, `none`, `required`, and named `function` or `custom` +objects. A named selection must identify a declared tool of the same kind. Use +its full catalog name or `namespace` plus `name`; a short name must be unique. +Unsupported selection forms (including `allowed_tools`) return a request error. + +The constraint belongs to this request and does not prune the inherited catalog. +The adapter communicates it to BPS, then validates the complete returned batch +against the selected identity and the original schema before emitting tool calls +or saving replay entries. A missing call or a different selected target fails; +it is not silently converted to `auto` or repaired into another operation. +Upstream constrained decoding is not provided. Normal text can still stream +before a final tool validation failure, which ends with `response.failed`. diff --git a/backend/internal/service/basispoints/request.go b/backend/internal/service/basispoints/request.go index dd69b434664b..267144661163 100644 --- a/backend/internal/service/basispoints/request.go +++ b/backend/internal/service/basispoints/request.go @@ -37,6 +37,8 @@ type Bridge struct { completedToolHistory map[string]bool disallowParallel bool clientStream bool + toolChoice string + selectedTool *tool } func decode(raw []byte, target any) error { @@ -137,10 +139,11 @@ func prepareWithInheritedCatalog(raw []byte, scope string, replay *ReplayCache, } b := &Bridge{nativeToolImages: nativeToolImages, RequestedEffort: requested, Effort: effort, tools: make(map[string]tool), unsupportedTools: make(map[string]bool), structured: structured, replay: replay, scope: scope} b.clientStream, _ = source["stream"].(bool) - choice := source["tool_choice"] - if choice != nil && text(choice) != "auto" && text(choice) != "none" { - return nil, nil, fmt.Errorf("basispoints supports tool_choice auto or none only") + choice, named, err := parseToolChoice(source["tool_choice"]) + if err != nil { + return nil, nil, err } + b.toolChoice = choice if parallel, exists := source["parallel_tool_calls"]; exists { enabled, ok := parallel.(bool) if !ok { @@ -160,12 +163,15 @@ func prepareWithInheritedCatalog(raw []byte, scope string, replay *ReplayCache, } } var catalog []any - if text(choice) != "none" { + if choice != "none" { catalog, err = b.collectClientCatalog(source, inherited) if err != nil { return nil, nil, err } } + if err := b.resolveToolChoice(named); err != nil { + return nil, nil, err + } var input []any switch v := source["input"].(type) { case string: @@ -217,6 +223,7 @@ func prepareWithInheritedCatalog(raw []byte, scope string, replay *ReplayCache, b.Warnings = append(b.Warnings, warning) protocol += "\n" + warning + ". These declarations were omitted. Do not claim to have used them. If the task requires one, explain the limitation or use a suitable declared client tool." } + protocol += b.toolChoiceInstructions() if structured != nil { protocol += "\n" + structured.instructions() } diff --git a/backend/internal/service/basispoints/tool_choice.go b/backend/internal/service/basispoints/tool_choice.go new file mode 100644 index 000000000000..d7affc77c9aa --- /dev/null +++ b/backend/internal/service/basispoints/tool_choice.go @@ -0,0 +1,115 @@ +package basispoints + +import ( + "fmt" + "strings" +) + +type namedToolChoice struct{ kind, name, namespace string } + +// Diagnostics contain fixed reasons, never caller-supplied names or values. +type toolChoiceRequestError struct{ reason string } + +func (e toolChoiceRequestError) Error() string { + return "basispoints tool_choice rejected; reason=" + e.reason +} + +type toolChoiceViolation struct{ reason string } + +func (e toolChoiceViolation) Error() string { + return "basispoints response violates tool_choice; reason=" + e.reason + "; no tool was executed" +} + +func parseToolChoice(value any) (string, *namedToolChoice, error) { + if value == nil { + return "auto", nil, nil + } + if mode, ok := value.(string); ok { + switch mode { + case "auto", "none", "required": + return mode, nil, nil + default: + return "", nil, toolChoiceRequestError{"unsupported_mode"} + } + } + choice, ok := value.(object) + if !ok { + return "", nil, toolChoiceRequestError{"invalid_shape"} + } + kind := text(choice["type"]) + if kind != "function" && kind != "custom" { + return "", nil, toolChoiceRequestError{"unsupported_type"} + } + name := text(choice["name"]) + if name == "" || name != strings.TrimSpace(name) { + return "", nil, toolChoiceRequestError{"invalid_name"} + } + namespace := "" + if raw, exists := choice["namespace"]; exists { + namespace, ok = raw.(string) + if !ok || namespace == "" || namespace != strings.TrimSpace(namespace) { + return "", nil, toolChoiceRequestError{"invalid_namespace"} + } + } + for key := range choice { + if key != "type" && key != "name" && key != "namespace" { + return "", nil, toolChoiceRequestError{"unsupported_field"} + } + } + return "required", &namedToolChoice{kind: kind, name: name, namespace: namespace}, nil +} + +func (b *Bridge) resolveToolChoice(choice *namedToolChoice) error { + if b.toolChoice == "required" && len(b.tools) == 0 { + return toolChoiceRequestError{"empty_catalog"} + } + if choice == nil { + return nil + } + for key, info := range b.tools { + if choice.name != key && choice.name != info.Name { + continue + } + if choice.namespace != "" && choice.namespace != info.Namespace { + continue + } + if b.selectedTool != nil { + return toolChoiceRequestError{"ambiguous_name"} + } + selected := info + b.selectedTool = &selected + } + if b.selectedTool == nil { + return toolChoiceRequestError{"undeclared_target"} + } + if b.selectedTool.Kind != choice.kind { + return toolChoiceRequestError{"type_mismatch"} + } + return nil +} + +func (b *Bridge) validateSelectedTool(item object) error { + if b.selectedTool == nil { + return nil + } + target := b.selectedTool + kind := "function_call" + if target.Kind == "custom" { + kind = "custom_tool_call" + } + if text(item["type"]) != kind || text(item["name"]) != target.Name || text(item["namespace"]) != target.Namespace { + return toolChoiceViolation{"wrong_target"} + } + return nil +} + +func (b *Bridge) toolChoiceInstructions() string { + if b.selectedTool != nil { + target := b.selectedTool + return fmt.Sprintf("\nThis response must call the declared %s tool %s in namespace %s at least once, using its catalog transport and unchanged parameter schema. Do not call any other tool. A text-only response fails this requirement. Other catalog entries remain for history only.", target.Kind, quoted(target.Name), quoted(target.Namespace)) + } + if b.toolChoice == "required" { + return "\nThis response must include at least one valid call to a tool declared in the current client catalog. Use its catalog transport and parameter schema. Text or a promise to call a tool does not satisfy tool_choice=required." + } + return "" +} diff --git a/backend/internal/service/basispoints/tool_choice_test.go b/backend/internal/service/basispoints/tool_choice_test.go new file mode 100644 index 000000000000..9b6c959a2bb3 --- /dev/null +++ b/backend/internal/service/basispoints/tool_choice_test.go @@ -0,0 +1,118 @@ +package basispoints + +import ( + "context" + "encoding/json" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func choiceTools() []any { + return []any{ + object{"type": "function", "name": "lookup", "parameters": object{"type": "object", "properties": object{"key": object{"type": "string"}}, "required": []any{"key"}, "additionalProperties": false}}, + object{"type": "function", "name": "other"}, + object{"type": "namespace", "name": "client", "tools": []any{object{"type": "custom", "name": "execute"}}}, + } +} + +func TestToolChoiceAcceptsDeclaredIdentity(t *testing.T) { + for _, choice := range []any{"required", object{"type": "function", "name": "lookup"}, object{"type": "custom", "name": "client.execute"}, object{"type": "custom", "name": "execute", "namespace": "client"}, object{"type": "custom", "name": "execute"}} { + t.Run(quoted(choice), func(t *testing.T) { + source := testSource() + source["tools"], source["tool_choice"] = choiceTools(), choice + wire, bridge := mustPrepare(t, source, "choice", nil) + require.Len(t, bridge.tools, 3, "selection must not prune the shared catalog") + require.NotContains(t, wire, "tool_choice", "BPS receives instructions, not unsupported native choice") + call := nativeCall(object{"name": "lookup", "arguments": object{"key": "value"}}) + if bridge.selectedTool != nil && bridge.selectedTool.Kind == "custom" { + call = repairCall("custom", "codex2api.custom/client.execute", "literal input") + } + response := repairResponse("resp", 1, 1, call) + require.NoError(t, bridge.translateResponse(response)) + }) + } +} + +func TestToolChoiceRejectsInvalidSelectionsWithoutEchoingValues(t *testing.T) { + for _, choice := range []any{false, "private-choice", object{"type": "allowed_tools"}, object{"type": "function", "name": "private-missing"}, object{"type": "function", "name": "lookup", "namespace": "private-namespace"}, object{"type": "custom", "name": "lookup"}, object{"type": "function", "name": "lookup", "namespace": false}, object{"type": "function", "name": "lookup", "extra": "private-value"}} { + source := testSource() + source["tools"], source["tool_choice"] = choiceTools(), choice + raw, err := json.Marshal(source) + require.NoError(t, err) + _, _, err = Prepare(raw, "choice", nil) + require.Error(t, err) + require.NotContains(t, err.Error(), "private-") + } + for _, tools := range []any{nil, []any{object{"type": "web_search"}}} { + source := testSource() + source["tools"], source["tool_choice"] = tools, "required" + raw, _ := json.Marshal(source) + _, _, err := Prepare(raw, "choice", nil) + require.ErrorContains(t, err, "empty_catalog") + } +} + +func TestToolChoiceRejectsAmbiguousShortNames(t *testing.T) { + source := testSource() + source["tools"] = []any{object{"type": "namespace", "name": "a", "tools": []any{object{"type": "function", "name": "lookup"}}}, object{"type": "namespace", "name": "b", "tools": []any{object{"type": "function", "name": "lookup"}}}} + source["tool_choice"] = object{"type": "function", "name": "lookup"} + raw, _ := json.Marshal(source) + _, _, err := Prepare(raw, "choice", nil) + require.ErrorContains(t, err, "ambiguous_name") + source["tool_choice"] = object{"type": "function", "name": "lookup", "namespace": "b"} + _, bridge := mustPrepare(t, source, "choice", nil) + require.Equal(t, "b", bridge.selectedTool.Namespace) +} + +func TestToolChoiceFailuresNeverDispatchPartialBatchOrRepairTargets(t *testing.T) { + for _, failure := range []string{"missing", "wrong", "mixed", "schema", "unknown"} { + t.Run(failure, func(t *testing.T) { + source := testSource() + source["tools"], source["tool_choice"], source["stream"] = choiceTools(), object{"type": "function", "name": "lookup"}, true + cache := new(ReplayCache) + _, bridge := mustPrepare(t, source, "choice", cache) + valid := nativeCall(object{"name": "lookup", "arguments": object{"key": "value"}}) + wrong := repairCall("wrong", "Call", `{"name":"other","arguments":{}}`) + items := []any{} + switch failure { + case "wrong": + items = []any{wrong} + case "mixed": + items = []any{valid, wrong} + case "schema": + items = []any{nativeCall(object{"name": "lookup", "arguments": object{"key": 1}})} + case "unknown": + items = []any{nativeCall(object{"name": "unknown", "arguments": object{}})} + } + response := repairResponse("resp", 12, 4, items...) + upstream := io.NopCloser(strings.NewReader(sse(object{"type": "response.completed", "response": response}))) + calls := 0 + stream := bridge.StreamWithRepairs(context.Background(), upstream, func(context.Context, object, error) (object, error) { calls++; return nil, nil }, func(context.Context) (io.ReadCloser, error) { calls++; return nil, nil }) + events := repairEvents(t, stream) + require.Zero(t, calls) + require.Equal(t, "response.failed", events[len(events)-1]["type"]) + for _, event := range events { + require.NotEqual(t, "response.output_item.added", event["type"]) + } + require.Nil(t, cache.get("choice", "call_native")) + require.Nil(t, cache.get("choice", "wrong")) + }) + } +} + +func TestToolChoiceRequiredAndLaterAutoRemainIndependent(t *testing.T) { + source := testSource() + source["tools"], source["tool_choice"] = choiceTools(), "required" + _, required := mustPrepare(t, source, "same", nil) + require.ErrorContains(t, required.translateResponse(repairResponse("resp", 1, 1)), "missing_call") + source["tool_choice"] = "auto" + _, automatic := mustPrepare(t, source, "same", nil) + require.NoError(t, automatic.translateResponse(repairResponse("resp", 1, 1))) + source["tool_choice"] = "none" + _, none := mustPrepare(t, source, "same", nil) + require.Empty(t, none.tools) + require.NoError(t, none.translateResponse(repairResponse("resp", 1, 1))) +} diff --git a/backend/internal/service/basispoints/tool_repair.go b/backend/internal/service/basispoints/tool_repair.go index 589080dd260d..0510925f5f4a 100644 --- a/backend/internal/service/basispoints/tool_repair.go +++ b/backend/internal/service/basispoints/tool_repair.go @@ -30,12 +30,18 @@ func (b *Bridge) validateToolResponse(response object) error { if err != nil { return err } + if err := b.validateSelectedTool(translated); err != nil { + return err + } id, call := text(translated["id"]), text(translated["call_id"]) if ids[id] || calls[call] { return fmt.Errorf("basispoints response contains duplicate tool identities") } ids[id], calls[call] = true, true } + if b.toolChoice == "required" && len(calls) == 0 { + return toolChoiceViolation{reason: "missing_call"} + } return nil } @@ -76,7 +82,8 @@ func (b *Bridge) translateCompleted(ctx context.Context, response object, repair return b.translateResponse(response) } var schemaError toolArgumentsSchemaError - if errors.As(validation, &schemaError) { + var choiceError toolChoiceViolation + if errors.As(validation, &schemaError) || errors.As(validation, &choiceError) { return validation } original, eligible := repairableTools(response) diff --git a/backend/internal/service/basispoints/unknown_tool_repair.go b/backend/internal/service/basispoints/unknown_tool_repair.go index 8b9e8746d9c3..2f4b0852d3f1 100644 --- a/backend/internal/service/basispoints/unknown_tool_repair.go +++ b/backend/internal/service/basispoints/unknown_tool_repair.go @@ -20,7 +20,7 @@ type RepairToolCall func(context.Context) (io.ReadCloser, error) func (b *Bridge) canRepair(response object, err error) bool { var unknown unknownClientToolError - if len(b.tools) == 0 || b.hasToolHistory || !errors.As(err, &unknown) || text(response["status"]) != "completed" { + if b.selectedTool != nil || len(b.tools) == 0 || b.hasToolHistory || !errors.As(err, &unknown) || text(response["status"]) != "completed" { return false } output, _ := response["output"].([]any) @@ -43,7 +43,7 @@ func (b *Bridge) canRepair(response object, err error) bool { // unexecuted native call can be returned to BPS as an executed:false result. func (b *Bridge) canRepairUnknownContinuation(response object, err error) bool { var unknown unknownClientToolError - if !b.hasToolHistory || b.structured != nil || len(b.completedToolHistory) == 0 || len(b.tools) == 0 || !errors.As(err, &unknown) || text(response["status"]) != "completed" { + if b.selectedTool != nil || !b.hasToolHistory || b.structured != nil || len(b.completedToolHistory) == 0 || len(b.tools) == 0 || !errors.As(err, &unknown) || text(response["status"]) != "completed" { return false } items, ok := repairableTools(response) diff --git a/backend/internal/service/openai_excel_bps_tools_test.go b/backend/internal/service/openai_excel_bps_tools_test.go index 0075936f0ad3..3af8664f9161 100644 --- a/backend/internal/service/openai_excel_bps_tools_test.go +++ b/backend/internal/service/openai_excel_bps_tools_test.go @@ -72,7 +72,7 @@ func TestExcelBPSToolFallbackPolicy(t *testing.T) { if forced { require.Error(t, err) require.Equal(t, http.StatusBadRequest, rec.Code) - require.Contains(t, rec.Body.String(), "basispoints supports tool_choice auto or none only") + require.Contains(t, rec.Body.String(), "basispoints tool_choice rejected") require.True(t, IsResponseCommitted(c)) require.Empty(t, upstream.requests) } else { From ee558fbabd44a87c3e04245849ba668bba21158a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:35:24 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test:=20=E6=9B=B4=E6=96=B0=E5=BF=85?= =?UTF-8?q?=E9=80=89=E5=B7=A5=E5=85=B7=E6=94=AF=E6=8C=81=E5=90=8E=E7=9A=84?= =?UTF-8?q?=E6=97=A7=E6=8B=92=E7=BB=9D=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_excel_bps_tools_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_excel_bps_tools_test.go b/backend/internal/service/openai_excel_bps_tools_test.go index 3af8664f9161..b3cb08673370 100644 --- a/backend/internal/service/openai_excel_bps_tools_test.go +++ b/backend/internal/service/openai_excel_bps_tools_test.go @@ -41,7 +41,7 @@ func TestExcelBPSToolFallbackPolicy(t *testing.T) { {"disabled image", map[string]any{"type": "image_generation"}, "none", ""}, {"forced search", map[string]any{"type": "web_search"}, map[string]any{"type": "web_search"}, "tool_choice"}, {"forced image", map[string]any{"type": "image_generation"}, map[string]any{"type": "image_generation"}, "tool_choice"}, - {"required search", map[string]any{"type": "web_search", "external_web_access": true}, "required", "web_search"}, + {"unsupported choice", map[string]any{"type": "web_search", "external_web_access": true}, "unsupported", "web_search"}, } for _, tc := range cases { for _, omit := range []bool{false, true} {