返回 DeepSeek-Reasonix
opencode_contract_wire_test.go
根目录 / internal / provider / openai / opencode_contract_wire_test.go
1 package openai
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "net/url"
11 "strings"
12 "sync/atomic"
13 "testing"
14
15 "reasonix/internal/provider"
16 )
17
18 type localOpenCodeGoTransport struct {
19 target *url.URL
20 }
21
22 func (t localOpenCodeGoTransport) RoundTrip(req *http.Request) (*http.Response, error) {
23 req = req.Clone(req.Context())
24 req.URL.Scheme, req.URL.Host = t.target.Scheme, t.target.Host
25 req.Host = t.target.Host
26 return http.DefaultTransport.RoundTrip(req)
27 }
28
29 func TestOpenCodeGoChatToolReplayOmitsToolName(t *testing.T) {
30 for _, base := range []string{"https://opencode.ai/zen/go/v1", "https://opencode.ai/inference/go/openai/v1"} {
31 t.Run(base, func(t *testing.T) { testOpenCodeGoChatToolReplay(t, base) })
32 }
33 }
34
35 func testOpenCodeGoChatToolReplay(t *testing.T, base string) {
36 var requests atomic.Int32
37 var session string
38 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
39 requestNumber := requests.Add(1)
40 endpoint, _ := url.Parse(base + "/chat/completions")
41 if r.URL.Path != endpoint.Path {
42 t.Errorf("request path = %q", r.URL.Path)
43 }
44 if id := r.Header.Get("x-opencode-session"); id == "" || (session != "" && id != session) {
45 t.Errorf("missing/unstable session header: %q", id)
46 } else {
47 session = id
48 }
49 if r.Header.Get("User-Agent") != "Reasonix" {
50 t.Error("missing Reasonix client identity")
51 }
52 var body struct {
53 Messages []map[string]json.RawMessage `json:"messages"`
54 }
55 if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
56 t.Errorf("decode request: %v", err)
57 w.WriteHeader(http.StatusBadRequest)
58 return
59 }
60 if requestNumber == 1 {
61 w.Header().Set("Content-Type", "text/event-stream")
62 _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"provider reasoning\"}}]}\n\n")
63 _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"bash\",\"arguments\":\"{}\"}}]}}]}\n\n")
64 _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n")
65 return
66 }
67 for i, message := range body.Messages {
68 if string(message["role"]) == `"assistant"` && string(message["reasoning_content"]) != `"provider reasoning"` {
69 w.WriteHeader(http.StatusBadRequest)
70 _, _ = io.WriteString(w, `{"error":{"message":"Missing reasoning_content on assistant tool call"}}`)
71 return
72 }
73 if string(message["role"]) != `"tool"` {
74 continue
75 }
76 if _, ok := message["name"]; ok {
77 w.WriteHeader(http.StatusBadRequest)
78 _, _ = fmt.Fprintf(w, `{"error":{"message":"messages[%d]: name is not supported by this endpoint"}}`, i)
79 return
80 }
81 if string(message["tool_call_id"]) != `"call_1"` || string(message["content"]) != `"ok"` {
82 t.Errorf("tool result = %v", message)
83 }
84 w.Header().Set("Content-Type", "text/event-stream")
85 _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"done\"}}]}\n\ndata: [DONE]\n\n")
86 return
87 }
88 t.Error("second request missing tool result")
89 w.WriteHeader(http.StatusBadRequest)
90 }))
91 defer srv.Close()
92 target, err := url.Parse(srv.URL)
93 if err != nil {
94 t.Fatal(err)
95 }
96 p, err := New(provider.Config{
97 Name: "opencode-go", BaseURL: base, Model: "deepseek-v4.1-flash", APIKey: "test",
98 HTTPClient: &http.Client{Transport: localOpenCodeGoTransport{target: target}},
99 })
100 if err != nil {
101 t.Fatal(err)
102 }
103 messages := []provider.Message{{Role: provider.RoleUser, Content: "run bash"}}
104 first, err := p.Stream(t.Context(), provider.Request{Messages: messages})
105 if err != nil {
106 t.Fatal(err)
107 }
108 var call *provider.ToolCall
109 var reasoning strings.Builder
110 for chunk := range first {
111 if chunk.Type == provider.ChunkError {
112 t.Fatal(chunk.Err)
113 }
114 if chunk.Type == provider.ChunkToolCall {
115 call = chunk.ToolCall
116 }
117 if chunk.Type == provider.ChunkReasoning {
118 reasoning.WriteString(chunk.Text)
119 }
120 }
121 if call == nil || call.ID != "call_1" || call.Name != "bash" {
122 t.Fatalf("first turn tool call = %+v", call)
123 }
124 messages = append(messages,
125 provider.Message{Role: provider.RoleAssistant, ReasoningContent: reasoning.String(), ToolCalls: []provider.ToolCall{*call}},
126 provider.Message{Role: provider.RoleTool, ToolCallID: call.ID, Name: call.Name, Content: "ok"},
127 )
128 second, err := p.Stream(t.Context(), provider.Request{Messages: messages})
129 if err != nil {
130 t.Fatal(err)
131 }
132 var text strings.Builder
133 for chunk := range second {
134 if chunk.Type == provider.ChunkError {
135 t.Fatal(chunk.Err)
136 }
137 if chunk.Type == provider.ChunkText {
138 text.WriteString(chunk.Text)
139 }
140 }
141 if requests.Load() != 2 || text.String() != "done" {
142 t.Fatalf("requests = %d, second response = %q", requests.Load(), text.String())
143 }
144 }
145
146 func TestOpenCodeGoToolNameOnlyOmittedOnOfficialChatRoute(t *testing.T) {
147 for _, tc := range []struct {
148 name, baseURL, requestURL string
149 wantName bool
150 }{
151 {name: "official chat", baseURL: "https://opencode.ai/zen/go/v1", wantName: false},
152 {name: "official request override", baseURL: "https://gateway.example/v1", requestURL: "https://opencode.ai/zen/go/v1/chat/completions", wantName: false},
153 {name: "custom request override", baseURL: "https://opencode.ai/zen/go/v1", requestURL: "https://gateway.example/v1/chat/completions", wantName: true},
154 {name: "other endpoint", baseURL: "https://api.xiaomimimo.com/v1", wantName: true},
155 } {
156 t.Run(tc.name, func(t *testing.T) {
157 extra := map[string]any{}
158 if tc.requestURL != "" {
159 extra["request_url"] = tc.requestURL
160 }
161 p, err := New(provider.Config{BaseURL: tc.baseURL, Model: "deepseek-v4-flash", Extra: extra})
162 if err != nil {
163 t.Fatal(err)
164 }
165 body, err := json.Marshal(p.(*client).buildRequest(provider.Request{Messages: []provider.Message{
166 {Role: provider.RoleAssistant, ToolCalls: []provider.ToolCall{{ID: "call_1", Name: "bash", Arguments: "{}"}}},
167 {Role: provider.RoleTool, ToolCallID: "call_1", Name: "bash", Content: "ok"},
168 }}))
169 if err != nil {
170 t.Fatal(err)
171 }
172 var wire struct {
173 Messages []map[string]json.RawMessage `json:"messages"`
174 }
175 if err := json.Unmarshal(body, &wire); err != nil {
176 t.Fatal(err)
177 }
178 _, hasName := wire.Messages[1]["name"]
179 if hasName != tc.wantName {
180 t.Fatalf("tool name present = %v, want %v: %s", hasName, tc.wantName, body)
181 }
182 })
183 }
184 }
185
186 func TestOpenCodeGoDeepSeekWireKeepsReasoningAndStableHistory(t *testing.T) {
187 for _, model := range []string{"deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp"} {
188 p, err := New(provider.Config{BaseURL: "https://opencode.ai/zen/go/v1", Model: model, Extra: map[string]any{"request_url": "https://opencode.ai/zen/go/v1/chat/completions", "thinking": "enabled", "effort": "max"}})
189 if err != nil {
190 t.Fatal(err)
191 }
192 c := p.(*client)
193 req := provider.Request{Messages: []provider.Message{{Role: provider.RoleUser, Content: "fixture"}, {Role: provider.RoleAssistant, ReasoningContent: "provider-reasoning", ToolCalls: []provider.ToolCall{{ID: "call-1", Name: "read_file", Arguments: "{}"}}}, {Role: provider.RoleTool, ToolCallID: "call-1", Content: "tool-result"}}, MaxTokens: 128}
194 body := c.buildRequest(req)
195 first, _ := json.Marshal(body)
196 second, _ := json.Marshal(c.buildRequest(req))
197 if !bytes.Equal(first, second) || !bytes.Contains(first, []byte(`"reasoning_effort":"max"`)) || !bytes.Contains(first, []byte(`"reasoning_content":"provider-reasoning"`)) {
198 t.Fatalf("%s lost effort/replay/cache stability: %s", model, first)
199 }
200 }
201 }
202
203 func TestOpenCodeGoV41UsesDeepSeekWireContractWithoutManualOverrides(t *testing.T) {
204 for _, base := range []string{"https://opencode.ai/zen/go/v1", "https://opencode.ai/inference/go/openai/v1"} {
205 p, err := New(provider.Config{BaseURL: base, Model: "deepseek-v4.1-flash"})
206 if err != nil {
207 t.Fatal(err)
208 }
209 c := p.(*client)
210 if !c.RequiresToolCallReasoning() {
211 t.Fatal("V4.1 must preserve provider-issued thinking")
212 }
213 req := provider.Request{Messages: []provider.Message{
214 {Role: provider.RoleUser, Content: "fixture"},
215 {Role: provider.RoleAssistant, Content: "previous answer", ReasoningContent: "previous reasoning"},
216 {Role: provider.RoleUser, Content: "run a tool"},
217 {Role: provider.RoleAssistant, ReasoningContent: "tool reasoning", ToolCalls: []provider.ToolCall{{ID: "call-1", Name: "read_file", Arguments: "{}"}}},
218 {Role: provider.RoleTool, ToolCallID: "call-1", Name: "read_file", Content: "tool-result"},
219 }, MaxTokens: 128}
220 for _, effort := range []string{"", "low", "high", "max", "disabled"} {
221 req.EffortOverride = effort
222 body := c.buildRequest(req)
223 first, err := json.Marshal(body)
224 if err != nil {
225 t.Fatal(err)
226 }
227 second, _ := json.Marshal(c.buildRequest(req))
228 if !bytes.Equal(first, second) || body.Model != "deepseek-v4.1-flash" {
229 t.Fatalf("unstable/rewritten request: %s", first)
230 }
231 wantThinking, wantEffort := "enabled", effort
232 if effort == "" {
233 wantEffort = "high"
234 }
235 if effort == "disabled" {
236 wantThinking, wantEffort = "disabled", ""
237 }
238 if body.Thinking == nil || body.Thinking.Type != wantThinking || body.ReasoningEffort != wantEffort {
239 t.Fatalf("effort %q: %s", effort, first)
240 }
241 for _, expected := range []string{`"reasoning_content":"previous reasoning"`, `"reasoning_content":"tool reasoning"`, `"tool_call_id":"call-1"`} {
242 if !bytes.Contains(first, []byte(expected)) {
243 t.Fatalf("missing %s: %s", expected, first)
244 }
245 }
246 if body.Messages[4].Name != nil {
247 t.Fatalf("tool result included rejected name: %s", first)
248 }
249 }
250 }
251 }
252
252 lines GO