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