Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions backend/internal/service/basispoints/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,21 @@ these ceilings are not throughput or memory-use guarantees.
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`.

# Context policy and current encrypted input

The bridge forwards an explicitly supplied `context_management` array, including
Expand Down
15 changes: 11 additions & 4 deletions backend/internal/service/basispoints/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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:
Expand Down Expand Up @@ -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()
}
Expand Down
115 changes: 115 additions & 0 deletions backend/internal/service/basispoints/tool_choice.go
Original file line number Diff line number Diff line change
@@ -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 ""
}
118 changes: 118 additions & 0 deletions backend/internal/service/basispoints/tool_choice_test.go
Original file line number Diff line number Diff line change
@@ -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)))
}
9 changes: 8 additions & 1 deletion backend/internal/service/basispoints/tool_repair.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions backend/internal/service/basispoints/unknown_tool_repair.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions backend/internal/service/openai_excel_bps_tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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} {
Expand Down Expand Up @@ -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 {
Expand Down
Loading