diff --git a/changelog/unreleased/toolcall-contract-package.md b/changelog/unreleased/toolcall-contract-package.md new file mode 100644 index 000000000..969a000b7 --- /dev/null +++ b/changelog/unreleased/toolcall-contract-package.md @@ -0,0 +1,10 @@ +### English + +- Add `internal/toolcall`: one canonical model of tool declarations, tool choice, argument repair, native call identity and rendering, so protocols stop each re-implementing the contract. +- Validate `tools`, `tool_choice` and `parallel_tool_calls` through that parser in the shared chat-request validation every protocol entry runs, so an orphan `auto` degrades to unspecified while `required` or a named choice fails instead of silently dropping the tool request. + +### 中文 + +- 新增 `internal/toolcall`:工具声明、工具选择、参数修复、原生调用身份与渲染只有一份规范模型,协议层不再各自实现这套契约。 +- Responses 入口与各协议的共用请求校验都通过该解析器校验 `tools`、`tool_choice`、`parallel_tool_calls`:孤立的 `auto` 降级为未指定,`required` 或指定工具则校验失败,不再静默丢弃工具请求。 + diff --git a/internal/toolcall/args.go b/internal/toolcall/args.go new file mode 100644 index 000000000..994ec00e7 --- /dev/null +++ b/internal/toolcall/args.go @@ -0,0 +1,193 @@ +package toolcall + +import ( + "encoding/json" + "strings" +) + +const maxCloseClosers = 24 + +// RepairArguments attempts formatting-level repair only. It returns ok=false +// when a value was cut mid-string, so callers never receive a value the model +// did not finish writing. +func RepairArguments(raw string) (string, bool) { + text := strings.TrimSpace(raw) + if text == "" { + return "{}", true + } + if json.Valid([]byte(text)) { + return text, true + } + candidates := argumentRepairCandidates(text) + for _, candidate := range candidates { + if json.Valid([]byte(candidate)) { + return candidate, true + } + } + for _, candidate := range candidates { + if closed, ok := closeArgumentTail(candidate); ok { + return closed, true + } + } + if prefix, ok := decodeArgumentPrefix(text); ok { + return prefix, true + } + return "", false +} + +func decodeArgumentPrefix(text string) (string, bool) { + decoder := json.NewDecoder(strings.NewReader(text)) + var value any + if err := decoder.Decode(&value); err != nil { + return "", false + } + var extra any + if err := decoder.Decode(&extra); err == nil { + return "", false + } + encoded, err := json.Marshal(value) + if err != nil { + return "", false + } + return string(encoded), true +} + +func argumentRepairCandidates(text string) []string { + candidates := []string{text} + if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text { + candidates = append(candidates, withoutTrailing) + } + if escaped := escapeBareQuotes(text); escaped != text { + candidates = append(candidates, escaped, stripTrailingCommas(escaped)) + } + return candidates +} + +// stripTrailingCommas removes `,` that directly precede a closing brace or +// bracket, which models emit routinely and strict JSON rejects. +func stripTrailingCommas(text string) string { + var out strings.Builder + out.Grow(len(text)) + for index := 0; index < len(text); index++ { + character := text[index] + if character == ',' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next < len(text) && (text[next] == '}' || text[next] == ']') { + continue + } + } + out.WriteByte(character) + } + return out.String() +} + +// escapeBareQuotes escapes `"` characters that appear inside a JSON string +// value. A closing quote is accepted only when the next non-space byte is one +// of `, } ] :` or the end of the buffer. +func escapeBareQuotes(text string) string { + var out strings.Builder + out.Grow(len(text)) + inString := false + for index := 0; index < len(text); { + character := text[index] + if !inString { + out.WriteByte(character) + if character == '"' { + inString = true + } + index++ + continue + } + if character == '\\' && index+1 < len(text) { + out.WriteString(text[index : index+2]) + index += 2 + continue + } + if character == '"' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next >= len(text) || strings.IndexByte(",}]:", text[next]) >= 0 { + out.WriteByte(character) + inString = false + } else { + out.WriteString(`\"`) + } + index++ + continue + } + out.WriteByte(character) + index++ + } + return out.String() +} + +// closeArgumentTail appends the closers the model never got to emit, but only +// when no string is left open - a value cut mid-string stays unrepaired. +func closeArgumentTail(text string) (string, bool) { + stack := make([]byte, 0, maxCloseClosers) + var out strings.Builder + out.Grow(len(text) + maxCloseClosers) + inString := false + for index := 0; index < len(text); index++ { + character := text[index] + if inString { + out.WriteByte(character) + if character == '\\' && index+1 < len(text) { + out.WriteByte(text[index+1]) + index++ + continue + } + if character == '"' { + inString = false + } + continue + } + switch character { + case '"': + inString = true + out.WriteByte(character) + case '{', '[': + if len(stack) >= maxCloseClosers { + return "", false + } + stack = append(stack, character) + out.WriteByte(character) + case '}', ']': + if len(stack) == 0 { + return "", false + } + open := stack[len(stack)-1] + if (character == '}' && open != '{') || (character == ']' && open != '[') { + return "", false + } + stack = stack[:len(stack)-1] + out.WriteByte(character) + default: + out.WriteByte(character) + } + } + if inString || len(stack) == 0 { + return "", false + } + for index := len(stack) - 1; index >= 0; index-- { + if stack[index] == '{' { + out.WriteString("}") + } else { + out.WriteString("]") + } + } + closed := stripTrailingCommas(out.String()) + if json.Valid([]byte(closed)) { + return closed, true + } + return "", false +} + +func isJSONSpace(character byte) bool { + return character == ' ' || character == '\t' || character == '\n' || character == '\r' +} diff --git a/internal/toolcall/model.go b/internal/toolcall/model.go new file mode 100644 index 000000000..80e82b222 --- /dev/null +++ b/internal/toolcall/model.go @@ -0,0 +1,243 @@ +// Package toolcall defines the provider-neutral tool-call contract shared by +// request translation, provider adapters, routing and the three public +// protocol renderers. +// +// The package deliberately does not import translate or any provider package. +// It owns validation and stream assembly; adapters own wire dialects. +package toolcall + +import ( + "encoding/json" + "fmt" + "strings" +) + +// Protocol is one public request dialect. It scopes fallback call indexes and +// selectors, but never tool identity. +type Protocol string + +const ( + ProtocolChat Protocol = "chat" + ProtocolMessages Protocol = "messages" + ProtocolResponses Protocol = "responses" +) + +func NormalizeProtocol(value string) Protocol { + switch strings.ToLower(strings.TrimSpace(value)) { + case "messages", "anthropic", "anthropic_messages": + return ProtocolMessages + case "responses", "openai_responses", "native_responses": + return ProtocolResponses + default: + return ProtocolChat + } +} + +// Dialect names the wire shape a provider adapter speaks. +type Dialect string + +const ( + DialectOpenAIChat Dialect = "openai_chat" + DialectAnthropic Dialect = "anthropic_messages" + DialectResponses Dialect = "openai_responses" + DialectPromptedTools Dialect = "prompted_tools" +) + +// ExecutionLevel records how strongly a provider can enforce a tool request. +// Native is a real upstream constraint; Validated is a prompt plus a +// post-response check; Prompted has no enforceable selector. +type ExecutionLevel string + +const ( + ExecutionNative ExecutionLevel = "native" + ExecutionValidated ExecutionLevel = "validated" + ExecutionPrompted ExecutionLevel = "prompted" + ExecutionNone ExecutionLevel = "none" +) + +// ChoiceMode is the canonical tool_choice state. Unspecified is distinct from +// auto: a missing selector must not be rewritten into an explicit one. +type ChoiceMode string + +const ( + ChoiceUnspecified ChoiceMode = "unspecified" + ChoiceNone ChoiceMode = "none" + ChoiceAuto ChoiceMode = "auto" + ChoiceRequired ChoiceMode = "required" + ChoiceNamed ChoiceMode = "named" +) + +// RepairMode makes historical argument repair explicit. Preserve keeps the raw +// bytes and reports invalid; SafeRepair only removes clearly unfinished syntax +// and never pads a truncated value; Reject returns an invalid-call error. +type RepairMode string + +const ( + RepairPreserve RepairMode = "preserve" + RepairSafe RepairMode = "safe-repair" + RepairReject RepairMode = "reject" +) + +// SchemaMode controls whether a request requires strict object schemas. +type SchemaMode string + +const ( + SchemaRelaxed SchemaMode = "relaxed" + SchemaStrict SchemaMode = "strict" +) + +// Spec is one declared tool. Name is the upstream wire name; Namespace and +// OriginalName preserve the protocol identity separately so a flat name can +// round-trip without guessing from underscores. +type Spec struct { + Name string `json:"name"` + OriginalName string `json:"original_name,omitempty"` + Namespace string `json:"namespace,omitempty"` + Description string `json:"description,omitempty"` + Parameters json.RawMessage `json:"parameters,omitempty"` + Strict bool `json:"strict,omitempty"` + Custom bool `json:"custom,omitempty"` + Source Protocol `json:"source,omitempty"` +} + +// Choice is a parsed tool_choice. Name is only set for ChoiceNamed. +type Choice struct { + Mode ChoiceMode `json:"mode"` + Name string `json:"name,omitempty"` +} + +// Policy carries request-level call constraints. +type Policy struct { + Parallel *bool `json:"parallel,omitempty"` + MaxCalls int `json:"max_calls,omitempty"` + Schema SchemaMode `json:"schema"` + Repair RepairMode `json:"repair"` + NativeStrict bool `json:"native_strict,omitempty"` +} + +// Request is the canonical tool declaration for one provider attempt. +type Request struct { + Protocol Protocol `json:"protocol"` + Specs []Spec `json:"specs"` + Choice Choice `json:"choice"` + Policy Policy `json:"policy"` + Diagnostics []string `json:"diagnostics,omitempty"` +} + +func (r Request) HasTools() bool { return len(r.Specs) > 0 } + +func (r Request) SpecByName(name string) (Spec, bool) { + name = strings.TrimSpace(name) + for _, spec := range r.Specs { + if spec.Name == name { + return spec, true + } + } + return Spec{}, false +} + +func (r Request) Names() []string { + names := make([]string, 0, len(r.Specs)) + for _, spec := range r.Specs { + names = append(names, spec.Name) + } + return names +} + +// CallStatus is the lifecycle of one tool call. +type CallStatus string + +const ( + CallStarted CallStatus = "started" + CallCompleted CallStatus = "completed" + CallInvalid CallStatus = "invalid" + CallFailed CallStatus = "failed" + CallTruncated CallStatus = "truncated" +) + +// Call is one ordered tool invocation. ArgumentsRaw is the exact concatenated +// provider byte stream; Arguments is the validated object for the renderer. +type Call struct { + Index int `json:"index"` + InternalID string `json:"internal_id"` + ProviderID string `json:"provider_id,omitempty"` + Name string `json:"name"` + Namespace string `json:"namespace,omitempty"` + OriginalName string `json:"original_name,omitempty"` + ArgumentsRaw string `json:"arguments_raw"` + Arguments json.RawMessage `json:"arguments,omitempty"` + Status CallStatus `json:"status"` + Repaired bool `json:"repaired,omitempty"` + Error string `json:"error,omitempty"` + Sealed bool `json:"sealed,omitempty"` +} + +// EventKind is one canonical stream event. +type EventKind string + +const ( + EventTextDelta EventKind = "text_delta" + EventReasoningDelta EventKind = "reasoning_delta" + EventCallStarted EventKind = "tool_call_started" + EventCallArguments EventKind = "tool_arguments_delta" + EventCallSealed EventKind = "tool_call_sealed" + EventTurnFailed EventKind = "turn_failed" +) + +// Event is a renderer-facing delta. Call is a snapshot copy; renderers must +// treat it as read-only. +type Event struct { + Kind EventKind `json:"kind"` + Text string `json:"text,omitempty"` + Call *Call `json:"call,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// TurnStatus is the mutually exclusive terminal state of one upstream turn. +type TurnStatus string + +const ( + TurnCompleted TurnStatus = "completed" + TurnToolCalls TurnStatus = "tool_calls" + TurnTruncated TurnStatus = "truncated" + TurnInvalid TurnStatus = "invalid" + TurnFailed TurnStatus = "failed" + TurnCanceled TurnStatus = "canceled" +) + +// TurnResult is the normalized assistant turn. UpstreamTerminal and +// DownstreamDelivered are deliberately separate facts. +type TurnResult struct { + Protocol Protocol `json:"protocol"` + Text string `json:"text"` + Reasoning string `json:"reasoning"` + Calls []Call `json:"calls,omitempty"` + FinishReason string `json:"finish_reason,omitempty"` + Status TurnStatus `json:"status"` + Error string `json:"error,omitempty"` + UpstreamTerminal string `json:"upstream_terminal,omitempty"` + DownstreamDelivered bool `json:"downstream_delivered,omitempty"` +} + +func (r TurnResult) HasCalls() bool { return len(r.Calls) > 0 } + +// Validate checks the canonical invariants every renderer relies on. +func (r TurnResult) Validate() error { + if r.Status == "" { + return fmt.Errorf("turn status required") + } + if r.Status == TurnCompleted || r.Status == TurnToolCalls { + if r.UpstreamTerminal != "done" { + return fmt.Errorf("successful turn requires upstream terminal done, got %q", r.UpstreamTerminal) + } + } + for index, call := range r.Calls { + if strings.TrimSpace(call.Name) == "" { + return fmt.Errorf("tool call %d has no name", index) + } + if call.Status == CallInvalid || call.Status == CallFailed || call.Status == CallTruncated { + return fmt.Errorf("tool call %d is %s: %s", index, call.Status, call.Error) + } + } + return nil +} diff --git a/internal/toolcall/native.go b/internal/toolcall/native.go new file mode 100644 index 000000000..fa8e09db9 --- /dev/null +++ b/internal/toolcall/native.go @@ -0,0 +1,1398 @@ +package toolcall + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" + "strconv" + "strings" +) + +// NativeLimits bounds the native Responses tool suffix that may be retained +// before it is validated. Every limit is checked before bytes are appended or +// copied, and the same limits are used by buffered and terminal-only turns. +type NativeLimits struct { + MaxFrames int + MaxBufferedBytes int + MaxArgumentBytes int + MaxCalls int + MaxJSONDepth int +} + +func DefaultNativeLimits() NativeLimits { + return NativeLimits{ + MaxFrames: 8192, + MaxBufferedBytes: 8 << 20, + MaxArgumentBytes: 1 << 20, + MaxCalls: 128, + MaxJSONDepth: 64, + } +} + +// NativeCall is one client-executed call after the visible stream and the +// terminal snapshot have been reconciled. +type NativeCall struct { + OutputIndex *int + ItemID string + CallID string + Type string + Name string + Namespace string + Arguments string + Input string + Custom bool +} + +// NativeDelivery is the immutable plan a native relay may write. It exists +// only after the stream calls and terminal snapshot have been reconciled. +type NativeDelivery struct { + Calls []NativeCall +} + +type nativeCall struct { + key string + itemID string + callID string + outputIndex *int + itemType string + name string + namespace string + arguments string + input string + completed bool + done map[string]nativeSnapshot + terminal *nativeTerminalCall + // deltaArgs / deltaInput are the exact concatenation of argument/input + // delta frames seen so far. A completion frame (arguments.done, + // output_item.done) must agree with this accumulated value; it may not + // silently replace the bytes the client was already going to receive. + deltaArgs string + deltaInput string + sawDelta bool +} + +type nativeSnapshot struct { + call *nativeCall + kind string + arguments string + input string +} + +type nativeEvent struct { + Type string `json:"type"` + Name string `json:"name"` + Namespace string `json:"namespace"` + ItemID string `json:"item_id"` + CallID string `json:"call_id"` + OutputIndex *int `json:"output_index"` + Delta string `json:"delta"` + Arguments json.RawMessage `json:"arguments"` + Input json.RawMessage `json:"input"` + Item *nativeItem `json:"item"` + Response json.RawMessage `json:"response"` +} + +type nativeItem struct { + ID string `json:"id"` + CallID string `json:"call_id"` + Type string `json:"type"` + Name string `json:"name"` + Namespace string `json:"namespace"` + Arguments json.RawMessage `json:"arguments"` + Input json.RawMessage `json:"input"` +} + +type nativeResponse struct { + ID string `json:"id"` + Status string `json:"status"` + Output []nativeItem `json:"output"` +} + +type nativeTerminalCall struct { + itemID string + callID string + outputIndex int + itemType string + name string + namespace string + arguments string + input string + spec Spec +} + +// NativeTurn is the single native Responses tool-round validator. It keeps +// independent output-index, output-item, and call-ID indexes and refuses to +// merge two already established calls through a late identity. +type NativeTurn struct { + request Request + limits NativeLimits + responseID string + started bool + frameCount int + bufferBytes int + calls map[string]*nativeCall + aliases map[string]string + order []string + snapshots []nativeSnapshot + finished bool + delivery *NativeDelivery + terminalErr error +} + +func NewNativeTurn(request Request, limits ...NativeLimits) *NativeTurn { + limit := DefaultNativeLimits() + if len(limits) > 0 { + limit = limits[0] + } + if limit.MaxFrames <= 0 { + limit.MaxFrames = DefaultNativeLimits().MaxFrames + } + if limit.MaxBufferedBytes <= 0 { + limit.MaxBufferedBytes = DefaultNativeLimits().MaxBufferedBytes + } + if limit.MaxArgumentBytes <= 0 { + limit.MaxArgumentBytes = DefaultNativeLimits().MaxArgumentBytes + } + if limit.MaxCalls <= 0 { + limit.MaxCalls = DefaultNativeLimits().MaxCalls + } + if limit.MaxJSONDepth <= 0 { + limit.MaxJSONDepth = DefaultNativeLimits().MaxJSONDepth + } + return &NativeTurn{ + request: request, limits: limit, + calls: make(map[string]*nativeCall), aliases: make(map[string]string), + } +} + +// Observe consumes one SSE JSON payload. eventName is the SSE event name when +// present; a payload whose JSON type conflicts with it is rejected. A response +// object embedded in any non-terminal event is inspected too, so a tool item +// cannot bypass reconciliation by arriving inside a control frame. +func (t *NativeTurn) Observe(eventName string, data []byte) error { + if t.finished { + return fmt.Errorf("native tool turn is already finished") + } + trimmed := bytes.TrimSpace(data) + if len(trimmed) == 0 || string(trimmed) == "[DONE]" { + return nil + } + var event nativeEvent + if err := json.Unmarshal(trimmed, &event); err != nil { + return fmt.Errorf("native event is not valid JSON: %w", err) + } + if event.Type == "" { + event.Type = strings.TrimSpace(eventName) + } + if event.Type == "" { + return nil + } + if eventName = strings.TrimSpace(eventName); eventName != "" && eventName != event.Type { + return fmt.Errorf("native SSE event %q conflicts with payload type %q", eventName, event.Type) + } + if t.started || nativeEventHasToolSignal(event) { + t.started = true + if t.frameCount+1 > t.limits.MaxFrames { + return fmt.Errorf("native SSE frame count exceeds %d", t.limits.MaxFrames) + } + if t.bufferBytes+len(data) > t.limits.MaxBufferedBytes { + return fmt.Errorf("native buffered bytes exceed %d", t.limits.MaxBufferedBytes) + } + t.frameCount++ + t.bufferBytes += len(data) + } + if len(event.Response) > 0 && !nativeTerminalEventType(event.Type) { + if err := t.observeResponseEnvelope(event.Response); err != nil { + return err + } + } + switch event.Type { + case "response.output_item.added", "response.output_item.done": + if event.Item == nil { + return nil + } + return t.observeItem(*event.Item, event.OutputIndex, event.Type == "response.output_item.done") + case "response.function_call_arguments.delta": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + return t.observeArgumentsDelta(itemID, callID, event.OutputIndex, name, namespace, event.Delta, false) + case "response.function_call_arguments.done": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + raw := event.Arguments + if len(bytes.TrimSpace(raw)) == 0 && event.Item != nil { + raw = event.Item.Arguments + } + return t.observeArgumentsDone(itemID, callID, event.OutputIndex, name, namespace, raw, false) + case "response.custom_tool_call_input.delta": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + return t.observeArgumentsDelta(itemID, callID, event.OutputIndex, name, namespace, event.Delta, true) + case "response.custom_tool_call_input.done": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + raw := event.Input + if len(bytes.TrimSpace(raw)) == 0 && event.Item != nil { + raw = event.Item.Input + } + return t.observeArgumentsDone(itemID, callID, event.OutputIndex, name, namespace, raw, true) + } + return nil +} + +func eventArgumentIDs(event nativeEvent) (string, string) { + itemID, callID := event.ItemID, event.CallID + if event.Item != nil { + if itemID == "" { + itemID = event.Item.ID + } + if callID == "" { + callID = event.Item.CallID + } + } + return itemID, callID +} + +func eventArgumentIdentity(event nativeEvent) (string, string) { + name, namespace := event.Name, event.Namespace + if event.Item != nil { + if name == "" { + name = event.Item.Name + } + if namespace == "" { + namespace = event.Item.Namespace + } + } + return name, namespace +} + +func nativeTerminalEventType(kind string) bool { + switch kind { + case "response.completed", "response.incomplete", "response.failed", "error": + return true + } + return false +} + +func (t *NativeTurn) observeResponseEnvelope(raw json.RawMessage) error { + var response nativeResponse + if err := json.Unmarshal(raw, &response); err != nil { + return fmt.Errorf("native response envelope is invalid: %w", err) + } + if response.ID != "" { + if t.responseID != "" && t.responseID != response.ID { + return fmt.Errorf("native response id changed from %q to %q", t.responseID, response.ID) + } + t.responseID = response.ID + } + for index := range response.Output { + item := response.Output[index] + if !nativeKnownItemType(item.Type) { + return fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + continue + } + itemIndex := index + completed := false + if item.Type == "function_call" { + arguments, hasArguments, err := nativeRawString(item.Arguments, false) + if err != nil { + return err + } + completed = hasArguments && strings.TrimSpace(arguments) != "" + } else { + input, hasInput, err := nativeRawInput(item.Input) + if err != nil { + return err + } + completed = hasInput && input != "" + } + if err := t.observeItem(item, &itemIndex, completed); err != nil { + return err + } + } + return nil +} + +func (t *NativeTurn) observeItem(item nativeItem, outputIndex *int, completed bool) error { + if !nativeKnownItemType(item.Type) { + return fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + return nil + } + call, err := t.resolve(item.ID, item.CallID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(item.ID, item.CallID, outputIndex); err != nil { + return err + } + if err := call.mergeName("", item.Namespace, item.Type); err != nil { + return err + } + if err := t.mergeEventName(call, item.Name, item.Namespace, item.Type == "custom_tool_call"); err != nil { + return err + } + arguments, hasArguments, err := nativeRawString(item.Arguments, false) + if err != nil { + return err + } + input, hasInput, err := nativeRawInput(item.Input) + if err != nil { + return err + } + // Check argument/input size and the accumulated delta on every item frame, + // not only on delta/done events. An oversized or contradictory item frame is + // permanently fatal for this call: a later same-identity frame with smaller + // valid arguments must not be allowed to rewrite it into a successful turn. + if len([]byte(arguments)) > t.limits.MaxArgumentBytes || len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if hasArguments && call.sawDelta && call.deltaArgs != arguments { + return fmt.Errorf("native tool call %q item arguments differ from the accumulated deltas", call.name) + } + if hasInput && call.sawDelta && call.deltaInput != input { + return fmt.Errorf("native tool call %q item input differs from the accumulated deltas", call.name) + } + if completed { + if item.Type == "function_call" { + if !hasArguments { + return fmt.Errorf("native tool call %q completed without arguments", call.name) + } + } else if !hasInput { + return fmt.Errorf("native custom tool call %q completed without input", call.name) + } + if err := t.validateSnapshotValues(call, string(item.Type), arguments, input, item.Type == "function_call"); err != nil { + return err + } + return t.addSnapshot(call, string(item.Type), arguments, input) + } + if hasArguments { + call.arguments = arguments + } + if hasInput { + call.input = input + } + return nil +} + +func (t *NativeTurn) observeArgumentsDelta(itemID, callID string, outputIndex *int, name, namespace, delta string, custom bool) error { + call, err := t.resolve(itemID, callID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(itemID, callID, outputIndex); err != nil { + return err + } + if err := t.mergeEventName(call, name, namespace, custom); err != nil { + return err + } + if call.completed { + return fmt.Errorf("native tool call %q received a delta after completion", call.name) + } + if len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if custom { + if len([]byte(delta)) > t.limits.MaxArgumentBytes || len([]byte(call.deltaInput))+len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q input exceeds the limit", call.name) + } + if call.itemType != "" && call.itemType != "custom_tool_call" { + return fmt.Errorf("native tool call %q changed type from %q to custom_tool_call", call.name, call.itemType) + } + call.itemType = "custom_tool_call" + call.sawDelta = true + call.deltaInput += delta + call.input += delta + return nil + } + if len([]byte(delta)) > t.limits.MaxArgumentBytes || len([]byte(call.deltaArgs))+len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if call.itemType != "" && call.itemType != "function_call" { + return fmt.Errorf("native tool call %q changed type from %q to function_call", call.name, call.itemType) + } + call.itemType = "function_call" + call.sawDelta = true + call.deltaArgs += delta + call.arguments += delta + return nil +} + +func (t *NativeTurn) observeArgumentsDone(itemID, callID string, outputIndex *int, name, namespace string, raw json.RawMessage, custom bool) error { + call, err := t.resolve(itemID, callID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(itemID, callID, outputIndex); err != nil { + return err + } + if err := t.mergeEventName(call, name, namespace, custom); err != nil { + return err + } + itemType := "function_call" + if custom { + itemType = "custom_tool_call" + } + if call.itemType != "" && call.itemType != itemType { + return fmt.Errorf("native tool call %q changed type from %q to %q", call.name, call.itemType, itemType) + } + call.itemType = itemType + if custom { + input, hasInput, err := nativeRawInput(raw) + if err != nil { + return err + } + if !hasInput { + return fmt.Errorf("native custom tool call %q completed without input", call.name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q input exceeds the limit", call.name) + } + if call.sawDelta && call.deltaInput != input { + return fmt.Errorf("native custom tool call %q completion input differs from the accumulated deltas", call.name) + } + if err := t.validateSnapshotValues(call, itemType, "", input, false); err != nil { + return err + } + return t.addSnapshot(call, "custom_tool_call_input.done", "", input) + } + text, hasArguments, err := nativeRawString(raw, true) + if err != nil { + return err + } + if !hasArguments { + return fmt.Errorf("native tool call %q completed without arguments", call.name) + } + if len([]byte(text)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if call.sawDelta && !semanticJSONEqual(call.deltaArgs, text) { + return fmt.Errorf("native tool call %q completion arguments differ from the accumulated deltas", call.name) + } + if err := t.validateSnapshotValues(call, itemType, text, "", true); err != nil { + return err + } + return t.addSnapshot(call, "function_call_arguments.done", text, "") +} + +func (t *NativeTurn) addSnapshot(call *nativeCall, kind, arguments, input string) error { + if len([]byte(arguments)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q completed arguments exceed the limit", call.name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q completed input exceeds the limit", call.name) + } + if call.completed && call.done == nil { + return fmt.Errorf("native tool call %q has inconsistent completion state", call.name) + } + if call.done == nil { + call.done = make(map[string]nativeSnapshot) + } + if previous, exists := call.done[kind]; exists { + if !snapshotEqual(previous, nativeSnapshot{call: call, kind: kind, arguments: arguments, input: input}) { + return fmt.Errorf("native tool call %q repeated completion with different content", call.name) + } + return nil + } + snapshot := nativeSnapshot{call: call, kind: kind, arguments: arguments, input: input} + if strings.Contains(kind, "custom") { + call.input = input + } else { + call.arguments = arguments + } + call.done[kind] = snapshot + call.completed = true + t.snapshots = append(t.snapshots, snapshot) + return nil +} + +func (t *NativeTurn) validateSnapshotValues(call *nativeCall, itemType, arguments, input string, function bool) error { + if function { + if err := validateStrictJSONObject(arguments, t.limits.MaxJSONDepth); err != nil { + return fmt.Errorf("native tool call %q arguments are invalid: %w", call.name, err) + } + } else if len(bytes.TrimSpace([]byte(call.name))) == 0 { + // A custom completion can arrive before the item name is bound. The + // terminal response is the authority for its identity and declaration, + // and Finish rejects the turn if no such call exists. + return nil + } + if len(bytes.TrimSpace([]byte(call.name))) > 0 { + spec, err := resolveNativeSpec(t.request, call.name, call.namespace, itemType) + if err != nil { + return err + } + if function { + if spec.Custom { + return fmt.Errorf("native tool call %q is declared as custom but arrived as function_call", call.name) + } + value, err := parseStrictJSONObject(arguments, t.limits.MaxJSONDepth) + if err != nil { + return err + } + if err := validateNativeSpecValue(spec, value); err != nil { + return err + } + } else if !spec.Custom { + return fmt.Errorf("native tool call %q is declared as function but arrived as custom_tool_call", call.name) + } + } + return nil +} + +func (t *NativeTurn) resolve(itemID, callID string, outputIndex *int) (*nativeCall, error) { + if t.calls == nil { + t.calls = make(map[string]*nativeCall) + t.aliases = make(map[string]string) + } + var matched []string + for _, alias := range nativeAliases(itemID, callID, outputIndex) { + if key, ok := t.aliases[alias]; ok && !containsString(matched, key) { + matched = append(matched, key) + } + } + if len(matched) > 1 { + return nil, fmt.Errorf("native tool identities point to different calls: %s", strings.Join(matched, ", ")) + } + if len(matched) == 1 { + return t.calls[matched[0]], nil + } + key := "item:" + itemID + if itemID == "" { + key = "call:" + callID + } + if itemID == "" && callID == "" && outputIndex != nil { + key = "index:" + strconv.Itoa(*outputIndex) + } + if key == "item:" || key == "call:" { + return nil, fmt.Errorf("native tool event has no stable identity") + } + if _, exists := t.calls[key]; exists { + return nil, fmt.Errorf("native tool identity %q was reused", key) + } + call := &nativeCall{key: key, done: make(map[string]nativeSnapshot)} + t.calls[key] = call + t.order = append(t.order, key) + for _, alias := range nativeAliases(itemID, callID, outputIndex) { + if existing, ok := t.aliases[alias]; ok && existing != key { + return nil, fmt.Errorf("native tool identity %q is already bound to another call", alias) + } + t.aliases[alias] = key + } + if len(t.order) > t.limits.MaxCalls { + return nil, fmt.Errorf("native tool call count exceeds %d", t.limits.MaxCalls) + } + return call, nil +} + +func (c *nativeCall) mergeIdentity(itemID, callID string, outputIndex *int) error { + if itemID != "" { + if c.itemID != "" && c.itemID != itemID { + return fmt.Errorf("native tool call item id changed from %q to %q", c.itemID, itemID) + } + c.itemID = itemID + } + if callID != "" { + if c.callID != "" && c.callID != callID { + return fmt.Errorf("native tool call id changed from %q to %q", c.callID, callID) + } + c.callID = callID + } + if outputIndex != nil { + if c.outputIndex != nil && *c.outputIndex != *outputIndex { + return fmt.Errorf("native tool call %q moved output index from %d to %d", c.name, *c.outputIndex, *outputIndex) + } + c.outputIndex = outputIndex + } + return nil +} + +func (c *nativeCall) mergeName(name, namespace, itemType string) error { + if itemType != "" { + if c.itemType != "" && c.itemType != itemType { + return fmt.Errorf("native tool call changed type from %q to %q", c.itemType, itemType) + } + c.itemType = itemType + } + if name != "" { + if c.name != "" && c.name != name { + return fmt.Errorf("native tool call changed name from %q to %q", c.name, name) + } + c.name = name + } + if namespace != "" { + if c.namespace != "" && c.namespace != namespace { + return fmt.Errorf("native tool call changed namespace from %q to %q", c.namespace, namespace) + } + c.namespace = namespace + } + return nil +} + +// mergeEventName binds a name carried by an argument event. Argument events +// often arrive after an added item and may spell the same declared tool either +// as its flattened wire name or as namespace + original name; that alias is +// legal. A different declared tool is an identity conflict and must fail. +func (t *NativeTurn) mergeEventName(call *nativeCall, name, namespace string, custom bool) error { + name = strings.TrimSpace(name) + namespace = strings.TrimSpace(namespace) + itemType := "function_call" + if custom { + itemType = "custom_tool_call" + } + if namespace != "" { + if call.namespace != "" && call.namespace != namespace { + return fmt.Errorf("native tool call changed namespace from %q to %q", call.namespace, namespace) + } + if call.name != "" { + if _, err := resolveNativeSpec(t.request, call.name, namespace, itemType); err != nil { + return err + } + } + call.namespace = namespace + } + if name == "" { + return nil + } + if call.name == "" { + call.name = name + return nil + } + if call.name == name { + return nil + } + streamSpec, streamErr := resolveNativeSpec(t.request, call.name, call.namespace, itemType) + eventSpec, eventErr := resolveNativeSpec(t.request, name, namespace, itemType) + if streamErr != nil || eventErr != nil || streamSpec.Name != eventSpec.Name { + return fmt.Errorf("native tool call changed name from %q to %q", call.name, name) + } + call.name = streamSpec.Name + return nil +} + +func snapshotEqual(a, b nativeSnapshot) bool { + if strings.Contains(a.kind, "custom") { + return a.input == b.input + } + return semanticJSONEqual(a.arguments, b.arguments) +} + +func nativeAliases(itemID, callID string, outputIndex *int) []string { + aliases := make([]string, 0, 3) + if itemID != "" { + aliases = append(aliases, "item:"+itemID) + } + if callID != "" { + aliases = append(aliases, "call:"+callID) + } + if outputIndex != nil { + aliases = append(aliases, "index:"+strconv.Itoa(*outputIndex)) + } + return aliases +} + +func nativeKnownItemType(kind string) bool { + switch kind { + case "", "message", "reasoning", "function_call", "custom_tool_call", + "mcp_call", "local_shell_call", "web_search_call", "file_search_call", + "code_interpreter_call", "image_generation_call": + return true + } + return false +} + +func nativeEventHasToolSignal(event nativeEvent) bool { + switch event.Type { + case "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done": + return true + } + if strings.Contains(event.Type, "mcp_call") { + return true + } + if event.Item != nil && (event.Item.Type == "function_call" || event.Item.Type == "custom_tool_call" || + event.Item.Type == "local_shell_call" || strings.HasSuffix(event.Item.Type, "_call")) { + return true + } + if len(event.Response) > 0 { + var response nativeResponse + if json.Unmarshal(event.Response, &response) == nil { + for _, item := range response.Output { + if item.Type == "function_call" || item.Type == "custom_tool_call" || + item.Type == "local_shell_call" || strings.HasSuffix(item.Type, "_call") { + return true + } + } + } + } + return false +} + +func containsString(values []string, value string) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + +func nativeRawString(raw json.RawMessage, required bool) (string, bool, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + if required { + return "", false, fmt.Errorf("string field is missing") + } + return "", false, nil + } + var value string + if err := json.Unmarshal(trimmed, &value); err != nil { + return "", true, fmt.Errorf("string field is not a string: %w", err) + } + return value, true, nil +} + +func nativeRawInput(raw json.RawMessage) (string, bool, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return "", false, nil + } + var value string + if err := json.Unmarshal(trimmed, &value); err != nil { + return "", true, fmt.Errorf("input field is not a string: %w", err) + } + return value, true, nil +} + +func validateNativeSpecValue(spec Spec, value map[string]any) error { + if len(spec.Parameters) > 0 && string(spec.Parameters) != "null" { + var schema any + if err := json.Unmarshal(spec.Parameters, &schema); err != nil { + return fmt.Errorf("tool %q schema is invalid: %w", spec.Name, err) + } + if err := validateValue(schema, schema, value, 0); err != nil { + return fmt.Errorf("tool %q arguments do not match schema: %w", spec.Name, err) + } + } + return nil +} + +func resolveNativeSpec(request Request, name, namespace, itemType string) (Spec, error) { + name = strings.TrimSpace(name) + if name == "" { + return Spec{}, fmt.Errorf("native tool call has no name") + } + if len(request.Specs) == 0 { + return Spec{}, fmt.Errorf("native response delivered tool call %q without a declared tool", name) + } + var candidates []Spec + for _, spec := range request.Specs { + if spec.Name != name { + continue + } + if namespace != "" && spec.Namespace != namespace { + continue + } + candidates = append(candidates, spec) + } + if len(candidates) == 0 && namespace != "" { + for _, spec := range request.Specs { + if spec.Namespace == namespace && (spec.OriginalName == name || spec.Name == name) { + candidates = append(candidates, spec) + } + } + } + if len(candidates) == 0 && namespace == "" { + for _, spec := range request.Specs { + if spec.OriginalName == name { + candidates = append(candidates, spec) + } + } + } + if len(candidates) == 0 { + return Spec{}, fmt.Errorf("native response delivered undeclared tool call %q", name) + } + if len(candidates) > 1 { + return Spec{}, fmt.Errorf("native tool name %q is ambiguous across declarations", name) + } + spec := candidates[0] + custom := itemType == "custom_tool_call" + if spec.Custom != custom { + return Spec{}, fmt.Errorf("native tool call %q has the wrong tool type for its declaration", name) + } + return spec, nil +} + +func validateStrictJSONObject(text string, maxDepth int) error { + if strings.TrimSpace(text) == "" { + return fmt.Errorf("arguments are empty") + } + if _, err := parseStrictJSONObject(text, maxDepth); err != nil { + return err + } + return nil +} + +func parseStrictJSONObject(text string, maxDepth int) (map[string]any, error) { + if strings.TrimSpace(text) == "" { + return nil, fmt.Errorf("arguments are empty") + } + decoder := json.NewDecoder(strings.NewReader(text)) + decoder.UseNumber() + value, err := decodeStrictJSONValue(decoder, 0, maxDepth) + if err != nil { + return nil, err + } + object, ok := value.(map[string]any) + if !ok { + return nil, fmt.Errorf("arguments must be a JSON object") + } + if _, err := decoder.Token(); err != io.EOF { + if err == nil { + return nil, fmt.Errorf("arguments contain a trailing JSON value") + } + return nil, fmt.Errorf("arguments contain trailing data: %w", err) + } + return object, nil +} + +func decodeStrictJSONValue(decoder *json.Decoder, depth, maxDepth int) (any, error) { + if depth > maxDepth { + return nil, fmt.Errorf("arguments nesting exceeds %d levels", maxDepth) + } + token, err := decoder.Token() + if err != nil { + return nil, err + } + switch value := token.(type) { + case json.Delim: + switch value { + case '{': + object := make(map[string]any) + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return nil, err + } + key, ok := keyToken.(string) + if !ok { + return nil, fmt.Errorf("object key is not a string") + } + if _, exists := object[key]; exists { + return nil, fmt.Errorf("arguments contain duplicate object key %q", key) + } + child, err := decodeStrictJSONValue(decoder, depth+1, maxDepth) + if err != nil { + return nil, err + } + object[key] = child + } + end, err := decoder.Token() + if err != nil { + return nil, err + } + if end != json.Delim('}') { + return nil, fmt.Errorf("object is not closed") + } + return object, nil + case '[': + var array []any + for decoder.More() { + child, err := decodeStrictJSONValue(decoder, depth+1, maxDepth) + if err != nil { + return nil, err + } + array = append(array, child) + } + end, err := decoder.Token() + if err != nil { + return nil, err + } + if end != json.Delim(']') { + return nil, fmt.Errorf("array is not closed") + } + return array, nil + default: + return nil, fmt.Errorf("unexpected JSON delimiter %q", value) + } + default: + return value, nil + } +} + +func semanticJSONEqual(left, right string) bool { + leftValue, err := parseStrictJSONValue(left) + if err != nil { + return false + } + rightValue, err := parseStrictJSONValue(right) + if err != nil { + return false + } + return reflect.DeepEqual(leftValue, rightValue) +} + +func parseStrictJSONValue(text string) (any, error) { + decoder := json.NewDecoder(strings.NewReader(text)) + decoder.UseNumber() + value, err := decodeStrictJSONValue(decoder, 0, 64) + if err != nil { + return nil, err + } + if _, err := decoder.Token(); err != io.EOF { + if err == nil { + return nil, fmt.Errorf("trailing JSON value") + } + return nil, err + } + return value, nil +} + +// Finish validates the terminal response once. After a successful Finish the +// turn accepts no more deltas and repeated calls return the same plan without +// producing a second delivery or settlement. +func (t *NativeTurn) Finish(responseRaw []byte, finish string) (*NativeDelivery, error) { + if t.finished { + return t.delivery, t.terminalErr + } + t.finished = true + delivery, err := t.ValidateTerminal(responseRaw, finish) + t.delivery, t.terminalErr = delivery, err + return delivery, err +} + +// ValidateTerminal reconciles every visible call and every completed snapshot +// with the terminal response object. A successful result is the only value +// from which the relay may construct its delivery. +func (t *NativeTurn) ValidateTerminal(responseRaw []byte, finish string) (*NativeDelivery, error) { + if len(responseRaw) > t.limits.MaxBufferedBytes { + return nil, fmt.Errorf("native terminal response exceeds the buffered byte limit") + } + var response nativeResponse + if err := json.Unmarshal(responseRaw, &response); err != nil { + return nil, fmt.Errorf("native terminal response is invalid: %w", err) + } + if response.ID != "" { + if t.responseID != "" && t.responseID != response.ID { + return nil, fmt.Errorf("native response id changed from %q to %q", t.responseID, response.ID) + } + t.responseID = response.ID + } + if strings.TrimSpace(finish) == "" { + switch response.Status { + case "incomplete": + finish = "length" + case "failed", "error": + finish = "error" + default: + finish = "stop" + } + } + // A terminal SSE event and the response object it carries must agree. An + // event claiming completion cannot smuggle status:"incomplete" (which would + // otherwise be treated as a usable turn), and an incomplete/errored event + // cannot be reclassified by a forged status:"completed" body. Empty or + // in_progress status is left to the existing finish/body checks below. + if err := validateNativeTerminalAgreement(finish, response.Status); err != nil { + return nil, err + } + terminal, err := t.parseTerminalCalls(response) + if err != nil { + return nil, err + } + if len(terminal) > t.limits.MaxCalls { + return nil, fmt.Errorf("native tool call count exceeds %d", t.limits.MaxCalls) + } + if finish == "length" { + if len(t.order) > 0 || len(terminal) > 0 { + return nil, fmt.Errorf("incomplete native response cannot deliver a tool call") + } + return &NativeDelivery{}, nil + } + if finish == "error" || response.Status == "failed" || response.Status == "error" { + return nil, fmt.Errorf("failed native response cannot deliver a tool call") + } + if len(t.order) == 0 { + if err := validateNativeRoundConstraints(t.request, terminal); err != nil { + return nil, err + } + return nativeDeliveryFromTerminal(terminal), nil + } + if len(terminal) == 0 { + return nil, fmt.Errorf("native terminal response omitted visible tool calls") + } + calls, err := t.reconcile(terminal) + if err != nil { + return nil, err + } + if err := validateNativeRoundConstraints(t.request, calls); err != nil { + return nil, err + } + delivery := &NativeDelivery{Calls: make([]NativeCall, 0, len(calls))} + for _, call := range calls { + callCopy := NativeCall{ + ItemID: call.itemID, CallID: call.callID, Type: call.itemType, + Name: call.name, Namespace: call.namespace, Arguments: call.arguments, + Input: call.input, Custom: call.itemType == "custom_tool_call", + } + if call.outputIndex >= 0 { + index := call.outputIndex + callCopy.OutputIndex = &index + } + delivery.Calls = append(delivery.Calls, callCopy) + } + return delivery, nil +} + +func (t *NativeTurn) parseTerminalCalls(response nativeResponse) ([]nativeTerminalCall, error) { + var calls []nativeTerminalCall + byItem := make(map[string]int) + byCall := make(map[string]int) + byIndex := make(map[int]int) + for index := range response.Output { + item := response.Output[index] + if !nativeKnownItemType(item.Type) { + return nil, fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + continue + } + if strings.TrimSpace(item.CallID) == "" { + return nil, fmt.Errorf("native terminal tool call %q has no call id", item.Name) + } + if item.ID != "" { + if previous, exists := byItem[item.ID]; exists { + return nil, fmt.Errorf("native terminal output repeats item id %q (positions %d and %d)", item.ID, previous, index) + } + byItem[item.ID] = len(calls) + } + if item.CallID != "" { + if previous, exists := byCall[item.CallID]; exists { + return nil, fmt.Errorf("native terminal output repeats call id %q (positions %d and %d)", item.CallID, previous, index) + } + byCall[item.CallID] = len(calls) + } + if previous, exists := byIndex[index]; exists { + return nil, fmt.Errorf("native terminal output reuses output position %d for calls %d and %d", index, previous, len(calls)) + } + byIndex[index] = len(calls) + spec, err := resolveNativeSpec(t.request, item.Name, item.Namespace, item.Type) + if err != nil { + return nil, err + } + arguments := "" + input := "" + hasInput := false + if item.Type == "function_call" { + arguments, _, err = nativeRawString(item.Arguments, true) + if err != nil { + return nil, fmt.Errorf("native tool call %q arguments are invalid: %w", item.Name, err) + } + if len([]byte(arguments)) > t.limits.MaxArgumentBytes { + return nil, fmt.Errorf("native tool call %q arguments exceed the limit", item.Name) + } + value, err := parseStrictJSONObject(arguments, t.limits.MaxJSONDepth) + if err != nil { + return nil, fmt.Errorf("native tool call %q arguments are invalid: %w", item.Name, err) + } + if err := validateNativeSpecValue(spec, value); err != nil { + return nil, err + } + } else { + input, hasInput, err = nativeRawInput(item.Input) + if err != nil { + return nil, fmt.Errorf("native custom tool call %q input is invalid: %w", item.Name, err) + } + if !hasInput { + return nil, fmt.Errorf("native custom tool call %q completed without input", item.Name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return nil, fmt.Errorf("native custom tool call %q input exceeds the limit", item.Name) + } + } + calls = append(calls, nativeTerminalCall{ + itemID: item.ID, callID: item.CallID, outputIndex: index, + itemType: item.Type, name: item.Name, namespace: item.Namespace, + arguments: arguments, input: input, spec: spec, + }) + } + return calls, nil +} + +func (t *NativeTurn) reconcile(terminal []nativeTerminalCall) ([]nativeTerminalCall, error) { + byItem := make(map[string]int) + byCall := make(map[string]int) + byIndex := make(map[int]int) + byName := make(map[string][]int) + for index := range terminal { + call := terminal[index] + if call.itemID != "" { + byItem[call.itemID] = index + } + if call.callID != "" { + byCall[call.callID] = index + } + byIndex[call.outputIndex] = index + byName[call.name] = appendUniqueIndex(byName[call.name], index) + if call.spec.Name != "" && call.spec.Name != call.name { + byName[call.spec.Name] = appendUniqueIndex(byName[call.spec.Name], index) + } + if call.spec.OriginalName != "" && call.spec.OriginalName != call.name { + byName[call.spec.OriginalName] = appendUniqueIndex(byName[call.spec.OriginalName], index) + } + } + matched := make(map[int]bool) + for _, key := range t.order { + call := t.calls[key] + var candidates []int + for _, alias := range nativeAliases(call.itemID, call.callID, call.outputIndex) { + var index int + var ok bool + switch { + case strings.HasPrefix(alias, "item:"): + index, ok = byItem[strings.TrimPrefix(alias, "item:")] + case strings.HasPrefix(alias, "call:"): + index, ok = byCall[strings.TrimPrefix(alias, "call:")] + case strings.HasPrefix(alias, "index:"): + position, err := strconv.Atoi(strings.TrimPrefix(alias, "index:")) + if err == nil { + index, ok = byIndex[position] + } + } + if ok && !containsInt(candidates, index) { + candidates = append(candidates, index) + } + } + if len(candidates) == 0 && call.name != "" { + candidates = byName[call.name] + if len(candidates) == 0 { + if spec, err := resolveNativeSpec(t.request, call.name, call.namespace, call.itemType); err == nil { + candidates = byName[spec.Name] + } + } + } + if len(candidates) != 1 { + return nil, fmt.Errorf("native visible tool call %q does not map to exactly one terminal call", call.name) + } + index := candidates[0] + if matched[index] { + return nil, fmt.Errorf("native terminal call at position %d matches more than one visible call", terminal[index].outputIndex) + } + matched[index] = true + if err := t.reconcileNativeCall(call, terminal[index]); err != nil { + return nil, err + } + call.terminal = &terminal[index] + } + if len(matched) != len(terminal) { + return nil, fmt.Errorf("native terminal response contains tool calls absent from the visible stream") + } + for _, snapshot := range t.snapshots { + if snapshot.call.terminal == nil { + return nil, fmt.Errorf("native completion snapshot has no terminal call") + } + terminalCall := *snapshot.call.terminal + if strings.Contains(snapshot.kind, "custom") { + if snapshot.input != terminalCall.input { + return nil, fmt.Errorf("native custom tool call %q completed with different input", snapshot.call.name) + } + continue + } + if !semanticJSONEqual(snapshot.arguments, terminalCall.arguments) { + return nil, fmt.Errorf("native tool call %q completed with arguments different from the terminal snapshot", snapshot.call.name) + } + } + return terminal, nil +} + +func (t *NativeTurn) reconcileNativeCall(call *nativeCall, terminal nativeTerminalCall) error { + if call.itemID != "" && terminal.itemID != "" && call.itemID != terminal.itemID { + return fmt.Errorf("native tool call item id changed from %q to %q", call.itemID, terminal.itemID) + } + if call.callID != "" && terminal.callID != "" && call.callID != terminal.callID { + return fmt.Errorf("native tool call id changed from %q to %q", call.callID, terminal.callID) + } + if call.itemType != "" && call.itemType != terminal.itemType { + return fmt.Errorf("native tool call %q changed type from %q to %q", call.name, call.itemType, terminal.itemType) + } + if call.name == "" { + call.name = terminal.name + } + if terminal.name != "" && call.name != terminal.name { + streamSpec, streamErr := resolveNativeSpec(t.request, call.name, call.namespace, call.itemType) + terminalSpec, terminalErr := resolveNativeSpec(t.request, terminal.name, terminal.namespace, terminal.itemType) + if streamErr != nil || terminalErr != nil || streamSpec.Name != terminalSpec.Name { + return fmt.Errorf("native tool call name changed from %q to %q", call.name, terminal.name) + } + } + if call.namespace != "" && terminal.namespace != "" && call.namespace != terminal.namespace { + return fmt.Errorf("native tool call namespace changed from %q to %q", call.namespace, terminal.namespace) + } + if call.outputIndex != nil && *call.outputIndex != terminal.outputIndex { + return fmt.Errorf("native tool call %q is at output index %d in the stream but %d in the terminal response", call.name, *call.outputIndex, terminal.outputIndex) + } + if call.itemID == "" { + call.itemID = terminal.itemID + } + if call.callID == "" { + call.callID = terminal.callID + } + if call.itemType == "" { + call.itemType = terminal.itemType + } + if call.namespace == "" { + call.namespace = terminal.namespace + } + if call.outputIndex == nil { + index := terminal.outputIndex + call.outputIndex = &index + } + if call.itemType == "custom_tool_call" { + if call.completed { + if call.input != terminal.input { + return fmt.Errorf("native custom tool call %q completed with different input", call.name) + } + } else if !strings.HasPrefix(terminal.input, call.input) { + return fmt.Errorf("native custom tool call %q visible input is not a prefix of the terminal input", call.name) + } + call.input = terminal.input + return nil + } + if call.completed { + if call.arguments != "" && !semanticJSONEqual(call.arguments, terminal.arguments) { + return fmt.Errorf("native tool call %q completed with arguments different from the terminal snapshot", call.name) + } + } else if !strings.HasPrefix(terminal.arguments, call.arguments) { + return fmt.Errorf("native tool call %q visible arguments are not a prefix of the terminal arguments", call.name) + } + call.arguments = terminal.arguments + return nil +} + +func containsInt(values []int, value int) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + +func appendUniqueIndex(values []int, value int) []int { + if containsInt(values, value) { + return values + } + return append(values, value) +} + +// validateNativeTerminalAgreement rejects a mismatch between the SSE terminal +// event's finish and the status inside the response object. The event is the +// authority; a disagreeing body is a malformed or forged terminal. +func validateNativeTerminalAgreement(finish, status string) error { + status = strings.ToLower(strings.TrimSpace(status)) + if status == "" { + return nil + } + switch finish { + case "stop": + if status == "incomplete" || status == "failed" || status == "error" || status == "in_progress" { + return fmt.Errorf("native terminal event claims completion but response status is %q", status) + } + case "length": + if status == "completed" || status == "failed" || status == "error" { + return fmt.Errorf("native terminal event claims an incomplete turn but response status is %q", status) + } + case "error": + if status == "completed" { + return fmt.Errorf("native terminal event claims failure but response status is %q", status) + } + } + return nil +} + +func validateNativeRoundConstraints(request Request, calls []nativeTerminalCall) error { + if len(calls) == 0 { + if request.Choice.Mode == ChoiceRequired || request.Choice.Mode == ChoiceNamed { + return fmt.Errorf("native response did not deliver the required tool call") + } + return nil + } + if !request.HasTools() { + return fmt.Errorf("native response delivered tool calls without any declared tool") + } + switch request.Choice.Mode { + case ChoiceNone: + return fmt.Errorf("native response delivered a tool call while tool_choice is none") + case ChoiceRequired: + if len(calls) == 0 { + return fmt.Errorf("native response did not deliver the required tool call") + } + case ChoiceNamed: + if len(calls) != 1 { + return fmt.Errorf("native named tool_choice requires exactly one call, got %d", len(calls)) + } + named := calls[0] + if request.Choice.Name != named.name && request.Choice.Name != named.spec.Name && request.Choice.Name != named.spec.OriginalName { + return fmt.Errorf("native response delivered %q while tool_choice names %q", named.name, request.Choice.Name) + } + } + if request.Policy.Parallel != nil && !*request.Policy.Parallel && len(calls) > 1 { + return fmt.Errorf("native response delivered %d calls while parallel_tool_calls is false", len(calls)) + } + if request.Policy.MaxCalls > 0 && len(calls) > request.Policy.MaxCalls { + return fmt.Errorf("native response delivered %d calls, exceeding max_calls %d", len(calls), request.Policy.MaxCalls) + } + return nil +} + +func nativeDeliveryFromTerminal(calls []nativeTerminalCall) *NativeDelivery { + delivery := &NativeDelivery{Calls: make([]NativeCall, 0, len(calls))} + for _, call := range calls { + index := call.outputIndex + delivery.Calls = append(delivery.Calls, NativeCall{ + OutputIndex: &index, ItemID: call.itemID, CallID: call.callID, + Type: call.itemType, Name: call.name, Namespace: call.namespace, + Arguments: call.arguments, Input: call.input, + Custom: call.itemType == "custom_tool_call", + }) + } + return delivery +} + +// ValidateNativeResponsesOutput validates a terminal response body without a +// visible stream, inferring the finish reason from the response object. Prefer +// ValidateNativeResponsesTurn when the SSE terminal event is available: the +// event type is authoritative and cannot be spoofed by a disagreeing body. +func ValidateNativeResponsesOutput(raw json.RawMessage, request Request) error { + return ValidateNativeResponsesTurn(raw, request, "") +} + +// ValidateNativeResponsesTurn validates a terminal response body using the SSE +// terminal event's finish reason as the authoritative outcome. A response that +// claims status:"completed" while the event is response.incomplete (or vice +// versa) is rejected, so a non-stream collector cannot accept a truncated or +// forged turn that the streaming relay already refuses. +func ValidateNativeResponsesTurn(raw json.RawMessage, request Request, eventFinish string) error { + turn := NewNativeTurn(request) + finish := strings.TrimSpace(eventFinish) + if finish == "" { + var response nativeResponse + if json.Unmarshal(raw, &response) == nil { + switch response.Status { + case "incomplete": + finish = "length" + case "failed", "error": + finish = "error" + } + } + } + _, err := turn.Finish(raw, finish) + return err +} diff --git a/internal/toolcall/native_identity_test.go b/internal/toolcall/native_identity_test.go new file mode 100644 index 000000000..9a9335c54 --- /dev/null +++ b/internal/toolcall/native_identity_test.go @@ -0,0 +1,81 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestNativeTurnAcceptsLateBindingCallIDAndItem(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","call_id":"call_1","name":"lookup","delta":"{}"}`)); err != nil { + t.Fatal(err) + } + if err := turn.Observe("response.output_item.done", []byte(`{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`)); err != nil { + t.Fatal(err) + } + if _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop"); err != nil { + t.Fatal(err) + } +} + +func TestNativeTurnAcceptsNonEmptyCustomCompletion(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"custom","name":"exec"}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`)); err != nil { + t.Fatal(err) + } + if err := turn.Observe("response.custom_tool_call_input.done", []byte(`{"type":"response.custom_tool_call_input.done","item_id":"ct_1","input":"pwd"}`)); err != nil { + t.Fatal(err) + } + plan, err := turn.Finish(nativeTerminalResponse(`[{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":"pwd"}]`), "stop") + if err != nil { + t.Fatal(err) + } + if len(plan.Calls) != 1 || plan.Calls[0].Input != "pwd" { + t.Fatalf("custom plan lost input: %+v", plan.Calls) + } +} + +func TestNativeTurnRejectsTerminalWithoutCallID(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","name":"lookup","arguments":"{}"}]`), "stop") + if err == nil || !strings.Contains(err.Error(), "call id") { + t.Fatalf("terminal without call_id must be rejected, got %v", err) + } +} + +func TestNativeTurnRejectsExplicitNamespaceMismatch(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","namespace":"ns1","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","namespace":"ns2","arguments":"{}"}]`), "stop") + if err == nil { + t.Fatal("explicit namespace mismatch must be rejected") + } +} + +func TestNativeTurnRejectsArgumentDoneNameConflict(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}},{"type":"function","name":"other","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + done := `{"type":"response.function_call_arguments.done","item_id":"fc_1","call_id":"call_1","name":"other","arguments":"{}"}` + if err := turn.Observe("response.function_call_arguments.done", []byte(done)); err == nil { + t.Fatal("argument completion name conflict must be rejected") + } +} + +func TestNativeTurnRejectsCompletedEventWithIncompleteBody(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + body := json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}`) + _, err := NewNativeTurn(request).Finish(body, "stop") + if err == nil { + t.Fatal("response.completed with status=incomplete must not deliver a tool call") + } +} diff --git a/internal/toolcall/native_test.go b/internal/toolcall/native_test.go new file mode 100644 index 000000000..22e75454b --- /dev/null +++ b/internal/toolcall/native_test.go @@ -0,0 +1,352 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func nativeTestRequest(t *testing.T, tools, choice string, parallel *bool) Request { + t.Helper() + var choiceRaw json.RawMessage + if choice != "" { + choiceRaw = json.RawMessage(choice) + } + request, err := ParseRequest(ProtocolResponses, json.RawMessage(tools), choiceRaw, parallel, RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + +func nativeTerminalResponse(output string) json.RawMessage { + return json.RawMessage(`{"id":"resp_1","status":"completed","output":` + output + `}`) +} + +func TestNativeTerminalRejectsEventBodyDisagreement(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + cases := []struct { + name, status, finish string + wantErr bool + }{ + {"completed event with completed body", "completed", "stop", false}, + {"completed event with incomplete body", "incomplete", "stop", true}, + {"incomplete event with completed body", "completed", "length", true}, + {"failed event with completed body", "completed", "error", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := json.RawMessage(`{"id":"resp_1","status":"` + tc.status + `","output":` + output + `}`) + err := ValidateNativeResponsesTurn(body, request, tc.finish) + if tc.wantErr && err == nil { + t.Fatal("event/body disagreement must be rejected") + } + if !tc.wantErr && err != nil { + t.Fatalf("consistent terminal was rejected: %v", err) + } + }) + } +} + +func TestNativeTerminalArgumentsAreStrictAndNeverRepaired(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + cases := []string{ + "", + `{"q":`, + `{"q":"ok"}{"q":"again"}`, + `{"q":"ok","q":"again"}`, + `["q"]`, + `"ok"`, + `null`, + } + for _, arguments := range cases { + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":` + strconvQuote(arguments) + `}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request); err == nil { + t.Fatalf("arguments %q must be rejected", arguments) + } + } +} + +func TestNativeTerminalAcceptsCanonicalArgumentsAndEmptyCustomInput(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request); err != nil { + t.Fatal(err) + } + + customRequest := nativeTestRequest(t, `[{"type":"custom","name":"shell","description":"run"}]`, "", nil) + customOutput := `[{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"shell","input":""}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(customOutput), customRequest); err != nil { + t.Fatal(err) + } +} + +func TestNativeTerminalHonorsChoiceAndParallelConstraints(t *testing.T) { + parallel := false + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", ¶llel) + two := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(two), request); err == nil { + t.Fatal("parallel_tool_calls=false must reject two terminal calls") + } + + none := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, `"none"`, nil) + one := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(one), none); err == nil { + t.Fatal("tool_choice none must reject a terminal call") + } + + required := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, `"required"`, nil) + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(`[]`), required); err == nil { + t.Fatal("required tool_choice must reject an empty terminal output") + } +} + +func TestNativeTurnFinishIsIdempotentAndSealsDeltas(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + first, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop") + if err != nil { + t.Fatal(err) + } + if len(first.Calls) != 1 { + t.Fatalf("calls = %d", len(first.Calls)) + } + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{}"}`)); err == nil { + t.Fatal("Observe after Finish must fail") + } + second, secondErr := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop") + if secondErr != nil || second == nil || len(second.Calls) != 1 { + t.Fatalf("repeat Finish must return the same plan, got %v %v", second, secondErr) + } +} + +func TestNativeLimitsRejectSuffixBytesBeforeAppend(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxArgumentBytes = 8 + turn := NewNativeTurn(request, limits) + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"123456789"}`)); err == nil { + t.Fatal("oversized argument delta must be rejected") + } +} + +func TestNativeLimitsRejectCompleteOutputSnapshotBytes(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxArgumentBytes = 8 + turn := NewNativeTurn(request, limits) + done := `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"123456789\"}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err == nil { + t.Fatal("oversized completed output item must be rejected") + } +} + +func TestNativeLimitsRejectCallCount(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxCalls = 1 + turn := NewNativeTurn(request, limits) + for _, id := range []string{"fc_1", "fc_2"} { + payload := `{"type":"response.output_item.added","item":{"id":"` + id + `","type":"function_call","call_id":"` + id + `","name":"lookup","arguments":""}}` + if id == "fc_2" { + if err := turn.Observe("response.output_item.added", []byte(payload)); err == nil { + t.Fatal("call count over the limit must be rejected") + } + continue + } + if err := turn.Observe("response.output_item.added", []byte(payload)); err != nil { + t.Fatal(err) + } + } +} + +func TestNativeTerminalRejectsUnknownExecutableItem(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + output := `[{"id":"x","type":"computer_call","call_id":"c","name":"computer"}]` + err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request) + if err == nil { + t.Fatal("unknown executable item must be rejected") + } + if !strings.Contains(err.Error(), "unsupported") { + t.Fatalf("expected unsupported item error, got %v", err) + } +} + +func TestNativeTurnRejectsTerminalThatOmitsVisibleParallelCall(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + for _, id := range []string{"fc_1", "fc_2"} { + added := `{"type":"response.output_item.added","item":{"id":"` + id + `","type":"function_call","call_id":"call_` + id + `","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + done := `{"type":"response.output_item.done","item":{"id":"` + id + `","type":"function_call","call_id":"call_` + id + `","name":"lookup","arguments":"{}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err != nil { + t.Fatal(err) + } + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_fc_1","name":"lookup","arguments":"{}"}]` + if _, err := turn.Finish(nativeTerminalResponse(terminal), "stop"); err == nil { + t.Fatal("terminal must not silently omit a visible completed call") + } +} + +func TestNativeTurnAcceptsInterleavedCallsWithMatchingTerminal(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + events := []struct { + name string + data string + }{ + {"response.output_item.added", `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`}, + {"response.output_item.added", `{"type":"response.output_item.added","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}`}, + {"response.output_item.done", `{"type":"response.output_item.done","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"}}`}, + {"response.output_item.done", `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`}, + } + for _, event := range events { + if err := turn.Observe(event.name, []byte(event.data)); err != nil { + t.Fatal(err) + } + } + terminal := `[{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"},{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + plan, err := turn.Finish(nativeTerminalResponse(terminal), "stop") + if err != nil { + t.Fatal(err) + } + if len(plan.Calls) != 2 { + t.Fatalf("calls = %d", len(plan.Calls)) + } +} + +func TestNativeTurnRejectsConflictingIdentity(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + first := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(first)); err != nil { + t.Fatal(err) + } + second := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(second)); err == nil { + t.Fatal("an item id must not switch call_id") + } +} + +func TestNativeTurnRejectsOutputIndexReuse(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + first := `{"type":"response.output_item.added","output_index":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(first)); err != nil { + t.Fatal(err) + } + second := `{"type":"response.output_item.added","output_index":0,"item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(second)); err == nil { + t.Fatal("output_index must not switch to another item id") + } +} + +func TestNativeTurnRejectsControlEnvelopeToolOmittedByTerminal(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + created := `{"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}` + if err := turn.Observe("response.created", []byte(created)); err != nil { + t.Fatal(err) + } + if _, err := turn.Finish(nativeTerminalResponse(`[]`), "stop"); err == nil { + t.Fatal("a tool item embedded in response.created must not disappear") + } +} + +func TestNativeTurnAllowsEmptyIncompleteButRejectsToolIncomplete(t *testing.T) { + request := nativeTestRequest(t, `[]`, "", nil) + turn := NewNativeTurn(request) + if _, err := turn.Finish(json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[]}`), "length"); err != nil { + t.Fatalf("tool-free incomplete should remain native truncation: %v", err) + } + + request = nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn = NewNativeTurn(request) + added := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + incomplete := json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":"}]}`) + if _, err := turn.Finish(incomplete, "length"); err == nil { + t.Fatal("a tool-bearing incomplete turn must be rejected") + } +} + +func FuzzNativeTurnNeverDeliversAnOmittedVisibleCall(f *testing.F) { + f.Add(`[]`) + f.Add(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`) + f.Add(`[{"type":"message"}]`) + f.Fuzz(func(t *testing.T, terminalOutput string) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + added := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + plan, err := turn.Finish(nativeTerminalResponse(terminalOutput), "stop") + if err == nil && len(plan.Calls) == 0 { + t.Fatalf("terminal output %q dropped a visible call", terminalOutput) + } + }) +} + +func TestNativeDeliveryContainsFinalIdentityAndFullArguments(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]` + delivery, err := turn.Finish(nativeTerminalResponse(terminal), "stop") + if err != nil { + t.Fatal(err) + } + if len(delivery.Calls) != 1 || delivery.Calls[0].CallID != "call_1" || delivery.Calls[0].Arguments != `{"q":"ok"}` { + t.Fatalf("delivery lost final identity/arguments: %+v", delivery.Calls) + } +} + +func BenchmarkNativeTurnFinish(b *testing.B) { + request, err := ParseRequest(ProtocolResponses, + json.RawMessage(`[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`), nil, nil, RepairSafe) + if err != nil { + b.Fatal(err) + } + added := []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`) + terminal := nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`) + b.ResetTimer() + for i := 0; i < b.N; i++ { + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", added); err != nil { + b.Fatal(err) + } + if _, err := turn.Finish(terminal, "stop"); err != nil { + b.Fatal(err) + } + } +} + +func TestNativeTurnComparesLargeIntegersWithoutFloatRounding(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]}}]`, "", nil) + turn := NewNativeTurn(request) + done := `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"n\":9007199254740993}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err != nil { + t.Fatal(err) + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"n\":9007199254740992}"}]` + if _, err := turn.Finish(nativeTerminalResponse(terminal), "stop"); err == nil { + t.Fatal("different large integers must not reconcile as equal") + } +} + +func strconvQuote(value string) string { + encoded, _ := json.Marshal(value) + return string(encoded) +} diff --git a/internal/toolcall/reducer.go b/internal/toolcall/reducer.go new file mode 100644 index 000000000..55c9e9699 --- /dev/null +++ b/internal/toolcall/reducer.go @@ -0,0 +1,435 @@ +package toolcall + +import ( + "fmt" + "sort" + "strings" +) + +// ChatToolDelta is one OpenAI Chat Completions tool_calls fragment. +type ChatToolDelta struct { + Index *int + ID string + Type string + Name string + Arguments string +} + +// ChatDelta is the subset of one Chat Completions chunk the reducer needs. +type ChatDelta struct { + Content string + Reasoning string + ToolCalls []ChatToolDelta + FinishReason string +} + +// Reducer assembles one upstream turn into stable tool calls. Identity is the +// provider call ID; index is only an auxiliary key scoped to this stream. +type Reducer struct { + request Request + + calls map[string]*Call + byIndex map[int]string + order []string + next int + + lastIndex int + text strings.Builder + reasoning strings.Builder + + finishReason string + terminal string + sealed bool + err error +} + +func NewReducer(request Request) *Reducer { + return &Reducer{ + request: request, + calls: make(map[string]*Call), + byIndex: make(map[int]string), + lastIndex: -1, + next: 1, + } +} + +func (r *Reducer) Text() string { return r.text.String() } +func (r *Reducer) Reasoning() string { return r.reasoning.String() } +func (r *Reducer) FinishReason() string { + return r.finishReason +} + +func (r *Reducer) Err() error { return r.err } + +// Absorb consumes one chunk. It returns renderer events for text, reasoning, +// call start and argument fragments. Error events are terminal. +func (r *Reducer) Absorb(delta ChatDelta) ([]Event, error) { + if r.sealed { + return nil, fmt.Errorf("tool stream already sealed") + } + if r.err != nil { + return nil, r.err + } + events := make([]Event, 0, 4) + if delta.Reasoning != "" { + r.reasoning.WriteString(delta.Reasoning) + events = append(events, Event{Kind: EventReasoningDelta, Text: delta.Reasoning}) + } + if delta.Content != "" { + r.text.WriteString(delta.Content) + events = append(events, Event{Kind: EventTextDelta, Text: delta.Content}) + } + for position := range delta.ToolCalls { + fragment := delta.ToolCalls[position] + call, started, err := r.resolveCall(fragment, position) + if err != nil { + r.err = err + return events, err + } + if started { + snapshot := *call + events = append(events, Event{Kind: EventCallStarted, Call: &snapshot}) + } + if fragment.Name != "" && len(r.request.Specs) > 0 { + if _, ok := r.request.SpecByName(fragment.Name); !ok { + r.invalidate(call, fmt.Sprintf("tool %q is not declared", fragment.Name)) + } + } + if fragment.ID != "" { + call.ProviderID = fragment.ID + call.InternalID = fragment.ID + } + if fragment.Name != "" { + if call.Name != "" && call.Name != fragment.Name { + r.invalidate(call, fmt.Sprintf("tool call id %q changed name from %q to %q", call.InternalID, call.Name, fragment.Name)) + } else { + call.Name = fragment.Name + } + } + if fragment.Arguments != "" { + call.ArgumentsRaw = mergeArgumentFragment(call.ArgumentsRaw, fragment.Arguments) + snapshot := *call + events = append(events, Event{Kind: EventCallArguments, Call: &snapshot}) + } + } + if delta.FinishReason != "" { + r.finishReason = delta.FinishReason + for _, id := range r.order { + // A call that fails final validation is reported by Finish; the + // chunk itself is still absorbed so renderers can see partial state. + _ = r.seal(r.calls[id]) + } + r.sealed = true + } + return events, nil +} + +// Finish seals the turn. terminal is done, eof, error, canceled or empty. +func (r *Reducer) Finish(terminal string) (TurnResult, error) { + if terminal == "" { + terminal = r.terminal + } + if terminal == "" { + terminal = "eof" + } + if !r.sealed { + for _, id := range r.order { + if err := r.seal(r.calls[id]); err != nil { + r.err = err + } + } + r.sealed = true + } + result := TurnResult{ + Protocol: r.request.Protocol, + Text: r.text.String(), + Reasoning: r.reasoning.String(), + FinishReason: r.finishReason, + UpstreamTerminal: terminal, + } + for _, id := range r.order { + result.Calls = append(result.Calls, *r.calls[id]) + } + for index := range result.Calls { + if result.Calls[index].Status == CallInvalid || result.Calls[index].Status == CallFailed || result.Calls[index].Status == CallTruncated { + if result.Calls[index].Status == CallTruncated { + result.Status = TurnTruncated + } else { + result.Status = TurnInvalid + } + result.Error = result.Calls[index].Error + return result, fmt.Errorf("%s", result.Error) + } + } + if r.err != nil { + result.Status = TurnInvalid + result.Error = r.err.Error() + return result, r.err + } + if strings.EqualFold(strings.TrimSpace(r.finishReason), "length") { + result.Status = TurnTruncated + result.Error = "upstream response finished with length" + return result, nil + } + if terminal == "error" { + result.Status = TurnFailed + result.Error = "upstream stream failed" + return result, fmt.Errorf("%s", result.Error) + } + if terminal == "canceled" { + result.Status = TurnCanceled + result.Error = "request canceled" + return result, fmt.Errorf("%s", result.Error) + } + if terminal != "done" { + result.Status = TurnTruncated + result.Error = "upstream ended without a terminal frame" + return result, fmt.Errorf("%s", result.Error) + } + if err := r.checkChoice(result); err != nil { + result.Status = TurnInvalid + result.Error = err.Error() + return result, err + } + if strings.EqualFold(strings.TrimSpace(r.finishReason), "tool_calls") && len(result.Calls) == 0 { + result.Status = TurnInvalid + result.Error = "finish_reason tool_calls without a tool call" + return result, fmt.Errorf("%s", result.Error) + } + if len(result.Calls) > 0 { + result.Status = TurnToolCalls + } else { + result.Status = TurnCompleted + } + return result, nil +} + +func (r *Reducer) checkChoice(result TurnResult) error { + choice := r.request.Choice + switch choice.Mode { + case ChoiceNone: + if len(result.Calls) > 0 { + return fmt.Errorf("tool_choice none was violated: model called %d tool(s)", len(result.Calls)) + } + case ChoiceRequired: + if len(result.Calls) == 0 { + return fmt.Errorf("tool_choice required was violated: model returned no tool call") + } + case ChoiceNamed: + if len(result.Calls) == 0 { + return fmt.Errorf("tool_choice %q was violated: model returned no tool call", choice.Name) + } + for _, call := range result.Calls { + if call.Name != choice.Name { + return fmt.Errorf("tool_choice %q was violated: model called %q", choice.Name, call.Name) + } + } + } + if r.request.Policy.MaxCalls > 0 && len(result.Calls) > r.request.Policy.MaxCalls { + return fmt.Errorf("tool call limit exceeded: %d > %d", len(result.Calls), r.request.Policy.MaxCalls) + } + if r.request.Policy.Parallel != nil && !*r.request.Policy.Parallel && len(result.Calls) > 1 { + return fmt.Errorf("parallel tool calls disabled: model returned %d calls", len(result.Calls)) + } + return nil +} + +func (r *Reducer) resolveCall(fragment ChatToolDelta, position int) (*Call, bool, error) { + index := -1 + if fragment.Index != nil { + index = *fragment.Index + } + if fragment.ID != "" { + if call, ok := r.calls[fragment.ID]; ok { + if index >= 0 { + r.bindIndex(index, call.InternalID) + } + return call, false, nil + } + if index >= 0 { + if existingID := r.byIndex[index]; existingID != "" { + existing := r.calls[existingID] + if existing != nil { + if existing.ProviderID == "" { + delete(r.calls, existing.InternalID) + for orderIndex := range r.order { + if r.order[orderIndex] == existing.InternalID { + r.order[orderIndex] = fragment.ID + break + } + } + existing.InternalID = fragment.ID + existing.ProviderID = fragment.ID + r.calls[fragment.ID] = existing + r.byIndex[index] = fragment.ID + return existing, false, nil + } + if existing.ProviderID != fragment.ID { + if err := r.seal(existing); err != nil { + return nil, false, err + } + delete(r.byIndex, index) + } + } + } + } + call := r.newCall(fragment, index) + return call, true, nil + } + if index >= 0 { + if existingID := r.byIndex[index]; existingID != "" { + call := r.calls[existingID] + if call != nil && !call.Sealed { + r.lastIndex = index + return call, false, nil + } + // Index reuse after a sealed call starts a new call. + delete(r.byIndex, index) + } + if fragment.Name != "" || r.lastIndex == index || r.lastIndex < 0 { + call := r.newCall(fragment, index) + return call, true, nil + } + call := r.newCall(fragment, index) + return call, true, nil + } + if fragment.Name != "" { + call := r.newCall(fragment, index) + return call, true, nil + } + // A nameless fragment without an index belongs to the most recent open + // call; if there is none, create a placeholder that will fail at seal time. + if len(r.order) > 0 { + call := r.calls[r.order[len(r.order)-1]] + if call != nil && !call.Sealed { + return call, false, nil + } + } + call := r.newCall(fragment, position) + return call, true, nil +} + +func (r *Reducer) newCall(fragment ChatToolDelta, index int) *Call { + id := fragment.ID + if id == "" { + id = fmt.Sprintf("local_%d", r.next) + r.next++ + } + call := &Call{ + Index: index, + InternalID: id, + ProviderID: fragment.ID, + Name: strings.TrimSpace(fragment.Name), + Status: CallStarted, + } + r.calls[id] = call + r.order = append(r.order, id) + r.lastIndex = index + if index >= 0 { + r.bindIndex(index, id) + } + return call +} + +func (r *Reducer) bindIndex(index int, id string) { + if index < 0 { + return + } + if existing := r.byIndex[index]; existing != "" && existing != id { + // The provider reused the index for a new call; the new call wins. + if call := r.calls[existing]; call != nil { + _ = r.seal(call) + } + } + r.byIndex[index] = id +} + +func (r *Reducer) seal(call *Call) error { + if call == nil || call.Sealed { + return nil + } + if call.Status == CallInvalid { + return fmt.Errorf("%s", call.Error) + } + call.Sealed = true + if strings.TrimSpace(call.Name) == "" { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool call %q has no name", call.InternalID) + return fmt.Errorf("%s", call.Error) + } + spec, ok := r.request.SpecByName(call.Name) + if len(r.request.Specs) == 0 { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool %q was returned without being declared", call.Name) + return fmt.Errorf("%s", call.Error) + } + if !ok { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool %q is not declared", call.Name) + return fmt.Errorf("%s", call.Error) + } + call.Namespace = spec.Namespace + call.OriginalName = spec.OriginalName + arguments, repaired, err := ValidateArguments(spec, call.ArgumentsRaw, r.request.Policy.Repair) + if err != nil { + call.Status = CallInvalid + call.Error = err.Error() + return err + } + call.Arguments = arguments + call.Repaired = repaired + call.Status = CallCompleted + return nil +} + +func (r *Reducer) invalidate(call *Call, reason string) { + if call == nil { + return + } + if call.Status == CallCompleted || call.Status == CallInvalid { + return + } + call.Status = CallInvalid + call.Error = reason +} + +func mergeArgumentFragment(base, fragment string) string { + if fragment == "" { + return base + } + if base == "" { + return fragment + } + // Some upstreams resend the full buffer on every chunk. + if len(fragment) > len(base) && strings.HasPrefix(fragment, base) { + return fragment + } + if len(fragment) >= 8 && strings.HasSuffix(base, fragment) { + return base + } + return base + fragment +} + +// Calls returns a copy in protocol order. +func (r *Reducer) Calls() []Call { + calls := make([]Call, 0, len(r.order)) + for _, id := range r.order { + if call := r.calls[id]; call != nil { + calls = append(calls, *call) + } + } + return calls +} + +// OrderedIndexes returns the canonical call order as indexes for renderers +// that still address calls by their original protocol index. +func (r *Reducer) OrderedIndexes() []int { + indexes := make([]int, 0, len(r.order)) + for _, id := range r.order { + if call := r.calls[id]; call != nil && call.Index >= 0 { + indexes = append(indexes, call.Index) + } + } + sort.Ints(indexes) + return indexes +} diff --git a/internal/toolcall/render.go b/internal/toolcall/render.go new file mode 100644 index 000000000..07a6ecf87 --- /dev/null +++ b/internal/toolcall/render.go @@ -0,0 +1,239 @@ +package toolcall + +import ( + "encoding/json" + "fmt" +) + +// ChatOutput is the buffered Chat Completions representation of one turn. +type ChatOutput struct { + Text string + Reasoning string + FinishReason string + Calls []Call +} + +// ContentBlock is one Anthropic Messages content block. +type ContentBlock struct { + Type string + Text string + ID string + Name string + Input json.RawMessage +} + +// ResponseItem is one Responses API output item. +type ResponseItem struct { + Type string + ID string + CallID string + Name string + Arguments string + Status string + Content []ContentBlock +} + +// RenderChatStream replays buffered Chat chunks through the canonical reducer +// and emits deterministic Chat chunks. It is used by tests and by adapters that +// need to re-normalize a buffered stream. +func RenderChatStream(request Request, deltas []ChatDelta) ([]ChatDelta, TurnResult, error) { + reducer := NewReducer(request) + for index := range deltas { + if _, err := reducer.Absorb(deltas[index]); err != nil { + return nil, reducer.snapshotResult(), err + } + } + result, err := reducer.Finish("done") + if err != nil { + return nil, result, err + } + out := make([]ChatDelta, 0, len(result.Calls)+2) + if result.Text != "" || result.Reasoning != "" { + out = append(out, ChatDelta{Content: result.Text, Reasoning: result.Reasoning}) + } + for index := range result.Calls { + if result.Status == TurnTruncated { + break + } + call := result.Calls[index] + callIndex := index + out = append(out, ChatDelta{ToolCalls: []ChatToolDelta{{ + Index: &callIndex, + ID: call.InternalID, + Type: "function", + Name: call.Name, + Arguments: string(call.Arguments), + }}}) + } + finish := result.FinishReason + if result.Status == TurnToolCalls { + finish = "tool_calls" + } else if finish == "" { + finish = "stop" + } + out = append(out, ChatDelta{FinishReason: finish}) + return out, result, nil +} + +// ReduceChatCompletion folds one buffered assistant turn into the canonical +// result. Callers must use this instead of trusting adapter JSON directly: +// argument and choice violations become errors, never a synthesized success. +func ReduceChatCompletion(request Request, content, reasoning, finishReason string, rawCalls json.RawMessage) (TurnResult, error) { + reducer := NewReducer(request) + delta := ChatDelta{Content: content, Reasoning: reasoning, FinishReason: finishReason} + if len(rawCalls) > 0 && string(rawCalls) != "null" { + var calls []struct { + ID string `json:"id"` + Type string `json:"type"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } + if err := json.Unmarshal(rawCalls, &calls); err != nil { + return TurnResult{}, fmt.Errorf("tool_calls: %w", err) + } + for index, call := range calls { + callIndex := index + delta.ToolCalls = append(delta.ToolCalls, ChatToolDelta{ + Index: &callIndex, + ID: call.ID, + Type: call.Type, + Name: call.Function.Name, + Arguments: call.Function.Arguments, + }) + } + } + if _, err := reducer.Absorb(delta); err != nil { + return reducer.snapshotResult(), err + } + return reducer.Finish("done") +} + +func RenderChat(result TurnResult) ChatOutput { + switch result.Status { + case TurnFailed, TurnInvalid, TurnCanceled: + return ChatOutput{FinishReason: "error"} + case TurnTruncated: + return ChatOutput{Text: result.Text, Reasoning: result.Reasoning, FinishReason: finishReasonFor(result)} + } + return ChatOutput{ + Text: result.Text, + Reasoning: result.Reasoning, + FinishReason: finishReasonFor(result), + Calls: append([]Call(nil), result.Calls...), + } +} + +func finishReasonFor(result TurnResult) string { + if result.Status == TurnToolCalls { + return "tool_calls" + } + if result.FinishReason != "" { + return result.FinishReason + } + return "stop" +} + +// RenderMessagesBlocks renders only valid turns. A failed or truncated turn is +// never converted into a successful content block list. +func RenderMessagesBlocks(result TurnResult) ([]ContentBlock, error) { + if result.Status == TurnFailed || result.Status == TurnTruncated || result.Status == TurnInvalid || result.Status == TurnCanceled { + return nil, failureFor(result) + } + blocks := make([]ContentBlock, 0, len(result.Calls)+1) + if result.Text != "" { + blocks = append(blocks, ContentBlock{Type: "text", Text: result.Text}) + } + for _, call := range result.Calls { + if err := requireCompletedCall(call); err != nil { + return nil, err + } + input := call.Arguments + if len(input) == 0 { + input = json.RawMessage("{}") + } + blocks = append(blocks, ContentBlock{ + Type: "tool_use", + ID: call.InternalID, + Name: call.Name, + Input: input, + }) + } + return blocks, nil +} + +// RenderResponsesItems renders only valid turns. Function call items are never +// emitted when the reducer marked their arguments invalid. +func RenderResponsesItems(result TurnResult) ([]ResponseItem, error) { + if result.Status == TurnFailed || result.Status == TurnTruncated || result.Status == TurnInvalid || result.Status == TurnCanceled { + return nil, failureFor(result) + } + items := make([]ResponseItem, 0, len(result.Calls)+1) + if result.Text != "" { + items = append(items, ResponseItem{ + Type: "message", + ID: "msg_" + stablePart(result.Protocol), + Status: "completed", + Content: []ContentBlock{{Type: "output_text", Text: result.Text}}, + }) + } + for _, call := range result.Calls { + if err := requireCompletedCall(call); err != nil { + return nil, err + } + items = append(items, ResponseItem{ + Type: "function_call", + ID: "fc_" + call.InternalID, + CallID: call.InternalID, + Name: call.Name, + Arguments: string(call.Arguments), + Status: "completed", + }) + } + return items, nil +} + +func requireCompletedCall(call Call) error { + if call.Status != CallCompleted { + if call.Error != "" { + return fmt.Errorf("%s", call.Error) + } + return fmt.Errorf("tool call %q is %s", call.InternalID, call.Status) + } + return nil +} + +func failureFor(result TurnResult) error { + if result.Error != "" { + return fmt.Errorf("%s", result.Error) + } + return fmt.Errorf("turn %s cannot be rendered as success", result.Status) +} + +func stablePart(protocol Protocol) string { + if protocol == "" { + return "chat" + } + return string(protocol) +} + +func (r *Reducer) snapshotResult() TurnResult { + result := TurnResult{ + Protocol: r.request.Protocol, + Text: r.text.String(), + Reasoning: r.reasoning.String(), + FinishReason: r.finishReason, + UpstreamTerminal: r.terminal, + Status: TurnFailed, + } + if r.err != nil { + result.Error = r.err.Error() + } + for _, id := range r.order { + if call := r.calls[id]; call != nil { + result.Calls = append(result.Calls, *call) + } + } + return result +} diff --git a/internal/toolcall/request.go b/internal/toolcall/request.go new file mode 100644 index 000000000..82a00964c --- /dev/null +++ b/internal/toolcall/request.go @@ -0,0 +1,387 @@ +package toolcall + +import ( + "encoding/json" + "fmt" + "strings" +) + +const defaultParameters = `{"type":"object","properties":{}}` + +// ParseRequest parses the normalized OpenAI tool array and selector used by +// all current adapters. It also accepts flat Responses function declarations so +// a native Responses body can be validated before an adapter is chosen. +func ParseRequest(protocol Protocol, tools, choice json.RawMessage, parallel *bool, repair RepairMode) (Request, error) { + if protocol == "" { + protocol = ProtocolChat + } + if repair == "" { + repair = RepairSafe + } + request := Request{Protocol: protocol, Policy: Policy{Repair: repair, Schema: SchemaRelaxed}} + specs, diagnostics, err := parseSpecs(protocol, tools) + if err != nil { + return Request{}, err + } + request.Specs = specs + request.Diagnostics = diagnostics + for _, spec := range specs { + if spec.Strict { + request.Policy.Schema = SchemaStrict + break + } + } + request.Policy.Parallel = cloneBool(parallel) + parsedChoice, diagnostic, err := parseChoice(specs, choice) + if err != nil { + return Request{}, err + } + if diagnostic != "" { + request.Diagnostics = append(request.Diagnostics, diagnostic) + } + request.Choice = parsedChoice + return request, nil +} + +func cloneBool(value *bool) *bool { + if value == nil { + return nil + } + copy := *value + return © +} + +func parseSpecs(protocol Protocol, raw json.RawMessage) ([]Spec, []string, error) { + if emptyJSON(raw) { + return nil, nil, nil + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return nil, nil, fmt.Errorf("tools must be an array") + } + specs := make([]Spec, 0, len(items)) + diagnostics := make([]string, 0) + seen := map[string]int{} + appendSpec := func(spec Spec) error { + if strings.TrimSpace(spec.Name) == "" { + return fmt.Errorf("tool name required") + } + if index, exists := seen[spec.Name]; exists { + return fmt.Errorf("duplicate tool name %q (tools[%d])", spec.Name, index) + } + seen[spec.Name] = len(specs) + specs = append(specs, spec) + return nil + } + for index, item := range items { + var object map[string]json.RawMessage + if err := json.Unmarshal(item, &object); err != nil { + return nil, nil, fmt.Errorf("tools[%d] must be an object", index) + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + switch kind { + case "namespace": + namespace := strings.TrimSpace(rawString(object["name"])) + nested, nestedDiagnostics, err := parseNamespace(protocol, namespace, object["tools"]) + if err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + diagnostics = append(diagnostics, nestedDiagnostics...) + for _, spec := range nested { + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + } + case "mcp", "web_search", "web_search_preview": + diagnostics = append(diagnostics, fmt.Sprintf("hosted tool tools[%d] type %q is not executable", index, kind)) + case "custom": + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + return nil, nil, fmt.Errorf("tools[%d].name required", index) + } + parameters := customParameters() + spec := Spec{ + Name: customWireName("", name), + OriginalName: name, + Description: rawString(object["description"]), + Parameters: parameters, + Custom: true, + Source: protocol, + } + if format := strings.TrimSpace(string(object["format"])); format != "" && format != "null" { + spec.Description = strings.TrimSpace(spec.Description + "\n\nCustom tool input format:\n" + format) + } + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + case "function", "": + spec, err := parseFunctionSpec(protocol, object) + if err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + default: + diagnostics = append(diagnostics, fmt.Sprintf("tool tools[%d] type %q is not supported", index, kind)) + } + } + return specs, diagnostics, nil +} + +func parseNamespace(protocol Protocol, namespace string, raw json.RawMessage) ([]Spec, []string, error) { + if emptyJSON(raw) { + return nil, nil, nil + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return nil, nil, fmt.Errorf("namespace tools must be an array") + } + specs := make([]Spec, 0, len(items)) + diagnostics := make([]string, 0) + for index, item := range items { + var object map[string]json.RawMessage + if err := json.Unmarshal(item, &object); err != nil { + return nil, nil, fmt.Errorf("namespace tools[%d] must be an object", index) + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + if kind != "" && kind != "function" && kind != "custom" { + diagnostics = append(diagnostics, fmt.Sprintf("namespace tool %q type %q is not supported", namespace, kind)) + continue + } + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + return nil, nil, fmt.Errorf("namespace tools[%d].name required", index) + } + spec := Spec{ + Name: qualifyName(namespace, name), + OriginalName: name, + Namespace: namespace, + Description: rawString(object["description"]), + Parameters: json.RawMessage(defaultParameters), + Source: protocol, + } + if kind == "custom" { + spec.Name = qualifyName(namespace, customWireName("", name)) + spec.Custom = true + spec.Parameters = customParameters() + } else { + parameters := rawJSON(object["parameters"]) + if len(parameters) == 0 { + parameters = rawJSON(object["input_schema"]) + } + if len(parameters) > 0 { + spec.Parameters = parameters + } + var strict bool + if json.Unmarshal(object["strict"], &strict) == nil { + spec.Strict = strict + } + } + if err := validateSpecSchema(spec); err != nil { + return nil, nil, fmt.Errorf("namespace tool %q: %w", spec.Name, err) + } + specs = append(specs, spec) + } + return specs, diagnostics, nil +} + +func parseFunctionSpec(protocol Protocol, object map[string]json.RawMessage) (Spec, error) { + var function map[string]json.RawMessage + if raw := rawJSON(object["function"]); len(raw) > 0 { + _ = json.Unmarshal(raw, &function) + } + name := firstNonEmpty(rawString(function["name"]), rawString(object["name"])) + description := firstNonEmpty(rawString(function["description"]), rawString(object["description"])) + parameters := firstNonEmptyRaw(rawJSON(function["parameters"]), rawJSON(object["parameters"]), rawJSON(object["input_schema"])) + if len(parameters) == 0 { + parameters = json.RawMessage(defaultParameters) + } + var strict bool + if json.Unmarshal(function["strict"], &strict) != nil { + _ = json.Unmarshal(object["strict"], &strict) + } + spec := Spec{ + Name: strings.TrimSpace(name), + OriginalName: strings.TrimSpace(name), + Description: description, + Parameters: parameters, + Strict: strict, + Source: protocol, + } + if namespace := strings.TrimSpace(rawString(object["namespace"])); namespace != "" { + spec.Namespace = namespace + spec.Name = qualifyName(namespace, spec.Name) + } + if err := validateSpecSchema(spec); err != nil { + return Spec{}, err + } + return spec, nil +} + +func validateSpecSchema(spec Spec) error { + if strings.TrimSpace(spec.Name) == "" { + return fmt.Errorf("tool name required") + } + if len(spec.Parameters) == 0 || string(spec.Parameters) == "null" { + spec.Parameters = json.RawMessage(defaultParameters) + } + return ValidateSchema(spec.Parameters) +} + +func parseChoice(specs []Spec, raw json.RawMessage) (Choice, string, error) { + if emptyJSON(raw) { + return Choice{Mode: ChoiceUnspecified}, "", nil + } + text, isString := rawStringOK(raw) + if isString { + switch strings.ToLower(strings.TrimSpace(text)) { + case "none": + return Choice{Mode: ChoiceNone}, "", nil + case "auto": + if len(specs) == 0 { + return Choice{Mode: ChoiceUnspecified}, "tool_choice auto dropped: no executable tools were declared", nil + } + return Choice{Mode: ChoiceAuto}, "", nil + case "required", "any": + if len(specs) == 0 { + return Choice{}, "", fmt.Errorf("tool_choice requires executable tools") + } + return Choice{Mode: ChoiceRequired}, "", nil + default: + name := strings.TrimSpace(text) + if name == "" { + return Choice{}, "", fmt.Errorf("tool_choice name required") + } + if _, ok := findSpec(specs, name); !ok { + return Choice{}, "", fmt.Errorf("tool_choice references undeclared tool %q", name) + } + return Choice{Mode: ChoiceNamed, Name: name}, "", nil + } + } + var object map[string]json.RawMessage + if err := json.Unmarshal(raw, &object); err != nil { + return Choice{}, "", fmt.Errorf("tool_choice must be a string or an object") + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + switch kind { + case "none": + return Choice{Mode: ChoiceNone}, "", nil + case "auto": + if len(specs) == 0 { + return Choice{Mode: ChoiceUnspecified}, "tool_choice auto dropped: no executable tools were declared", nil + } + return Choice{Mode: ChoiceAuto}, "", nil + case "required", "any": + if len(specs) == 0 { + return Choice{}, "", fmt.Errorf("tool_choice requires executable tools") + } + return Choice{Mode: ChoiceRequired}, "", nil + case "function", "custom", "tool": + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + var function map[string]json.RawMessage + if json.Unmarshal(rawJSON(object["function"]), &function) == nil { + name = strings.TrimSpace(rawString(function["name"])) + } + } + if kind == "custom" { + name = customWireName(rawString(object["namespace"]), name) + } + if namespace := strings.TrimSpace(rawString(object["namespace"])); namespace != "" { + name = qualifyName(namespace, name) + } + if name == "" { + return Choice{}, "", fmt.Errorf("tool_choice.name required") + } + if _, ok := findSpec(specs, name); !ok { + return Choice{}, "", fmt.Errorf("tool_choice references undeclared tool %q", name) + } + return Choice{Mode: ChoiceNamed, Name: name}, "", nil + default: + return Choice{}, "", fmt.Errorf("tool_choice type %q is not supported", kind) + } +} + +func findSpec(specs []Spec, name string) (Spec, bool) { + for _, spec := range specs { + if spec.Name == name { + return spec, true + } + } + return Spec{}, false +} + +func customWireName(namespace, name string) string { + name = strings.TrimSpace(name) + if name == "" { + return "" + } + namespace = strings.TrimSpace(namespace) + if namespace == "" { + return "__codex_custom__" + name + } + return strings.TrimRight(namespace, "_") + "__codex_custom__" + name +} + +func qualifyName(namespace, name string) string { + name = strings.TrimSpace(name) + namespace = strings.TrimSpace(namespace) + if namespace == "" { + return name + } + return namespace + "__" + name +} + +func customParameters() json.RawMessage { + return json.RawMessage(`{"type":"object","properties":{"input":{"type":"string","description":"Raw freeform input for the custom tool."}},"required":["input"],"additionalProperties":false}`) +} + +func emptyJSON(raw json.RawMessage) bool { + text := strings.TrimSpace(string(raw)) + return text == "" || text == "null" || text == "[]" +} + +func rawJSON(raw json.RawMessage) json.RawMessage { + if len(raw) == 0 || string(raw) == "null" { + return nil + } + return raw +} + +func firstNonEmptyRaw(values ...json.RawMessage) json.RawMessage { + for _, value := range values { + if len(value) > 0 && string(value) != "null" { + return value + } + } + return nil +} + +func rawString(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var value string + if json.Unmarshal(raw, &value) == nil { + return value + } + return "" +} + +func rawStringOK(raw json.RawMessage) (string, bool) { + var value string + if json.Unmarshal(raw, &value) == nil { + return value, true + } + return "", false +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/internal/toolcall/schema.go b/internal/toolcall/schema.go new file mode 100644 index 000000000..a8c787b9b --- /dev/null +++ b/internal/toolcall/schema.go @@ -0,0 +1,482 @@ +package toolcall + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "strings" +) + +// ValidateSchema performs the structural checks a routing/adapter contract +// needs before a tool is advertised. It intentionally accepts unknown JSON +// Schema keywords, but rejects malformed type/properties/required shapes. +func ValidateSchema(raw json.RawMessage) error { + text := strings.TrimSpace(string(raw)) + if text == "" || text == "null" { + return nil + } + if text == "true" || text == "false" { + return nil + } + var schema map[string]json.RawMessage + if err := json.Unmarshal(raw, &schema); err != nil { + return fmt.Errorf("tool schema must be an object") + } + return validateSchemaNode(schema, 0) +} + +func validateSchemaNode(schema map[string]json.RawMessage, depth int) error { + if depth > 64 { + return fmt.Errorf("tool schema nesting exceeds 64 levels") + } + if refRaw, ok := schema["$ref"]; ok { + var ref string + if err := json.Unmarshal(refRaw, &ref); err != nil { + return fmt.Errorf("schema $ref must be a string") + } + ref = strings.TrimSpace(ref) + if ref == "" || ref[0] != '#' { + return fmt.Errorf("schema $ref %q is not a local JSON pointer", ref) + } + } + if typeRaw, ok := schema["type"]; ok { + if err := validateSchemaType(typeRaw); err != nil { + return err + } + } + if propertiesRaw, ok := schema["properties"]; ok { + var properties map[string]json.RawMessage + if err := json.Unmarshal(propertiesRaw, &properties); err != nil { + return fmt.Errorf("schema properties must be an object") + } + for name, property := range properties { + var child map[string]json.RawMessage + if err := json.Unmarshal(property, &child); err != nil { + return fmt.Errorf("schema property %q must be an object", name) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema property %q: %w", name, err) + } + } + } + if requiredRaw, ok := schema["required"]; ok { + var required []string + if err := json.Unmarshal(requiredRaw, &required); err != nil { + return fmt.Errorf("schema required must be an array of strings") + } + propertiesRaw := schema["properties"] + var properties map[string]json.RawMessage + if len(propertiesRaw) > 0 { + _ = json.Unmarshal(propertiesRaw, &properties) + } + for _, name := range required { + if strings.TrimSpace(name) == "" { + return fmt.Errorf("schema required contains an empty name") + } + if _, exists := properties[name]; !exists { + return fmt.Errorf("schema required names undeclared property %q", name) + } + } + } + if itemsRaw, ok := schema["items"]; ok { + var child map[string]json.RawMessage + if err := json.Unmarshal(itemsRaw, &child); err != nil { + return fmt.Errorf("schema items must be an object") + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema items: %w", err) + } + } + if additionalRaw, ok := schema["additionalProperties"]; ok { + text := strings.TrimSpace(string(additionalRaw)) + if text != "true" && text != "false" { + var child map[string]json.RawMessage + if err := json.Unmarshal(additionalRaw, &child); err != nil { + return fmt.Errorf("schema additionalProperties must be bool or object") + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema additionalProperties: %w", err) + } + } + } + for _, keyword := range []string{"anyOf", "oneOf", "allOf"} { + raw, ok := schema[keyword] + if !ok { + continue + } + var children []json.RawMessage + if err := json.Unmarshal(raw, &children); err != nil || len(children) == 0 { + return fmt.Errorf("schema %s must be a non-empty array", keyword) + } + for index, childRaw := range children { + var child map[string]json.RawMessage + if err := json.Unmarshal(childRaw, &child); err != nil { + return fmt.Errorf("schema %s[%d] must be an object", keyword, index) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema %s[%d]: %w", keyword, index, err) + } + } + } + for _, keyword := range []string{"$defs", "definitions"} { + raw, ok := schema[keyword] + if !ok { + continue + } + var definitions map[string]json.RawMessage + if err := json.Unmarshal(raw, &definitions); err != nil { + return fmt.Errorf("schema %s must be an object", keyword) + } + for name, childRaw := range definitions { + var child map[string]json.RawMessage + if err := json.Unmarshal(childRaw, &child); err != nil { + return fmt.Errorf("schema %s.%s must be an object", keyword, name) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema %s.%s: %w", keyword, name, err) + } + } + } + return nil +} + +func validateSchemaType(raw json.RawMessage) error { + var single string + if json.Unmarshal(raw, &single) == nil { + return validateTypeName(single) + } + var list []string + if json.Unmarshal(raw, &list) == nil { + if len(list) == 0 { + return fmt.Errorf("schema type array must not be empty") + } + for _, item := range list { + if err := validateTypeName(item); err != nil { + return err + } + } + return nil + } + return fmt.Errorf("schema type must be a string or string array") +} + +func validateTypeName(name string) error { + switch strings.ToLower(strings.TrimSpace(name)) { + case "object", "array", "string", "number", "integer", "boolean", "null": + return nil + default: + return fmt.Errorf("schema type %q is not supported", name) + } +} + +// ValidateArguments validates one call's argument bytes against its spec. It +// repairs only when the request policy explicitly allows safe repair. +func ValidateArguments(spec Spec, raw string, mode RepairMode) (json.RawMessage, bool, error) { + text := strings.TrimSpace(raw) + repaired := false + if text == "" { + text = "{}" + repaired = true + } + if !json.Valid([]byte(text)) { + switch mode { + case RepairSafe: + fixed, ok := RepairArguments(text) + if !ok { + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + } + text, repaired = fixed, true + case RepairPreserve: + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + default: + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + } + } + var value any + decoder := json.NewDecoder(bytes.NewReader([]byte(text))) + decoder.UseNumber() + if err := decoder.Decode(&value); err != nil { + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON: %w", spec.Name, err) + } + if len(spec.Parameters) > 0 && string(spec.Parameters) != "null" { + var schema any + if err := json.Unmarshal(spec.Parameters, &schema); err != nil { + return nil, false, fmt.Errorf("tool %q schema is invalid: %w", spec.Name, err) + } + if err := validateValue(schema, schema, value, 0); err != nil { + return nil, false, fmt.Errorf("tool %q arguments do not match schema: %w", spec.Name, err) + } + } + normalized, err := json.Marshal(value) + if err != nil { + return nil, false, fmt.Errorf("tool %q arguments cannot be encoded: %w", spec.Name, err) + } + return normalized, repaired, nil +} + +func validateValue(root, schema, value any, depth int) error { + if depth > 64 { + return fmt.Errorf("schema nesting exceeds 64 levels") + } + switch typed := schema.(type) { + case bool: + if !typed { + return fmt.Errorf("schema is false") + } + return nil + case map[string]any: + if ref, ok := typed["$ref"].(string); ok && strings.TrimSpace(ref) != "" { + resolved, err := resolveSchemaRef(root, ref) + if err != nil { + return err + } + if err := validateValue(root, resolved, value, depth+1); err != nil { + return fmt.Errorf("$ref %q: %w", ref, err) + } + } + if enum, ok := typed["enum"].([]any); ok && len(enum) > 0 { + matched := false + for _, candidate := range enum { + if jsonEqual(candidate, value) { + matched = true + break + } + } + if !matched { + return fmt.Errorf("value is not in enum") + } + } + if constant, ok := typed["const"]; ok && !jsonEqual(constant, value) { + return fmt.Errorf("value does not equal const") + } + if err := validateComposed(root, typed, value, depth); err != nil { + return err + } + if typeValue, ok := typed["type"]; ok { + if err := matchType(typeValue, value); err != nil { + return err + } + } + switch value.(type) { + case map[string]any: + return validateObject(root, typed, value.(map[string]any), depth) + case []any: + return validateArray(root, typed, value.([]any), depth) + } + return nil + default: + return fmt.Errorf("schema must be an object or bool") + } +} + +func resolveSchemaRef(root any, ref string) (any, error) { + ref = strings.TrimSpace(ref) + if ref == "#" { + return root, nil + } + if !strings.HasPrefix(ref, "#/") { + return nil, fmt.Errorf("$ref %q is not a local JSON pointer", ref) + } + current := root + for _, token := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { + token = strings.ReplaceAll(strings.ReplaceAll(token, "~1", "/"), "~0", "~") + switch node := current.(type) { + case map[string]any: + value, ok := node[token] + if !ok { + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + current = value + case []any: + index, err := strconv.Atoi(token) + if err != nil || index < 0 || index >= len(node) { + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + current = node[index] + default: + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + } + return current, nil +} + +func validateComposed(root any, schema map[string]any, value any, depth int) error { + if anyOf, ok := schema["anyOf"].([]any); ok && len(anyOf) > 0 { + matched := false + for _, candidate := range anyOf { + if validateValue(root, candidate, value, depth+1) == nil { + matched = true + break + } + } + if !matched { + return fmt.Errorf("value matches no anyOf branch") + } + } + if oneOf, ok := schema["oneOf"].([]any); ok && len(oneOf) > 0 { + matches := 0 + for _, candidate := range oneOf { + if validateValue(root, candidate, value, depth+1) == nil { + matches++ + } + } + if matches != 1 { + return fmt.Errorf("value matches %d oneOf branches", matches) + } + } + if allOf, ok := schema["allOf"].([]any); ok { + for _, candidate := range allOf { + if err := validateValue(root, candidate, value, depth+1); err != nil { + return fmt.Errorf("allOf: %w", err) + } + } + } + return nil +} + +func validateObject(root any, schema map[string]any, object map[string]any, depth int) error { + properties, _ := schema["properties"].(map[string]any) + if required, ok := schema["required"].([]any); ok { + for _, nameValue := range required { + name, _ := nameValue.(string) + if _, exists := object[name]; !exists { + return fmt.Errorf("required property %q is missing", name) + } + } + } + for name, value := range object { + property, declared := properties[name] + if declared { + if err := validateValue(root, property, value, depth+1); err != nil { + return fmt.Errorf("property %q: %w", name, err) + } + continue + } + if additional, ok := schema["additionalProperties"]; ok { + switch additional := additional.(type) { + case bool: + if !additional { + return fmt.Errorf("additional property %q is not allowed", name) + } + case map[string]any: + if err := validateValue(root, additional, value, depth+1); err != nil { + return fmt.Errorf("additional property %q: %w", name, err) + } + } + } + } + return nil +} + +func validateArray(root any, schema map[string]any, array []any, depth int) error { + items, ok := schema["items"] + if !ok { + return nil + } + for index, value := range array { + if err := validateValue(root, items, value, depth+1); err != nil { + return fmt.Errorf("item %d: %w", index, err) + } + } + return nil +} + +func matchType(typeValue any, value any) error { + switch typed := typeValue.(type) { + case string: + if typeMatches(typed, value) { + return nil + } + return fmt.Errorf("value is %s, want %s", valueType(value), typed) + case []any: + for _, candidate := range typed { + name, _ := candidate.(string) + if typeMatches(name, value) { + return nil + } + } + return fmt.Errorf("value is %s, want one of %v", valueType(value), typed) + default: + return fmt.Errorf("schema type is invalid") + } +} + +func typeMatches(name string, value any) bool { + switch strings.ToLower(strings.TrimSpace(name)) { + case "object": + _, ok := value.(map[string]any) + return ok + case "array": + _, ok := value.([]any) + return ok + case "string": + _, ok := value.(string) + return ok + case "boolean": + _, ok := value.(bool) + return ok + case "null": + return value == nil + case "number": + switch value.(type) { + case json.Number, float64, int, int64: + return true + } + return false + case "integer": + number, ok := value.(json.Number) + if !ok { + return false + } + text := number.String() + return !strings.ContainsAny(text, ".eE") + default: + return false + } +} + +func valueType(value any) string { + switch value.(type) { + case map[string]any: + return "object" + case []any: + return "array" + case string: + return "string" + case bool: + return "boolean" + case nil: + return "null" + case json.Number, float64, int, int64: + return "number" + default: + return fmt.Sprintf("%T", value) + } +} + +func jsonEqual(left, right any) bool { + leftJSON, leftErr := json.Marshal(left) + rightJSON, rightErr := json.Marshal(right) + if leftErr != nil || rightErr != nil { + return false + } + return bytes.Equal(leftJSON, rightJSON) +} + +// Numeric helpers are kept here so future schema keywords can use the same +// exact representation as the validated value. +func numberString(value any) string { + switch typed := value.(type) { + case json.Number: + return typed.String() + case float64: + return strconv.FormatFloat(typed, 'g', -1, 64) + case int: + return strconv.Itoa(typed) + case int64: + return strconv.FormatInt(typed, 10) + default: + return "" + } +} diff --git a/internal/toolcall/toolcall_test.go b/internal/toolcall/toolcall_test.go new file mode 100644 index 000000000..77fc5fa57 --- /dev/null +++ b/internal/toolcall/toolcall_test.go @@ -0,0 +1,261 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestParseRequestCanonicalChoiceAndSpecs(t *testing.T) { + tools := json.RawMessage(`[ + {"type":"function","function":{"name":"read_file","description":"read a file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}, + {"type":"function","function":{"name":"write_file","parameters":{"type":"object","properties":{"path":{"type":"string"},"body":{"type":"string"}},"required":["path"]}}} + ]`) + request, err := ParseRequest(ProtocolChat, tools, json.RawMessage(`{"type":"function","function":{"name":"read_file"}}`), boolPtr(false), RepairSafe) + if err != nil { + t.Fatal(err) + } + if len(request.Specs) != 2 || request.Specs[0].Name != "read_file" { + t.Fatalf("specs = %+v", request.Specs) + } + if request.Choice.Mode != ChoiceNamed || request.Choice.Name != "read_file" { + t.Fatalf("choice = %+v", request.Choice) + } + if request.Policy.Parallel == nil || *request.Policy.Parallel { + t.Fatalf("parallel = %+v", request.Policy.Parallel) + } + if request.Policy.Repair != RepairSafe { + t.Fatalf("repair = %q", request.Policy.Repair) + } +} + +func TestParseRequestRejectsUndeclaredNamedTool(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`) + _, err := ParseRequest(ProtocolChat, tools, json.RawMessage(`{"type":"function","function":{"name":"shell"}}`), nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "undeclared") { + t.Fatalf("err = %v", err) + } +} + +func TestParseRequestRejectsRequiredWithoutTools(t *testing.T) { + _, err := ParseRequest(ProtocolChat, nil, json.RawMessage(`"required"`), nil, RepairSafe) + if err == nil { + t.Fatal("expected required without tools to fail") + } +} + +func TestParseRequestRejectsDuplicateToolNames(t *testing.T) { + tools := json.RawMessage(`[ + {"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}, + {"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}} + ]`) + _, err := ParseRequest(ProtocolChat, tools, nil, nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "duplicate") { + t.Fatalf("err = %v", err) + } +} + +func TestParseRequestRejectsInvalidSchema(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":"not-an-object"}}}]`) + _, err := ParseRequest(ProtocolChat, tools, nil, nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "properties") { + t.Fatalf("err = %v", err) + } +} + +func TestReducerStableIDAcrossFragments(t *testing.T) { + request, parseErr := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`), nil, nil, RepairSafe) + if parseErr != nil { + t.Fatal(parseErr) + } + reducer := NewReducer(request) + chunks := []ChatDelta{ + {ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":`}}}, + {ToolCalls: []ChatToolDelta{{Arguments: `"a.go"}`}}}, + } + for index := range chunks { + if _, err := reducer.Absorb(chunks[index]); err != nil { + t.Fatal(err) + } + } + result, err := reducer.Finish("done") + if err != nil { + t.Fatal(err) + } + if result.Status != TurnToolCalls || len(result.Calls) != 1 { + t.Fatalf("result = %+v", result) + } + if string(result.Calls[0].Arguments) != `{"path":"a.go"}` { + t.Fatalf("args = %s", result.Calls[0].Arguments) + } +} + +func TestReducerSeparatesSameNameDifferentID(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + zero := 0 + chunks := []ChatDelta{ + {ToolCalls: []ChatToolDelta{{Index: &zero, ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}}, + {ToolCalls: []ChatToolDelta{{Index: &zero, ID: "call_2", Name: "read_file", Arguments: `{"path":"b"}`}}, FinishReason: "tool_calls"}, + } + for index := range chunks { + if _, err := reducer.Absorb(chunks[index]); err != nil { + t.Fatal(err) + } + } + result, err := reducer.Finish("done") + if err != nil { + t.Fatal(err) + } + if len(result.Calls) != 2 { + t.Fatalf("calls = %+v", result.Calls) + } + if string(result.Calls[0].Arguments) != `{"path":"a"}` || string(result.Calls[1].Arguments) != `{"path":"b"}` { + t.Fatalf("calls = %+v", result.Calls) + } +} + +func TestReducerRejectsMissingTerminalFrame(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{Content: "partial"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("eof") + if err == nil || result.Status != TurnTruncated { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsTruncatedArguments(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "run", Arguments: `{"cmd":"rm -rf /tmp/fo`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRequiredChoiceViolation(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), json.RawMessage(`"required"`), nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{Content: "I cannot call tools."}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerNoneChoiceViolation(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), json.RawMessage(`"none"`), nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{}`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsToolCallsFinishWithoutCalls(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{Content: "no call", FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsLengthFinishEvenWhenArgumentsParse(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}, FinishReason: "length"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err != nil || result.Status != TurnTruncated { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsUnsolicitedCallsWhenRequestDeclaresNoTools(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } + out := RenderChat(result) + if out.FinishReason != "error" || len(out.Calls) != 0 { + t.Fatalf("undeclared call rendered: %+v", out) + } +} + +func TestRenderMessagesAndResponsesRejectInvalidTurn(t *testing.T) { + invalid := TurnResult{Status: TurnInvalid, Error: "bad arguments", Calls: []Call{{Name: "read_file", InternalID: "call_1", Status: CallInvalid}}} + if _, err := RenderMessagesBlocks(invalid); err == nil { + t.Fatal("messages renderer accepted an invalid turn") + } + if _, err := RenderResponsesItems(invalid); err == nil { + t.Fatal("responses renderer accepted an invalid turn") + } +} + +func TestValidateArgumentsResolvesLocalSchemaRefs(t *testing.T) { + spec := Spec{Name: "read_file", Parameters: json.RawMessage(`{ + "type":"object", + "properties":{"file":{"$ref":"#/$defs/file"}}, + "required":["file"], + "$defs":{"file":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}} + }`)} + if _, _, err := ValidateArguments(spec, `{"file":{}}`, RepairSafe); err == nil || !strings.Contains(err.Error(), "path") { + t.Fatalf("missing $ref required property error = %v", err) + } + if _, _, err := ValidateArguments(spec, `{"file":{"path":"README.md"}}`, RepairSafe); err != nil { + t.Fatalf("valid $ref arguments rejected: %v", err) + } + rootRef := Spec{Name: "root_ref", Parameters: json.RawMessage(`{"$ref":"#/$defs/root","$defs":{"root":{"type":"object","properties":{"value":{"type":"integer"}},"required":["value"]}}}`)} + if _, _, err := ValidateArguments(rootRef, `{"value":"not-an-integer"}`, RepairSafe); err == nil { + t.Fatal("root $ref accepted a non-integer") + } + external := Spec{Name: "external", Parameters: json.RawMessage(`{"$ref":"https://example.com/schema.json"}`)} + if err := ValidateSchema(external.Parameters); err == nil { + t.Fatal("external $ref was accepted as a local schema") + } +} + +func TestRenderChatMarksToolCalls(t *testing.T) { + result := TurnResult{Status: TurnToolCalls, UpstreamTerminal: "done", FinishReason: "stop", Calls: []Call{{InternalID: "call_1", Name: "read_file", Arguments: json.RawMessage(`{"path":"a"}`), Status: CallCompleted}}} + out := RenderChat(result) + if out.FinishReason != "tool_calls" { + t.Fatalf("finish = %q", out.FinishReason) + } + if len(out.Calls) != 1 || out.Calls[0].Name != "read_file" { + t.Fatalf("calls = %+v", out.Calls) + } +} + +func TestRenderChatDropsToolCallsFromTruncatedTurn(t *testing.T) { + out := RenderChat(TurnResult{Status: TurnTruncated, FinishReason: "length", Text: "partial", Calls: []Call{{InternalID: "call_1", Name: "read_file", Arguments: json.RawMessage(`{"path":"a"}`), Status: CallCompleted}}}) + if out.FinishReason != "length" || out.Text != "partial" || len(out.Calls) != 0 { + t.Fatalf("truncated turn exposed calls: %+v", out) + } +} + +func TestRenderChatDoesNotTurnFailureIntoSavableOutput(t *testing.T) { + out := RenderChat(TurnResult{Status: TurnInvalid, Error: "bad", Text: "partial", Calls: []Call{{Name: "read_file", Status: CallInvalid}}}) + if out.FinishReason != "error" || out.Text != "" || len(out.Calls) != 0 { + t.Fatalf("failed turn rendered as success: %+v", out) + } +} + +func boolPtr(value bool) *bool { return &value } diff --git a/internal/translate/compat.go b/internal/translate/compat.go index 8ec626f74..2ce4cc8f9 100644 --- a/internal/translate/compat.go +++ b/internal/translate/compat.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "strings" + + "github.com/caigee-cmd/cli2api/internal/toolcall" ) // RestoreResponseToolNames only visits protocol containers, never user content @@ -249,9 +251,9 @@ func translateResponses(request ResponsesRequest) (ChatRequest, map[string]Respo if err != nil { return ChatRequest{}, nil, err } - // Codex Desktop compact / recovery turns can keep a tool_choice while - // tools normalize to empty (hosted shells dropped, etc). Drop the - // orphan choice instead of failing the whole turn. + // A hosted-only tool list may normalize to empty while `auto` remains. That + // degrades to unspecified; required/named must fail validation instead of + // being silently cleared. chat.ToolChoice = sanitizeToolChoice(chat.Tools, toolChoice) chat.ResponseFormat, err = translateResponsesTextFormat(request.Text) if err != nil { @@ -784,104 +786,38 @@ func ValidateChatRequest(request *ChatRequest) error { return fmt.Errorf("max_tokens and max_completion_tokens are mutually exclusive") } request.ToolChoice = sanitizeToolChoice(request.Tools, request.ToolChoice) - return validateToolChoice(request.Tools, request.ToolChoice) + _, err := toolcall.ParseRequest(toolcall.ProtocolChat, request.Tools, request.ToolChoice, request.ParallelToolCalls, toolcall.RepairSafe) + return err } -// sanitizeToolChoice drops orphan tool_choice values when tools are empty, and -// clears named tool choices that no longer exist after tool normalization. +// sanitizeToolChoice only degrades an orphan `auto` to unspecified. Every +// stronger choice is left in place for the canonical parser to reject: silently +// clearing `required` or a named tool would turn a failed tool request into a +// successful text turn. func sanitizeToolChoice(tools, choice json.RawMessage) json.RawMessage { if emptyJSON(choice) { return nil } if emptyJSON(tools) { - return nil + return dropOrphanAuto(choice) } var declared []map[string]json.RawMessage if json.Unmarshal(tools, &declared) != nil || len(declared) == 0 { - return nil - } - names := make(map[string]bool, len(declared)) - for _, tool := range declared { - name, _ := rawJSONString(tool["name"]) - if name == "" { - fn, _ := tool["function"] - var function map[string]json.RawMessage - if json.Unmarshal(fn, &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" { - names[strings.TrimSpace(name)] = true - } - } - if text, ok := rawJSONString(choice); ok { - switch strings.ToLower(strings.TrimSpace(text)) { - case "none", "auto", "required": - return choice - default: - if names[strings.TrimSpace(text)] { - return choice - } - return nil - } + return dropOrphanAuto(choice) } - var object map[string]json.RawMessage - if json.Unmarshal(choice, &object) != nil { - return choice - } - name := rawMapString(object, "name") - if name == "" { - var function map[string]json.RawMessage - if json.Unmarshal(object["function"], &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" && !names[strings.TrimSpace(name)] { + return choice +} + +func dropOrphanAuto(choice json.RawMessage) json.RawMessage { + if text, ok := rawJSONString(choice); ok && strings.EqualFold(strings.TrimSpace(text), "auto") { return nil } return choice } func validateToolChoice(tools, choice json.RawMessage) error { - if emptyJSON(choice) { - return nil - } - if emptyJSON(tools) { - return fmt.Errorf("tool_choice requires tools") - } - var declared []map[string]json.RawMessage - if err := json.Unmarshal(tools, &declared); err != nil || len(declared) == 0 { - return fmt.Errorf("tool_choice requires tools") - } - names := make(map[string]bool, len(declared)) - for _, tool := range declared { - name, _ := rawJSONString(tool["name"]) - if name == "" { - fn, _ := tool["function"] - var function map[string]json.RawMessage - if json.Unmarshal(fn, &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" { - names[strings.TrimSpace(name)] = true - } - } - var object map[string]json.RawMessage - if json.Unmarshal(choice, &object) != nil { - return nil - } - name := rawMapString(object, "name") - if name == "" { - var function map[string]json.RawMessage - if json.Unmarshal(object["function"], &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" && !names[strings.TrimSpace(name)] { - return fmt.Errorf("tool_choice references undeclared tool %q", name) - } - return nil + _, err := toolcall.ParseRequest(toolcall.ProtocolChat, tools, choice, nil, toolcall.RepairSafe) + return err } func mergeJSONArray(left, right json.RawMessage) json.RawMessage { diff --git a/internal/translate/compat_test.go b/internal/translate/compat_test.go index 6e826870c..50ef13747 100644 --- a/internal/translate/compat_test.go +++ b/internal/translate/compat_test.go @@ -6,21 +6,15 @@ import ( "testing" ) -func TestTranslateResponsesDropsOrphanToolChoiceWhenToolsEmpty(t *testing.T) { - chat, err := TranslateResponses(ResponsesRequest{ +func TestTranslateResponsesRejectsNamedChoiceWhenToolsEmpty(t *testing.T) { + _, err := TranslateResponses(ResponsesRequest{ Model: "devin/gpt-5-6-sol", Input: json.RawMessage(`[{"role":"user","content":[{"type":"input_text","text":"compact this conversation"}]}]`), Tools: json.RawMessage(`[{"type":"mcp","server_label":"codex_app"},{"type":"web_search"}]`), ToolChoice: json.RawMessage(`{"type":"function","name":"exec_command"}`), }) - if err != nil { - t.Fatal(err) - } - if len(chat.Tools) > 0 { - t.Fatalf("tools=%s want empty after hosted shells drop", chat.Tools) - } - if len(chat.ToolChoice) > 0 { - t.Fatalf("tool_choice=%s want dropped", chat.ToolChoice) + if err == nil || !strings.Contains(err.Error(), "tool_choice") { + t.Fatalf("named choice without tools error = %v", err) } } diff --git a/internal/translate/native_responses.go b/internal/translate/native_responses.go index d11a68c08..65e2ededc 100644 --- a/internal/translate/native_responses.go +++ b/internal/translate/native_responses.go @@ -143,6 +143,16 @@ func (r *NativeResponsesRequest) Compat() (ResponsesTranslation, error) { return TranslateResponsesRequest(source) } +// ToolingFields returns the request's tool declarations, tool_choice and +// parallel_tool_calls as the client sent them. The native adapter owns their +// dialect; routing parses them through the same canonical model as Chat. +func (r *NativeResponsesRequest) ToolingFields() (tools, choice, parallel json.RawMessage) { + if r == nil { + return nil, nil, nil + } + return r.fields["tools"], r.fields["tool_choice"], r.fields["parallel_tool_calls"] +} + // RequestedReasoningEffort is the client's reasoning.effort, empty when absent. func (r *NativeResponsesRequest) RequestedReasoningEffort() string { var reasoning struct { diff --git a/internal/translate/responses_collect_test.go b/internal/translate/responses_collect_test.go index 5ec343c49..da961495a 100644 --- a/internal/translate/responses_collect_test.go +++ b/internal/translate/responses_collect_test.go @@ -46,3 +46,18 @@ func TestCollectResponsesRejectsTerminalWithoutResponse(t *testing.T) { t.Fatalf("missing response error = %v", err) } } + +func TestCollectResponsesKeepsEventFinishReason(t *testing.T) { + // The SSE event type is authoritative even when the embedded response + // object claims a different status. The collector must expose the event's + // finish so the non-stream validator can reject the disagreement. + sse := "event: response.incomplete\n" + + "data: {\"type\":\"response.incomplete\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n" + got, err := CollectResponses(strings.NewReader(sse)) + if err != nil { + t.Fatal(err) + } + if got.FinishReason != "length" { + t.Fatalf("event finish reason lost: %q", got.FinishReason) + } +} diff --git a/internal/translate/session_seed.go b/internal/translate/session_seed.go index e22599fb9..c849d38bb 100644 --- a/internal/translate/session_seed.go +++ b/internal/translate/session_seed.go @@ -261,7 +261,6 @@ func compactSessionJSON(raw json.RawMessage) string { return compact.String() } - // PrefixSessionSeed is the cache-affine part of ContentSessionSeed: model, // tools and the leading system/developer prefix only. It deliberately excludes // the first user message so workbuddy2api-hub-style sharding does not scatter