1package provider
2
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "runtime"
12 "strings"
13 "time"
14)
15
16// Codex (ChatGPT subscription) client. Uses OpenAI's Responses API via
17// chatgpt.com/backend-api with the chatgpt-account-id handshake.
18//
19// Wire protocol notes:
20// - Endpoint: POST https://chatgpt.com/backend-api/codex/responses
21// - Headers: Authorization: Bearer <access_token>, chatgpt-account-id: <id>,
22// OpenAI-Beta: responses=experimental, originator: zot
23// - Body: OpenAI Responses API shape (not chat/completions).
24// input: [{role, content: [{type: "input_text" | "input_image" | ... }]}]
25// instructions: <system prompt>
26// tools: [{type:"function", name, description, parameters, strict}]
27// stream: true
28// - SSE events: response.output_item.added, response.output_text.delta,
29// response.function_call_arguments.delta, response.output_item.done,
30// response.completed, response.failed, error
31//
32// The access_token comes from the OpenAI OAuth flow (auth.openai.com).
33// The accountID is parsed from the id_token JWT's `chatgpt_account_id`
34// claim; see auth/oauth.go.
35
36const codexDefaultBaseURL = "https://chatgpt.com/backend-api/codex/responses"
37
38type codexClient struct {
39 token string
40 accountID string
41 baseURL string
42 http *http.Client
43}
44
45// NewOpenAICodex creates a client that talks to ChatGPT's Codex endpoint
46// using a subscription OAuth access token and the user's ChatGPT
47// account id. baseURL may be empty to use the default.
48func NewOpenAICodex(token, accountID, baseURL string) Client {
49 if baseURL == "" {
50 baseURL = codexDefaultBaseURL
51 }
52 return &codexClient{
53 token: token,
54 accountID: accountID,
55 baseURL: strings.TrimRight(baseURL, "/"),
56 http: &http.Client{Timeout: 0},
57 }
58}
59
60func (c *codexClient) Name() string { return "openai-codex" }
61
62// ---- Responses API wire types (subset needed for zot's surface) ----
63
64type codexInputText struct {
65 Type string `json:"type"` // "input_text"
66 Text string `json:"text"`
67}
68
69type codexInputImage struct {
70 Type string `json:"type"` // "input_image"
71 Detail string `json:"detail"`
72 ImageURL string `json:"image_url"`
73}
74
75type codexOutputText struct {
76 Type string `json:"type"` // "output_text"
77 Text string `json:"text"`
78 Annotations []any `json:"annotations"`
79}
80
81type codexInputMessage struct {
82 Type string `json:"type,omitempty"` // "message" (optional for input)
83 Role string `json:"role"`
84 Content []any `json:"content"`
85}
86
87type codexOutputMessage struct {
88 Type string `json:"type"` // "message"
89 Role string `json:"role"`
90 Status string `json:"status,omitempty"`
91 ID string `json:"id,omitempty"`
92 Content []codexOutputText `json:"content"`
93}
94
95type codexFunctionCall struct {
96 Type string `json:"type"` // "function_call"
97 ID string `json:"id,omitempty"`
98 CallID string `json:"call_id"`
99 Name string `json:"name"`
100 Arguments string `json:"arguments"` // JSON string
101}
102
103type codexFunctionCallOutput struct {
104 Type string `json:"type"` // "function_call_output"
105 CallID string `json:"call_id"`
106 Output string `json:"output"` // string (or ResponseFunctionCallOutputItemList for images; v1 only uses string)
107}
108
109// codexReasoningItem mirrors the Responses API "reasoning" output item.
110// We capture it on incoming streams and replay it verbatim on follow-up
111// requests: the API rejects assistant tool-call replays without it when
112// thinking is enabled.
113type codexReasoningItem struct {
114 Type string `json:"type"` // "reasoning"
115 ID string `json:"id,omitempty"`
116 EncryptedContent string `json:"encrypted_content,omitempty"`
117 // Summary is required by the Responses API even when no summary text
118 // was streamed; encode an empty array rather than omitting the field.
119 Summary []codexReasoningSummary `json:"summary"`
120}
121
122type codexReasoningSummary struct {
123 Type string `json:"type"` // "summary_text"
124 Text string `json:"text"`
125}
126
127type codexTool struct {
128 Type string `json:"type"` // "function"
129 Name string `json:"name"`
130 Description string `json:"description,omitempty"`
131 Parameters json.RawMessage `json:"parameters"`
132}
133
134type codexRequest struct {
135 Model string `json:"model"`
136 Store bool `json:"store"`
137 Stream bool `json:"stream"`
138 Instructions string `json:"instructions,omitempty"`
139 Input []any `json:"input"`
140 Tools []codexTool `json:"tools,omitempty"`
141 ToolChoice string `json:"tool_choice,omitempty"`
142 ParallelToolCalls bool `json:"parallel_tool_calls"`
143 Include []string `json:"include,omitempty"`
144}
145
146// ---- Request building ----
147
148func (c *codexClient) buildRequest(req Request) (*codexRequest, error) {
149 m, err := FindModel("openai-codex", req.Model)
150 if err != nil {
151 m, err = FindModel("openai", req.Model)
152 }
153 if err != nil {
154 return nil, err
155 }
156 _ = m
157
158 body := &codexRequest{
159 Model: req.Model,
160 Store: false,
161 Stream: true,
162 Instructions: req.System,
163 ParallelToolCalls: true,
164 Include: []string{"reasoning.encrypted_content"},
165 }
166 if len(req.Tools) > 0 {
167 body.ToolChoice = "auto"
168 for _, t := range req.Tools {
169 params := t.Schema
170 if len(params) == 0 {
171 params = json.RawMessage(`{"type":"object","properties":{}}`)
172 }
173 body.Tools = append(body.Tools, codexTool{
174 Type: "function",
175 Name: t.Name,
176 Description: t.Description,
177 Parameters: params,
178 })
179 }
180 }
181
182 msgIdx := 0
183 req.Messages = RepairOrphanedToolResults(req.Messages)
184 for _, msg := range req.Messages {
185 switch msg.Role {
186 case RoleUser:
187 content := []any{}
188 for _, c := range msg.Content {
189 switch v := c.(type) {
190 case TextBlock:
191 if v.Text != "" {
192 content = append(content, codexInputText{Type: "input_text", Text: v.Text})
193 }
194 case ImageBlock:
195 url := "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
196 content = append(content, codexInputImage{Type: "input_image", Detail: "auto", ImageURL: url})
197 }
198 }
199 if len(content) == 0 {
200 continue
201 }
202 body.Input = append(body.Input, codexInputMessage{Role: "user", Content: content})
203 case RoleAssistant:
204 // Emit one output_message per text block, one function_call per
205 // tool call, and one reasoning item per ReasoningBlock,
206 // preserving the order so the model sees the same interleaving
207 // we captured. The reasoning replay is what keeps OpenAI
208 // Codex from rejecting follow-up tool calls with
209 // "thinking is enabled but reasoning_content is missing".
210 for _, c := range msg.Content {
211 switch v := c.(type) {
212 case ReasoningBlock:
213 item := codexReasoningItem{
214 Type: "reasoning",
215 ID: v.ID,
216 EncryptedContent: v.Encrypted,
217 Summary: []codexReasoningSummary{},
218 }
219 if v.Summary != "" {
220 item.Summary = []codexReasoningSummary{{Type: "summary_text", Text: v.Summary}}
221 }
222 body.Input = append(body.Input, item)
223 case TextBlock:
224 if v.Text == "" {
225 continue
226 }
227 msgIdx++
228 body.Input = append(body.Input, codexOutputMessage{
229 Type: "message",
230 Role: "assistant",
231 Status: "completed",
232 ID: fmt.Sprintf("msg_%d", msgIdx),
233 Content: []codexOutputText{
234 {Type: "output_text", Text: v.Text, Annotations: []any{}},
235 },
236 })
237 case ToolCallBlock:
238 args := string(v.Arguments)
239 if args == "" || !json.Valid([]byte(args)) {
240 args = "{}"
241 }
242 callID, _ := splitCallID(v.ID)
243 body.Input = append(body.Input, codexFunctionCall{
244 Type: "function_call",
245 CallID: callID,
246 Name: v.Name,
247 Arguments: args,
248 })
249 }
250 }
251 case RoleTool:
252 for _, c := range msg.Content {
253 if tr, ok := c.(ToolResultBlock); ok {
254 var text strings.Builder
255 for _, inner := range tr.Content {
256 if tb, ok := inner.(TextBlock); ok {
257 if text.Len() > 0 {
258 text.WriteString("\n")
259 }
260 text.WriteString(tb.Text)
261 }
262 }
263 callID, _ := splitCallID(tr.CallID)
264 body.Input = append(body.Input, codexFunctionCallOutput{
265 Type: "function_call_output",
266 CallID: callID,
267 Output: text.String(),
268 })
269 }
270 }
271 }
272 }
273
274 return body, nil
275}
276
277func splitCallID(id string) (string, string) {
278 if i := strings.Index(id, "|"); i >= 0 {
279 return id[:i], id[i+1:]
280 }
281 return id, ""
282}
283
284// ---- Streaming ----
285
286func (c *codexClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
287 wire, err := c.buildRequest(req)
288 if err != nil {
289 return nil, err
290 }
291 body, err := json.Marshal(wire)
292 if err != nil {
293 return nil, err
294 }
295
296 newReq := func() (*http.Request, error) {
297 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
298 if err != nil {
299 return nil, err
300 }
301 httpReq.Header.Set("content-type", "application/json")
302 httpReq.Header.Set("accept", "text/event-stream")
303 httpReq.Header.Set("authorization", "Bearer "+c.token)
304 httpReq.Header.Set("chatgpt-account-id", c.accountID)
305 httpReq.Header.Set("openai-beta", "responses=experimental")
306 httpReq.Header.Set("originator", "zot")
307 httpReq.Header.Set("user-agent", fmt.Sprintf("zot (%s %s)", runtime.GOOS, runtime.GOARCH))
308 return httpReq, nil
309 }
310
311 resp, err := doStreamWithRetry(ctx, c.http, newReq)
312 if err != nil {
313 return nil, fmt.Errorf("openai-codex: %w", err)
314 }
315 if resp.StatusCode != http.StatusOK {
316 b, _ := io.ReadAll(resp.Body)
317 resp.Body.Close()
318 return nil, fmt.Errorf("openai-codex: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
319 }
320
321 out := make(chan Event, 16)
322 go c.runStream(ctx, resp, req, out)
323 return out, nil
324}
325
326func (c *codexClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
327 defer close(out)
328 defer resp.Body.Close()
329
330 model, _ := FindModel("openai-codex", req.Model)
331 if model.ID == "" {
332 model, _ = FindModel("openai", req.Model)
333 }
334 out <- EventStart{Model: req.Model, Provider: "openai-codex"}
335
336 raw := make(chan sseEvent, 16)
337 go readSSE(resp.Body, raw)
338
339 // Accumulators. The Responses API emits output_items in order; each
340 // item is either a "message" (text) or a "function_call". We track
341 // the in-flight item by its index.
342 type itemState struct {
343 kind string // "message" | "function_call" | "reasoning"
344 callID string
345 name string
346 argsBuf strings.Builder
347 textBuf strings.Builder
348 summary strings.Builder
349 rawID string
350 encrypted string
351 announced bool
352 }
353 var (
354 items = map[int]*itemState{}
355 order []int
356 usage Usage
357 stop StopReason = StopEnd
358 finalErr error
359 )
360
361 assemble := func() Message {
362 content := []Content{}
363 for _, idx := range order {
364 it := items[idx]
365 switch it.kind {
366 case "message":
367 if it.textBuf.Len() > 0 {
368 content = append(content, TextBlock{Text: it.textBuf.String()})
369 }
370 case "function_call":
371 args := it.argsBuf.String()
372 if args == "" || !json.Valid([]byte(args)) {
373 args = "{}"
374 }
375 content = append(content, ToolCallBlock{
376 ID: it.callID, Name: it.name, Arguments: json.RawMessage(args),
377 })
378 case "reasoning":
379 if it.encrypted == "" && it.summary.Len() == 0 && it.rawID == "" {
380 continue
381 }
382 content = append(content, ReasoningBlock{
383 ID: it.rawID,
384 Summary: it.summary.String(),
385 Encrypted: it.encrypted,
386 })
387 }
388 }
389 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
390 }
391
392 sendDone := func() {
393 usage.CostUSD = ComputeCost(model, usage)
394 out <- EventUsage{Usage: usage}
395 out <- EventDone{Stop: stop, Err: finalErr, Message: assemble()}
396 }
397
398 for {
399 select {
400 case <-ctx.Done():
401 stop = StopAborted
402 finalErr = ctx.Err()
403 sendDone()
404 return
405 case ev, ok := <-raw:
406 if !ok {
407 sendDone()
408 return
409 }
410 var head struct {
411 Type string `json:"type"`
412 }
413 if err := json.Unmarshal([]byte(ev.Data), &head); err != nil {
414 continue
415 }
416
417 switch head.Type {
418 case "response.output_item.added":
419 var p struct {
420 OutputIndex int `json:"output_index"`
421 Item struct {
422 Type string `json:"type"` // "message" | "function_call" | "reasoning"
423 ID string `json:"id"`
424 CallID string `json:"call_id"`
425 Name string `json:"name"`
426 EncryptedContent string `json:"encrypted_content"`
427 } `json:"item"`
428 }
429 _ = json.Unmarshal([]byte(ev.Data), &p)
430 it := &itemState{}
431 switch p.Item.Type {
432 case "message":
433 it.kind = "message"
434 case "function_call":
435 it.kind = "function_call"
436 it.callID = p.Item.CallID
437 it.name = p.Item.Name
438 if !it.announced {
439 it.announced = true
440 out <- EventToolStart{ID: it.callID, Name: it.name}
441 }
442 case "reasoning":
443 it.kind = "reasoning"
444 it.rawID = p.Item.ID
445 it.encrypted = p.Item.EncryptedContent
446 default:
447 continue
448 }
449 items[p.OutputIndex] = it
450 order = append(order, p.OutputIndex)
451 case "response.output_text.delta":
452 var p struct {
453 OutputIndex int `json:"output_index"`
454 Delta string `json:"delta"`
455 }
456 _ = json.Unmarshal([]byte(ev.Data), &p)
457 if it, ok := items[p.OutputIndex]; ok && it.kind == "message" {
458 it.textBuf.WriteString(p.Delta)
459 out <- EventTextDelta{Delta: p.Delta}
460 }
461 case "response.reasoning_summary_text.delta":
462 var p struct {
463 OutputIndex int `json:"output_index"`
464 Delta string `json:"delta"`
465 }
466 _ = json.Unmarshal([]byte(ev.Data), &p)
467 if it, ok := items[p.OutputIndex]; ok && it.kind == "reasoning" {
468 it.summary.WriteString(p.Delta)
469 }
470 case "response.reasoning_summary_text.done":
471 // summary text already accumulated via deltas
472 case "response.function_call_arguments.delta":
473 var p struct {
474 OutputIndex int `json:"output_index"`
475 Delta string `json:"delta"`
476 }
477 _ = json.Unmarshal([]byte(ev.Data), &p)
478 if it, ok := items[p.OutputIndex]; ok && it.kind == "function_call" {
479 it.argsBuf.WriteString(p.Delta)
480 out <- EventToolArgs{ID: it.callID, Delta: p.Delta}
481 }
482 case "response.output_item.done":
483 var p struct {
484 OutputIndex int `json:"output_index"`
485 Item struct {
486 Type string `json:"type"`
487 ID string `json:"id"`
488 EncryptedContent string `json:"encrypted_content"`
489 Summary []struct {
490 Type string `json:"type"`
491 Text string `json:"text"`
492 } `json:"summary"`
493 } `json:"item"`
494 }
495 _ = json.Unmarshal([]byte(ev.Data), &p)
496 if it, ok := items[p.OutputIndex]; ok {
497 switch it.kind {
498 case "function_call":
499 out <- EventToolEnd{ID: it.callID}
500 case "reasoning":
501 if p.Item.EncryptedContent != "" {
502 it.encrypted = p.Item.EncryptedContent
503 }
504 if it.rawID == "" && p.Item.ID != "" {
505 it.rawID = p.Item.ID
506 }
507 for _, s := range p.Item.Summary {
508 if s.Text == "" {
509 continue
510 }
511 if it.summary.Len() > 0 {
512 it.summary.WriteString("\n")
513 }
514 it.summary.WriteString(s.Text)
515 }
516 }
517 }
518 case "response.completed", "response.done":
519 var p struct {
520 Response struct {
521 Usage struct {
522 InputTokens int `json:"input_tokens"`
523 OutputTokens int `json:"output_tokens"`
524 InputTokensDetails struct {
525 CachedTokens int `json:"cached_tokens"`
526 } `json:"input_tokens_details"`
527 } `json:"usage"`
528 Status string `json:"status"`
529 } `json:"response"`
530 }
531 _ = json.Unmarshal([]byte(ev.Data), &p)
532 usage.InputTokens = p.Response.Usage.InputTokens - p.Response.Usage.InputTokensDetails.CachedTokens
533 if usage.InputTokens < 0 {
534 usage.InputTokens = p.Response.Usage.InputTokens
535 }
536 usage.OutputTokens = p.Response.Usage.OutputTokens
537 usage.CacheReadTokens = p.Response.Usage.InputTokensDetails.CachedTokens
538
539 hadTool := false
540 for _, it := range items {
541 if it.kind == "function_call" {
542 hadTool = true
543 break
544 }
545 }
546 if hadTool {
547 stop = StopToolUse
548 } else {
549 stop = StopEnd
550 }
551 sendDone()
552 return
553 case "response.failed":
554 var p struct {
555 Response struct {
556 Error struct {
557 Message string `json:"message"`
558 } `json:"error"`
559 } `json:"response"`
560 }
561 _ = json.Unmarshal([]byte(ev.Data), &p)
562 stop = StopError
563 finalErr = fmt.Errorf("codex: %s", p.Response.Error.Message)
564 sendDone()
565 return
566 case "error":
567 var p struct {
568 Message string `json:"message"`
569 Code string `json:"code"`
570 }
571 _ = json.Unmarshal([]byte(ev.Data), &p)
572 msg := p.Message
573 if msg == "" {
574 msg = p.Code
575 }
576 stop = StopError
577 finalErr = fmt.Errorf("codex error: %s", msg)
578 sendDone()
579 return
580 }
581 }
582 }
583}