v0.3.93 0192a2e

openai.go RawHistoryFolder

1package provider
2
3import (
4	"bytes"
5	"context"
6	"encoding/base64"
7	"encoding/json"
8	"fmt"
9	"io"
10	"net/http"
11	"regexp"
12	"strings"
13	"time"
14)
15
16const openaiDefaultBaseURL = "https://api.openai.com"
17
18// versionSegmentSuffix matches a trailing API version segment such as
19// "/v1" or Z.AI's "/v4".
20var versionSegmentSuffix = regexp.MustCompile(`/v\d+$`)
21
22// chatCompletionsURL builds the chat-completions endpoint for an
23// OpenAI-compatible base URL. A base that already carries an API
24// version segment gets "/chat/completions" appended directly; a bare
25// host (e.g. api.openai.com) gets the conventional "/v1/chat/completions".
26//
27// Matching any "/vN" segment (not just "/v1") keeps Z.AI's coding-plan
28// base, which ends in "/paas/v4", from getting a spurious "/v1" that
29// yields ".../paas/v4/v1/chat/completions" and a 404.
30func chatCompletionsURL(baseURL string) string {
31	if versionSegmentSuffix.MatchString(baseURL) {
32		return baseURL + "/chat/completions"
33	}
34	return baseURL + "/v1/chat/completions"
35}
36
37type openaiClient struct {
38	apiKey              string
39	baseURL             string
40	chatCompletionsPath string
41	name                string
42	oauth               bool // when true, apiKey actually holds an OAuth access token
43	headers             map[string]string
44	http                *http.Client
45}
46
47// NewOpenAI creates an OpenAI client using an API key. baseURL may be empty.
48func NewOpenAI(apiKey, baseURL string) Client {
49	if baseURL == "" {
50		baseURL = openaiDefaultBaseURL
51	}
52	return &openaiClient{
53		apiKey:  apiKey,
54		baseURL: strings.TrimRight(baseURL, "/"),
55		name:    "openai",
56		http:    &http.Client{Timeout: 0},
57	}
58}
59
60// NewOpenAIOAuth creates an OpenAI client using a subscription OAuth access token.
61// The token is sent as an HTTP Bearer credential on the standard chat/completions endpoint.
62func NewOpenAIOAuth(accessToken, baseURL string) Client {
63	if baseURL == "" {
64		baseURL = openaiDefaultBaseURL
65	}
66	return &openaiClient{
67		apiKey:  accessToken,
68		baseURL: strings.TrimRight(baseURL, "/"),
69		name:    "openai",
70		oauth:   true,
71		http:    &http.Client{Timeout: 0},
72	}
73}
74
75// NewKimi creates a Kimi/Moonshot client. Kimi's chat API is OpenAI-compatible.
76func NewKimi(apiKey, baseURL string) Client {
77	return NewKimiWithHeaders(apiKey, baseURL, nil)
78}
79
80// NewDeepSeek creates a DeepSeek client. DeepSeek's chat API is
81// OpenAI-compatible at https://api.deepseek.com/v1.
82func NewDeepSeek(apiKey, baseURL string) Client {
83	if baseURL == "" {
84		baseURL = "https://api.deepseek.com/v1"
85	}
86	return &openaiClient{
87		apiKey:  apiKey,
88		baseURL: strings.TrimRight(baseURL, "/"),
89		name:    "deepseek",
90		http:    &http.Client{Timeout: 0},
91	}
92}
93
94// NewKimiWithHeaders creates a Kimi/Moonshot client with extra headers.
95// Subscription tokens from Kimi Code need the official CLI's X-Msh-* headers.
96func NewKimiWithHeaders(apiKey, baseURL string, headers map[string]string) Client {
97	if baseURL == "" {
98		baseURL = "https://api.kimi.com/coding/v1"
99	}
100	return &openaiClient{
101		apiKey:  apiKey,
102		baseURL: strings.TrimRight(baseURL, "/"),
103		name:    "kimi",
104		headers: headers,
105		http:    &http.Client{Timeout: 0},
106	}
107}
108
109func (c *openaiClient) Name() string {
110	if c.name != "" {
111		return c.name
112	}
113	return "openai"
114}
115
116// ---- wire types ----
117
118type oaiContentText struct {
119	Type string `json:"type"` // "text"
120	Text string `json:"text"`
121}
122
123type oaiContentImage struct {
124	Type     string `json:"type"` // "image_url"
125	ImageURL struct {
126		URL string `json:"url"`
127	} `json:"image_url"`
128}
129
130type oaiToolCallFn struct {
131	Name      string `json:"name"`
132	Arguments string `json:"arguments"` // JSON string
133}
134
135type oaiToolCall struct {
136	ID        string          `json:"id"`
137	Type      string          `json:"type"` // "function" or "openrouter:..."
138	Function  oaiToolCallFn   `json:"function,omitempty"`
139	Name      string          `json:"name,omitempty"`
140	Arguments json.RawMessage `json:"arguments,omitempty"`
141}
142
143type oaiMessage struct {
144	Role       string        `json:"role"`
145	Content    interface{}   `json:"content,omitempty"` // string or []block
146	Name       string        `json:"name,omitempty"`
147	ToolCalls  []oaiToolCall `json:"tool_calls,omitempty"`
148	ToolCallID string        `json:"tool_call_id,omitempty"`
149	Tools      []oaiTool     `json:"tools,omitempty"`
150	// ReasoningContent carries the model's chain-of-thought summary
151	// alongside an assistant tool-call message. Required by Kimi's
152	// chat completions endpoint when thinking is enabled and the
153	// assistant message contains a tool call; OpenAI ignores it.
154	ReasoningContent string `json:"reasoning_content,omitempty"`
155}
156
157type oaiTool struct {
158	Type       string          `json:"type"` // "function" or "openrouter:..."
159	Parameters json.RawMessage `json:"parameters,omitempty"`
160	Function   *struct {
161		Name        string          `json:"name"`
162		Description string          `json:"description,omitempty"`
163		Parameters  json.RawMessage `json:"parameters"`
164	} `json:"function,omitempty"`
165}
166
167type oaiStreamOptions struct {
168	IncludeUsage bool `json:"include_usage"`
169}
170
171type oaiRequest struct {
172	Model            string            `json:"model"`
173	Messages         []oaiMessage      `json:"messages"`
174	Tools            []oaiTool         `json:"tools,omitempty"`
175	ToolChoice       string            `json:"tool_choice,omitempty"`
176	Stream           bool              `json:"stream"`
177	StreamOptions    *oaiStreamOptions `json:"stream_options,omitempty"`
178	Temperature      *float32          `json:"temperature,omitempty"`
179	MaxTokens        *int              `json:"max_tokens,omitempty"`
180	MaxCompletionTok *int              `json:"max_completion_tokens,omitempty"`
181	ReasoningEffort  string            `json:"reasoning_effort,omitempty"`
182	SessionID        string            `json:"session_id,omitempty"`
183	MaxToolCalls     int               `json:"max_tool_calls,omitempty"`
184}
185
186// ---- request building ----
187
188func (c *openaiClient) buildRequest(req Request) (*oaiRequest, error) {
189	// The OpenAI wire client is shared by many providers, so prefer its own
190	// provider namespace before falling back to a provider-agnostic lookup.
191	m, err := FindModel(c.Name(), req.Model)
192	if err != nil {
193		m, err = FindModel("", req.Model)
194	}
195	if err != nil {
196		// Unknown model: use sensible defaults so local/custom
197		// models still work without a catalog entry.
198		m = Model{
199			ID:            req.Model,
200			ContextWindow: 32768,
201			MaxOutput:     8192,
202		}
203	}
204	reasoning := ClampReasoningForModel(m, req.Reasoning)
205	out := &oaiRequest{
206		Model:         req.Model,
207		Stream:        true,
208		StreamOptions: &oaiStreamOptions{IncludeUsage: true},
209		Temperature:   req.Temperature,
210	}
211	if c.Name() == "openrouter" {
212		if req.SessionID != "" {
213			out.SessionID = req.SessionID
214		}
215		if req.MaxToolCalls > 0 {
216			out.MaxToolCalls = req.MaxToolCalls
217		}
218	}
219
220	maxTok := req.MaxTokens
221	if maxTok <= 0 {
222		maxTok = m.MaxOutput
223	}
224	// Clamp max_tokens so output plus a minimum input reservation fits
225	// within the context window. Some providers (OpenRouter) enforce
226	// input + max_output <= context_length and reject requests where the
227	// total exceeds it. Reserving headroom guarantees the system prompt,
228	// first message, and tool definitions have room.
229	//
230	// The cap is derived from the context window, never from MaxOutput:
231	// MaxOutput is already the output ceiling, so subtracting from it
232	// would shrink every model's budget even when its output comfortably
233	// fits the window. We only lower maxTok when ContextWindow - reserve
234	// is actually tighter than the requested budget, which is exactly the
235	// pathological case (e.g. a model whose MaxOutput equals its window).
236	//
237	// The reserve is proportional (window/8, capped at 4096) rather than a
238	// flat 4096 so small-window models aren't over-penalized: a flat 4096
239	// would halve gpt-4's 8192 budget, while window/8 reserves a sensible
240	// 1024 there and still tops out at 4096 for large contexts.
241	//
242	// Some providers (OpenRouter) report inflated model-level context
243	// windows (e.g. 1000000) while the serving provider enforces a much
244	// tighter limit (e.g. 262144). Discovery already prefers the serving
245	// provider's smaller context_length, so m.ContextWindow is the real
246	// limit by the time we get here.
247	if m.ContextWindow > 0 {
248		reserve := m.ContextWindow / 8
249		const maxReserve = 4096
250		if reserve > maxReserve {
251			reserve = maxReserve
252		}
253		clamped := m.ContextWindow - reserve
254		if clamped < 1 {
255			clamped = 1
256		}
257		if maxTok > clamped {
258			maxTok = clamped
259		}
260	}
261	if m.Reasoning {
262		if maxTok > 0 {
263			out.MaxCompletionTok = &maxTok
264		}
265		effort := OpenAIReasoningEffort(reasoning)
266		if usesAdaptiveThinking(m) {
267			// Some gateways expose adaptive-thinking Anthropic models through
268			// the OpenAI-compatible chat-completions wire. They accept the
269			// same reasoning_effort knob, including the top "xhigh" tier;
270			// don't clamp zot's "maximum" to "high" for those models.
271			effort = OpenAICompatAnthropicEffort(reasoning)
272		}
273		if hasReasoningLevelOverride(m, req.Reasoning) {
274			// Explicit model mappings describe the endpoint's actual effort
275			// values and take precedence over conservative protocol defaults.
276			effort = reasoning
277		}
278		if c.Name() == "yolo-auto" && effort == "minimum" {
279			// The advertised wire value is minimal, not zot's UI spelling.
280			effort = "minimal"
281		}
282		if effort != "" {
283			out.ReasoningEffort = effort
284		}
285	} else if maxTok > 0 {
286		// Omit max_tokens when unknown (some discovered models don't
287		// advertise an output cap) so the server applies its own default
288		// instead of receiving an invalid max_tokens: 0.
289		out.MaxTokens = &maxTok
290	}
291
292	if req.System != "" {
293		out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
294	}
295
296	deferredMode := supportsDeferredTools(c.Name()) && isKimiDeferredModel(req.Model)
297	toolByName := make(map[string]Tool, len(req.Tools))
298	for _, t := range req.Tools {
299		toolByName[t.Name] = t
300	}
301	activatedTools := activatedToolNames(req.Messages)
302
303	// DeepSeek's chat-completions API rejects the multimodal content
304	// schema (parts arrays containing image_url). Force every user/tool
305	// message to a plain string and silently drop image blocks for
306	// this provider so historical sessions with screenshots still replay.
307	textOnly := c.name == "deepseek"
308
309	req.Messages = RepairOrphanedToolResults(req.Messages)
310	for msgIndex := 0; msgIndex < len(req.Messages); msgIndex++ {
311		msg := req.Messages[msgIndex]
312		addedToolNames := append([]string(nil), msg.AddedToolNames...)
313		switch msg.Role {
314		case RoleUser:
315			content := buildOAIUserContent(msg.Content, textOnly)
316			out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
317		case RoleAssistant:
318			am := oaiMessage{Role: "assistant"}
319			var text strings.Builder
320			var reasoning strings.Builder
321			for _, b := range msg.Content {
322				switch v := b.(type) {
323				case TextBlock:
324					if strings.TrimSpace(v.Text) == "" {
325						continue
326					}
327					if text.Len() > 0 {
328						text.WriteString("\n")
329					}
330					text.WriteString(v.Text)
331				case ToolCallBlock:
332					if v.Server {
333						continue
334					}
335					args := v.Arguments
336					if len(args) == 0 || !json.Valid(args) {
337						args = json.RawMessage("{}")
338					}
339					am.ToolCalls = append(am.ToolCalls, oaiToolCall{
340						ID:   v.ID,
341						Type: "function",
342						Function: oaiToolCallFn{
343							Name:      v.Name,
344							Arguments: string(args),
345						},
346					})
347				case ReasoningBlock:
348					if v.Summary != "" {
349						if reasoning.Len() > 0 {
350							reasoning.WriteString("\n")
351						}
352						reasoning.WriteString(v.Summary)
353					}
354				}
355			}
356			if text.Len() > 0 {
357				am.Content = text.String()
358			}
359			if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
360				am.ReasoningContent = reasoning.String()
361			}
362			// Kimi rejects assistant messages with neither visible text nor
363			// tool calls ("assistant must not be empty"). This can happen when
364			// a previous stream produced only reasoning_content, which zot keeps
365			// internally for provider replay but cannot send back as standalone
366			// assistant content on OpenAI-compatible chat-completions APIs.
367			if am.Content == nil && len(am.ToolCalls) == 0 {
368				continue
369			}
370			out.Messages = append(out.Messages, am)
371		case RoleTool:
372			// Chat Completions tool messages only carry text. Keep every
373			// tool result paired with its call, then deliver any images in
374			// one user message after the complete batch of tool results.
375			// Strict OpenAI-compatible APIs reject image_url blocks on a
376			// role=tool message.
377			var images []Content
378			groupEnd := msgIndex
379			for groupEnd < len(req.Messages) && req.Messages[groupEnd].Role == RoleTool {
380				toolMessage := req.Messages[groupEnd]
381				if groupEnd > msgIndex {
382					addedToolNames = append(addedToolNames, toolMessage.AddedToolNames...)
383				}
384				for _, b := range toolMessage.Content {
385					if tr, ok := b.(ToolResultBlock); ok {
386						content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
387						out.Messages = append(out.Messages, oaiMessage{
388							Role:       "tool",
389							ToolCallID: tr.CallID,
390							Content:    content,
391						})
392						if !textOnly {
393							for _, inner := range tr.Content {
394								if image, ok := inner.(ImageBlock); ok {
395									images = append(images, image)
396								}
397							}
398						}
399					}
400				}
401				groupEnd++
402			}
403			// The built-in OpenAI client also persists this image mirror so
404			// Responses-routed models can consume it. Reuse that next message
405			// instead of sending the image twice.
406			hasPersistedMirror := groupEnd < len(req.Messages) && isOpenAIToolImageMirror(req.Messages[groupEnd])
407			if len(images) > 0 && !hasPersistedMirror {
408				content := append([]Content{TextBlock{Text: "Tool output included the following image content:"}}, images...)
409				out.Messages = append(out.Messages, oaiMessage{
410					Role:    "user",
411					Content: buildOAIContentBlocks(content, false),
412				})
413			}
414			msgIndex = groupEnd - 1
415		}
416		if deferredMode {
417			var loaded []oaiTool
418			for _, name := range addedToolNames {
419				if t, ok := toolByName[name]; ok && t.Deferred {
420					loaded = append(loaded, makeOAITool(t))
421				}
422			}
423			if len(loaded) > 0 {
424				out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
425			}
426		}
427	}
428
429	for _, t := range req.Tools {
430		if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
431			continue
432		}
433		out.Tools = append(out.Tools, makeOAITool(t))
434	}
435	if len(out.Tools) > 0 {
436		out.ToolChoice = "auto"
437	}
438
439	return out, nil
440}
441
442func isKimiDeferredModel(model string) bool {
443	model = strings.ToLower(model)
444	return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
445}
446
447// supportsDeferredTools reports whether a provider speaks Moonshot's
448// deferred-tools handshake, where a tool that becomes available mid-conversation
449// is delivered on a system message carrying a `tools` array.
450//
451// That message is a Moonshot API extension, not OpenAI wire format: it has no
452// content, which a strict chat-completions schema rejects outright. Gondola,
453// which serves kimi-k3 on top of Venice, answers "messages.N: Invalid input"
454// and the conversation cannot recover, because the injection is rebuilt from
455// message history on every later turn. Providers outside this list take the
456// standard path instead, where an activated deferred tool joins the top-level
457// tools array.
458func supportsDeferredTools(provider string) bool {
459	return provider == "moonshotai" || provider == "moonshotai-cn"
460}
461
462func isOpenRouterServerToolType(typ string) bool {
463	return strings.HasPrefix(typ, "openrouter:")
464}
465
466func makeOAITool(t Tool) oaiTool {
467	if isOpenRouterServerToolType(t.Name) {
468		return oaiTool{Type: t.Name, Parameters: t.Schema}
469	}
470	var tool oaiTool
471	tool.Type = "function"
472	tool.Function = &struct {
473		Name        string          `json:"name"`
474		Description string          `json:"description,omitempty"`
475		Parameters  json.RawMessage `json:"parameters"`
476	}{
477		Name:        t.Name,
478		Description: t.Description,
479		Parameters:  t.Schema,
480	}
481	return tool
482}
483
484func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
485	hasImage := false
486	for _, b := range blocks {
487		if _, ok := b.(ImageBlock); ok {
488			hasImage = true
489			break
490		}
491	}
492	if textOnly || !hasImage {
493		var sb strings.Builder
494		for _, b := range blocks {
495			if tb, ok := b.(TextBlock); ok {
496				if sb.Len() > 0 {
497					sb.WriteString("\n")
498				}
499				sb.WriteString(tb.Text)
500			}
501		}
502		return sb.String()
503	}
504	return buildOAIContentBlocks(blocks, false)
505}
506
507func buildOAIToolContent(blocks []Content, isError, textOnly bool) string {
508	var sb strings.Builder
509	hasImage := false
510	for _, b := range blocks {
511		switch v := b.(type) {
512		case TextBlock:
513			if sb.Len() > 0 {
514				sb.WriteString("\n")
515			}
516			sb.WriteString(v.Text)
517		case ImageBlock:
518			hasImage = true
519		}
520	}
521	if sb.Len() == 0 && hasImage && !textOnly {
522		sb.WriteString("(see attached image)")
523	}
524	if isError && sb.Len() > 0 {
525		sb.WriteString(" [error]")
526	}
527	return sb.String()
528}
529
530func isOpenAIToolImageMirror(msg Message) bool {
531	if msg.Role != RoleUser || len(msg.Content) < 2 {
532		return false
533	}
534	text, ok := msg.Content[0].(TextBlock)
535	if !ok || text.Text != "Tool output included the following image content:" {
536		return false
537	}
538	for _, content := range msg.Content[1:] {
539		if _, ok := content.(ImageBlock); ok {
540			return true
541		}
542	}
543	return false
544}
545
546func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
547	var arr []interface{}
548	for _, b := range blocks {
549		switch v := b.(type) {
550		case TextBlock:
551			arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
552		case ImageBlock:
553			var img oaiContentImage
554			img.Type = "image_url"
555			img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
556			arr = append(arr, img)
557		}
558	}
559	if isError {
560		arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
561	}
562	return arr
563}
564
565// ---- streaming ----
566
567func (c *openaiClient) chatCompletionsURL() string {
568	if c.chatCompletionsPath != "" {
569		return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
570	}
571	return chatCompletionsURL(c.baseURL)
572}
573
574func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
575	endpoint := c.chatCompletionsURL()
576	wire, err := c.buildRequest(req)
577	if err != nil {
578		return nil, err
579	}
580	body, err := json.Marshal(wire)
581	if err != nil {
582		return nil, err
583	}
584	newReq := func() (*http.Request, error) {
585		httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
586		if err != nil {
587			return nil, err
588		}
589		httpReq.Header.Set("content-type", "application/json")
590		httpReq.Header.Set("accept", "text/event-stream")
591		httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
592		for k, v := range c.headers {
593			httpReq.Header.Set(k, v)
594		}
595		return httpReq, nil
596	}
597
598	resp, err := doStreamWithRetry(ctx, c.http, newReq)
599	if err != nil {
600		return nil, fmt.Errorf("%s: %w", c.Name(), err)
601	}
602	if resp.StatusCode != http.StatusOK {
603		b, _ := io.ReadAll(resp.Body)
604		resp.Body.Close()
605		return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
606	}
607
608	out := make(chan Event, 16)
609	go c.runStream(ctx, resp, req, out)
610	return out, nil
611}
612
613func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
614	defer close(out)
615	defer resp.Body.Close()
616
617	model, _ := FindModel("", req.Model)
618	out <- EventStart{Model: req.Model, Provider: c.Name()}
619
620	raw := make(chan sseEvent, 16)
621	go readSSE(resp.Body, raw)
622
623	// Interleaved block tracking: text and tool_calls preserve their
624	// emission order so the assistant message renders in the same order
625	// the model produced it. The builder fires one kind of block at a
626	// time — incoming text deltas after a tool_call split into a fresh
627	// text block; subsequent tool_calls each get their own slot.
628	type blockEntry struct {
629		kind      string // "text" | "tool_use"
630		textBuf   strings.Builder
631		toolID    string
632		toolName  string
633		toolArgs  strings.Builder
634		announced bool
635		server    bool
636	}
637	var (
638		blocks       []*blockEntry
639		currentText  *blockEntry             // most-recent text block, nil if none
640		toolByIdx    = map[int]*blockEntry{} // openai tool_call index -> block
641		reasoningBuf strings.Builder
642		usage        Usage
643		stop         StopReason = StopEnd
644		finalErr     error
645	)
646
647	appendText := func(delta string) {
648		if currentText == nil {
649			currentText = &blockEntry{kind: "text"}
650			blocks = append(blocks, currentText)
651		}
652		currentText.textBuf.WriteString(delta)
653	}
654
655	getOrCreateTool := func(idx int) *blockEntry {
656		if t, ok := toolByIdx[idx]; ok {
657			return t
658		}
659		t := &blockEntry{kind: "tool_use"}
660		toolByIdx[idx] = t
661		blocks = append(blocks, t)
662		// A new tool block breaks the current text block. Subsequent text
663		// deltas will start a fresh text block after this tool.
664		currentText = nil
665		return t
666	}
667
668	assembleMsg := func() Message {
669		content := []Content{}
670		for _, b := range blocks {
671			switch b.kind {
672			case "text":
673				if b.textBuf.Len() > 0 {
674					content = append(content, TextBlock{Text: b.textBuf.String()})
675				}
676			case "tool_use":
677				args := b.toolArgs.String()
678				if args == "" || !json.Valid([]byte(args)) {
679					args = "{}"
680				}
681				content = append(content, ToolCallBlock{
682					ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args), Server: b.server,
683				})
684			}
685		}
686		if reasoningBuf.Len() > 0 {
687			content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
688		}
689		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
690	}
691
692	sendDone := func() {
693		usage.CostUSD = ComputeCost(model, usage)
694		out <- EventUsage{Usage: usage}
695		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
696	}
697
698	for {
699		select {
700		case <-ctx.Done():
701			stop = StopAborted
702			finalErr = ctx.Err()
703			sendDone()
704			return
705		case ev, ok := <-raw:
706			if !ok {
707				sendDone()
708				return
709			}
710			if ev.Data == "[DONE]" {
711				sendDone()
712				return
713			}
714			var chunk struct {
715				Choices []struct {
716					Index int `json:"index"`
717					Delta struct {
718						Content          string `json:"content"`
719						ReasoningContent string `json:"reasoning_content"`
720						ToolCalls        []struct {
721							Index     int             `json:"index"`
722							ID        string          `json:"id"`
723							Type      string          `json:"type"`
724							Name      string          `json:"name"`
725							Arguments json.RawMessage `json:"arguments"`
726							Function  struct {
727								Name      string `json:"name"`
728								Arguments string `json:"arguments"`
729							} `json:"function"`
730						} `json:"tool_calls"`
731					} `json:"delta"`
732					FinishReason string `json:"finish_reason"`
733				} `json:"choices"`
734				Usage *struct {
735					PromptTokens        int `json:"prompt_tokens"`
736					CompletionTokens    int `json:"completion_tokens"`
737					PromptTokensDetails struct {
738						CachedTokens int `json:"cached_tokens"`
739					} `json:"prompt_tokens_details"`
740					CompletionTokensDetails *struct {
741						ReasoningTokens int `json:"reasoning_tokens"`
742					} `json:"completion_tokens_details"`
743				} `json:"usage"`
744				Error *struct {
745					Message string `json:"message"`
746					Type    string `json:"type"`
747				} `json:"error"`
748			}
749			if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
750				continue
751			}
752			if chunk.Error != nil {
753				stop = StopError
754				finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
755				sendDone()
756				return
757			}
758			if chunk.Usage != nil {
759				usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
760				if usage.InputTokens < 0 {
761					usage.InputTokens = chunk.Usage.PromptTokens
762				}
763				usage.OutputTokens = chunk.Usage.CompletionTokens
764				usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
765				if details := chunk.Usage.CompletionTokensDetails; details != nil {
766					usage.ReasoningTokens = details.ReasoningTokens
767					usage.ReasoningTokensKnown = true
768				}
769			}
770			for _, ch := range chunk.Choices {
771				if ch.Delta.ReasoningContent != "" {
772					reasoningBuf.WriteString(ch.Delta.ReasoningContent)
773				}
774				if ch.Delta.Content != "" {
775					appendText(ch.Delta.Content)
776					out <- EventTextDelta{Delta: ch.Delta.Content}
777				}
778				for _, tc := range ch.Delta.ToolCalls {
779					t := getOrCreateTool(tc.Index)
780					if tc.ID != "" {
781						t.toolID = tc.ID
782					}
783					if isOpenRouterServerToolType(tc.Type) {
784						t.server = true
785						if tc.Name != "" {
786							t.toolName = tc.Name
787						} else if t.toolName == "" {
788							t.toolName = tc.Type
789						}
790						if len(tc.Arguments) > 0 {
791							t.toolArgs.Write(tc.Arguments)
792						}
793					}
794					if tc.Function.Name != "" {
795						t.toolName = tc.Function.Name
796						if isOpenRouterServerToolType(tc.Function.Name) {
797							t.server = true
798						}
799					}
800					if !t.announced && t.toolID != "" && t.toolName != "" {
801						t.announced = true
802						out <- EventToolStart{ID: t.toolID, Name: t.toolName}
803					}
804					if tc.Function.Arguments != "" {
805						t.toolArgs.WriteString(tc.Function.Arguments)
806						if t.announced {
807							out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
808						}
809					}
810				}
811				switch ch.FinishReason {
812				case "stop":
813					stop = StopEnd
814				case "length":
815					stop = StopLength
816				case "tool_calls", "function_call":
817					stop = StopToolUse
818					hasClientTool := false
819					for _, b := range blocks {
820						if b.kind == "tool_use" && b.announced {
821							out <- EventToolEnd{ID: b.toolID}
822							if !b.server {
823								hasClientTool = true
824							}
825						}
826					}
827					if !hasClientTool {
828						// OpenRouter executed every tool server-side; the
829						// client must not send tool_result messages.
830						stop = StopEnd
831					}
832				}
833			}
834		}
835	}
836}

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