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
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 zot'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}
167
168// ---- Request building ----
169
170func (c *codexClient) findModel(id string) (Model, error) {
171 if c.providerName != "" && c.providerName != "openai-codex" {
172 if m, err := FindModel(c.providerName, id); err == nil {
173 return m, nil
174 }
175 }
176 if m, err := FindModel("openai-codex", id); err == nil {
177 return m, nil
178 }
179 return FindModel("openai", id)
180}
181
182func (c *codexClient) buildRequest(req Request) (*codexRequest, error) {
183 m, err := c.findModel(req.Model)
184 if err != nil {
185 return nil, err
186 }
187 reasoning := ClampReasoningForModel(m, req.Reasoning)
188
189 body := &codexRequest{
190 Model: req.Model,
191 Store: false,
192 Stream: true,
193 Instructions: req.System,
194 ParallelToolCalls: true,
195 Include: []string{"reasoning.encrypted_content"},
196 }
197 if m.Reasoning {
198 if effort := OpenAICodexReasoningEffort(reasoning, req.Model); effort != "" {
199 body.Reasoning = &codexReasoningConfig{Effort: effort}
200 }
201 }
202 activeTools := activeToolDefinitions(req.Tools, req.Messages)
203 if len(activeTools) > 0 {
204 body.ToolChoice = "auto"
205 for _, t := range activeTools {
206 params := t.Schema
207 if len(params) == 0 {
208 params = json.RawMessage(`{"type":"object","properties":{}}`)
209 }
210 body.Tools = append(body.Tools, codexTool{
211 Type: "function",
212 Name: t.Name,
213 Description: t.Description,
214 Parameters: params,
215 })
216 }
217 }
218
219 msgIdx := 0
220 req.Messages = RepairOrphanedToolResults(req.Messages)
221 for _, msg := range req.Messages {
222 switch msg.Role {
223 case RoleUser:
224 content := []any{}
225 for _, c := range msg.Content {
226 switch v := c.(type) {
227 case TextBlock:
228 if v.Text != "" {
229 content = append(content, codexInputText{Type: "input_text", Text: v.Text})
230 }
231 case ImageBlock:
232 url := "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
233 content = append(content, codexInputImage{Type: "input_image", Detail: "auto", ImageURL: url})
234 }
235 }
236 if len(content) == 0 {
237 continue
238 }
239 body.Input = append(body.Input, codexInputMessage{Role: "user", Content: content})
240 case RoleAssistant:
241 // Emit one output_message per text block, one function_call per
242 // tool call, and one reasoning item per ReasoningBlock,
243 // preserving the order so the model sees the same interleaving
244 // we captured. The reasoning replay is what keeps OpenAI
245 // Codex from rejecting follow-up tool calls with
246 // "thinking is enabled but reasoning_content is missing".
247 for _, c := range msg.Content {
248 switch v := c.(type) {
249 case ReasoningBlock:
250 item := codexReasoningItem{
251 Type: "reasoning",
252 ID: v.ID,
253 EncryptedContent: v.Encrypted,
254 Summary: []codexReasoningSummary{},
255 }
256 if v.Summary != "" {
257 item.Summary = []codexReasoningSummary{{Type: "summary_text", Text: v.Summary}}
258 }
259 body.Input = append(body.Input, item)
260 case TextBlock:
261 if v.Text == "" {
262 continue
263 }
264 msgIdx++
265 body.Input = append(body.Input, codexOutputMessage{
266 Type: "message",
267 Role: "assistant",
268 Status: "completed",
269 ID: fmt.Sprintf("msg_%d", msgIdx),
270 Content: []codexOutputText{
271 {Type: "output_text", Text: v.Text, Annotations: []any{}},
272 },
273 })
274 case ToolCallBlock:
275 args := string(v.Arguments)
276 if args == "" || !json.Valid([]byte(args)) {
277 args = "{}"
278 }
279 callID, _ := splitCallID(v.ID)
280 body.Input = append(body.Input, codexFunctionCall{
281 Type: "function_call",
282 CallID: callID,
283 Name: v.Name,
284 Arguments: args,
285 })
286 }
287 }
288 case RoleTool:
289 for _, c := range msg.Content {
290 if tr, ok := c.(ToolResultBlock); ok {
291 var text strings.Builder
292 imageCount := 0
293 for _, inner := range tr.Content {
294 switch v := inner.(type) {
295 case TextBlock:
296 if text.Len() > 0 {
297 text.WriteString("\n")
298 }
299 text.WriteString(v.Text)
300 case ImageBlock:
301 imageCount++
302 }
303 }
304 // The Responses API function_call_output only carries a
305 // string, so image bytes cannot ride along here. The agent
306 // loop mirrors any tool-result images into the following
307 // user message (which this client does serialize as
308 // input_image). Leave a short text note so an image-only
309 // result is not an empty output the API may reject, and so
310 // the model knows the image arrives next.
311 out := text.String()
312 if out == "" && imageCount > 0 {
313 if imageCount == 1 {
314 out = "[image returned; see the following message]"
315 } else {
316 out = fmt.Sprintf("[%d images returned; see the following message]", imageCount)
317 }
318 }
319 callID, _ := splitCallID(tr.CallID)
320 body.Input = append(body.Input, codexFunctionCallOutput{
321 Type: "function_call_output",
322 CallID: callID,
323 Output: out,
324 })
325 }
326 }
327 }
328 }
329
330 return body, nil
331}
332
333func splitCallID(id string) (string, string) {
334 if i := strings.Index(id, "|"); i >= 0 {
335 return id[:i], id[i+1:]
336 }
337 return id, ""
338}
339
340func usesCodexCLIRouting(model string) bool {
341 switch model {
342 case "gpt-5.6-luna", "gpt-5.6-luna-pro", "gpt-5.6-terra", "gpt-5.6-terra-pro":
343 return true
344 default:
345 return false
346 }
347}
348
349func newCodexSessionID() string {
350 var b [16]byte
351 if _, err := rand.Read(b[:]); err != nil {
352 return fmt.Sprintf("zot-%d", time.Now().UnixNano())
353 }
354 return strings.Join([]string{
355 hex.EncodeToString(b[0:4]),
356 hex.EncodeToString(b[4:6]),
357 hex.EncodeToString(b[6:8]),
358 hex.EncodeToString(b[8:10]),
359 hex.EncodeToString(b[10:16]),
360 }, "-")
361}
362
363// ---- Streaming ----
364
365func (c *codexClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
366 wire, err := c.buildRequest(req)
367 if err != nil {
368 return nil, err
369 }
370 if c.modelName != nil {
371 wire.Model = c.modelName(wire.Model)
372 }
373 var codexCLISessionID string
374 if !c.disableCLIRouting && (c.cliRoutingAll || usesCodexCLIRouting(wire.Model)) {
375 codexCLISessionID = newCodexSessionID()
376 wire.PromptCacheKey = codexCLISessionID
377 }
378 body, err := json.Marshal(wire)
379 if err != nil {
380 return nil, err
381 }
382
383 newReq := func() (*http.Request, error) {
384 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
385 if err != nil {
386 return nil, err
387 }
388 httpReq.Header.Set("content-type", "application/json")
389 httpReq.Header.Set("accept", "text/event-stream")
390 httpReq.Header.Set("authorization", "Bearer "+c.token)
391 httpReq.Header.Set("chatgpt-account-id", c.accountID)
392 httpReq.Header.Set("openai-beta", "responses=experimental")
393 if codexCLISessionID != "" {
394 // The ChatGPT Codex backend only admits (and reliably serves)
395 // requests that follow Codex CLI routing metadata; other client
396 // identities are load-shed with "servers are currently
397 // overloaded" errors even when capacity is fine.
398 httpReq.Header.Set("originator", "codex_cli_rs")
399 httpReq.Header.Set("session-id", codexCLISessionID)
400 httpReq.Header.Set("user-agent", "codex_cli_rs/0.0.0")
401 } else {
402 httpReq.Header.Set("originator", "zot")
403 httpReq.Header.Set("user-agent", fmt.Sprintf("zot (%s %s)", runtime.GOOS, runtime.GOARCH))
404 }
405 return httpReq, nil
406 }
407
408 resp, err := doStreamWithRetry(ctx, c.http, newReq)
409 if err != nil {
410 return nil, fmt.Errorf("openai-codex: %w", err)
411 }
412 if resp.StatusCode != http.StatusOK {
413 b, _ := io.ReadAll(resp.Body)
414 resp.Body.Close()
415 return nil, fmt.Errorf("openai-codex: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
416 }
417
418 out := make(chan Event, 16)
419 go c.runStream(ctx, resp, req, out)
420 return out, nil
421}
422
423func (c *codexClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
424 defer close(out)
425 defer resp.Body.Close()
426
427 model, _ := c.findModel(req.Model)
428 providerName := c.providerName
429 if providerName == "" {
430 providerName = "openai-codex"
431 }
432 out <- EventStart{Model: req.Model, Provider: providerName}
433
434 raw := make(chan sseEvent, 16)
435 go readSSE(resp.Body, raw)
436
437 // Accumulators. The Responses API emits output_items in order; each
438 // item is either a "message" (text) or a "function_call". We track
439 // the in-flight item by its index.
440 type itemState struct {
441 kind string // "message" | "function_call" | "reasoning"
442 callID string
443 name string
444 argsBuf strings.Builder
445 textBuf strings.Builder
446 summary strings.Builder
447 rawID string
448 encrypted string
449 announced bool
450 }
451 var (
452 items = map[int]*itemState{}
453 order []int
454 usage Usage
455 stop StopReason = StopEnd
456 finalErr error
457 )
458
459 assemble := func() Message {
460 content := []Content{}
461 for _, idx := range order {
462 it := items[idx]
463 switch it.kind {
464 case "message":
465 if it.textBuf.Len() > 0 {
466 content = append(content, TextBlock{Text: it.textBuf.String()})
467 }
468 case "function_call":
469 args := it.argsBuf.String()
470 if args == "" || !json.Valid([]byte(args)) {
471 args = "{}"
472 }
473 content = append(content, ToolCallBlock{
474 ID: it.callID, Name: it.name, Arguments: json.RawMessage(args),
475 })
476 case "reasoning":
477 if it.encrypted == "" && it.summary.Len() == 0 && it.rawID == "" {
478 continue
479 }
480 content = append(content, ReasoningBlock{
481 ID: it.rawID,
482 Summary: it.summary.String(),
483 Encrypted: it.encrypted,
484 })
485 }
486 }
487 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
488 }
489
490 sendDone := func() {
491 usage.CostUSD = ComputeCost(model, usage)
492 out <- EventUsage{Usage: usage}
493 out <- EventDone{Stop: stop, Err: finalErr, Message: assemble()}
494 }
495
496 for {
497 select {
498 case <-ctx.Done():
499 stop = StopAborted
500 finalErr = ctx.Err()
501 sendDone()
502 return
503 case ev, ok := <-raw:
504 if !ok {
505 sendDone()
506 return
507 }
508 var head struct {
509 Type string `json:"type"`
510 }
511 if err := json.Unmarshal([]byte(ev.Data), &head); err != nil {
512 continue
513 }
514
515 switch head.Type {
516 case "response.output_item.added":
517 var p struct {
518 OutputIndex int `json:"output_index"`
519 Item struct {
520 Type string `json:"type"` // "message" | "function_call" | "reasoning"
521 ID string `json:"id"`
522 CallID string `json:"call_id"`
523 Name string `json:"name"`
524 EncryptedContent string `json:"encrypted_content"`
525 } `json:"item"`
526 }
527 _ = json.Unmarshal([]byte(ev.Data), &p)
528 it := &itemState{}
529 switch p.Item.Type {
530 case "message":
531 it.kind = "message"
532 case "function_call":
533 it.kind = "function_call"
534 it.callID = p.Item.CallID
535 it.name = p.Item.Name
536 if !it.announced {
537 it.announced = true
538 out <- EventToolStart{ID: it.callID, Name: it.name}
539 }
540 case "reasoning":
541 it.kind = "reasoning"
542 it.rawID = p.Item.ID
543 it.encrypted = p.Item.EncryptedContent
544 default:
545 continue
546 }
547 items[p.OutputIndex] = it
548 order = append(order, p.OutputIndex)
549 case "response.output_text.delta":
550 var p struct {
551 OutputIndex int `json:"output_index"`
552 Delta string `json:"delta"`
553 }
554 _ = json.Unmarshal([]byte(ev.Data), &p)
555 if it, ok := items[p.OutputIndex]; ok && it.kind == "message" {
556 it.textBuf.WriteString(p.Delta)
557 out <- EventTextDelta{Delta: p.Delta}
558 }
559 case "response.reasoning_summary_text.delta":
560 var p struct {
561 OutputIndex int `json:"output_index"`
562 Delta string `json:"delta"`
563 }
564 _ = json.Unmarshal([]byte(ev.Data), &p)
565 if it, ok := items[p.OutputIndex]; ok && it.kind == "reasoning" {
566 it.summary.WriteString(p.Delta)
567 }
568 case "response.reasoning_summary_text.done":
569 // summary text already accumulated via deltas
570 case "response.function_call_arguments.delta":
571 var p struct {
572 OutputIndex int `json:"output_index"`
573 Delta string `json:"delta"`
574 }
575 _ = json.Unmarshal([]byte(ev.Data), &p)
576 if it, ok := items[p.OutputIndex]; ok && it.kind == "function_call" {
577 it.argsBuf.WriteString(p.Delta)
578 out <- EventToolArgs{ID: it.callID, Delta: p.Delta}
579 }
580 case "response.output_item.done":
581 var p struct {
582 OutputIndex int `json:"output_index"`
583 Item struct {
584 Type string `json:"type"`
585 ID string `json:"id"`
586 EncryptedContent string `json:"encrypted_content"`
587 Summary []struct {
588 Type string `json:"type"`
589 Text string `json:"text"`
590 } `json:"summary"`
591 } `json:"item"`
592 }
593 _ = json.Unmarshal([]byte(ev.Data), &p)
594 if it, ok := items[p.OutputIndex]; ok {
595 switch it.kind {
596 case "function_call":
597 out <- EventToolEnd{ID: it.callID}
598 case "reasoning":
599 if p.Item.EncryptedContent != "" {
600 it.encrypted = p.Item.EncryptedContent
601 }
602 if it.rawID == "" && p.Item.ID != "" {
603 it.rawID = p.Item.ID
604 }
605 for _, s := range p.Item.Summary {
606 if s.Text == "" {
607 continue
608 }
609 if it.summary.Len() > 0 {
610 it.summary.WriteString("\n")
611 }
612 it.summary.WriteString(s.Text)
613 }
614 }
615 }
616 case "response.completed", "response.done":
617 var p struct {
618 Response struct {
619 Usage struct {
620 InputTokens int `json:"input_tokens"`
621 OutputTokens int `json:"output_tokens"`
622 InputTokensDetails struct {
623 CachedTokens int `json:"cached_tokens"`
624 } `json:"input_tokens_details"`
625 OutputTokensDetails *struct {
626 ReasoningTokens int `json:"reasoning_tokens"`
627 } `json:"output_tokens_details"`
628 } `json:"usage"`
629 Status string `json:"status"`
630 } `json:"response"`
631 }
632 _ = json.Unmarshal([]byte(ev.Data), &p)
633 usage.InputTokens = p.Response.Usage.InputTokens - p.Response.Usage.InputTokensDetails.CachedTokens
634 if usage.InputTokens < 0 {
635 usage.InputTokens = p.Response.Usage.InputTokens
636 }
637 usage.OutputTokens = p.Response.Usage.OutputTokens
638 usage.CacheReadTokens = p.Response.Usage.InputTokensDetails.CachedTokens
639 if details := p.Response.Usage.OutputTokensDetails; details != nil {
640 usage.ReasoningTokens = details.ReasoningTokens
641 usage.ReasoningTokensKnown = true
642 }
643
644 hadTool := false
645 for _, it := range items {
646 if it.kind == "function_call" {
647 hadTool = true
648 break
649 }
650 }
651 if hadTool {
652 stop = StopToolUse
653 } else {
654 stop = StopEnd
655 }
656 sendDone()
657 return
658 case "response.failed":
659 var p struct {
660 Response struct {
661 Error struct {
662 Message string `json:"message"`
663 } `json:"error"`
664 } `json:"response"`
665 }
666 _ = json.Unmarshal([]byte(ev.Data), &p)
667 stop = StopError
668 finalErr = fmt.Errorf("codex: %s", p.Response.Error.Message)
669 sendDone()
670 return
671 case "error":
672 var p struct {
673 Message string `json:"message"`
674 Code string `json:"code"`
675 Error struct {
676 Message string `json:"message"`
677 Code string `json:"code"`
678 } `json:"error"`
679 }
680 _ = json.Unmarshal([]byte(ev.Data), &p)
681 msg := p.Message
682 if msg == "" {
683 msg = p.Error.Message
684 }
685 if msg == "" {
686 msg = p.Code
687 }
688 if msg == "" {
689 msg = p.Error.Code
690 }
691 if msg == "" {
692 msg = strings.TrimSpace(ev.Data)
693 }
694 stop = StopError
695 label := c.errorLabel
696 if label == "" {
697 label = "codex"
698 }
699 finalErr = fmt.Errorf("%s error: %s", label, msg)
700 sendDone()
701 return
702 }
703 }
704 }
705}