diff --git a/changelog/unreleased/provider-tool-profiles.md b/changelog/unreleased/provider-tool-profiles.md new file mode 100644 index 000000000..71c00c8da --- /dev/null +++ b/changelog/unreleased/provider-tool-profiles.md @@ -0,0 +1,9 @@ +### English + +- Give every adapter the canonical tool profile from `internal/toolcall`, so declared tools, tool choice and parallel calls reach the upstream payload unchanged. +- Replay a transient failure inside the adapter and report the internal retry count, keep an upstream `Retry-After` instead of a generic backoff, and stop a stream that ends without a terminal frame. + +### 中文 + +- 各适配器统一使用 `internal/toolcall` 的规范工具档案,声明的工具、工具选择与并行调用原样进入上游请求体。 +- 瞬时失败由适配器就地重放并回报内部重试次数,保留上游 `Retry-After` 而非通用退避,并对没有终态帧的流立即结束。 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/providers/client_ua.go b/internal/providers/client_ua.go index 419e9a1ad..f0672e346 100644 --- a/internal/providers/client_ua.go +++ b/internal/providers/client_ua.go @@ -34,16 +34,12 @@ func ClientUserAgentFromContext(ctx context.Context) string { // WithConversation records the gateway session key so a provider can keep one // upstream conversation id across the turns of a chat. Routing still owns the -// key; this only carries it. +// key; this only carries it. An empty key clears any inherited conversation. func WithConversation(ctx context.Context, key string) context.Context { if ctx == nil { ctx = context.Background() } - key = strings.TrimSpace(key) - if key == "" { - return ctx - } - return context.WithValue(ctx, conversationKey{}, key) + return context.WithValue(ctx, conversationKey{}, strings.TrimSpace(key)) } // ConversationFromContext returns the session key set by WithConversation, or diff --git a/internal/providers/codex/sse.go b/internal/providers/codex/sse.go index c5549a33d..c07d6a091 100644 --- a/internal/providers/codex/sse.go +++ b/internal/providers/codex/sse.go @@ -261,6 +261,16 @@ func (c *streamConverter) handleEvent(event, payload string) { c.finishReason = "stop" if typ == "response.incomplete" { c.finishReason = "length" + } else { + for _, item := range resp.Response.Output { + var probe struct { + Type string `json:"type"` + } + if json.Unmarshal(item, &probe) == nil && isResponsesToolItem(probe.Type) { + c.finishReason = "tool_calls" + break + } + } } c.sawTerminal = true c.emitUsage() @@ -270,15 +280,36 @@ func (c *streamConverter) handleEvent(event, payload string) { var errObj struct { Message string `json:"message"` Code string `json:"code"` + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + Response struct { + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + } `json:"response"` } _ = json.Unmarshal([]byte(payload), &errObj) - c.emitDone() + message := firstNonEmpty(errObj.Message, errObj.Error.Message, errObj.Response.Error.Message, "upstream response failed") + code := firstNonEmpty(errObj.Code, errObj.Error.Code, errObj.Response.Error.Code, "upstream_error") + c.emitError(message, code) c.sawTerminal = true case "response.created": // no-op; gateway synthesizes its own response.created } } +func isResponsesToolItem(kind string) bool { + switch kind { + case "function_call", "custom_tool_call", "local_shell_call", "mcp_call": + return true + default: + return false + } +} + func (c *streamConverter) emitContent(text string) { if text == "" { return @@ -401,6 +432,18 @@ func (c *streamConverter) emitDone() { _, _ = c.writer.Write([]byte("data: [DONE]\n\n")) } +func (c *streamConverter) emitError(message, code string) { + payload, err := json.Marshal(map[string]any{"error": map[string]any{ + "message": message, + "code": code, + "type": "upstream_error", + }}) + if err != nil { + return + } + _, _ = c.writer.Write([]byte("data: " + string(payload) + "\n\n")) +} + func (c *streamConverter) writeChunk(obj map[string]any) { obj["object"] = "chat.completion.chunk" obj["model"] = c.model diff --git a/internal/providers/codex/sse_test.go b/internal/providers/codex/sse_test.go index cf10423a6..1f57ca0e5 100644 --- a/internal/providers/codex/sse_test.go +++ b/internal/providers/codex/sse_test.go @@ -47,6 +47,52 @@ data: {"type":"response.completed","response":{"status":"completed","usage":{"in } } +func TestRewriteStreamMapsToolOutputToToolCallsFinish(t *testing.T) { + sse := `event: response.output_item.added +data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}} + +event: response.function_call_arguments.done +data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":"{\"city\":\"Tokyo\"}"} + +event: response.completed +data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":1,"output_tokens":1},"output":[{"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}]}} + +` + stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol") + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(stream.Reader) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), `"finish_reason":"tool_calls"`) { + t.Fatalf("tool output finished without tool_calls: %s", body) + } +} + +func TestRewriteStreamFailureIsAnErrorNotStop(t *testing.T) { + sse := `event: response.failed +data: {"type":"response.failed","response":{"status":"failed","error":{"message":"quota exhausted","code":"insufficient_quota"}}} + +` + stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol") + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(stream.Reader) + if err != nil { + t.Fatal(err) + } + out := string(body) + if !strings.Contains(out, `"error"`) || !strings.Contains(out, "quota exhausted") { + t.Fatalf("failure was not relayed as an error: %s", out) + } + if strings.Contains(out, `"finish_reason":"stop"`) || strings.Contains(out, "[DONE]") { + t.Fatalf("failure was turned into a successful terminal: %s", out) + } +} + // An item that is not a tool call must not consume a tool-call index or emit a // chunk, otherwise a reasoning item would shift every later call. func TestRewriteStreamIgnoresNonToolOutputItems(t *testing.T) { diff --git a/internal/providers/devin/chat.go b/internal/providers/devin/chat.go index 86b6b09c1..e71c081ca 100644 --- a/internal/providers/devin/chat.go +++ b/internal/providers/devin/chat.go @@ -223,6 +223,7 @@ func (c *Client) buildChatHTTPRequestFromPayload(ctx context.Context, credential payload.System, payload.Prompts, payload.Tools, + payload.ToolChoice, payload.Temperature, payload.MaxTokens, "", diff --git a/internal/providers/devin/payload.go b/internal/providers/devin/payload.go index 284000337..88408c73f 100644 --- a/internal/providers/devin/payload.go +++ b/internal/providers/devin/payload.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/caigee-cmd/cli2api/internal/providers" + chatpb "github.com/caigee-cmd/cli2api/internal/providers/devin/devinpb/chat_pb" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -24,6 +25,7 @@ type ChatPayload struct { System string Prompts []Prompt Tools []Tool + ToolChoice *chatpb.ChatToolChoice Temperature *float64 MaxTokens int ModelUID string @@ -83,6 +85,7 @@ func BuildChatPayload(req translate.ChatRequest, catalogLevels map[string][]stri System: system, Prompts: prompts, Tools: tools, + ToolChoice: parseToolChoice(req.ToolChoice, aliases), Temperature: temp, MaxTokens: maxTokens, ModelUID: modelUID, @@ -269,6 +272,47 @@ func parseTools(raw json.RawMessage, aliases *toolAliasMaps) []Tool { return out } +func parseToolChoice(raw json.RawMessage, aliases *toolAliasMaps) *chatpb.ChatToolChoice { + if len(raw) == 0 || string(raw) == "null" { + return nil + } + var text string + if json.Unmarshal(raw, &text) == nil { + switch strings.ToLower(strings.TrimSpace(text)) { + case "auto", "none", "required": + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: strings.ToLower(strings.TrimSpace(text))}} + default: + name := strings.TrimSpace(text) + if name == "" { + return nil + } + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}} + } + } + var object map[string]any + if json.Unmarshal(raw, &object) != nil { + return nil + } + kind, _ := object["type"].(string) + kind = strings.ToLower(strings.TrimSpace(kind)) + switch kind { + case "none", "auto", "required": + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: kind}} + case "function", "custom", "tool": + name, _ := object["name"].(string) + if fn, ok := object["function"].(map[string]any); ok { + name, _ = fn["name"].(string) + } + name = strings.TrimSpace(name) + if name == "" { + return nil + } + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}} + default: + return nil + } +} + func expandNamespaceTools(raw json.RawMessage, namespace string) []Tool { var wrapper struct { Tools []json.RawMessage `json:"tools"` diff --git a/internal/providers/devin/wire.go b/internal/providers/devin/wire.go index ab6110d52..5b386a655 100644 --- a/internal/providers/devin/wire.go +++ b/internal/providers/devin/wire.go @@ -224,6 +224,7 @@ func BuildGetChatMessageRequest( systemPrompt string, prompts []Prompt, tools []Tool, + toolChoice *chatpb.ChatToolChoice, temperature *float64, maxTokens int, sessionID string, @@ -252,6 +253,9 @@ func BuildGetChatMessageRequest( PlannerMode: commonpb.ConversationalPlannerMode_CONVERSATIONAL_PLANNER_MODE_DEFAULT, ChatModelUid: chatModelUID, } + if toolChoice != nil { + req.ToolChoice = toolChoice + } if strings.TrimSpace(systemPrompt) != "" { req.Prompt = systemPrompt } diff --git a/internal/providers/devin/wire_test.go b/internal/providers/devin/wire_test.go index d7e0c28e3..f873bec5b 100644 --- a/internal/providers/devin/wire_test.go +++ b/internal/providers/devin/wire_test.go @@ -47,6 +47,7 @@ func TestChatRequestWireContract(t *testing.T) { Images: []Image{{Base64Data: "aGVsbG8=", MimeType: "image/png"}}, Thinking: "reason", Signature: []byte("signature"), SignatureType: "type"}}, []Tool{{Name: "lookup", Description: "description", Parameters: []byte(`{"type":"object"}`)}}, + nil, &temperature, 1234, t.Name(), "cascade") if err != nil { t.Fatal(err) diff --git a/internal/providers/interfaces.go b/internal/providers/interfaces.go index 4feb11732..02163bb06 100644 --- a/internal/providers/interfaces.go +++ b/internal/providers/interfaces.go @@ -123,6 +123,8 @@ type ChatOutcome struct { // ReasoningLevel is the clamped reasoning level actually sent upstream, // empty when the provider did not include one in the payload. ReasoningLevel string + // InternalRetries counts same-account replays the adapter performed. + InternalRetries int } // ResolvedChat carries provider-side metadata for a stream request that the @@ -131,6 +133,9 @@ type ResolvedChat struct { // ReasoningLevel is the clamped reasoning level actually sent upstream, // empty when the provider did not include one in the payload. ReasoningLevel string + // InternalRetries counts same-account replays the adapter performed + // before opening this stream. + InternalRetries int } // ProviderChat executes chat for one account. Stream implementations return @@ -341,6 +346,10 @@ type Error struct { Code string Type string RetryAfter time.Duration + // InternalRetries counts upstream requests the adapter already replayed + // before returning this failure. The executor adds it to the route attempt + // so one route attempt does not hide several wire requests. + InternalRetries int } func (e *Error) Error() string { diff --git a/internal/providers/kimi/chat.go b/internal/providers/kimi/chat.go index 48e37a1e1..61a0211d8 100644 --- a/internal/providers/kimi/chat.go +++ b/internal/providers/kimi/chat.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -201,16 +202,25 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err if err != nil { return providers.ChatOutcome{}, err } + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -239,6 +249,13 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("kimi stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("kimi stream: %s", message) + } if chunk.Usage != nil { if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage = chatUsage{ @@ -262,6 +279,7 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err } if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -280,6 +298,9 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("kimi stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/kimi/flows_test.go b/internal/providers/kimi/flows_test.go index 0b3a41f91..ca7969234 100644 --- a/internal/providers/kimi/flows_test.go +++ b/internal/providers/kimi/flows_test.go @@ -1032,3 +1032,15 @@ func TestDeviceLoginPendingDoesNotWidenInterval(t *testing.T) { t.Fatalf("pending widened the interval to %v", got) } } + +func TestCollectChatStreamRejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatStream(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "kimi-k2"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} diff --git a/internal/providers/meta/client.go b/internal/providers/meta/client.go index c79e4d4e5..c6edd70c6 100644 --- a/internal/providers/meta/client.go +++ b/internal/providers/meta/client.go @@ -38,7 +38,7 @@ type Client struct { transports proxyutil.TransportCache - nowFn func() time.Time + nowFn func() time.Time authHost string // test override for AuthHost mintURL string // test override for MintURL @@ -163,7 +163,6 @@ func (c *Client) Probe(ctx context.Context, accountID string) (providers.Account return providers.AccountHealth{Ready: true, Hot: true, UID: uid}, nil } - // Quota returns nil — Meta Muse does not expose a usage/quota endpoint // in CPA 8.0.40; the console shows "unknown" rather than a fake zero. func (c *Client) Quota(ctx context.Context, accountID string) (*providers.QuotaInfo, error) { diff --git a/internal/providers/meta/constants.go b/internal/providers/meta/constants.go index 677ce49aa..2cd05f166 100644 --- a/internal/providers/meta/constants.go +++ b/internal/providers/meta/constants.go @@ -15,10 +15,10 @@ const ( // Wire constants aligned with CPA v8.0.40 (internal/auth/meta + meta_executor). const ( - ClientID = "1031625952748946" - AuthHost = "https://auth.meta.com" - ChatBase = "https://api.meta.ai/v1" - MintURL = "https://api.meta.ai/muse-code/key" + ClientID = "1031625952748946" + AuthHost = "https://auth.meta.com" + ChatBase = "https://api.meta.ai/v1" + MintURL = "https://api.meta.ai/muse-code/key" DeviceAuthorizationPath = "/oidc/device/authorization/" TokenPath = "/oidc/device/token/" @@ -27,9 +27,9 @@ const ( // AuthUserAgent is sent on device/token/mint (CPA muse-code/1.0.2). AuthUserAgent = "muse-code/1.0.2" // ChatUserAgent and ClientIDHeader match CPA meta_executor fingerprints. - ChatUserAgent = "muse-build/1.3.0 (interactive; macos-aarch64; build ac7280f2aca67769d1455a8847bb502b617d50f6)" - ClientIDHeader = "tbh:tui" - ResponsesPath = "/responses" + ChatUserAgent = "muse-build/1.3.0 (interactive; macos-aarch64; build ac7280f2aca67769d1455a8847bb502b617d50f6)" + ClientIDHeader = "tbh:tui" + ResponsesPath = "/responses" ) const ( diff --git a/internal/providers/meta/meta_test.go b/internal/providers/meta/meta_test.go index bd4723e0d..876981670 100644 --- a/internal/providers/meta/meta_test.go +++ b/internal/providers/meta/meta_test.go @@ -346,7 +346,6 @@ func TestMuseAliasResolves(t *testing.T) { } } - func TestAccountProxyOverridesGlobal(t *testing.T) { store := newFakeStore() store.addAccount("a1") diff --git a/internal/providers/meta/oauth.go b/internal/providers/meta/oauth.go index 8c7dcda32..0f83199bc 100644 --- a/internal/providers/meta/oauth.go +++ b/internal/providers/meta/oauth.go @@ -223,15 +223,15 @@ func truncate(body []byte) string { func applyLoginBundle(token tokenPayload, minted mintedKeyResponse, now time.Time) Credential { dca := strings.TrimSpace(token.AccessToken) cred := Credential{ - Format: CredentialFormatOAuth, - DCAToken: dca, - AccessToken: dca, - TokenType: firstNonEmpty(token.TokenType, "Bearer"), - ExpiresIn: token.ExpiresIn, - APIKey: strings.TrimSpace(minted.APIKey), - BaseURL: normalizeBase(minted.BaseURL), - Email: strings.TrimSpace(minted.UserEmail), - Name: strings.TrimSpace(minted.UserFullName), + Format: CredentialFormatOAuth, + DCAToken: dca, + AccessToken: dca, + TokenType: firstNonEmpty(token.TokenType, "Bearer"), + ExpiresIn: token.ExpiresIn, + APIKey: strings.TrimSpace(minted.APIKey), + BaseURL: normalizeBase(minted.BaseURL), + Email: strings.TrimSpace(minted.UserEmail), + Name: strings.TrimSpace(minted.UserFullName), SubsTierName: strings.TrimSpace(minted.SubsTierName), SubsTierID: strings.TrimSpace(minted.SubsTierID), IsSubsActive: minted.IsSubsActive, diff --git a/internal/providers/meta/sse.go b/internal/providers/meta/sse.go index 3946a37ec..4a28ba8be 100644 --- a/internal/providers/meta/sse.go +++ b/internal/providers/meta/sse.go @@ -261,6 +261,16 @@ func (c *streamConverter) handleEvent(event, payload string) { c.finishReason = "stop" if typ == "response.incomplete" { c.finishReason = "length" + } else { + for _, item := range resp.Response.Output { + var probe struct { + Type string `json:"type"` + } + if json.Unmarshal(item, &probe) == nil && isResponsesToolItem(probe.Type) { + c.finishReason = "tool_calls" + break + } + } } c.sawTerminal = true c.emitUsage() @@ -270,15 +280,36 @@ func (c *streamConverter) handleEvent(event, payload string) { var errObj struct { Message string `json:"message"` Code string `json:"code"` + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + Response struct { + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + } `json:"response"` } _ = json.Unmarshal([]byte(payload), &errObj) - c.emitDone() + message := firstNonEmpty(errObj.Message, errObj.Error.Message, errObj.Response.Error.Message, "upstream response failed") + code := firstNonEmpty(errObj.Code, errObj.Error.Code, errObj.Response.Error.Code, "upstream_error") + c.emitError(message, code) c.sawTerminal = true case "response.created": // no-op; gateway synthesizes its own response.created } } +func isResponsesToolItem(kind string) bool { + switch kind { + case "function_call", "custom_tool_call", "local_shell_call", "mcp_call": + return true + default: + return false + } +} + func (c *streamConverter) emitContent(text string) { if text == "" { return @@ -401,6 +432,18 @@ func (c *streamConverter) emitDone() { _, _ = c.writer.Write([]byte("data: [DONE]\n\n")) } +func (c *streamConverter) emitError(message, code string) { + payload, err := json.Marshal(map[string]any{"error": map[string]any{ + "message": message, + "code": code, + "type": "upstream_error", + }}) + if err != nil { + return + } + _, _ = c.writer.Write([]byte("data: " + string(payload) + "\n\n")) +} + func (c *streamConverter) writeChunk(obj map[string]any) { obj["object"] = "chat.completion.chunk" obj["model"] = c.model diff --git a/internal/providers/minimaxcode/minimaxcode_test.go b/internal/providers/minimaxcode/minimaxcode_test.go index 1a31cb4e8..4f645eb5e 100644 --- a/internal/providers/minimaxcode/minimaxcode_test.go +++ b/internal/providers/minimaxcode/minimaxcode_test.go @@ -326,6 +326,26 @@ func TestChatStreamToolCalls(t *testing.T) { } } +func TestAnthropicDecoderBindsArgumentsToBlockIndex(t *testing.T) { + decoder := newAnthropicDecoder() + first, _, err := decoder.frame("content_block_start", `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_1","name":"first"}}`) + if err != nil || len(first) != 1 || first[0].ToolCalls[0].Index != 0 { + t.Fatalf("first start = %+v err=%v", first, err) + } + second, _, err := decoder.frame("content_block_start", `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_2","name":"second"}}`) + if err != nil || len(second) != 1 || second[0].ToolCalls[0].Index != 1 { + t.Fatalf("second start = %+v err=%v", second, err) + } + delta, _, err := decoder.frame("content_block_delta", `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"a\":1}"}}`) + if err != nil || len(delta) != 1 || delta[0].ToolCalls[0].Index != 0 { + t.Fatalf("first delta bound to %+v err=%v", delta, err) + } + delta, _, err = decoder.frame("content_block_delta", `{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"b\":2}"}}`) + if err != nil || len(delta) != 1 || delta[0].ToolCalls[0].Index != 1 { + t.Fatalf("second delta bound to %+v err=%v", delta, err) + } +} + func TestBuildChatBodyCarriesSamplingAndToolChoice(t *testing.T) { req := translate.ChatRequest{ Model: "MiniMax-M3", diff --git a/internal/providers/minimaxcode/sse.go b/internal/providers/minimaxcode/sse.go index b2ae9903a..babf33c65 100644 --- a/internal/providers/minimaxcode/sse.go +++ b/internal/providers/minimaxcode/sse.go @@ -25,10 +25,11 @@ type toolCallDelta struct { } type anthropicDecoder struct { - sentRole bool - toolIndex int - finish string - usage streamUsage + sentRole bool + toolIndex int + toolIndexByBlock map[int]int + finish string + usage streamUsage } type streamUsage struct { @@ -143,6 +144,10 @@ func (d *anthropicDecoder) frame(eventType string, payload string) ([]openAIDelt block, _ := event["content_block"].(map[string]any) if jsonStr(block, "type") == "tool_use" { d.toolIndex++ + if d.toolIndexByBlock == nil { + d.toolIndexByBlock = map[int]int{} + } + d.toolIndexByBlock[jsonIntValue(event["index"])] = d.toolIndex call := toolCallDelta{Index: d.toolIndex, ID: jsonStr(block, "id"), Name: jsonStr(block, "name"), HasID: true, HasName: true} if call.ID == "" { call.ID = newToolID() @@ -162,7 +167,11 @@ func (d *anthropicDecoder) frame(eventType string, payload string) ([]openAIDelt } case "input_json_delta": if partial := jsonStr(delta, "partial_json"); partial != "" { - call := toolCallDelta{Index: d.toolIndex, Arguments: partial} + toolIndex := d.toolIndex + if mapped, ok := d.toolIndexByBlock[jsonIntValue(event["index"])]; ok { + toolIndex = mapped + } + call := toolCallDelta{Index: toolIndex, Arguments: partial} return []openAIDelta{{ToolCalls: []toolCallDelta{call}}}, false, nil } } diff --git a/internal/providers/opencode/opencode_test.go b/internal/providers/opencode/opencode_test.go index feb783fc0..0f2a20cfb 100644 --- a/internal/providers/opencode/opencode_test.go +++ b/internal/providers/opencode/opencode_test.go @@ -646,3 +646,60 @@ func TestQuotaFallback(t *testing.T) { t.Fatalf("zen info=%+v hits=%d/%d err=%v", info, primaryHits, fallbackHits, err) } } + +func TestBuildPayloadKeepsToolsAndMapsChoiceAcrossProtocols(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"lookup","parameters":{"type":"object"}}}]`) + cases := []struct { + protocol string + choice string + want any + }{ + {protoAnthropic, `"none"`, map[string]any{"type": "none"}}, + {protoAnthropic, `"required"`, map[string]any{"type": "any"}}, + {protoResponses, `"none"`, "none"}, + {protoResponses, `"required"`, "required"}, + {protoChat, `"none"`, "none"}, + } + for _, tc := range cases { + raw, err := buildPayload(tc.protocol, translate.ChatRequest{ + Model: "gpt-5", + Tools: tools, + ToolChoice: json.RawMessage(tc.choice), + Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "gpt-5") + if err != nil { + t.Fatalf("%s/%s: %v", tc.protocol, tc.choice, err) + } + var body map[string]any + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatal(err) + } + if _, ok := body["tools"]; !ok { + t.Fatalf("%s/%s dropped tools: %s", tc.protocol, tc.choice, raw) + } + got, _ := body["tool_choice"].(map[string]any) + if wantMap, ok := tc.want.(map[string]any); ok { + for key, value := range wantMap { + if got[key] != value { + t.Fatalf("%s/%s tool_choice=%v want %v", tc.protocol, tc.choice, body["tool_choice"], tc.want) + } + } + continue + } + if got, _ := body["tool_choice"].(string); got != tc.want { + t.Fatalf("%s/%s tool_choice=%v want %v", tc.protocol, tc.choice, body["tool_choice"], tc.want) + } + } +} + +func TestCollectChatSSERejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatSSE(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "gpt-5"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "gpt-5"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "gpt-5"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} diff --git a/internal/providers/opencode/payload.go b/internal/providers/opencode/payload.go index f2febba11..0aa5f52ca 100644 --- a/internal/providers/opencode/payload.go +++ b/internal/providers/opencode/payload.go @@ -393,7 +393,7 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b if json.Unmarshal(raw, &text) == nil { switch strings.ToLower(strings.TrimSpace(text)) { case "none": - return nil, false + choice["type"] = "none" case "required", "any": choice["type"] = "any" case "auto": @@ -405,10 +405,13 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b typ, _ := object["type"].(string) switch strings.ToLower(strings.TrimSpace(typ)) { case "none": - return nil, false - case "function": + choice["type"] = "none" + case "function", "custom": function, _ := object["function"].(map[string]any) name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } if name = strings.TrimSpace(name); name != "" { choice["type"] = "tool" choice["name"] = name @@ -423,7 +426,7 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b } return map[string]any{"type": "auto", "disable_parallel_tool_use": true}, true } - if parallelDisabled { + if parallelDisabled && choice["type"] != "none" { choice["disable_parallel_tool_use"] = true } return choice, true @@ -437,7 +440,7 @@ func responseToolChoice(raw json.RawMessage) (any, bool) { if json.Unmarshal(raw, &text) == nil { switch strings.ToLower(strings.TrimSpace(text)) { case "none": - return nil, false + return "none", true case "required", "any": return "required", true case "auto": @@ -450,15 +453,18 @@ func responseToolChoice(raw json.RawMessage) (any, bool) { return nil, true } typ, _ := object["type"].(string) - if strings.EqualFold(typ, "function") { + if strings.EqualFold(typ, "function") || strings.EqualFold(typ, "custom") { function, _ := object["function"].(map[string]any) name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } if name = strings.TrimSpace(name); name != "" { return map[string]any{"type": "function", "name": name}, true } } if strings.EqualFold(typ, "none") { - return nil, false + return "none", true } return nil, true } diff --git a/internal/providers/opencode/sse.go b/internal/providers/opencode/sse.go index ea56a5f81..e175b13b1 100644 --- a/internal/providers/opencode/sse.go +++ b/internal/providers/opencode/sse.go @@ -601,16 +601,25 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) return providers.ChatOutcome{}, err } agg := &sseAggregate{tools: map[int]*collectedTool{}, finish: "stop"} + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -637,6 +646,13 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("opencode stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("opencode stream: %s", message) + } if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage.prompt = chunk.Usage.PromptTokens agg.usage.completion = chunk.Usage.CompletionTokens @@ -647,6 +663,7 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) agg.reasoning.WriteString(choice.Delta.ReasoningContent) if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -665,6 +682,9 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("opencode stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/qoder/direct.go b/internal/providers/qoder/direct.go index f5ac340d1..eb0ef7486 100644 --- a/internal/providers/qoder/direct.go +++ b/internal/providers/qoder/direct.go @@ -197,11 +197,12 @@ func (d *Direct) ChatNonStream(ctx context.Context, accountID string, req transl for attempt := 0; attempt < 2; attempt++ { outcome, err := d.chatNonStreamOnce(ctx, accountID, req) if err == nil { + outcome.InternalRetries = attempt return outcome, nil } last = err if !isImageConversionTimeoutErr(err) || attempt == 1 { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, withDirectRetries(err, attempt) } // hub cdd95ef: one same-account bounded retry; no rotation/cooldown. } @@ -233,7 +234,7 @@ func (d *Direct) chatNonStreamOnce(ctx context.Context, accountID string, req tr return providers.ChatOutcome{}, err } if resp.StatusCode >= 300 { - return providers.ChatOutcome{}, upstreamStatusError(resp.StatusCode, raw) + return providers.ChatOutcome{}, upstreamStatusError(resp.StatusCode, raw, resp.Header) } outcome, err := outcomeFromUpstreamSSE(prepared.model, raw, prepared.allowed) if err != nil { @@ -248,16 +249,30 @@ func (d *Direct) ChatStream(ctx context.Context, accountID string, req translate for attempt := 0; attempt < 2; attempt++ { resp, resolved, err := d.chatStreamOnce(ctx, accountID, req) if err == nil { + resolved.InternalRetries = attempt return resp, resolved, nil } last = err if !isImageConversionTimeoutErr(err) || attempt == 1 { - return nil, providers.ResolvedChat{}, err + return nil, providers.ResolvedChat{}, withDirectRetries(err, attempt) } } return nil, providers.ResolvedChat{}, last } +// withDirectRetries tags a classified error with the same-account replays the +// Direct client already performed. +func withDirectRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + var pe *providers.Error + if errors.As(err, &pe) && pe != nil { + pe.InternalRetries = retries + } + return err +} + func (d *Direct) chatStreamOnce(ctx context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { prepared, err := d.prepare(ctx, accountID, req) if err != nil { @@ -276,7 +291,7 @@ func (d *Direct) chatStreamOnce(ctx context.Context, accountID string, req trans raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() release() - return nil, providers.ResolvedChat{}, upstreamStatusError(resp.StatusCode, raw) + return nil, providers.ResolvedChat{}, upstreamStatusError(resp.StatusCode, raw, resp.Header) } resp.Body = releaseOnClose{ReadCloser: resp.Body, release: release} guarded, err := ensureMeaningfulUpstream(resp, d.ttfb) @@ -301,16 +316,23 @@ const defaultQueueRetryAfter = 5 * time.Second // clientVersionTooLowMessage explains Qoder's HTTP 430 hard gate. const clientVersionTooLowMessage = "client version too low (HTTP 430): Qoder requires a newer client version; upgrade cli2api. This is not an account or network problem." -func upstreamStatusError(status int, body []byte) error { +func upstreamStatusError(status int, body []byte, headers ...http.Header) error { message := strings.TrimSpace(string(body)) if message == "" { message = fmt.Sprintf("qoder upstream status %d", status) } + var headerHint time.Duration + if len(headers) > 0 { + headerHint = providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")) + } // 10605 is model-level queueing, not an account fault (qoder2api-hub // 6b7f65b / 67aa3ce): no cooldown, no dead mark, no failover (which would // rebind the session to another account); surface Retry-After instead. if busy := qauth.ParseBusyEnvelope(status, body); busy != nil { retry := busy.RetryAfter + if retry <= 0 { + retry = headerHint + } if retry <= 0 { retry = defaultQueueRetryAfter } @@ -338,7 +360,7 @@ func upstreamStatusError(status int, body []byte) error { case http.StatusBadRequest: kind = accounts.KindInvalidRequest } - return &providers.Error{Kind: kind, Status: status, Message: message} + return &providers.Error{Kind: kind, Status: status, Message: message, RetryAfter: headerHint} } // emptyUpstreamError mirrors the worker path's upstream_empty classification. @@ -957,7 +979,7 @@ func outcomeFromUpstreamSSE(model string, raw []byte, names ...map[string]struct if err != nil { return providers.ChatOutcome{}, err } - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { if isImageConversionTimeoutMessage(frame.errText) { return providers.ChatOutcome{}, imageConversionTimeoutError(frame.errText) } @@ -1366,6 +1388,8 @@ func newCompletionID() string { return "chatcmpl-" + strings.ReplaceAll(id, "-", "") } +var errQoderSSETerminal = errors.New("qoder SSE terminal frame") + func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { completionID := newCompletionID() var sawFinish, sawTools, sawPayload, sawError bool @@ -1385,7 +1409,10 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { if len(frame.tools) > 0 { sawTools = true } - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { + // An upstream error frame is terminal even when the same frame (or + // an earlier one) carried content. Returning nil here would let the + // final [DONE] below report a failed turn as success. sawError = true errPayload := map[string]any{"message": frame.errText, "type": "api_error", "code": frame.busyCode} if frame.busyCode != "" { @@ -1403,8 +1430,13 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { } } payload, _ := json.Marshal(map[string]any{"error": errPayload}) - _, err := fmt.Fprintf(w, "data: %s\n\n", payload) - return err + if _, writeErr := fmt.Fprintf(w, "data: %s\n\n", payload); writeErr != nil { + return writeErr + } + // The error frame is terminal. Return a sentinel so the converter + // stops before any later content or synthetic finish chunk while the + // already-written error frame is still relayed cleanly. + return errQoderSSETerminal } chunk := map[string]any{ "id": completionID, "object": "chat.completion.chunk", "model": model, @@ -1433,9 +1465,14 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { _, err = fmt.Fprintf(w, "data: %s\n\n", payload) return err }) - if err != nil { + if err != nil && !errors.Is(err, errQoderSSETerminal) { return err } + if sawError { + // The failure frame is already on the wire; no success terminal may + // follow it. + return nil + } if !sawFinish { if sawPayload { // Upstream streamed real content but was cut before the terminal diff --git a/internal/providers/qoder/terminal_test.go b/internal/providers/qoder/terminal_test.go new file mode 100644 index 000000000..4aa467d60 --- /dev/null +++ b/internal/providers/qoder/terminal_test.go @@ -0,0 +1,64 @@ +package qoder + +import ( + "bytes" + "strings" + "testing" +) + +// A buffered (non-stream) turn that produced content and then received an +// upstream error frame is a failed turn, not a successful partial answer. +func TestOutcomeFromUpstreamSSEFailsOnLateErrorFrame(t *testing.T) { + raw := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"invalid_request_error","message":"context window exceeded"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + _, err := outcomeFromUpstreamSSE("glm-5.2", []byte(raw)) + if err == nil || !strings.Contains(err.Error(), "context window exceeded") { + t.Fatalf("late error frame was ignored: %v", err) + } +} + +func TestOutcomeFromUpstreamSSEKeepsSuccessfulTurn(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" + + `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}` + "\n\n" + "data: [DONE]\n\n" + out, err := outcomeFromUpstreamSSE("glm-5.2", []byte(raw)) + if err != nil || out.Content != "hello" || out.FinishReason != "stop" { + t.Fatalf("out=%+v err=%v", out, err) + } +} + +// A frame that carries both tool-convertible content and an error must still +// terminate as an error; the converter must not emit a normal [DONE]. +func TestWriteOpenAIChunksToolFrameWithErrorStaysFailed(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"partial","tool_calls":[{"index":0,"id":"call_1","function":{"name":"lookup","arguments":"{}"}}]}}],"error":{"message":"boom","type":"api_error"}}` + "\n\n" + + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := writeOpenAIChunks(&out, strings.NewReader(raw), "glm-5.2"); err != nil { + t.Fatalf("rewrite failed: %v", err) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed a same-frame error: %q", out.String()) + } + if !strings.Contains(out.String(), "boom") { + t.Fatalf("error frame missing: %q", out.String()) + } +} + +// terminal error frame. +func TestWriteOpenAIChunksStopsAfterErrorFrame(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"partial"}}]}` + "\n\n" + + `data: {"error":{"message":"boom","type":"api_error"}}` + "\n\n" + + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := writeOpenAIChunks(&out, strings.NewReader(raw), "glm-5.2"); err != nil { + t.Fatalf("rewrite failed: %v", err) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed an error frame: %q", out.String()) + } + if !strings.Contains(out.String(), "boom") { + t.Fatalf("error frame missing: %q", out.String()) + } +} diff --git a/internal/providers/qoder/tool_stream.go b/internal/providers/qoder/tool_stream.go index 439f26fcf..8f263f854 100644 --- a/internal/providers/qoder/tool_stream.go +++ b/internal/providers/qoder/tool_stream.go @@ -85,7 +85,7 @@ func rewriteToolTagFrames(w io.Writer, src io.Reader, allowed map[string]struct{ frame := frameFromBody(body, nil) // Pass errors / usage / structured tools / reasoning through; only // content is subject to tool-tag hold. - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { if holding { if err := flushHold(""); err != nil { return err @@ -106,6 +106,9 @@ func rewriteToolTagFrames(w io.Writer, src io.Reader, allowed map[string]struct{ if frame.reasoning != "" { delta["reasoning_content"] = frame.reasoning } + if frame.content != "" { + delta["content"] = frame.content + } if decoded != nil { delta["tool_calls"] = decoded } diff --git a/internal/providers/qoder/tool_tags.go b/internal/providers/qoder/tool_tags.go index 744b85e01..f99b19e8d 100644 --- a/internal/providers/qoder/tool_tags.go +++ b/internal/providers/qoder/tool_tags.go @@ -10,23 +10,23 @@ import ( // Fake XML / marker constants mirrored from qoder2api-hub issue #140 (e6e7622) // and the shared leak-marker helpers that parse_tool_call_tags depends on. const ( - toolCallOpen = "]*)>`) - callTagCloseRE = regexp.MustCompile(`(?i)<\s*/\s*tool_call\s*>`) + callTagOpenRE = regexp.MustCompile(`(?i)<\s*tool_call\b([^>]*)>`) + callTagCloseRE = regexp.MustCompile(`(?i)<\s*/\s*tool_call\s*>`) callTagAttrNameRE = regexp.MustCompile(`(?i)\b(?:name|tool|tool_name|function)\s*=\s*(?:"([^"]+)"|'([^']+)')`) - callTagLeadRE = regexp.MustCompile(`^\s*([A-Za-z_][A-Za-z0-9_.:\-]*)\s*`) - leakMarkerRE = regexp.MustCompile(`[\[<(]*\s*assistant\s*请求调用工具\s*[\]>)]?`) - leakStructRE = regexp.MustCompile( + callTagLeadRE = regexp.MustCompile(`^\s*([A-Za-z_][A-Za-z0-9_.:\-]*)\s*`) + leakMarkerRE = regexp.MustCompile(`[\[<(]*\s*assistant\s*请求调用工具\s*[\]>)]?`) + leakStructRE = regexp.MustCompile( `name\s*=\s*["']|`) ) diff --git a/internal/providers/qoder/tool_tags_test.go b/internal/providers/qoder/tool_tags_test.go index a7db25a94..ed5479786 100644 --- a/internal/providers/qoder/tool_tags_test.go +++ b/internal/providers/qoder/tool_tags_test.go @@ -35,9 +35,9 @@ func TestParseToolCallTagsUserSample(t *testing.T) { func TestParseToolCallTagsShapes(t *testing.T) { cases := []struct { - name string - text string - allow map[string]struct{} + name string + text string + allow map[string]struct{} wantName string }{ {"bare", `Bash {"command":"ls -la"}`, map[string]struct{}{"Bash": {}}, "Bash"}, @@ -175,6 +175,26 @@ func TestRecoverToolTagStreamRewritesFakeXML(t *testing.T) { } } +func TestRecoverToolTagStreamPreservesErrorsAndSameFrameText(t *testing.T) { + allowed := map[string]struct{}{"Bash": {}} + upstream := "data: " + `{"body":{"error":{"message":"upstream exploded"},"choices":[{"delta":{"content":"partial text"}}]}}` + "\n\n" + + "data: " + `{"body":{"choices":[{"delta":{"content":"before tool","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Bash","arguments":"{\"command\":\"pwd\"}"}}]}}]}}` + "\n\n" + var out strings.Builder + if err := rewriteToolTagFrames(&out, strings.NewReader(upstream), allowed); err != nil { + t.Fatal(err) + } + body := out.String() + if !strings.Contains(body, "upstream exploded") { + t.Fatalf("same-frame error dropped: %s", body) + } + if !strings.Contains(body, "before tool") { + t.Fatalf("same-frame text dropped: %s", body) + } + if !strings.Contains(body, `"tool_calls"`) || !strings.Contains(body, `"Bash"`) { + t.Fatalf("tool calls dropped: %s", body) + } +} + func TestUpstreamStatusErrorMapsImageConversionTimeout(t *testing.T) { err := upstreamStatusError(http.StatusBadGateway, []byte(`{"message":"Image conversion timeout"}`)) if !isImageConversionTimeoutErr(err) { diff --git a/internal/providers/retry_after.go b/internal/providers/retry_after.go new file mode 100644 index 000000000..2a234abc4 --- /dev/null +++ b/internal/providers/retry_after.go @@ -0,0 +1,30 @@ +package providers + +import ( + "net/http" + "strconv" + "strings" + "time" +) + +// ParseRetryAfterHeader parses an upstream Retry-After header. It accepts both +// forms defined by RFC 9110: delay-seconds and an HTTP date. A non-positive or +// unparseable value yields zero. +func ParseRetryAfterHeader(raw string) time.Duration { + text := strings.TrimSpace(raw) + if text == "" { + return 0 + } + if seconds, err := strconv.ParseFloat(text, 64); err == nil { + if seconds > 0 { + return time.Duration(seconds * float64(time.Second)) + } + return 0 + } + if at, err := http.ParseTime(text); err == nil { + if wait := time.Until(at); wait > 0 { + return wait + } + } + return 0 +} diff --git a/internal/providers/retry_after_test.go b/internal/providers/retry_after_test.go new file mode 100644 index 000000000..04749860e --- /dev/null +++ b/internal/providers/retry_after_test.go @@ -0,0 +1,20 @@ +package providers + +import ( + "net/http" + "testing" + "time" +) + +func TestParseRetryAfterHeader(t *testing.T) { + if got := ParseRetryAfterHeader("7"); got != 7*time.Second { + t.Fatalf("seconds = %v", got) + } + future := time.Now().Add(30 * time.Second).UTC().Format(http.TimeFormat) + if got := ParseRetryAfterHeader(future); got < 20*time.Second || got > 31*time.Second { + t.Fatalf("http date = %v", got) + } + if got := ParseRetryAfterHeader("not-a-delay"); got != 0 { + t.Fatalf("invalid = %v", got) + } +} diff --git a/internal/providers/retry_count.go b/internal/providers/retry_count.go new file mode 100644 index 000000000..507814370 --- /dev/null +++ b/internal/providers/retry_count.go @@ -0,0 +1,46 @@ +package providers + +import "errors" + +// retryCountError carries the number of same-account wire retries that +// preceded a failure which is not itself a *Error (for example a body read +// failure after a successful token-refresh resend). +type retryCountError struct { + err error + retries int +} + +func (e *retryCountError) Error() string { return e.err.Error() } +func (e *retryCountError) Unwrap() error { return e.err } +func (e *retryCountError) RetryCount() int { + if e == nil { + return 0 + } + return e.retries +} + +// TagInternalRetries preserves the retry count on any error shape. +func TagInternalRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + return &retryCountError{err: err, retries: retries} +} + +// InternalRetriesOf extracts the retry count from a providers.Error or a +// TagInternalRetries wrapper. +func InternalRetriesOf(err error) int { + if err == nil { + return 0 + } + var pe *Error + if errors.As(err, &pe) && pe != nil { + return pe.InternalRetries + } + type retryCounter interface{ RetryCount() int } + var counted retryCounter + if errors.As(err, &counted) && counted != nil { + return counted.RetryCount() + } + return 0 +} diff --git a/internal/providers/toolprofile.go b/internal/providers/toolprofile.go new file mode 100644 index 000000000..976567c6d --- /dev/null +++ b/internal/providers/toolprofile.go @@ -0,0 +1,102 @@ +package providers + +import ( + "strings" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +// ToolProfile is the provider-declared contract routing needs before it +// reserves an account. It is deliberately coarser than each adapter's wire +// details: a capability is advertised only when the adapter can guarantee it. +type ToolProfile struct { + Execution toolcall.ExecutionLevel `json:"execution"` + Choices []toolcall.ChoiceMode `json:"choices"` + ParallelOff bool `json:"parallel_off"` + StrictSchema bool `json:"strict_schema"` + ResultFormat string `json:"result_format"` + StableStreamID bool `json:"stable_stream_id"` +} + +func (p ToolProfile) SupportsChoice(mode toolcall.ChoiceMode) bool { + if mode == "" || mode == toolcall.ChoiceUnspecified { + return true + } + if p.Execution == toolcall.ExecutionNone { + return false + } + for _, supported := range p.Choices { + if supported == mode { + return true + } + } + return false +} + +func (p ToolProfile) SupportsTools() bool { + return p.Execution != "" && p.Execution != toolcall.ExecutionNone && len(p.Choices) > 0 +} + +func allChoices() []toolcall.ChoiceMode { + return []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone, toolcall.ChoiceRequired, toolcall.ChoiceNamed} +} + +// ToolProfileFor declares the conservative per-family tool contract. A model +// may narrow it, but no adapter may claim a capability it cannot enforce: +// choice modes and parallel-off are routing gates, not documentation. +func ToolProfileFor(provider, model string) ToolProfile { + switch strings.ToLower(strings.TrimSpace(provider)) { + case "qoder": + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: true, StrictSchema: true, ResultFormat: "native", StableStreamID: true} + case "workbuddy": + // WorkBuddy converts function schemas and tool_choice, but its normalizer + // rebuilds each function tool and drops the strict flag; the request body + // now carries parallel_tool_calls, yet the adapter cannot guarantee that + // upstream honors it. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "trae": + // Trae converts choice, but drops the client's parallel limit and the + // strict flag while rebuilding tools; `none` deletes tools instead of + // using a native selector. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "devin": + // The Connect-RPC request carries native tool definitions, tool calls, + // results and a ChatToolChoice (auto/none/required/named). The adapter + // rewrites namespaced names to stable aliases before sending. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: false} + case "command": + // Command sends tools but its request struct has no tool_choice field. + return ToolProfile{Execution: toolcall.ExecutionPrompted, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto}, ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "codex": + // The Chat-compat payload rewrites function tools into Responses shape + // and drops the strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "responses", StableStreamID: true} + case "meta": + // Same Chat-compat normalization as Codex: function tools are rebuilt + // without the strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "responses", StableStreamID: true} + case "zhipu", "kimi", "codearts": + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: true, ResultFormat: "openai_chat", StableStreamID: true} + case "qwenwork": + // Only `none` is special-cased; required/named have no native field. + return ToolProfile{Execution: toolcall.ExecutionValidated, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "kiro": + // Kiro accepts Anthropic client tools but expresses partial selection in + // the prompt; required/named cannot be guaranteed natively. + return ToolProfile{Execution: toolcall.ExecutionPrompted, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "doubaowork": + // Tools are parsed from prompt/output and required/named are verified + // after the fact. A validated profile is still not a native guarantee. + return ToolProfile{Execution: toolcall.ExecutionValidated, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "minimaxcode": + // The Anthropic payload rebuilds each function tool as name + + // input_schema, so the OpenAI strict flag is not forwarded. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "anthropic", StableStreamID: true} + case "opencode": + // Chat/Responses/Anthropic payloads all rebuild function tools and drop + // the OpenAI strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "opencode", StableStreamID: true} + default: + return ToolProfile{} + } +} diff --git a/internal/providers/toolprofile_test.go b/internal/providers/toolprofile_test.go new file mode 100644 index 000000000..d3cfa450b --- /dev/null +++ b/internal/providers/toolprofile_test.go @@ -0,0 +1,79 @@ +package providers + +import ( + "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +func TestEveryToolProviderHasAContract(t *testing.T) { + for _, descriptor := range List() { + if !descriptor.Capabilities.Tools { + continue + } + profile := ToolProfileFor(descriptor.ID, "") + if !profile.SupportsTools() { + t.Fatalf("%s advertises tools but has no tool contract: %+v", descriptor.ID, profile) + } + if profile.Execution == toolcall.ExecutionNone || profile.ResultFormat == "" { + t.Fatalf("%s has an incomplete contract: %+v", descriptor.ID, profile) + } + seen := map[toolcall.ChoiceMode]bool{} + for _, choice := range profile.Choices { + if choice == toolcall.ChoiceUnspecified || seen[choice] { + t.Fatalf("%s has an invalid choice list: %+v", descriptor.ID, profile.Choices) + } + seen[choice] = true + } + } +} + +func TestToolProfileChoiceParallelAndSchemaMatrix(t *testing.T) { + type expectation struct { + choices []toolcall.ChoiceMode + parallelOff bool + strict bool + } + want := map[string]expectation{ + "qoder": {allChoices(), true, true}, + "workbuddy": {allChoices(), false, false}, + "trae": {allChoices(), false, false}, + "devin": {allChoices(), false, false}, + "command": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto}, false, false}, + "codex": {allChoices(), false, false}, + "meta": {allChoices(), false, false}, + "zhipu": {allChoices(), false, true}, + "kimi": {allChoices(), false, true}, + "codearts": {allChoices(), false, true}, + "qwenwork": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "kiro": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "doubaowork": {allChoices(), false, false}, + "minimaxcode": {allChoices(), false, false}, + "opencode": {allChoices(), false, false}, + } + if len(want) != len(List()) { + t.Fatalf("matrix covers %d providers, registry has %d", len(want), len(List())) + } + for provider, expected := range want { + profile := ToolProfileFor(provider, "some-model") + if profile.ParallelOff != expected.parallelOff || profile.StrictSchema != expected.strict { + t.Fatalf("%s policy = %+v, want parallelOff=%v strict=%v", provider, profile, expected.parallelOff, expected.strict) + } + for _, mode := range []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone, toolcall.ChoiceRequired, toolcall.ChoiceNamed} { + allowed := false + for _, choice := range expected.choices { + allowed = allowed || choice == mode + } + if profile.SupportsChoice(mode) != allowed { + t.Fatalf("%s SupportsChoice(%s) = %v, want %v", provider, mode, !allowed, allowed) + } + } + } +} + +func TestUnknownProviderHasNoToolContract(t *testing.T) { + profile := ToolProfileFor("unknown", "model") + if profile.SupportsTools() || profile.SupportsChoice(toolcall.ChoiceAuto) { + t.Fatalf("unknown provider must not claim tools: %+v", profile) + } +} diff --git a/internal/providers/trae/checkin.go b/internal/providers/trae/checkin.go index 58b9bc3e5..1e886293d 100644 --- a/internal/providers/trae/checkin.go +++ b/internal/providers/trae/checkin.go @@ -32,6 +32,8 @@ func (AlreadyCheckedInError) AlreadyCheckedIn() bool { return true } // re-probe so success is only reported when the account actually flipped. // "今日已签到" maps to Status="already"; session-dead surfaces KindAuth so the // manager can flag the account for re-login. +var checkinNow = time.Now + func (client *Client) Checkin(ctx context.Context, accountID string) (providers.CheckinResult, error) { credential, err := client.credential(ctx, accountID) if err != nil { @@ -62,7 +64,7 @@ func (client *Client) Checkin(ctx context.Context, accountID string) (providers. if errors.As(err, &already) { // The claim endpoint may replay yesterday's grant during the brief // post-midnight window; do not record that as today's success. - if providers.CheckinClaimProvisional(time.Now()) { + if providers.CheckinClaimProvisional(checkinNow()) { return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核"}, nil } return providers.CheckinResult{Status: "already", Message: already.Msg}, nil diff --git a/internal/providers/trae/checkin_test.go b/internal/providers/trae/checkin_test.go index 463531fd2..0c39cbbf3 100644 --- a/internal/providers/trae/checkin_test.go +++ b/internal/providers/trae/checkin_test.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" "testing" + "time" ) // seedCheckinCredential stores a long-lived Trae credential so Checkin does @@ -114,6 +115,9 @@ func TestCheckinAlreadyByBusinessMessage(t *testing.T) { } func TestCheckinClaimAlreadyRace(t *testing.T) { + oldNow := checkinNow + checkinNow = func() time.Time { return time.Date(2026, 1, 2, 12, 0, 0, 0, time.Local) } + defer func() { checkinNow = oldNow }() client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { diff --git a/internal/providers/trae/client.go b/internal/providers/trae/client.go index ec222c19f..1343603e5 100644 --- a/internal/providers/trae/client.go +++ b/internal/providers/trae/client.go @@ -150,32 +150,32 @@ func (c *Client) httpClient(ctx context.Context, accountID string) (*http.Client return &client, nil } -func (c *Client) do(ctx context.Context, accountID, method, rawURL string, body []byte, setHeaders func(http.Header)) ([]byte, int, error) { +func (c *Client) do(ctx context.Context, accountID, method, rawURL string, body []byte, setHeaders func(http.Header)) ([]byte, int, http.Header, error) { var reader io.Reader if body != nil { reader = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, rawURL, reader) if err != nil { - return nil, 0, err + return nil, 0, nil, err } if setHeaders != nil { setHeaders(req.Header) } client, err := c.httpClient(ctx, accountID) if err != nil { - return nil, 0, err + return nil, 0, nil, err } resp, err := client.Do(req) if err != nil { - return nil, 0, err + return nil, 0, nil, err } defer resp.Body.Close() payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { - return nil, resp.StatusCode, err + return nil, resp.StatusCode, resp.Header, err } - return payload, resp.StatusCode, nil + return payload, resp.StatusCode, resp.Header, nil } func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.LoginSession, error) { @@ -714,12 +714,12 @@ func (c *Client) ExchangeToken(ctx context.Context, accountID string, credential if err != nil { return credential, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathExchange, body, SetOAuthHeaders) + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathExchange, body, SetOAuthHeaders) if err != nil { return credential, err } if status >= 300 { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } return decodeExchangeCredential(credential, payload) } @@ -772,7 +772,7 @@ func (c *Client) exchangeDeviceBound(ctx context.Context, accountID string, cred if err != nil { return credential, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, UgHost+pathExchangeCode, body, func(h http.Header) { + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, UgHost+pathExchangeCode, body, func(h http.Header) { SetOAuthHeaders(h) if credential.AccessToken != "" { h.Set("Authorization", "Cloud-IDE-JWT "+credential.AccessToken) @@ -785,7 +785,7 @@ func (c *Client) exchangeDeviceBound(ctx context.Context, accountID string, cred if status >= 300 { // Log the verdict, never the payload: it carries token material. log.Printf("trae: bound exchange rejected account=%s status=%d code=%s", accountID, status, firstNonEmpty(extractMetadataCode(payload), extractCode(string(payload)))) - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } log.Printf("trae: bound exchange accepted account=%s", accountID) return decodeExchangeCredential(credential, payload) @@ -866,8 +866,9 @@ func (c *Client) ExchangeAuthCode(ctx context.Context, accountID string, credent } var payload []byte var status int + var headers http.Header for i, host := range hosts { - payload, status, err = c.do(ctx, accountID, http.MethodPost, host+pathExchangeCode, body, SetOAuthHeaders) + payload, status, headers, err = c.do(ctx, accountID, http.MethodPost, host+pathExchangeCode, body, SetOAuthHeaders) if err != nil { log.Printf("trae: ExchangeAuthCode request failed account=%s host=%s: %v", accountID, host, err) return credential, err @@ -878,11 +879,11 @@ func (c *Client) ExchangeAuthCode(ctx context.Context, accountID string, credent // Log status and the extracted error code only — never the raw payload. log.Printf("trae: ExchangeAuthCode upstream error account=%s host=%s status=%d code=%s", accountID, host, status, firstNonEmpty(extractMetadataCode(payload), extractCode(string(payload)))) if i == len(hosts)-1 || !isInvalidParameter(status, payload) { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } } if status >= 300 { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } credential, err = decodeExchangeCredential(credential, payload) if err != nil { @@ -905,7 +906,7 @@ func (c *Client) GetUserInfo(ctx context.Context, accountID string, credential C if err != nil { return userInfo{}, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathUserInfo, body, func(h http.Header) { + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathUserInfo, body, func(h http.Header) { SetOAuthHeaders(h) if credential.AccessToken != "" { h.Set("X-Cloudide-Token", credential.AccessToken) @@ -915,7 +916,7 @@ func (c *Client) GetUserInfo(ctx context.Context, accountID string, credential C return userInfo{}, err } if status >= 300 { - return userInfo{}, classifiedError(status, payload) + return userInfo{}, classifiedError(status, payload, headers) } var env struct { Result struct { @@ -1012,13 +1013,13 @@ func (c *Client) fetchCatalogScene(ctx context.Context, accountID string, creden if err != nil { return nil, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.ChatBase()+pathModels, body, + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.ChatBase()+pathModels, body, func(h http.Header) { SetCatalogHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, payload) + return nil, classifiedError(status, payload, headers) } out, err := parseCatalogModels(payload, function) if err != nil { @@ -1085,6 +1086,9 @@ func (c *Client) chatRequest(ctx context.Context, credential Credential, req tra "tools": req.Tools, "tool_choice": req.ToolChoice, } + if req.ParallelToolCalls != nil { + body["parallel_tool_calls"] = *req.ParallelToolCalls + } if len(req.ResponseFormat) > 0 && string(req.ResponseFormat) != "null" { body["response_format"] = json.RawMessage(req.ResponseFormat) } @@ -1162,7 +1166,7 @@ func (c *Client) ChatNonStream(ctx context.Context, accountID string, req transl defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) if resp.StatusCode >= 300 { - return providers.ChatOutcome{}, classifiedError(resp.StatusCode, body) + return providers.ChatOutcome{}, classifiedError(resp.StatusCode, body, resp.Header) } aggregate, err := Aggregate(bytes.NewReader(body)) if err != nil { @@ -1197,7 +1201,7 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate if resp.StatusCode >= 300 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() - return nil, providers.ResolvedChat{}, classifiedError(resp.StatusCode, body) + return nil, providers.ResolvedChat{}, classifiedError(resp.StatusCode, body, resp.Header) } streamResp, err := rewriteSoloStream(resp.Body, req.Model) if err != nil { @@ -1260,8 +1264,14 @@ func outcomeFromAggregate(aggregate map[string]any, fallbackModel string) (provi return out, nil } -func classifiedError(status int, body []byte) error { - return wrapClassified(Classify(status, string(body)), extractCode(string(body))) +func classifiedError(status int, body []byte, headers ...http.Header) error { + out := wrapClassified(Classify(status, string(body)), extractCode(string(body))) + if pe, ok := out.(*providers.Error); ok && len(headers) > 0 { + if hint := providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")); hint > 0 { + pe.RetryAfter = hint + } + } + return out } // isInvalidParameter reports the upstream's "无效参数" rejection (code 10101). @@ -1430,13 +1440,13 @@ func (c *Client) Quota(ctx context.Context, accountID string) (*providers.QuotaI } func (c *Client) UserEntUsage(ctx context.Context, accountID string, credential Credential) (general, work entitlementBucket, err error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathEntUsage, []byte("{}"), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathEntUsage, []byte("{}"), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return entitlementBucket{}, entitlementBucket{}, err } if status >= 300 { - return entitlementBucket{}, entitlementBucket{}, classifiedError(status, body) + return entitlementBucket{}, entitlementBucket{}, classifiedError(status, body, headers) } general, work = parseEntitlementBuckets(body) if general.total == 0 && general.remain == 0 && general.used == 0 && work.total == 0 && work.remain == 0 && work.used == 0 { @@ -1567,25 +1577,25 @@ func int64FromAny(value any) int64 { } func (c *Client) checkinStatusBody(ctx context.Context, accountID string, credential Credential) ([]byte, error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinStatus, checkinReqSourceBody(credential), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinStatus, checkinReqSourceBody(credential), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, body) + return nil, classifiedError(status, body, headers) } return body, nil } func (c *Client) CheckinClaim(ctx context.Context, accountID string, credential Credential) ([]byte, error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinClaim, checkinReqSourceBody(credential), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinClaim, checkinReqSourceBody(credential), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, body) + return nil, classifiedError(status, body, headers) } return body, nil } diff --git a/internal/providers/trae/client_test.go b/internal/providers/trae/client_test.go index f388e481b..3c2ff4738 100644 --- a/internal/providers/trae/client_test.go +++ b/internal/providers/trae/client_test.go @@ -747,6 +747,54 @@ func TestChatNonStreamAggregatesToolsAndReasoning(t *testing.T) { } } +func TestAggregateKeepsSoloToolCallsByStableID(t *testing.T) { + stream := "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"first\",\"arguments\":\"{\\\"a\\\":\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"1}\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_2\",\"type\":\"function\",\"function\":{\"name\":\"second\",\"arguments\":\"{}\"}}]}\n\n" + + "event: done\ndata: {\"finish_reason\":\"tool-calls\"}\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + choices, _ := aggregate["choices"].([]map[string]any) + if len(choices) != 1 { + t.Fatalf("choices=%#v", aggregate["choices"]) + } + message, _ := choices[0]["message"].(map[string]any) + calls, _ := message["tool_calls"].([]any) + if len(calls) != 2 { + t.Fatalf("index reuse collapsed calls: %#v", calls) + } + first, _ := calls[0].(map[string]any) + second, _ := calls[1].(map[string]any) + if first["id"] != "call_1" || second["id"] != "call_2" { + t.Fatalf("call ids = %#v", calls) + } +} + +func TestAggregateAdoptsLateSoloToolCallID(t *testing.T) { + stream := "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"arguments\":\"{}\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_late\"}]}\n\n" + + "event: done\ndata: {\"finish_reason\":\"tool-calls\"}\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + choices, _ := aggregate["choices"].([]map[string]any) + if len(choices) != 1 { + t.Fatalf("choices=%#v", aggregate["choices"]) + } + message, _ := choices[0]["message"].(map[string]any) + calls, _ := message["tool_calls"].([]any) + if len(calls) != 1 { + t.Fatalf("late id duplicated call: %#v", calls) + } + call, _ := calls[0].(map[string]any) + if call["id"] != "call_late" { + t.Fatalf("late id not adopted: %#v", call) + } +} + // Solo answers 200 and only then fails inside the stream, so the quota error // cannot surface as a ChatStream return value: bytes are already committed. // The rewritten body must report it as a read error once drained. diff --git a/internal/providers/trae/payload.go b/internal/providers/trae/payload.go index f6f9ebb5d..d1b453406 100644 --- a/internal/providers/trae/payload.go +++ b/internal/providers/trae/payload.go @@ -145,7 +145,9 @@ func normalizeTools(obj map[string]any) { normalized, err := translate.NormalizeOpenAITools(encoded) if err != nil || len(normalized) == 0 { delete(obj, "tools") - delete(obj, "tool_choice") + if choice, ok := obj["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(obj, "tool_choice") + } return } var list []any diff --git a/internal/providers/trae/sse.go b/internal/providers/trae/sse.go index fc0810f87..6af90ef8e 100644 --- a/internal/providers/trae/sse.go +++ b/internal/providers/trae/sse.go @@ -8,7 +8,6 @@ import ( "fmt" "io" "net/http" - "sort" "strings" "sync/atomic" "time" @@ -99,10 +98,11 @@ func normalizeTraeUsage(raw []byte) any { func Aggregate(reader io.Reader) (map[string]any, error) { result := map[string]any{"object": "chat.completion"} message := map[string]any{"role": "assistant"} - toolCalls := map[int]map[string]any{} + toolCalls := map[string]map[string]any{} + indexToKey := map[int]string{} finishReason := "stop" var content, reasoning strings.Builder - var order []int + var order []string sawDone := false var usage any model := "" @@ -132,7 +132,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { if out.FinishReason != "" { finishReason = out.FinishReason } - mergeSoloToolCalls(toolCalls, &order, out.ToolCalls) + mergeSoloToolCalls(toolCalls, indexToKey, &order, out.ToolCalls) case "token_usage": usage = normalizeTraeUsage(ev.Data) case "done": @@ -163,10 +163,9 @@ func Aggregate(reader io.Reader) (map[string]any, error) { message["reasoning_content"] = reasoning.String() } if len(toolCalls) > 0 { - sort.Ints(order) calls := make([]any, 0, len(order)) - for _, index := range order { - calls = append(calls, toolCalls[index]) + for _, key := range order { + calls = append(calls, toolCalls[key]) } message["tool_calls"] = calls } @@ -358,13 +357,23 @@ func startSoloRewrite(src io.ReadCloser, upstream io.Closer, model string) (*htt var se streamError _ = json.Unmarshal(ev.Data, &se) payload, _ := json.Marshal(se.Error()) + // Emit the failure frame only: a following [DONE] would make a + // failed turn look like a successful terminal to strict clients. _, _ = fmt.Fprintf(pw, "event: error\ndata: %s\n\n", payload) - _, _ = io.WriteString(pw, "data: [DONE]\n\n") streamErr.Store(classifiedFromSolo(se)) return nil } return nil }) + if err != nil && !ended { + // The transport failed before Solo sent a terminal event. Writing a + // synthetic finish chunk plus [DONE] here used to convert a truncated + // stream (for example UnexpectedEOF) into a reported success; the + // downstream relay stopped reading at [DONE] and never saw the + // deferred read error. Surface the failure instead. + _ = pw.CloseWithError(err) + return + } if !ended { usage := pendingUsage if usage == nil && lastUsage != nil { @@ -508,7 +517,7 @@ func scanSolo(reader io.Reader, handle func(soloEvent) error) error { return flush() } -func mergeSoloToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMessage) { +func mergeSoloToolCalls(merged map[string]map[string]any, indexToKey map[int]string, order *[]string, raw json.RawMessage) { if len(raw) == 0 || string(raw) == "null" { return } @@ -518,13 +527,38 @@ func mergeSoloToolCalls(merged map[int]map[string]any, order *[]int, raw json.Ra if v, ok := item["index"].(float64); ok { index = int(v) } - call, exists := merged[index] + id, _ := item["id"].(string) + key := "" + if id != "" { + key = "id:" + id + } else if previous, ok := indexToKey[index]; ok { + key = previous + } else { + key = fmt.Sprintf("index:%d", index) + } + if id != "" { + if previous, ok := indexToKey[index]; ok && previous != key { + if call, exists := merged[previous]; exists && call["id"] == nil { + call["id"] = id + merged[key] = call + delete(merged, previous) + for i, orderedKey := range *order { + if orderedKey == previous { + (*order)[i] = key + break + } + } + } + } + } + indexToKey[index] = key + call, exists := merged[key] if !exists { call = map[string]any{"index": index, "type": "function"} - merged[index] = call - *order = append(*order, index) + merged[key] = call + *order = append(*order, key) } - if id, _ := item["id"].(string); id != "" { + if id != "" { call["id"] = id } if typ, _ := item["type"].(string); typ != "" { diff --git a/internal/providers/trae/terminal_test.go b/internal/providers/trae/terminal_test.go new file mode 100644 index 000000000..ae1d8613c --- /dev/null +++ b/internal/providers/trae/terminal_test.go @@ -0,0 +1,69 @@ +package trae + +import ( + "io" + "strings" + "testing" +) + +type failingStream struct { + data []byte + err error +} + +func (f *failingStream) Read(p []byte) (int, error) { + if len(f.data) > 0 { + n := copy(p, f.data) + f.data = f.data[n:] + return n, nil + } + return 0, f.err +} + +func (f *failingStream) Close() error { return nil } + +// A transport read failure before Solo's `done` event must not be converted +// into a synthetic finish chunk plus [DONE]. Downstream used to stop at [DONE] +// and record the truncated turn as a success. +func TestRewriteSoloStreamDoesNotSynthesizeTerminalOnReadError(t *testing.T) { + stream := "event: metadata\ndata: {\"model\":\"glm-5.2\"}\n\n" + + "event: output\ndata: {\"response\":\"partial\"}\n\n" + src := &failingStream{data: []byte(stream), err: io.ErrUnexpectedEOF} + resp, err := rewriteSoloStream(src, "glm-5.2") + if err != nil { + t.Fatalf("headers should be exposed before the read error: %v", err) + } + defer resp.Body.Close() + body, readErr := io.ReadAll(resp.Body) + if readErr == nil { + t.Fatal("truncated stream was reported as complete") + } + text := string(body) + if strings.Contains(text, "data: [DONE]") || strings.Contains(text, `"finish_reason":"stop"`) { + t.Fatalf("failure was converted into a success terminal: %q", text) + } + if !strings.Contains(text, "partial") { + t.Fatalf("content before the failure should stay relayed: %q", text) + } +} + +// A clean EOF without `done` keeps the existing salvage behavior: the upstream +// delivered a full body, so a synthesized terminal is a compatibility fallback, +// not a failure conversion. +func TestRewriteSoloStreamStillSalvagesCleanEOF(t *testing.T) { + stream := "event: metadata\ndata: {\"model\":\"glm-5.2\"}\n\n" + + "event: output\ndata: {\"response\":\"complete\"}\n\n" + src := &failingStream{data: []byte(stream), err: io.EOF} + resp, err := rewriteSoloStream(src, "glm-5.2") + if err != nil { + t.Fatalf("salvage path failed: %v", err) + } + defer resp.Body.Close() + body, readErr := io.ReadAll(resp.Body) + if readErr != nil { + t.Fatalf("clean EOF must not surface as an error: %v", readErr) + } + if !strings.Contains(string(body), "data: [DONE]") { + t.Fatalf("clean EOF salvage lost its terminal: %q", body) + } +} diff --git a/internal/providers/workbuddy/client.go b/internal/providers/workbuddy/client.go index c01e14a3a..7c5c7442f 100644 --- a/internal/providers/workbuddy/client.go +++ b/internal/providers/workbuddy/client.go @@ -479,6 +479,9 @@ func (c *Client) chatRequest(ctx context.Context, accountID string, credential C "tools": req.Tools, "tool_choice": req.ToolChoice, } + if req.ParallelToolCalls != nil { + body["parallel_tool_calls"] = *req.ParallelToolCalls + } // The re-built body used to drop the caller's `thinking` object entirely. // Keep it so applyChatReasoning (and PrepareBody, which preserves unknown // keys) can relay an explicit disabled-thinking request upstream. @@ -508,24 +511,25 @@ func (c *Client) ChatNonStream(ctx context.Context, accountID string, req transl if err != nil { return providers.ChatOutcome{}, err } - resp, err := c.sendChat(ctx, accountID, credential, req, httpReq) + resp, retries, err := c.sendChat(ctx, accountID, credential, req, httpReq) if err != nil { return providers.ChatOutcome{}, err } defer resp.Body.Close() body, readErr := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) if readErr != nil { - return providers.ChatOutcome{}, fmt.Errorf("read workbuddy stream: %w", readErr) + return providers.ChatOutcome{}, providers.TagInternalRetries(fmt.Errorf("read workbuddy stream: %w", readErr), retries) } aggregate, err := Aggregate(bytes.NewReader(body)) if err != nil { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, providers.TagInternalRetries(err, retries) } outcome, err := outcomeFromAggregate(aggregate) if err != nil { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, providers.TagInternalRetries(err, retries) } outcome.ReasoningLevel = resolved.ReasoningLevel + outcome.InternalRetries = retries return outcome, nil } @@ -538,10 +542,11 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate if err != nil { return nil, providers.ResolvedChat{}, err } - resp, err := c.sendChat(ctx, accountID, credential, req, httpReq) + resp, retries, err := c.sendChat(ctx, accountID, credential, req, httpReq) if err != nil { return nil, providers.ResolvedChat{}, err } + resolved.InternalRetries = retries return rewriteChatStream(resp), resolved, nil } @@ -554,46 +559,49 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate // so the pool applies short cooldown + failover without marking the account // login_required. TLS certificate verification failures are deterministic // configuration errors and are reported without retry. -func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, req translate.ChatRequest, httpReq *http.Request) (*http.Response, error) { +func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, req translate.ChatRequest, httpReq *http.Request) (*http.Response, int, error) { client, err := c.httpClient(ctx, accountID) if err != nil { - return nil, err + return nil, 0, err } client.Timeout = 0 refreshed := false + // attempts counts only requests actually sent again after a successful + // token refresh. A refresh that fails before the resend is not a retry. + attempts := 0 for { // Fail over when the upstream accepts but never sends a response head // (see ttfb.go). Kept inside sendChat so the 401 refresh loop still runs. resp, err := doWithFirstByteTimeout(client, httpReq, resolveFirstByteTimeout()) if err != nil { - return nil, wrapTransportError(err) + return nil, attempts, withInternalRetries(wrapTransportError(err), attempts) } if resp.StatusCode < 300 { - return resp, nil + return resp, attempts, nil } body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() if resp.StatusCode != http.StatusUnauthorized || refreshed || credential.RefreshToken == "" { - return nil, classifiedError(resp.StatusCode, body) + return nil, attempts, withInternalRetries(classifiedError(resp.StatusCode, body, resp.Header), attempts) } refreshed = true fresh, refreshErr := c.Refresh(ctx, accountID, credential) if refreshErr != nil { if tlsErr := tlsVerifyError(refreshErr); tlsErr != nil { - return nil, tlsErr + return nil, 0, tlsErr } if refreshFailureIsAuth(refreshErr) { - out := classifiedError(resp.StatusCode, body) + out := classifiedError(resp.StatusCode, body, resp.Header) if pe, ok := out.(*providers.Error); ok && pe.Kind == accounts.KindAuth { pe.Message = "token refresh after 401 failed; re-login required" } - return nil, out + return nil, 0, out } // Non-auth refresh failure (transport / 5xx / etc.): keep the // account out of login_required; pool short-cools via Unavailable. summary := refreshErr.Error() _ = c.store.Observe(ctx, accountID, credential.UID, "error", "token refresh after 401: "+summary, accounts.KindUnavailable) - return nil, &providers.Error{ + return nil, 0, &providers.Error{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: "token refresh after 401 unavailable: " + summary, @@ -602,9 +610,24 @@ func (c *Client) sendChat(ctx context.Context, accountID string, credential Cred credential = fresh httpReq, _, err = c.chatRequest(ctx, accountID, credential, req) if err != nil { - return nil, err + return nil, 0, err } + attempts = 1 + } +} + +// withInternalRetries tags a classified adapter error with the number of +// same-account replays that preceded it. Errors that are not providers.Error +// stay untouched. +func withInternalRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + var pe *providers.Error + if errors.As(err, &pe) && pe != nil { + pe.InternalRetries = retries } + return err } // tlsVerifyHint mirrors workbuddy2api-hub #441: certificate failures are a @@ -706,10 +729,15 @@ func outcomeFromAggregate(aggregate map[string]any) (providers.ChatOutcome, erro return out, nil } -func classifiedError(status int, body []byte) error { +func classifiedError(status int, body []byte, headers ...http.Header) error { classified := Classify(status, string(body)) out := &providers.Error{Kind: classified.Kind, Status: classified.Status, Message: classified.Message} - if classified.Kind == accounts.KindRateLimit { + if len(headers) > 0 { + if hint := providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")); hint > 0 { + out.RetryAfter = hint + } + } + if classified.Kind == accounts.KindRateLimit && out.RetryAfter <= 0 { if reset := parseQuotaReset(string(body), time.Now()); reset > 0 { out.RetryAfter = reset } diff --git a/internal/providers/workbuddy/client_test.go b/internal/providers/workbuddy/client_test.go index cbd6db1b0..adad4c246 100644 --- a/internal/providers/workbuddy/client_test.go +++ b/internal/providers/workbuddy/client_test.go @@ -2472,7 +2472,7 @@ func TestOutcomeFromAggregateReadsConsumedCredit(t *testing.T) { `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":16,"completion_tokens":2,"credit":0.75}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2504,7 +2504,7 @@ func TestOutcomeFromAggregatePreservesCacheUsage(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":16,"completion_tokens":2,` + test.usage + `}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2527,7 +2527,7 @@ func TestOutcomeFromAggregateMissingCreditStaysNil(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2545,7 +2545,7 @@ func TestOutcomeFromAggregateExplicitZeroCredit(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1,"credit":0}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } diff --git a/internal/providers/workbuddy/credential.go b/internal/providers/workbuddy/credential.go index 359445fc9..53655717a 100644 --- a/internal/providers/workbuddy/credential.go +++ b/internal/providers/workbuddy/credential.go @@ -86,8 +86,8 @@ const ( pathModelsCN = "/console/enterprises/personal/models" pathModelsGlobal = "/v2/enterprises/personal/models" pathProductConfig = "/v3/config" - pathUserResource = "/v2/billing/meter/get-user-resource" - pathDailyCheckin = "/v2/billing/meter/daily-checkin" + pathUserResource = "/v2/billing/meter/get-user-resource" + pathDailyCheckin = "/v2/billing/meter/daily-checkin" sessionDeadCode = 12153 sessionDeadText = "Offline user session not found" diff --git a/internal/providers/workbuddy/credential_test.go b/internal/providers/workbuddy/credential_test.go index 61d8258ba..da82114b1 100644 --- a/internal/providers/workbuddy/credential_test.go +++ b/internal/providers/workbuddy/credential_test.go @@ -141,7 +141,6 @@ func TestDecodeCredentialNestedAndSnakeStillWork(t *testing.T) { } } - func TestSplitImportClientExportTypePack(t *testing.T) { payload := []byte(`{ "exportType":"WorkBuddy-accounts", @@ -228,8 +227,8 @@ func TestSplitImportFormatCaseAlias(t *testing.T) { func TestIsGlobalWorkbuddyCN(t *testing.T) { cases := []struct { - domain string - global bool + domain string + global bool }{ {"www.workbuddy.cn", false}, {"workbuddy.cn", false}, diff --git a/internal/providers/workbuddy/payload.go b/internal/providers/workbuddy/payload.go index 5ec6ed0d5..2a818b015 100644 --- a/internal/providers/workbuddy/payload.go +++ b/internal/providers/workbuddy/payload.go @@ -63,7 +63,12 @@ func normalizeTools(body map[string]any) { } if len(normalized) == 0 { delete(body, "tools") - delete(body, "tool_choice") + // Only an orphan auto degrades safely. A required/named selector must + // stay on the wire so upstream rejects it instead of silently answering + // with plain text. + if choice, ok := body["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(body, "tool_choice") + } return } var tools []any @@ -450,7 +455,9 @@ func dropEmptyTools(body map[string]any) { list, ok := raw.([]any) if ok && len(list) == 0 { delete(body, "tools") - delete(body, "tool_choice") + if choice, ok := body["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(body, "tool_choice") + } } } diff --git a/internal/providers/workbuddy/sse.go b/internal/providers/workbuddy/sse.go index 9fe640211..c93ca9643 100644 --- a/internal/providers/workbuddy/sse.go +++ b/internal/providers/workbuddy/sse.go @@ -4,12 +4,14 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" - "sort" "strings" "time" + + "github.com/caigee-cmd/cli2api/internal/providers" ) // Aggregate converts an upstream SSE stream into one Chat Completions object, @@ -19,26 +21,36 @@ func Aggregate(reader io.Reader) (map[string]any, error) { "object": "chat.completion", } message := map[string]any{"role": "assistant"} - toolCalls := map[int]map[string]any{} + toolCalls := map[string]map[string]any{} + indexToKey := map[int]string{} finishReason := "stop" var content, reasoning strings.Builder - var order []int + var order []string sawDone := false + var terminalErr error scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) - for scanner.Scan() { - line := strings.TrimSuffix(scanner.Text(), "\r") - if !strings.HasPrefix(line, "data:") { - continue + var frame []string + flush := func() error { + if len(frame) == 0 { + return nil } - payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + payload := sseDataPayload(frame) + frame = nil if payload == "" { - continue + return nil } if payload == "[DONE]" { sawDone = true - break + return errSSEStreamDone + } + // A terminal error frame is authoritative: never aggregate the content + // that happened to arrive before it into a successful completion, and + // never let a later [DONE] turn the failure into success. + if terminal, ok := terminalSSEPayloadError(payload); ok { + terminalErr = terminal + return errSSEStreamDone } var chunk struct { ID string `json:"id"` @@ -57,7 +69,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { } `json:"choices"` } if err := json.Unmarshal([]byte(payload), &chunk); err != nil { - continue + return nil } if chunk.ID != "" { result["id"] = chunk.ID @@ -72,7 +84,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { result["usage"] = chunk.Usage } if len(chunk.Choices) == 0 { - continue + return nil } choice := chunk.Choices[0] if choice.FinishReason != "" { @@ -84,12 +96,29 @@ func Aggregate(reader io.Reader) (map[string]any, error) { content.WriteString(choice.Delta.Content) reasoning.WriteString(choice.Delta.ReasoningContent) if len(choice.Delta.ToolCalls) > 0 && string(choice.Delta.ToolCalls) != "null" { - mergeToolCalls(toolCalls, &order, choice.Delta.ToolCalls) + mergeToolCalls(toolCalls, indexToKey, &order, choice.Delta.ToolCalls) } + return nil + } + for scanner.Scan() { + line := strings.TrimSuffix(scanner.Text(), "\r") + if line == "" { + if err := flush(); err != nil { + if errors.Is(err, errSSEStreamDone) { + break + } + return nil, err + } + continue + } + frame = append(frame, line) } if err := scanner.Err(); err != nil { return nil, err } + if terminalErr != nil { + return nil, terminalErr + } if !sawDone { return nil, fmt.Errorf("workbuddy stream ended before [DONE]") } @@ -99,10 +128,9 @@ func Aggregate(reader io.Reader) (map[string]any, error) { message["reasoning_content"] = reasoning.String() } if len(toolCalls) > 0 { - sort.Ints(order) calls := make([]any, 0, len(order)) - for _, index := range order { - calls = append(calls, toolCalls[index]) + for _, key := range order { + calls = append(calls, toolCalls[key]) } message["tool_calls"] = calls } @@ -120,7 +148,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { return result, nil } -func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMessage) { +func mergeToolCalls(merged map[string]map[string]any, indexToKey map[int]string, order *[]string, raw json.RawMessage) { var deltas []struct { Index int `json:"index"` ID string `json:"id"` @@ -134,11 +162,37 @@ func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMes return } for _, delta := range deltas { - call, exists := merged[delta.Index] + key := "" + if delta.ID != "" { + key = "id:" + delta.ID + } else if previous, ok := indexToKey[delta.Index]; ok { + key = previous + } else { + key = fmt.Sprintf("index:%d", delta.Index) + } + if delta.ID != "" { + if previous, ok := indexToKey[delta.Index]; ok && previous != key { + if call, exists := merged[previous]; exists && call["id"] == nil { + call["id"] = delta.ID + merged[key] = call + delete(merged, previous) + for i, orderedKey := range *order { + if orderedKey == previous { + (*order)[i] = key + break + } + } + } + } + indexToKey[delta.Index] = key + } else { + indexToKey[delta.Index] = key + } + call, exists := merged[key] if !exists { call = map[string]any{"index": delta.Index} - merged[delta.Index] = call - *order = append(*order, delta.Index) + merged[key] = call + *order = append(*order, key) } if delta.ID != "" { call["id"] = delta.ID @@ -152,7 +206,9 @@ func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMes function = map[string]any{} call["function"] = function } - function["name"] = delta.Function.Name + if name, _ := function["name"].(string); name == "" { + function["name"] = delta.Function.Name + } } if delta.Function.Arguments != "" { function, _ := call["function"].(map[string]any) @@ -192,30 +248,172 @@ func copySanitizedSSE(src io.Reader, dst io.Writer) error { scanner := bufio.NewScanner(src) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) sentRole := false - for scanner.Scan() { - line := strings.TrimSuffix(scanner.Text(), "\r") - if line == "" { - continue + var frame []string + flush := func() error { + if len(frame) == 0 { + return nil } - if !strings.HasPrefix(line, "data:") { - if _, err := fmt.Fprintf(dst, "%s\n", line); err != nil { + payload := sseDataPayload(frame) + original := strings.Join(frame, "\n") + "\n\n" + frame = nil + if payload == "" { + return nil + } + if payload == "[DONE]" { + if _, err := io.WriteString(dst, original); err != nil { return err } - continue + return errSSEStreamDone } - payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if payload == "" { - continue + // Preserve the upstream failure frame verbatim: the sanitizer used to + // drop a frame that carried only an error object, leaving the later + // [DONE] as the only terminal signal and turning a failure into success. + if terminal, ok := terminalSSEPayloadError(payload); ok { + if _, err := io.WriteString(dst, original); err != nil { + return err + } + return terminal } cleaned, ok := sanitizeSSEPayload(payload, &sentRole) if !ok { - continue + return nil } if _, err := fmt.Fprintf(dst, "data: %s\n\n", cleaned); err != nil { return err } + return nil + } + for scanner.Scan() { + line := strings.TrimSuffix(scanner.Text(), "\r") + if line == "" { + if err := flush(); err != nil { + if errors.Is(err, errSSEStreamDone) { + return nil + } + return err + } + continue + } + frame = append(frame, line) + } + if err := scanner.Err(); err != nil { + return err + } + if err := flush(); err != nil && !errors.Is(err, errSSEStreamDone) { + return err + } + return nil +} + +var errSSEStreamDone = errors.New("sse stream reached its terminal frame") + +// sseDataPayload joins every data: line in an SSE frame. The SSE specification +// concatenates multiple data lines with a newline before JSON decoding; treating +// each line as a separate payload made a legal multi-line error look like two +// unparseable chunks and let the following [DONE] become the only terminal frame. +func sseDataPayload(frame []string) string { + parts := make([]string, 0, len(frame)) + for _, line := range frame { + line = strings.TrimSuffix(line, "\r") + if !strings.HasPrefix(line, "data:") { + continue + } + value := strings.TrimPrefix(line, "data:") + if strings.HasPrefix(value, " ") { + value = value[1:] + } + parts = append(parts, value) + } + return strings.TrimSpace(strings.Join(parts, "\n")) +} + +// terminalSSEPayloadError reports whether a data payload is an upstream +// terminal failure rather than a chat chunk. WorkBuddy emits several error +// envelopes (OpenAI-shaped {"error":{...}}, {"type":"error",...}, and +// {"code":...,"msg":...}); all of them must stop the relay instead of being +// filtered out and replaced by the following [DONE]. +func terminalSSEPayloadError(payload string) (*providers.Error, bool) { + if payload == "" || payload == "[DONE]" { + return nil, false + } + var chunk map[string]any + if json.Unmarshal([]byte(payload), &chunk) != nil { + return nil, false + } + rawErr, hasError := chunk["error"] + hasError = hasError && rawErr != nil + typ, _ := chunk["type"].(string) + isErrorType := strings.EqualFold(strings.TrimSpace(typ), "error") || strings.EqualFold(strings.TrimSpace(typ), "response.failed") + _, hasChoices := chunk["choices"] + code := stringifySSECode(chunk["code"]) + message := firstSSEString(chunk, "message", "msg") + if !hasError && !isErrorType { + // A bare code/message object without choices is still an upstream + // failure; a normal chunk always carries choices or usage. + if hasChoices || chunk["usage"] != nil || code == "" || message == "" { + return nil, false + } + } + status := 0 + for _, key := range []string{"status", "status_code", "statusCode"} { + if value, ok := chunk[key].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + break + } + } + if status == 0 { + if value, ok := chunk["code"].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + } + } + inner, _ := rawErr.(map[string]any) + if inner != nil { + if message == "" { + message = firstSSEString(inner, "message", "msg") + } + if code == "" { + code = stringifySSECode(inner["code"]) + } + if typ == "" { + typ, _ = inner["type"].(string) + typ = strings.TrimSpace(typ) + } + if status == 0 { + if value, ok := inner["status"].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + } + } + } + if message == "" { + message = strings.TrimSpace(payload) + } + if typ == "" { + typ = "error" + } + return &providers.Error{Status: status, Message: message, Code: code, Type: typ}, true +} + +func stringifySSECode(value any) string { + switch typed := value.(type) { + case string: + return strings.TrimSpace(typed) + case float64: + if typed == float64(int64(typed)) { + return fmt.Sprintf("%d", int64(typed)) + } + return fmt.Sprintf("%v", typed) + default: + return "" + } +} + +func firstSSEString(obj map[string]any, keys ...string) string { + for _, key := range keys { + if value, ok := obj[key].(string); ok && strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } } - return scanner.Err() + return "" } func sanitizeSSEPayload(payload string, sentRole *bool) (string, bool) { diff --git a/internal/providers/workbuddy/terminal_test.go b/internal/providers/workbuddy/terminal_test.go new file mode 100644 index 000000000..f96f7d937 --- /dev/null +++ b/internal/providers/workbuddy/terminal_test.go @@ -0,0 +1,148 @@ +package workbuddy + +import ( + "bytes" + "errors" + "net/http" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +// A 200 response whose only terminal signal is an error frame must never be +// aggregated into a successful completion, even when a [DONE] follows it. +func TestAggregateFailsOnErrorFrameBeforeDone(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"invalid_request_error","message":"bad input"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + _, err := Aggregate(strings.NewReader(stream)) + if err == nil { + t.Fatal("error frame was aggregated as success") + } + var providerErr *providers.Error + if !errors.As(err, &providerErr) || !strings.Contains(providerErr.Message, "bad input") { + t.Fatalf("err=%v", err) + } +} + +func TestAggregateFailsOnBareCodeMessageFrame(t *testing.T) { + stream := `data: {"code":11148,"msg":"tool calls do not match"}` + "\n\n" + `data: [DONE]` + "\n\n" + _, err := Aggregate(strings.NewReader(stream)) + if err == nil || !strings.Contains(err.Error(), "tool calls do not match") { + t.Fatalf("bare code/message frame was not terminal: %v", err) + } +} + +// The sanitizer must pass the failure frame through instead of dropping it and +// forwarding the later [DONE] as the only terminal signal. +func TestCopySanitizedSSEPreservesErrorFrame(t *testing.T) { + input := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"rate_limit_error","message":"slow down"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + var out bytes.Buffer + err := copySanitizedSSE(strings.NewReader(input), &out) + if err == nil { + t.Fatal("copySanitizedSSE must fail on an error frame") + } + if !strings.Contains(out.String(), "slow down") { + t.Fatalf("failure frame was dropped: %q", out.String()) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator was forwarded after a failure: %q", out.String()) + } +} + +func TestCopySanitizedSSEKeepsOrdinaryChunks(t *testing.T) { + input := `data: {"choices":[{"delta":{"content":"ok"}}]}` + "\n\n" + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := copySanitizedSSE(strings.NewReader(input), &out); err != nil { + t.Fatalf("ordinary stream failed: %v", err) + } + if !strings.Contains(out.String(), `"ok"`) || strings.Count(out.String(), "[DONE]") != 1 { + t.Fatalf("ordinary stream was changed: %q", out.String()) + } +} + +func TestClassifiedErrorPreservesRetryAfterHeader(t *testing.T) { + headers := make(http.Header) + headers.Set("Retry-After", "7") + err := classifiedError(http.StatusTooManyRequests, []byte(`{"message":"slow down"}`), headers) + var providerErr *providers.Error + if !errors.As(err, &providerErr) { + t.Fatalf("err type = %T", err) + } + if providerErr.RetryAfter != 7*time.Second { + t.Fatalf("retry after = %v", providerErr.RetryAfter) + } +} + +// A legal SSE frame can split its JSON across multiple data: lines. Splitting +// the lines apart used to lose the error entirely and let a later [DONE] win. +func TestMultiLineErrorFrameStaysTerminal(t *testing.T) { + input := "data: {\"error\":{\"type\":\"invalid_request_error\",\n" + + "data: \"message\":\"bad input\"}}\n\n" + + "data: [DONE]\n\n" + if _, err := Aggregate(strings.NewReader(input)); err == nil || !strings.Contains(err.Error(), "bad input") { + t.Fatalf("aggregate lost a multi-line error frame: %v", err) + } + var out bytes.Buffer + if err := copySanitizedSSE(strings.NewReader(input), &out); err == nil { + t.Fatalf("sanitizer accepted a multi-line error frame: %q", out.String()) + } + if !strings.Contains(out.String(), "bad input") { + t.Fatalf("sanitizer dropped the multi-line error frame: %q", out.String()) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed the multi-line error: %q", out.String()) + } +} + +func TestAggregateKeepsToolCallsByStableIDWhenIndexReused(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"first","arguments":"{\"a\":"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"1}"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_2","type":"function","function":{"name":"second","arguments":"{}"}}]}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + calls, _ := aggregate["choices"].([]map[string]any)[0]["message"].(map[string]any)["tool_calls"].([]any) + if len(calls) != 2 { + t.Fatalf("index reuse collapsed calls: %#v", calls) + } + first, _ := calls[0].(map[string]any) + second, _ := calls[1].(map[string]any) + if first["id"] != "call_1" || second["id"] != "call_2" { + t.Fatalf("call ids = %#v", calls) + } +} + +func TestAggregateAdoptsLateToolCallID(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"type":"function","function":{"name":"lookup","arguments":"{}"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_late"}]}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + calls, _ := aggregate["choices"].([]map[string]any)[0]["message"].(map[string]any)["tool_calls"].([]any) + if len(calls) != 1 { + t.Fatalf("late id duplicated call: %#v", calls) + } + call, _ := calls[0].(map[string]any) + if call["id"] != "call_late" { + t.Fatalf("late id not adopted: %#v", call) + } +} diff --git a/internal/providers/zhipu/chat.go b/internal/providers/zhipu/chat.go index 24fd46e67..7b0be0e4a 100644 --- a/internal/providers/zhipu/chat.go +++ b/internal/providers/zhipu/chat.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -128,16 +129,25 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if err != nil { return providers.ChatOutcome{}, err } + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -158,6 +168,13 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("zhipu stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("zhipu stream: %s", message) + } if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage = chunk.Usage } @@ -166,6 +183,7 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) agg.reasoning.WriteString(choice.Delta.ReasoningContent) if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -184,6 +202,9 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("zhipu stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/zhipu/zhipu_test.go b/internal/providers/zhipu/zhipu_test.go index 217eb0da1..4939906ee 100644 --- a/internal/providers/zhipu/zhipu_test.go +++ b/internal/providers/zhipu/zhipu_test.go @@ -229,3 +229,15 @@ func mustJSON(t *testing.T, value any) []byte { } return raw } + +func TestCollectChatSSERejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatSSE(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "glm-5.2"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "glm-5.2"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "glm-5.2"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} 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