xonecas.io
6312
Ga

go-opencode-ai-zen-sdk / commit a9649b5

feat: streaming api only matching the @ai-sdk implementations

xonecas2026-02-19 a9649b5df2ca262c797695199fef420d3a1ba5d3 parent 0975b2e

24 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+128−86
@@ -8,7 +8,7 @@ Minimal Go SDK for OpenCode Zen.
88 go get github.com/sacenox/go-opencode-ai-zen-sdk
99 ```
1010
11-## Usage
11+## Agent Loop Example (tools + streaming)
1212
1313 ```go
1414 package main
@@ -17,105 +17,152 @@ import (
1717 "context"
1818 "encoding/json"
1919 "fmt"
20+ "strings"
21+ "time"
2022
2123 zen "github.com/sacenox/go-opencode-ai-zen-sdk"
2224 )
2325
26+type toolCall struct {
27+ ID string
28+ Name string
29+ Args strings.Builder
30+ Full string
31+}
32+
2433 func main() {
2534 client, err := zen.NewClient(zen.Config{APIKey: "your-key"})
2635 if err != nil {
2736 panic(err)
2837 }
2938
30- req := zen.UnifiedRequest{
31- Model: "gpt-5.2-codex",
32- Body: map[string]any{
33- "input": "Write a Go hello world",
39+ tools := map[string]func(context.Context, json.RawMessage) (string, error){
40+ "add": func(_ context.Context, args json.RawMessage) (string, error) {
41+ var input struct {
42+ A float64 `json:"a"`
43+ B float64 `json:"b"`
44+ }
45+ if err := json.Unmarshal(args, &input); err != nil {
46+ return "", err
47+ }
48+ return fmt.Sprintf("%.0f", input.A+input.B), nil
3449 },
3550 }
3651
37- resp, err := client.UnifiedCreate(context.Background(), req)
38- if err != nil {
39- panic(err)
52+ messages := []zen.NormalizedMessage{{
53+ Role: "user",
54+ Content: "What is 3 + 4, then double it?",
55+ }}
56+
57+ maxSteps := 6
58+ for step := 0; step < maxSteps; step++ {
59+ req := zen.NormalizedRequest{
60+ Model: "gpt-5.1",
61+ System: "You are a precise assistant. Use tools when needed.",
62+ Messages: messages,
63+ Reasoning: &zen.NormalizedReasoning{Effort: "low"},
64+ Tools: []zen.NormalizedTool{
65+ {
66+ Name: "add",
67+ Description: "Adds two numbers",
68+ Parameters: json.RawMessage(`{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}`),
69+ },
70+ },
71+ ToolChoice: &zen.NormalizedToolChoice{Type: zen.ToolChoiceAuto},
72+ }
73+
74+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
75+ deltas, errs, err := client.Stream(ctx, req)
76+ if err != nil {
77+ cancel()
78+ panic(err)
79+ }
80+
81+ var text strings.Builder
82+ toolCalls := map[int]*toolCall{}
83+ var ordered []*toolCall
84+
85+ for d := range deltas {
86+ switch d.Type {
87+ case zen.DeltaText:
88+ text.WriteString(d.Content)
89+ case zen.DeltaToolCallBegin:
90+ call := &toolCall{ID: d.ToolCallID, Name: d.ToolCallName}
91+ toolCalls[d.ToolCallIndex] = call
92+ ordered = append(ordered, call)
93+ case zen.DeltaToolCallArgumentsDelta:
94+ if call := toolCalls[d.ToolCallIndex]; call != nil {
95+ call.Args.WriteString(d.ArgumentsDelta)
96+ }
97+ case zen.DeltaToolCallDone:
98+ call := toolCalls[d.ToolCallIndex]
99+ if call == nil {
100+ call = &toolCall{}
101+ toolCalls[d.ToolCallIndex] = call
102+ ordered = append(ordered, call)
103+ }
104+ call.ID = d.ToolCallID
105+ call.Name = d.ToolCallName
106+ if d.ArgumentsFull != "" {
107+ call.Full = d.ArgumentsFull
108+ } else {
109+ call.Full = call.Args.String()
110+ }
111+ }
112+ }
113+ if err := <-errs; err != nil {
114+ cancel()
115+ panic(err)
116+ }
117+ cancel()
118+
119+ if len(ordered) == 0 {
120+ messages = append(messages, zen.NormalizedMessage{
121+ Role: "assistant",
122+ Content: text.String(),
123+ })
124+ fmt.Println(text.String())
125+ break
126+ }
127+
128+ assistant := zen.NormalizedMessage{Role: "assistant"}
129+ for _, call := range ordered {
130+ assistant.ToolCalls = append(assistant.ToolCalls, zen.NormalizedToolCall{
131+ ID: call.ID,
132+ Name: call.Name,
133+ Arguments: json.RawMessage(call.Full),
134+ })
135+ }
136+ messages = append(messages, assistant)
137+
138+ for _, call := range ordered {
139+ tool := tools[call.Name]
140+ if tool == nil {
141+ messages = append(messages, zen.NormalizedMessage{
142+ Role: "tool",
143+ ToolCallID: call.ID,
144+ Content: fmt.Sprintf("unknown tool: %s", call.Name),
145+ })
146+ continue
147+ }
148+ result, err := tool(context.Background(), json.RawMessage(call.Full))
149+ if err != nil {
150+ result = "error: " + err.Error()
151+ }
152+ messages = append(messages, zen.NormalizedMessage{
153+ Role: "tool",
154+ ToolCallID: call.ID,
155+ Content: result,
156+ })
157+ }
40158 }
41-
42- var payload map[string]any
43- _ = json.Unmarshal(resp.Body, &payload)
44- fmt.Println(payload)
45-}
46-```
47-
48-## Normalized Request (reasoning + tools)
49-
50-```go
51-req := zen.NormalizedRequest{
52- Model: "gpt-5.2-codex",
53- System: "You are a precise coding assistant.",
54- Messages: []zen.NormalizedMessage{
55- {Role: "user", Content: "Explain what a mutex is."},
56- },
57- Reasoning: &zen.NormalizedReasoning{Effort: "low"},
58- Tools: []zen.NormalizedTool{
59- {
60- Name: "lookup",
61- Description: "Query internal docs",
62- Parameters: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}`),
63- },
64- },
65- ToolChoice: &zen.NormalizedToolChoice{Type: zen.ToolChoiceAuto},
66-}
67-
68-resp, err := client.UnifiedCreateNormalized(ctx, req)
69-if err != nil {
70- panic(err)
71-}
72-fmt.Println(string(resp.Body))
73-```
74-
75-## Gemini (models endpoint)
76-
77-```go
78-req := zen.GeminiRequest{
79- Contents: []zen.GeminiContent{
80- {Role: "user", Parts: []zen.GeminiPart{{Text: "Explain Go interfaces"}}},
81- },
82-}
83-
84-resp, err := client.CreateModelContentTyped(ctx, "gemini-3-pro", req)
85-if err != nil {
86- panic(err)
87-}
88-fmt.Println(string(resp))
89-```
90-
91-## Streaming
92-
93-```go
94-events, errs, err := client.UnifiedStream(ctx, zen.UnifiedRequest{
95- Model: "gpt-5.2-codex",
96- Stream: true,
97- Body: map[string]any{
98- "input": "Stream me a poem",
99- "stream": true,
100- },
101-})
102-if err != nil {
103- panic(err)
104-}
105-
106-for ev := range events {
107- fmt.Println(ev.Event, string(ev.Data))
108-}
109-
110-if err := <-errs; err != nil {
111- panic(err)
112159 }
113160 ```
114161
115162 ## List Models
116163
117164 ```go
118-resp, err := client.ListModels(ctx)
165+resp, err := client.ListModels(context.Background())
119166 if err != nil {
120167 panic(err)
121168 }
@@ -146,9 +193,4 @@ This project is not affiliated with opencode.ai.
146193 set it for streaming calls — `http.Client.Timeout` is a total round-trip deadline
147194 that fires while the SSE body is still being read, causing spurious
148195 `context deadline exceeded (Client.Timeout ...)` errors. Use the request
149- `context.Context` to enforce deadlines instead:
150- ```go
151- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
152- defer cancel()
153- events, errs, err := client.UnifiedStream(ctx, req)
154- ```
196+ `context.Context` to enforce deadlines instead.
auth.go+69−0
@@ -0,0 +1,69 @@
1+package zen
2+
3+import (
4+ "net/http"
5+ "strings"
6+)
7+
8+func (c *Client) applyRequestHeaders(req *http.Request, endpoint EndpointType, streaming bool, forceAllAuth bool) {
9+ if req.Body != nil {
10+ req.Header.Set("Content-Type", "application/json")
11+ }
12+
13+ if streaming {
14+ req.Header.Set("Accept", "text/event-stream")
15+ }
16+
17+ c.applyAuthHeaders(req, endpoint, forceAllAuth)
18+ if endpoint == EndpointMessages {
19+ req.Header.Set("anthropic-version", "2023-06-01")
20+ if streaming {
21+ req.Header.Set("anthropic-beta", "fine-grained-tool-streaming-2025-05-14")
22+ }
23+ }
24+
25+ req.Header.Set("User-Agent", c.cfg.UserAgent)
26+}
27+
28+func (c *Client) applyAuthHeaders(req *http.Request, endpoint EndpointType, forceAll bool) {
29+ if forceAll {
30+ c.setBearer(req)
31+ c.setAPIKey(req)
32+ c.setGoogAPIKey(req)
33+ return
34+ }
35+
36+ switch c.cfg.AuthHeader {
37+ case AuthHeaderBearer:
38+ c.setBearer(req)
39+ case AuthHeaderAPIKey:
40+ c.setAPIKey(req)
41+ case AuthHeaderGoogAPIKey:
42+ c.setGoogAPIKey(req)
43+ default:
44+ switch endpoint {
45+ case EndpointMessages:
46+ c.setAPIKey(req)
47+ case EndpointModels:
48+ c.setGoogAPIKey(req)
49+ default:
50+ c.setBearer(req)
51+ }
52+ }
53+}
54+
55+func (c *Client) setBearer(req *http.Request) {
56+ key := c.cfg.APIKey
57+ if !strings.HasPrefix(strings.ToLower(key), "bearer ") {
58+ key = "Bearer " + key
59+ }
60+ req.Header.Set("Authorization", key)
61+}
62+
63+func (c *Client) setAPIKey(req *http.Request) {
64+ req.Header.Set("x-api-key", c.cfg.APIKey)
65+}
66+
67+func (c *Client) setGoogAPIKey(req *http.Request) {
68+ req.Header.Set("x-goog-api-key", c.cfg.APIKey)
69+}
chat_completions.go+0−55
@@ -1,55 +0,0 @@
1-package zen
2-
3-import (
4- "context"
5- "encoding/json"
6-)
7-
8-func (c *Client) CreateChatCompletion(ctx context.Context, body any, raw json.RawMessage) (json.RawMessage, error) {
9- payload, err := jsonBody(body, raw)
10- if err != nil {
11- return nil, err
12- }
13- data, _, err := c.doRequest(ctx, "POST", "/chat/completions", payload)
14- if err != nil {
15- return nil, err
16- }
17- return json.RawMessage(data), nil
18-}
19-
20-func (c *Client) CreateChatCompletionTyped(ctx context.Context, req ChatCompletionsRequest) (json.RawMessage, error) {
21- return c.CreateChatCompletion(ctx, req, nil)
22-}
23-
24-func (c *Client) StreamChatCompletion(ctx context.Context, body any, raw json.RawMessage) (<-chan StreamEvent, <-chan error, error) {
25- payload, err := jsonBody(body, raw)
26- if err != nil {
27- return nil, nil, err
28- }
29-
30- stream, err := c.startStream(ctx, "POST", "/chat/completions", payload)
31- if err != nil {
32- return nil, nil, err
33- }
34-
35- errs := make(chan error, 1)
36- out := make(chan StreamEvent)
37- go func() {
38- defer close(out)
39- defer close(errs)
40- defer func() { _ = stream.Close() }()
41-
42- for ev := range stream.Events {
43- out <- ev
44- }
45- if stream.Err != nil {
46- errs <- stream.Err
47- }
48- }()
49-
50- return out, errs, nil
51-}
52-
53-func (c *Client) StreamChatCompletionTyped(ctx context.Context, req ChatCompletionsRequest) (<-chan StreamEvent, <-chan error, error) {
54- return c.StreamChatCompletion(ctx, req, nil)
55-}
client.go+2−19
@@ -1,19 +1,6 @@
11 package zen
22
3-import (
4- "context"
5- "net/http"
6- "time"
7-)
8-
9-// defaultResponseHeaderTimeout is applied to the transport of the internally
10-// created HTTP client when the caller does not supply their own *http.Client.
11-// It guards against a server that accepts the TCP connection but never sends
12-// response headers (hung server / network black-hole). It deliberately does
13-// NOT use http.Client.Timeout, which is a total round-trip deadline that fires
14-// while the response body is still being read and therefore kills long-running
15-// SSE streams.
16-const defaultResponseHeaderTimeout = 30 * time.Second
3+import "net/http"
174
185 type Client struct {
196 cfg Config
@@ -37,7 +24,7 @@ func NewClient(cfg Config) (*Client, error) {
3724 } else {
3825 transport = &http.Transport{}
3926 }
40- transport.ResponseHeaderTimeout = defaultResponseHeaderTimeout
27+ transport.ResponseHeaderTimeout = cfg.ResponseHeaderTimeout
4128 httpClient = &http.Client{
4229 Transport: transport,
4330 // cfg.Timeout is 0 by default (unlimited). If the caller sets it
@@ -52,7 +39,3 @@ func NewClient(cfg Config) (*Client, error) {
5239 httpClient: httpClient,
5340 }, nil
5441 }
55-
56-func (c *Client) Do(ctx context.Context, method, path string, body []byte) ([]byte, http.Header, error) {
57- return c.doRequest(ctx, method, path, body)
58-}
cmd/test_models/main.go+61−252
@@ -41,24 +41,18 @@ func main() {
4141 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
4242 defer cancel()
4343
44- var results []testResult
45-
4644 sections := []struct {
4745 name string
4846 fn func(context.Context, *zen.Client, string) testResult
4947 }{
50- {"Non-Streaming", testModel},
51- {"Streaming", testModelStream},
52- {"UnifiedCreate", testUnifiedCreate},
53- {"UnifiedStream", testUnifiedStream},
54- {"UnifiedCreateNormalized", testUnifiedCreateNormalized},
55- {"UnifiedStreamNormalized", testUnifiedStreamNormalized},
56- {"ToolHistory (normalized)", testToolHistoryNormalized},
57- {"ToolHistory (stream)", testToolHistoryNormalizedStream},
58- {"Reasoning (normalized)", testReasoningNormalized},
59- {"Reasoning (stream)", testReasoningNormalizedStream},
48+ {"StreamEvents", testStreamEvents},
49+ {"StreamParsed", testStreamParsed},
50+ {"ToolHistory (stream)", testToolHistoryStream},
51+ {"Reasoning (stream)", testReasoningStream},
6052 }
6153
54+ var results []testResult
55+
6256 for _, s := range sections {
6357 fmt.Printf("=== %s ===\n", s.name)
6458 for _, modelID := range probeModels {
@@ -78,173 +72,60 @@ func main() {
7872 fmt.Printf("=== Summary: %d/%d passed ===\n", successCount, len(results))
7973 for _, r := range results {
8074 if !r.Success {
81- mode := "non-stream"
82- if r.Stream {
83- mode = "stream"
84- }
85- fmt.Printf(" FAILED [%s] %s (%s): %s\n", mode, r.Model, r.Endpoint, r.Error)
75+ fmt.Printf(" FAILED [stream] %s (%s): %s\n", r.Model, r.Endpoint, r.Error)
8676 }
8777 }
8878 }
8979
90-func testModel(ctx context.Context, client *zen.Client, modelID string) testResult {
91- endpoint := routeForModel(modelID)
80+func testStreamEvents(ctx context.Context, client *zen.Client, modelID string) testResult {
9281 start := time.Now()
93-
94- var resp json.RawMessage
95- var err error
96- var reqBody []byte
97-
98- switch endpoint {
99- case "responses":
100- body := map[string]any{"model": modelID, "input": "Say ok"}
101- reqBody, _ = json.Marshal(body)
102- resp, err = client.CreateResponse(ctx, body, nil)
103- case "messages":
104- body := map[string]any{
105- "model": modelID,
106- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
107- "max_tokens": 64,
108- }
109- reqBody, _ = json.Marshal(body)
110- resp, err = client.CreateMessage(ctx, body, nil)
111- case "models":
112- req := zen.GeminiRequest{
113- Contents: []zen.GeminiContent{{Role: "user", Parts: []zen.GeminiPart{{Text: "Say ok"}}}},
114- }
115- reqBody, _ = json.Marshal(req)
116- resp, err = client.CreateModelContentTyped(ctx, modelID, req)
117- default:
118- body := map[string]any{
119- "model": modelID,
120- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
121- }
122- reqBody, _ = json.Marshal(body)
123- resp, err = client.CreateChatCompletion(ctx, body, nil)
124- }
125-
126- return makeResult(modelID, endpoint, false, string(reqBody), string(resp), err, time.Since(start))
127-}
128-
129-func testModelStream(ctx context.Context, client *zen.Client, modelID string) testResult {
13082 endpoint := routeForModel(modelID)
131- start := time.Now()
132-
133- var eventCh <-chan zen.StreamEvent
134- var errCh <-chan error
135- var err error
136- var reqBody []byte
137-
138- switch endpoint {
139- case "responses":
140- body := map[string]any{"model": modelID, "input": "Say ok", "stream": true}
141- reqBody, _ = json.Marshal(body)
142- eventCh, errCh, err = client.StreamResponse(ctx, body, nil)
143- case "messages":
144- body := map[string]any{
145- "model": modelID,
146- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
147- "max_tokens": 64,
148- "stream": true,
149- }
150- reqBody, _ = json.Marshal(body)
151- eventCh, errCh, err = client.StreamMessage(ctx, body, nil)
152- case "models":
153- req := zen.GeminiRequest{
154- Contents: []zen.GeminiContent{{Role: "user", Parts: []zen.GeminiPart{{Text: "Say ok"}}}},
155- }
156- reqBody, _ = json.Marshal(req)
157- eventCh, errCh, err = client.StreamModelContentTyped(ctx, modelID, req)
158- default:
159- body := map[string]any{
160- "model": modelID,
161- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
162- "stream": true,
163- }
164- reqBody, _ = json.Marshal(body)
165- eventCh, errCh, err = client.StreamChatCompletion(ctx, body, nil)
166- }
167-
168- return drainStream(modelID, endpoint, string(reqBody), eventCh, errCh, err, start)
169-}
170-
171-func unifiedBody(modelID string) (any, string) {
172- m := strings.ToLower(strings.TrimSpace(modelID))
173- switch {
174- case strings.HasPrefix(m, "gpt-"):
175- return map[string]any{"model": modelID, "input": "Say ok"}, "responses"
176- case strings.HasPrefix(m, "claude-"):
177- return map[string]any{
178- "model": modelID,
179- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
180- "max_tokens": 64,
181- }, "messages"
182- case strings.HasPrefix(m, "gemini-"):
183- return zen.GeminiRequest{
184- Contents: []zen.GeminiContent{{Role: "user", Parts: []zen.GeminiPart{{Text: "Say ok"}}}},
185- }, "models"
186- default:
187- return map[string]any{
188- "model": modelID,
189- "messages": []map[string]string{{"role": "user", "content": "Say ok"}},
190- }, "chat_completions"
191- }
192-}
193-
194-func testUnifiedCreate(ctx context.Context, client *zen.Client, modelID string) testResult {
195- body, endpoint := unifiedBody(modelID)
196- start := time.Now()
197- reqBody, _ := json.Marshal(body)
198-
199- resp, err := client.UnifiedCreate(ctx, zen.UnifiedRequest{Model: modelID, Body: body})
200- if err != nil {
201- return makeResult(modelID, endpoint, false, string(reqBody), "", err, time.Since(start))
83+ req := zen.NormalizedRequest{
84+ Model: modelID,
85+ Messages: []zen.NormalizedMessage{{Role: "user", Content: "Say ok"}},
20286 }
203- return makeResult(modelID, string(resp.Endpoint), false, string(reqBody), truncate(string(resp.Body), 100), nil, time.Since(start))
204-}
205-
206-func testUnifiedStream(ctx context.Context, client *zen.Client, modelID string) testResult {
207- body, endpoint := unifiedBody(modelID)
208- start := time.Now()
209- reqBody, _ := json.Marshal(body)
87+ reqBody, _ := json.Marshal(req)
21088
211- eventCh, errCh, err := client.UnifiedStream(ctx, zen.UnifiedRequest{Model: modelID, Body: body, Stream: true})
89+ eventCh, errCh, err := client.StreamEvents(ctx, req)
21290 return drainUnifiedStream(modelID, endpoint, string(reqBody), eventCh, errCh, err, start)
21391 }
21492
215-func testUnifiedCreateNormalized(ctx context.Context, client *zen.Client, modelID string) testResult {
93+func testStreamParsed(ctx context.Context, client *zen.Client, modelID string) testResult {
94+ start := time.Now()
95+ endpoint := routeForModel(modelID)
21696 req := zen.NormalizedRequest{
21797 Model: modelID,
21898 Messages: []zen.NormalizedMessage{{Role: "user", Content: "Say ok"}},
21999 }
220- start := time.Now()
221100 reqBody, _ := json.Marshal(req)
222101
223- resp, err := client.UnifiedCreateNormalized(ctx, req)
102+ deltaCh, errCh, err := client.Stream(ctx, req)
224103 if err != nil {
225- return makeResult(modelID, "auto", false, string(reqBody), "", err, time.Since(start))
104+ return makeResult(modelID, endpoint, true, string(reqBody), "", err, time.Since(start))
226105 }
227- return makeResult(modelID, string(resp.Endpoint), false, string(reqBody), truncate(string(resp.Body), 100), nil, time.Since(start))
228-}
229106
230-func testUnifiedStreamNormalized(ctx context.Context, client *zen.Client, modelID string) testResult {
231- req := zen.NormalizedRequest{
232- Model: modelID,
233- Messages: []zen.NormalizedMessage{{Role: "user", Content: "Say ok"}},
234- Stream: true,
107+ var textBuf, reasoningBuf strings.Builder
108+ var count int
109+ for d := range deltaCh {
110+ count++
111+ switch d.Type {
112+ case zen.DeltaText:
113+ textBuf.WriteString(d.Content)
114+ case zen.DeltaReasoning:
115+ reasoningBuf.WriteString(d.Content)
116+ }
117+ }
118+ if streamErr := <-errCh; streamErr != nil {
119+ return makeResult(modelID, endpoint, true, string(reqBody), "", streamErr, time.Since(start))
235120 }
236- start := time.Now()
237- reqBody, _ := json.Marshal(req)
238121
239- eventCh, errCh, err := client.UnifiedStreamNormalized(ctx, req)
240- return drainUnifiedStream(modelID, "auto", string(reqBody), eventCh, errCh, err, start)
122+ resp := fmt.Sprintf("deltas=%d text=%s reasoning=%s", count, truncate(textBuf.String(), 40), truncate(reasoningBuf.String(), 40))
123+ return makeResult(modelID, endpoint, true, string(reqBody), resp, nil, time.Since(start))
241124 }
242125
243126 // toolHistory returns a pre-built two-turn tool-use conversation:
244127 //
245128 // user → assistant+tool_call → tool_result → user follow-up
246-//
247-// The model is expected to incorporate the tool result in its reply.
248129 func toolHistory() []zen.NormalizedMessage {
249130 return []zen.NormalizedMessage{
250131 {Role: "user", Content: "What is 3 + 4?"},
@@ -259,7 +140,9 @@ func toolHistory() []zen.NormalizedMessage {
259140 }
260141 }
261142
262-func testToolHistoryNormalized(ctx context.Context, client *zen.Client, modelID string) testResult {
143+func testToolHistoryStream(ctx context.Context, client *zen.Client, modelID string) testResult {
144+ start := time.Now()
145+ endpoint := routeForModel(modelID)
263146 req := zen.NormalizedRequest{
264147 Model: modelID,
265148 System: "You are a calculator assistant. When given a tool result, use it to answer the user.",
@@ -272,80 +155,46 @@ func testToolHistoryNormalized(ctx context.Context, client *zen.Client, modelID
272155 },
273156 },
274157 }
275- start := time.Now()
276158 reqBody, _ := json.Marshal(req)
277159
278- resp, err := client.UnifiedCreateNormalized(ctx, req)
160+ deltaCh, errCh, err := client.Stream(ctx, req)
279161 if err != nil {
280- return makeResult(modelID, "auto", false, string(reqBody), "", err, time.Since(start))
162+ return makeResult(modelID, endpoint, true, string(reqBody), "", err, time.Since(start))
281163 }
282- return makeResult(modelID, string(resp.Endpoint), false, string(reqBody), truncate(string(resp.Body), 100), nil, time.Since(start))
283-}
284164
285-func testToolHistoryNormalizedStream(ctx context.Context, client *zen.Client, modelID string) testResult {
286- req := zen.NormalizedRequest{
287- Model: modelID,
288- System: "You are a calculator assistant. When given a tool result, use it to answer the user.",
289- Messages: toolHistory(),
290- Tools: []zen.NormalizedTool{
291- {
292- Name: "add",
293- Description: "Adds two numbers",
294- Parameters: json.RawMessage(`{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}`),
295- },
296- },
297- Stream: true,
165+ var textBuf strings.Builder
166+ var count int
167+ for d := range deltaCh {
168+ count++
169+ if d.Type == zen.DeltaText {
170+ textBuf.WriteString(d.Content)
171+ }
298172 }
299- start := time.Now()
300- reqBody, _ := json.Marshal(req)
301-
302- eventCh, errCh, err := client.UnifiedStreamNormalized(ctx, req)
303- return drainUnifiedStream(modelID, "auto", string(reqBody), eventCh, errCh, err, start)
304-}
305-
306-func testReasoningNormalized(ctx context.Context, client *zen.Client, modelID string) testResult {
307- req := zen.NormalizedRequest{
308- Model: modelID,
309- Messages: []zen.NormalizedMessage{{Role: "user", Content: "What is 2 + 2? Think step by step."}},
310- Reasoning: &zen.NormalizedReasoning{Effort: "low"},
173+ if streamErr := <-errCh; streamErr != nil {
174+ return makeResult(modelID, endpoint, true, string(reqBody), "", streamErr, time.Since(start))
311175 }
312- start := time.Now()
313- reqBody, _ := json.Marshal(req)
314176
315- resp, err := client.UnifiedCreateNormalized(ctx, req)
316- if err != nil {
317- return makeResult(modelID, "auto", false, string(reqBody), "", err, time.Since(start))
318- }
319- // Parse the response body to check for reasoning content.
320- hasReasoning := responseHasReasoning(resp.Body)
321- summary := truncate(string(resp.Body), 100)
322- if !hasReasoning {
323- return makeResult(modelID, string(resp.Endpoint), false, string(reqBody),
324- "no reasoning content in response: "+summary,
325- fmt.Errorf("model %s: response contained no reasoning/thinking content", modelID),
326- time.Since(start))
327- }
328- return makeResult(modelID, string(resp.Endpoint), false, string(reqBody), summary, nil, time.Since(start))
177+ resp := fmt.Sprintf("deltas=%d text=%s", count, truncate(textBuf.String(), 60))
178+ return makeResult(modelID, endpoint, true, string(reqBody), resp, nil, time.Since(start))
329179 }
330180
331-func testReasoningNormalizedStream(ctx context.Context, client *zen.Client, modelID string) testResult {
181+func testReasoningStream(ctx context.Context, client *zen.Client, modelID string) testResult {
182+ start := time.Now()
183+ endpoint := routeForModel(modelID)
332184 req := zen.NormalizedRequest{
333185 Model: modelID,
334186 Messages: []zen.NormalizedMessage{{Role: "user", Content: "What is 2 + 2? Think step by step."}},
335187 Reasoning: &zen.NormalizedReasoning{Effort: "low"},
336- Stream: true,
337188 }
338- start := time.Now()
339189 reqBody, _ := json.Marshal(req)
340190
341- deltaCh, errCh, err := client.UnifiedStreamNormalizedParsed(ctx, req)
191+ deltaCh, errCh, err := client.Stream(ctx, req)
342192 if err != nil {
343- return makeResult(modelID, "auto", true, string(reqBody), "", err, time.Since(start))
193+ return makeResult(modelID, endpoint, true, string(reqBody), "", err, time.Since(start))
344194 }
345195
346196 var textBuf, reasoningBuf strings.Builder
347197 var deltaCount int
348- var resolvedEndpoint string
349198 for d := range deltaCh {
350199 deltaCount++
351200 switch d.Type {
@@ -356,17 +205,16 @@ func testReasoningNormalizedStream(ctx context.Context, client *zen.Client, mode
356205 }
357206 }
358207 if streamErr := <-errCh; streamErr != nil {
359- return makeResult(modelID, "auto", true, string(reqBody), "", streamErr, time.Since(start))
208+ return makeResult(modelID, endpoint, true, string(reqBody), "", streamErr, time.Since(start))
360209 }
361- _ = resolvedEndpoint
362210
363211 if reasoningBuf.Len() == 0 {
364- return makeResult(modelID, "auto", true, string(reqBody),
212+ return makeResult(modelID, endpoint, true, string(reqBody),
365213 fmt.Sprintf("deltas=%d text=%s", deltaCount, truncate(textBuf.String(), 60)),
366214 fmt.Errorf("model %s: stream contained no reasoning/thinking deltas", modelID),
367215 time.Since(start))
368216 }
369- return makeResult(modelID, "auto", true, string(reqBody),
217+ return makeResult(modelID, endpoint, true, string(reqBody),
370218 fmt.Sprintf("deltas=%d reasoning=%s text=%s",
371219 deltaCount,
372220 truncate(reasoningBuf.String(), 40),
@@ -374,45 +222,6 @@ func testReasoningNormalizedStream(ctx context.Context, client *zen.Client, mode
374222 nil, time.Since(start))
375223 }
376224
377-// responseHasReasoning checks whether a raw JSON response body from any endpoint
378-// contains reasoning or thinking content.
379-func responseHasReasoning(body json.RawMessage) bool {
380- // Generic scan: look for non-empty reasoning/thinking fields across all formats.
381- // chat_completions: choices[].message.reasoning_content
382- // responses: output[].content[].type == "reasoning"
383- // messages: content[].type == "thinking"
384- // gemini: candidates[].content.parts[].thought == true
385- var v map[string]json.RawMessage
386- if err := json.Unmarshal(body, &v); err != nil {
387- return false
388- }
389- raw := string(body)
390- return strings.Contains(raw, `"reasoning_content"`) ||
391- strings.Contains(raw, `"thinking"`) ||
392- strings.Contains(raw, `"thought":true`) ||
393- strings.Contains(raw, `"type":"reasoning"`) ||
394- strings.Contains(raw, `"type":"thinking"`)
395-}
396-
397-// drainStream consumes a StreamEvent channel and builds a testResult.
398-func drainStream(modelID, endpoint, reqBody string, eventCh <-chan zen.StreamEvent, errCh <-chan error, initErr error, start time.Time) testResult {
399- if initErr != nil {
400- return makeResult(modelID, endpoint, true, reqBody, "", initErr, time.Since(start))
401- }
402- var count int
403- var last string
404- for ev := range eventCh {
405- count++
406- if len(ev.Data) > 0 {
407- last = string(ev.Data)
408- }
409- }
410- if err := <-errCh; err != nil {
411- return makeResult(modelID, endpoint, true, reqBody, "", err, time.Since(start))
412- }
413- return makeResult(modelID, endpoint, true, reqBody, fmt.Sprintf("events=%d last=%s", count, truncate(last, 80)), nil, time.Since(start))
414-}
415-
416225 // drainUnifiedStream consumes a UnifiedEvent channel and builds a testResult.
417226 func drainUnifiedStream(modelID, endpoint, reqBody string, eventCh <-chan zen.UnifiedEvent, errCh <-chan error, initErr error, start time.Time) testResult {
418227 if initErr != nil {
@@ -456,6 +265,9 @@ func makeResult(modelID, endpoint string, stream bool, req, resp string, err err
456265
457266 func routeForModel(model string) string {
458267 m := strings.ToLower(strings.TrimSpace(model))
268+ if strings.HasPrefix(m, "opencode/") {
269+ m = strings.TrimPrefix(m, "opencode/")
270+ }
459271 switch {
460272 case strings.HasPrefix(m, "gpt-"):
461273 return "responses"
@@ -473,10 +285,7 @@ func printResult(r testResult) {
473285 if !r.Success {
474286 status = "✗"
475287 }
476- mode := "non-stream"
477- if r.Stream {
478- mode = "stream"
479- }
288+ mode := "stream"
480289 fmt.Printf(" %s %-25s [%-15s] [%-10s] %v\n", status, r.Model, r.Endpoint, mode, r.Latency)
481290 }
482291
config.go+24−8
@@ -15,6 +15,15 @@ type RetryConfig struct {
1515 Backoff func(attempt int) time.Duration
1616 }
1717
18+type AuthHeader string
19+
20+const (
21+ AuthHeaderAuto AuthHeader = "auto"
22+ AuthHeaderBearer AuthHeader = "authorization"
23+ AuthHeaderAPIKey AuthHeader = "x-api-key"
24+ AuthHeaderGoogAPIKey AuthHeader = "x-goog-api-key"
25+)
26+
1827 type Config struct {
1928 APIKey string
2029 BaseURL string
@@ -28,14 +37,17 @@ type Config struct {
2837 // Leave at 0 (the default) for streaming calls and enforce deadlines via
2938 // the request context instead (e.g. context.WithTimeout / WithDeadline).
3039 //
31- // The internal transport always applies a 30-second
32- // ResponseHeaderTimeout independently of this field, protecting against
33- // servers that accept the connection but never send headers. This field
34- // has no effect when HTTPClient is supplied by the caller.
35- Timeout time.Duration
36- UserAgent string
37- HTTPClient *http.Client
38- Retry RetryConfig
40+ // ResponseHeaderTimeout sets http.Transport.ResponseHeaderTimeout on the
41+ // internal HTTP client. Leave at 0 (the default) to match fetch behavior
42+ // and avoid aborting slow-starting streaming responses.
43+ //
44+ // This field has no effect when HTTPClient is supplied by the caller.
45+ ResponseHeaderTimeout time.Duration
46+ Timeout time.Duration
47+ UserAgent string
48+ HTTPClient *http.Client
49+ Retry RetryConfig
50+ AuthHeader AuthHeader
3951 }
4052
4153 func (c *Config) applyDefaults() error {
@@ -53,6 +65,10 @@ func (c *Config) applyDefaults() error {
5365 c.UserAgent = "go-opencode-zen-sdk/0.1"
5466 }
5567
68+ if c.AuthHeader == "" {
69+ c.AuthHeader = AuthHeaderAuto
70+ }
71+
5672 if c.Retry.Backoff == nil {
5773 c.Retry.Backoff = func(attempt int) time.Duration {
5874 base := 200 * time.Millisecond
docs/gemini-streaming-workaround.md+0−242
@@ -1,242 +0,0 @@
1-# Gemini: Streaming Workaround for the Zen Proxy
2-
3-## Background
4-
5-The opencode zen proxy (`https://opencode.ai/zen/v1`) is a server-side gateway that
6-translates between the native wire formats of different AI providers and a unified
7-request/response model used by the opencode platform. Clients send requests to
8-provider-specific endpoint prefixes and the proxy forwards them to the correct
9-upstream API, handles authentication, tracks usage for billing, and converts
10-responses back.
11-
12-The three main endpoint families are:
13-
14-| Prefix | Provider | Auth header |
15-|---------------------|-----------|---------------------|
16-| `/responses` | OpenAI | `Authorization: Bearer` |
17-| `/messages` | Anthropic | `x-api-key` |
18-| `/models/<model>` | Google | `x-goog-api-key` |
19-
20-Gemini models are accessed through the `/models/<model>` prefix. The proxy route
21-that handles this is a SolidStart dynamic segment (`[model].ts`) which reads the
22-model name from the URL and dispatches to the `googleHelper` provider adapter.
23-
24----
25-
26-## The Bug
27-
28-### Server-side: `json.usage` vs `json.usageMetadata`
29-
30-The zen proxy's central request handler (`handler.ts`) has a single code path for
31-non-streaming responses:
32-
33-```typescript
34-// handler.ts ~line 190
35-if (!isStream) {
36- const json = await res.json()
37- const usageInfo = providerInfo.normalizeUsage(json.usage) // <-- BUG
38- ...
39-}
40-```
41-
42-`json.usage` is the field name used by OpenAI-style responses. Gemini's upstream
43-API, however, places token counts inside a different field called `usageMetadata`:
44-
45-```json
46-{
47- "candidates": [...],
48- "usageMetadata": {
49- "promptTokenCount": 11,
50- "candidatesTokenCount": 3,
51- "totalTokenCount": 14
52- }
53-}
54-```
55-
56-When the proxy calls `normalizeUsage(json.usage)` for a Gemini response,
57-`json.usage` is `undefined`. The `googleHelper.normalizeUsage` function then
58-immediately tries to read `usage.promptTokenCount`, which throws:
59-
60-```
61-Cannot read properties of undefined (reading 'promptTokenCount')
62-```
63-
64-The proxy returns this as an HTTP 500 to the client.
65-
66-### Client-side: hardcoded `Authorization: Bearer` in streaming
67-
68-A second, independent bug existed in this SDK's own `startStream` function
69-(`stream.go`). It hardcoded the OpenAI-style authorization header for all
70-requests, regardless of provider:
71-
72-```go
73-// stream.go (before fix)
74-req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
75-```
76-
77-The non-streaming `doRequest` function in `http.go` already had the correct
78-per-provider routing:
79-
80-```go
81-switch {
82-case strings.HasPrefix(path, "/messages"):
83- req.Header.Set("x-api-key", c.cfg.APIKey)
84-case strings.HasPrefix(path, "/models/") && strings.Contains(path, "gemini"):
85- req.Header.Set("x-goog-api-key", c.cfg.APIKey)
86-default:
87- req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
88-}
89-```
90-
91-But `startStream` bypassed `doRequest` entirely and opened its own `http.Request`,
92-so this routing logic was never applied. Any streaming Gemini call would send
93-`Authorization: Bearer <key>` and be rejected by the proxy's authentication layer.
94-
95----
96-
97-## Why the opencode CLI Was Not Affected
98-
99-The opencode CLI uses `@ai-sdk/google` (the Vercel AI SDK's Google adapter) to
Cut short: this commit's diff is over 1000 lines.
docs/normalized-stream-parsing.md+0−72
Cut short: this commit's diff is over 1000 lines.
gemini.go+0−79
Cut short: this commit's diff is over 1000 lines.
http.go+2−13
Cut short: this commit's diff is over 1000 lines.
messages.go+0−55
Cut short: this commit's diff is over 1000 lines.
models.go+1−1
Cut short: this commit's diff is over 1000 lines.
normalize_helpers_test.go+2−2
Cut short: this commit's diff is over 1000 lines.
normalized.go+84−20
Cut short: this commit's diff is over 1000 lines.
normalized_test.go+8−2
Cut short: this commit's diff is over 1000 lines.
parse.go+1−1
Cut short: this commit's diff is over 1000 lines.
parse_test.go+13−13
Cut short: this commit's diff is over 1000 lines.
responses.go+0−55
Cut short: this commit's diff is over 1000 lines.
stream.go+2−14
Cut short: this commit's diff is over 1000 lines.
stream_test.go+6−6
Cut short: this commit's diff is over 1000 lines.
types_gemini.go+3−1
Cut short: this commit's diff is over 1000 lines.
types_responses.go+9−3
Cut short: this commit's diff is over 1000 lines.
unified.go+71−197
Cut short: this commit's diff is over 1000 lines.
unified_test.go+23−14
Cut short: this commit's diff is over 1000 lines.