v0.2.82 444a7ea

openai_codex.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close