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 codexReasoningConfig struct {
135 Effort string `json:"effort,omitempty"`
136}
137
138type codexRequest struct {
139 Model string `json:"model"`
140 Store bool `json:"store"`
141 Stream bool `json:"stream"`
142 Instructions string `json:"instructions,omitempty"`
143 Input []any `json:"input"`
144 Tools []codexTool `json:"tools,omitempty"`
145 ToolChoice string `json:"tool_choice,omitempty"`
146 ParallelToolCalls bool `json:"parallel_tool_calls"`
147 Include []string `json:"include,omitempty"`
148 Reasoning *codexReasoningConfig `json:"reasoning,omitempty"`
149}
150
151// ---- Request building ----
152
153func (c *codexClient) buildRequest(req Request) (*codexRequest, error) {
154 m, err := FindModel("openai-codex", req.Model)
155 if err != nil {
156 m, err = FindModel("openai", req.Model)
157 }
158 if err != nil {
159 return nil, err
160 }
161 _ = m
162
163 body := &codexRequest{
164 Model: req.Model,
165 Store: false,
166 Stream: true,
167 Instructions: req.System,
168 ParallelToolCalls: true,
169 Include: []string{"reasoning.encrypted_content"},
170 }
171 if m.Reasoning {
172 if effort := OpenAICodexReasoningEffort(req.Reasoning); effort != "" {
173 body.Reasoning = &codexReasoningConfig{Effort: effort}
174 }
175 }
176 if len(req.Tools) > 0 {
177 body.ToolChoice = "auto"
178 for _, t := range req.Tools {
179 params := t.Schema
180 if len(params) == 0 {
181 params = json.RawMessage(`{"type":"object","properties":{}}`)
182 }
183 body.Tools = append(body.Tools, codexTool{
184 Type: "function",
185 Name: t.Name,
186 Description: t.Description,
187 Parameters: params,
188 })
189 }
190 }
191
192 msgIdx := 0
193 req.Messages = RepairOrphanedToolResults(req.Messages)
194 for _, msg := range req.Messages {
195 switch msg.Role {
196 case RoleUser:
197 content := []any{}
198 for _, c := range msg.Content {
199 switch v := c.(type) {
200 case TextBlock:
201 if v.Text != "" {
202 content = append(content, codexInputText{Type: "input_text", Text: v.Text})
203 }
204 case ImageBlock:
205 url := "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
206 content = append(content, codexInputImage{Type: "input_image", Detail: "auto", ImageURL: url})
207 }
208 }
209 if len(content) == 0 {
210 continue
211 }
212 body.Input = append(body.Input, codexInputMessage{Role: "user", Content: content})
213 case RoleAssistant:
214 // Emit one output_message per text block, one function_call per
215 // tool call, and one reasoning item per ReasoningBlock,
216 // preserving the order so the model sees the same interleaving
217 // we captured. The reasoning replay is what keeps OpenAI
218 // Codex from rejecting follow-up tool calls with
219 // "thinking is enabled but reasoning_content is missing".
220 for _, c := range msg.Content {
221 switch v := c.(type) {
222 case ReasoningBlock:
223 item := codexReasoningItem{
224 Type: "reasoning",
225 ID: v.ID,
226 EncryptedContent: v.Encrypted,
227 Summary: []codexReasoningSummary{},
228 }
229 if v.Summary != "" {
230 item.Summary = []codexReasoningSummary{{Type: "summary_text", Text: v.Summary}}
231 }
232 body.Input = append(body.Input, item)
233 case TextBlock:
234 if v.Text == "" {
235 continue
236 }
237 msgIdx++
238 body.Input = append(body.Input, codexOutputMessage{
239 Type: "message",
240 Role: "assistant",
241 Status: "completed",
242 ID: fmt.Sprintf("msg_%d", msgIdx),
243 Content: []codexOutputText{
244 {Type: "output_text", Text: v.Text, Annotations: []any{}},
245 },
246 })
247 case ToolCallBlock:
248 args := string(v.Arguments)
249 if args == "" || !json.Valid([]byte(args)) {
250 args = "{}"
251 }
252 callID, _ := splitCallID(v.ID)
253 body.Input = append(body.Input, codexFunctionCall{
254 Type: "function_call",
255 CallID: callID,
256 Name: v.Name,
257 Arguments: args,
258 })
259 }
260 }
261 case RoleTool:
262 for _, c := range msg.Content {
263 if tr, ok := c.(ToolResultBlock); ok {
264 var text strings.Builder
265 for _, inner := range tr.Content {
266 if tb, ok := inner.(TextBlock); ok {
267 if text.Len() > 0 {
268 text.WriteString("\n")
269 }
270 text.WriteString(tb.Text)
271 }
272 }
273 callID, _ := splitCallID(tr.CallID)
274 body.Input = append(body.Input, codexFunctionCallOutput{
275 Type: "function_call_output",
276 CallID: callID,
277 Output: text.String(),
278 })
279 }
280 }
281 }
282 }
283
284 return body, nil
285}
286
287func splitCallID(id string) (string, string) {
288 if i := strings.Index(id, "|"); i >= 0 {
289 return id[:i], id[i+1:]
290 }
291 return id, ""
292}
293
294// ---- Streaming ----
295
296func (c *codexClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
297 wire, err := c.buildRequest(req)
298 if err != nil {
299 return nil, err
300 }
301 body, err := json.Marshal(wire)
302 if err != nil {
303 return nil, err
304 }
305
306 newReq := func() (*http.Request, error) {
307 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
308 if err != nil {
309 return nil, err
310 }
311 httpReq.Header.Set("content-type", "application/json")
312 httpReq.Header.Set("accept", "text/event-stream")
313 httpReq.Header.Set("authorization", "Bearer "+c.token)
314 httpReq.Header.Set("chatgpt-account-id", c.accountID)
315 httpReq.Header.Set("openai-beta", "responses=experimental")
316 httpReq.Header.Set("originator", "zot")
317 httpReq.Header.Set("user-agent", fmt.Sprintf("zot (%s %s)", runtime.GOOS, runtime.GOARCH))
318 return httpReq, nil
319 }
320
321 resp, err := doStreamWithRetry(ctx, c.http, newReq)
322 if err != nil {
323 return nil, fmt.Errorf("openai-codex: %w", err)
324 }
325 if resp.StatusCode != http.StatusOK {
326 b, _ := io.ReadAll(resp.Body)
327 resp.Body.Close()
328 return nil, fmt.Errorf("openai-codex: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
329 }
330
331 out := make(chan Event, 16)
332 go c.runStream(ctx, resp, req, out)
333 return out, nil
334}
335
336func (c *codexClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
337 defer close(out)
338 defer resp.Body.Close()
339
340 model, _ := FindModel("openai-codex", req.Model)
341 if model.ID == "" {
342 model, _ = FindModel("openai", req.Model)
343 }
344 out <- EventStart{Model: req.Model, Provider: "openai-codex"}
345
346 raw := make(chan sseEvent, 16)
347 go readSSE(resp.Body, raw)
348
349 // Accumulators. The Responses API emits output_items in order; each
350 // item is either a "message" (text) or a "function_call". We track
351 // the in-flight item by its index.
352 type itemState struct {
353 kind string // "message" | "function_call" | "reasoning"
354 callID string
355 name string
356 argsBuf strings.Builder
357 textBuf strings.Builder
358 summary strings.Builder
359 rawID string
360 encrypted string
361 announced bool
362 }
363 var (
364 items = map[int]*itemState{}
365 order []int
366 usage Usage
367 stop StopReason = StopEnd
368 finalErr error
369 )
370
371 assemble := func() Message {
372 content := []Content{}
373 for _, idx := range order {
374 it := items[idx]
375 switch it.kind {
376 case "message":
377 if it.textBuf.Len() > 0 {
378 content = append(content, TextBlock{Text: it.textBuf.String()})
379 }
380 case "function_call":
381 args := it.argsBuf.String()
382 if args == "" || !json.Valid([]byte(args)) {
383 args = "{}"
384 }
385 content = append(content, ToolCallBlock{
386 ID: it.callID, Name: it.name, Arguments: json.RawMessage(args),
387 })
388 case "reasoning":
389 if it.encrypted == "" && it.summary.Len() == 0 && it.rawID == "" {
390 continue
391 }
392 content = append(content, ReasoningBlock{
393 ID: it.rawID,
394 Summary: it.summary.String(),
395 Encrypted: it.encrypted,
396 })
397 }
398 }
399 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
400 }
401
402 sendDone := func() {
403 usage.CostUSD = ComputeCost(model, usage)
404 out <- EventUsage{Usage: usage}
405 out <- EventDone{Stop: stop, Err: finalErr, Message: assemble()}
406 }
407
408 for {
409 select {
410 case <-ctx.Done():
411 stop = StopAborted
412 finalErr = ctx.Err()
413 sendDone()
414 return
415 case ev, ok := <-raw:
416 if !ok {
417 sendDone()
418 return
419 }
420 var head struct {
421 Type string `json:"type"`
422 }
423 if err := json.Unmarshal([]byte(ev.Data), &head); err != nil {
424 continue
425 }
426
427 switch head.Type {
428 case "response.output_item.added":
429 var p struct {
430 OutputIndex int `json:"output_index"`
431 Item struct {
432 Type string `json:"type"` // "message" | "function_call" | "reasoning"
433 ID string `json:"id"`
434 CallID string `json:"call_id"`
435 Name string `json:"name"`
436 EncryptedContent string `json:"encrypted_content"`
437 } `json:"item"`
438 }
439 _ = json.Unmarshal([]byte(ev.Data), &p)
440 it := &itemState{}
441 switch p.Item.Type {
442 case "message":
443 it.kind = "message"
444 case "function_call":
445 it.kind = "function_call"
446 it.callID = p.Item.CallID
447 it.name = p.Item.Name
448 if !it.announced {
449 it.announced = true
450 out <- EventToolStart{ID: it.callID, Name: it.name}
451 }
452 case "reasoning":
453 it.kind = "reasoning"
454 it.rawID = p.Item.ID
455 it.encrypted = p.Item.EncryptedContent
456 default:
457 continue
458 }
459 items[p.OutputIndex] = it
460 order = append(order, p.OutputIndex)
461 case "response.output_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 == "message" {
468 it.textBuf.WriteString(p.Delta)
469 out <- EventTextDelta{Delta: p.Delta}
470 }
471 case "response.reasoning_summary_text.delta":
472 var p struct {
473 OutputIndex int `json:"output_index"`
474 Delta string `json:"delta"`
475 }
476 _ = json.Unmarshal([]byte(ev.Data), &p)
477 if it, ok := items[p.OutputIndex]; ok && it.kind == "reasoning" {
478 it.summary.WriteString(p.Delta)
479 }
480 case "response.reasoning_summary_text.done":
481 // summary text already accumulated via deltas
482 case "response.function_call_arguments.delta":
483 var p struct {
484 OutputIndex int `json:"output_index"`
485 Delta string `json:"delta"`
486 }
487 _ = json.Unmarshal([]byte(ev.Data), &p)
488 if it, ok := items[p.OutputIndex]; ok && it.kind == "function_call" {
489 it.argsBuf.WriteString(p.Delta)
490 out <- EventToolArgs{ID: it.callID, Delta: p.Delta}
491 }
492 case "response.output_item.done":
493 var p struct {
494 OutputIndex int `json:"output_index"`
495 Item struct {
496 Type string `json:"type"`
497 ID string `json:"id"`
498 EncryptedContent string `json:"encrypted_content"`
499 Summary []struct {
500 Type string `json:"type"`
501 Text string `json:"text"`
502 } `json:"summary"`
503 } `json:"item"`
504 }
505 _ = json.Unmarshal([]byte(ev.Data), &p)
506 if it, ok := items[p.OutputIndex]; ok {
507 switch it.kind {
508 case "function_call":
509 out <- EventToolEnd{ID: it.callID}
510 case "reasoning":
511 if p.Item.EncryptedContent != "" {
512 it.encrypted = p.Item.EncryptedContent
513 }
514 if it.rawID == "" && p.Item.ID != "" {
515 it.rawID = p.Item.ID
516 }
517 for _, s := range p.Item.Summary {
518 if s.Text == "" {
519 continue
520 }
521 if it.summary.Len() > 0 {
522 it.summary.WriteString("\n")
523 }
524 it.summary.WriteString(s.Text)
525 }
526 }
527 }
528 case "response.completed", "response.done":
529 var p struct {
530 Response struct {
531 Usage struct {
532 InputTokens int `json:"input_tokens"`
533 OutputTokens int `json:"output_tokens"`
534 InputTokensDetails struct {
535 CachedTokens int `json:"cached_tokens"`
536 } `json:"input_tokens_details"`
537 } `json:"usage"`
538 Status string `json:"status"`
539 } `json:"response"`
540 }
541 _ = json.Unmarshal([]byte(ev.Data), &p)
542 usage.InputTokens = p.Response.Usage.InputTokens - p.Response.Usage.InputTokensDetails.CachedTokens
543 if usage.InputTokens < 0 {
544 usage.InputTokens = p.Response.Usage.InputTokens
545 }
546 usage.OutputTokens = p.Response.Usage.OutputTokens
547 usage.CacheReadTokens = p.Response.Usage.InputTokensDetails.CachedTokens
548
549 hadTool := false
550 for _, it := range items {
551 if it.kind == "function_call" {
552 hadTool = true
553 break
554 }
555 }
556 if hadTool {
557 stop = StopToolUse
558 } else {
559 stop = StopEnd
560 }
561 sendDone()
562 return
563 case "response.failed":
564 var p struct {
565 Response struct {
566 Error struct {
567 Message string `json:"message"`
568 } `json:"error"`
569 } `json:"response"`
570 }
571 _ = json.Unmarshal([]byte(ev.Data), &p)
572 stop = StopError
573 finalErr = fmt.Errorf("codex: %s", p.Response.Error.Message)
574 sendDone()
575 return
576 case "error":
577 var p struct {
578 Message string `json:"message"`
579 Code string `json:"code"`
580 }
581 _ = json.Unmarshal([]byte(ev.Data), &p)
582 msg := p.Message
583 if msg == "" {
584 msg = p.Code
585 }
586 stop = StopError
587 finalErr = fmt.Errorf("codex error: %s", msg)
588 sendDone()
589 return
590 }
591 }
592 }
593}