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