v0.3.68 a98ca1a

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 effort != "" {
279			out.ReasoningEffort = effort
280		}
281	} else if maxTok > 0 {
282		// Omit max_tokens when unknown (some discovered models don't
283		// advertise an output cap) so the server applies its own default
284		// instead of receiving an invalid max_tokens: 0.
285		out.MaxTokens = &maxTok
286	}
287
288	if req.System != "" {
289		out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
290	}
291
292	deferredMode := supportsDeferredTools(c.Name()) && isKimiDeferredModel(req.Model)
293	toolByName := make(map[string]Tool, len(req.Tools))
294	for _, t := range req.Tools {
295		toolByName[t.Name] = t
296	}
297	activatedTools := activatedToolNames(req.Messages)
298
299	// DeepSeek's chat-completions API rejects the multimodal content
300	// schema (parts arrays containing image_url). Force every user/tool
301	// message to a plain string and silently drop image blocks for
302	// this provider so historical sessions with screenshots still replay.
303	textOnly := c.name == "deepseek"
304
305	req.Messages = RepairOrphanedToolResults(req.Messages)
306	for msgIndex := 0; msgIndex < len(req.Messages); msgIndex++ {
307		msg := req.Messages[msgIndex]
308		addedToolNames := append([]string(nil), msg.AddedToolNames...)
309		switch msg.Role {
310		case RoleUser:
311			content := buildOAIUserContent(msg.Content, textOnly)
312			out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
313		case RoleAssistant:
314			am := oaiMessage{Role: "assistant"}
315			var text strings.Builder
316			var reasoning strings.Builder
317			for _, b := range msg.Content {
318				switch v := b.(type) {
319				case TextBlock:
320					if strings.TrimSpace(v.Text) == "" {
321						continue
322					}
323					if text.Len() > 0 {
324						text.WriteString("\n")
325					}
326					text.WriteString(v.Text)
327				case ToolCallBlock:
328					if v.Server {
329						continue
330					}
331					args := v.Arguments
332					if len(args) == 0 || !json.Valid(args) {
333						args = json.RawMessage("{}")
334					}
335					am.ToolCalls = append(am.ToolCalls, oaiToolCall{
336						ID:   v.ID,
337						Type: "function",
338						Function: oaiToolCallFn{
339							Name:      v.Name,
340							Arguments: string(args),
341						},
342					})
343				case ReasoningBlock:
344					if v.Summary != "" {
345						if reasoning.Len() > 0 {
346							reasoning.WriteString("\n")
347						}
348						reasoning.WriteString(v.Summary)
349					}
350				}
351			}
352			if text.Len() > 0 {
353				am.Content = text.String()
354			}
355			if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
356				am.ReasoningContent = reasoning.String()
357			}
358			// Kimi rejects assistant messages with neither visible text nor
359			// tool calls ("assistant must not be empty"). This can happen when
360			// a previous stream produced only reasoning_content, which zot keeps
361			// internally for provider replay but cannot send back as standalone
362			// assistant content on OpenAI-compatible chat-completions APIs.
363			if am.Content == nil && len(am.ToolCalls) == 0 {
364				continue
365			}
366			out.Messages = append(out.Messages, am)
367		case RoleTool:
368			// Chat Completions tool messages only carry text. Keep every
369			// tool result paired with its call, then deliver any images in
370			// one user message after the complete batch of tool results.
371			// Strict OpenAI-compatible APIs reject image_url blocks on a
372			// role=tool message.
373			var images []Content
374			groupEnd := msgIndex
375			for groupEnd < len(req.Messages) && req.Messages[groupEnd].Role == RoleTool {
376				toolMessage := req.Messages[groupEnd]
377				if groupEnd > msgIndex {
378					addedToolNames = append(addedToolNames, toolMessage.AddedToolNames...)
379				}
380				for _, b := range toolMessage.Content {
381					if tr, ok := b.(ToolResultBlock); ok {
382						content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
383						out.Messages = append(out.Messages, oaiMessage{
384							Role:       "tool",
385							ToolCallID: tr.CallID,
386							Content:    content,
387						})
388						if !textOnly {
389							for _, inner := range tr.Content {
390								if image, ok := inner.(ImageBlock); ok {
391									images = append(images, image)
392								}
393							}
394						}
395					}
396				}
397				groupEnd++
398			}
399			// The built-in OpenAI client also persists this image mirror so
400			// Responses-routed models can consume it. Reuse that next message
401			// instead of sending the image twice.
402			hasPersistedMirror := groupEnd < len(req.Messages) && isOpenAIToolImageMirror(req.Messages[groupEnd])
403			if len(images) > 0 && !hasPersistedMirror {
404				content := append([]Content{TextBlock{Text: "Tool output included the following image content:"}}, images...)
405				out.Messages = append(out.Messages, oaiMessage{
406					Role:    "user",
407					Content: buildOAIContentBlocks(content, false),
408				})
409			}
410			msgIndex = groupEnd - 1
411		}
412		if deferredMode {
413			var loaded []oaiTool
414			for _, name := range addedToolNames {
415				if t, ok := toolByName[name]; ok && t.Deferred {
416					loaded = append(loaded, makeOAITool(t))
417				}
418			}
419			if len(loaded) > 0 {
420				out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
421			}
422		}
423	}
424
425	for _, t := range req.Tools {
426		if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
427			continue
428		}
429		out.Tools = append(out.Tools, makeOAITool(t))
430	}
431	if len(out.Tools) > 0 {
432		out.ToolChoice = "auto"
433	}
434
435	return out, nil
436}
437
438func isKimiDeferredModel(model string) bool {
439	model = strings.ToLower(model)
440	return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
441}
442
443// supportsDeferredTools reports whether a provider speaks Moonshot's
444// deferred-tools handshake, where a tool that becomes available mid-conversation
445// is delivered on a system message carrying a `tools` array.
446//
447// That message is a Moonshot API extension, not OpenAI wire format: it has no
448// content, which a strict chat-completions schema rejects outright. Gondola,
449// which serves kimi-k3 on top of Venice, answers "messages.N: Invalid input"
450// and the conversation cannot recover, because the injection is rebuilt from
451// message history on every later turn. Providers outside this list take the
452// standard path instead, where an activated deferred tool joins the top-level
453// tools array.
454func supportsDeferredTools(provider string) bool {
455	return provider == "moonshotai" || provider == "moonshotai-cn"
456}
457
458func isOpenRouterServerToolType(typ string) bool {
459	return strings.HasPrefix(typ, "openrouter:")
460}
461
462func makeOAITool(t Tool) oaiTool {
463	if isOpenRouterServerToolType(t.Name) {
464		return oaiTool{Type: t.Name, Parameters: t.Schema}
465	}
466	var tool oaiTool
467	tool.Type = "function"
468	tool.Function = &struct {
469		Name        string          `json:"name"`
470		Description string          `json:"description,omitempty"`
471		Parameters  json.RawMessage `json:"parameters"`
472	}{
473		Name:        t.Name,
474		Description: t.Description,
475		Parameters:  t.Schema,
476	}
477	return tool
478}
479
480func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
481	hasImage := false
482	for _, b := range blocks {
483		if _, ok := b.(ImageBlock); ok {
484			hasImage = true
485			break
486		}
487	}
488	if textOnly || !hasImage {
489		var sb strings.Builder
490		for _, b := range blocks {
491			if tb, ok := b.(TextBlock); ok {
492				if sb.Len() > 0 {
493					sb.WriteString("\n")
494				}
495				sb.WriteString(tb.Text)
496			}
497		}
498		return sb.String()
499	}
500	return buildOAIContentBlocks(blocks, false)
501}
502
503func buildOAIToolContent(blocks []Content, isError, textOnly bool) string {
504	var sb strings.Builder
505	hasImage := false
506	for _, b := range blocks {
507		switch v := b.(type) {
508		case TextBlock:
509			if sb.Len() > 0 {
510				sb.WriteString("\n")
511			}
512			sb.WriteString(v.Text)
513		case ImageBlock:
514			hasImage = true
515		}
516	}
517	if sb.Len() == 0 && hasImage && !textOnly {
518		sb.WriteString("(see attached image)")
519	}
520	if isError && sb.Len() > 0 {
521		sb.WriteString(" [error]")
522	}
523	return sb.String()
524}
525
526func isOpenAIToolImageMirror(msg Message) bool {
527	if msg.Role != RoleUser || len(msg.Content) < 2 {
528		return false
529	}
530	text, ok := msg.Content[0].(TextBlock)
531	if !ok || text.Text != "Tool output included the following image content:" {
532		return false
533	}
534	for _, content := range msg.Content[1:] {
535		if _, ok := content.(ImageBlock); ok {
536			return true
537		}
538	}
539	return false
540}
541
542func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
543	var arr []interface{}
544	for _, b := range blocks {
545		switch v := b.(type) {
546		case TextBlock:
547			arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
548		case ImageBlock:
549			var img oaiContentImage
550			img.Type = "image_url"
551			img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
552			arr = append(arr, img)
553		}
554	}
555	if isError {
556		arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
557	}
558	return arr
559}
560
561// ---- streaming ----
562
563func (c *openaiClient) chatCompletionsURL() string {
564	if c.chatCompletionsPath != "" {
565		return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
566	}
567	return chatCompletionsURL(c.baseURL)
568}
569
570func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
571	endpoint := c.chatCompletionsURL()
572	wire, err := c.buildRequest(req)
573	if err != nil {
574		return nil, err
575	}
576	body, err := json.Marshal(wire)
577	if err != nil {
578		return nil, err
579	}
580	newReq := func() (*http.Request, error) {
581		httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
582		if err != nil {
583			return nil, err
584		}
585		httpReq.Header.Set("content-type", "application/json")
586		httpReq.Header.Set("accept", "text/event-stream")
587		httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
588		for k, v := range c.headers {
589			httpReq.Header.Set(k, v)
590		}
591		return httpReq, nil
592	}
593
594	resp, err := doStreamWithRetry(ctx, c.http, newReq)
595	if err != nil {
596		return nil, fmt.Errorf("%s: %w", c.Name(), err)
597	}
598	if resp.StatusCode != http.StatusOK {
599		b, _ := io.ReadAll(resp.Body)
600		resp.Body.Close()
601		return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
602	}
603
604	out := make(chan Event, 16)
605	go c.runStream(ctx, resp, req, out)
606	return out, nil
607}
608
609func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
610	defer close(out)
611	defer resp.Body.Close()
612
613	model, _ := FindModel("", req.Model)
614	out <- EventStart{Model: req.Model, Provider: c.Name()}
615
616	raw := make(chan sseEvent, 16)
617	go readSSE(resp.Body, raw)
618
619	// Interleaved block tracking: text and tool_calls preserve their
620	// emission order so the assistant message renders in the same order
621	// the model produced it. The builder fires one kind of block at a
622	// time — incoming text deltas after a tool_call split into a fresh
623	// text block; subsequent tool_calls each get their own slot.
624	type blockEntry struct {
625		kind      string // "text" | "tool_use"
626		textBuf   strings.Builder
627		toolID    string
628		toolName  string
629		toolArgs  strings.Builder
630		announced bool
631		server    bool
632	}
633	var (
634		blocks       []*blockEntry
635		currentText  *blockEntry             // most-recent text block, nil if none
636		toolByIdx    = map[int]*blockEntry{} // openai tool_call index -> block
637		reasoningBuf strings.Builder
638		usage        Usage
639		stop         StopReason = StopEnd
640		finalErr     error
641	)
642
643	appendText := func(delta string) {
644		if currentText == nil {
645			currentText = &blockEntry{kind: "text"}
646			blocks = append(blocks, currentText)
647		}
648		currentText.textBuf.WriteString(delta)
649	}
650
651	getOrCreateTool := func(idx int) *blockEntry {
652		if t, ok := toolByIdx[idx]; ok {
653			return t
654		}
655		t := &blockEntry{kind: "tool_use"}
656		toolByIdx[idx] = t
657		blocks = append(blocks, t)
658		// A new tool block breaks the current text block. Subsequent text
659		// deltas will start a fresh text block after this tool.
660		currentText = nil
661		return t
662	}
663
664	assembleMsg := func() Message {
665		content := []Content{}
666		for _, b := range blocks {
667			switch b.kind {
668			case "text":
669				if b.textBuf.Len() > 0 {
670					content = append(content, TextBlock{Text: b.textBuf.String()})
671				}
672			case "tool_use":
673				args := b.toolArgs.String()
674				if args == "" || !json.Valid([]byte(args)) {
675					args = "{}"
676				}
677				content = append(content, ToolCallBlock{
678					ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args), Server: b.server,
679				})
680			}
681		}
682		if reasoningBuf.Len() > 0 {
683			content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
684		}
685		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
686	}
687
688	sendDone := func() {
689		usage.CostUSD = ComputeCost(model, usage)
690		out <- EventUsage{Usage: usage}
691		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
692	}
693
694	for {
695		select {
696		case <-ctx.Done():
697			stop = StopAborted
698			finalErr = ctx.Err()
699			sendDone()
700			return
701		case ev, ok := <-raw:
702			if !ok {
703				sendDone()
704				return
705			}
706			if ev.Data == "[DONE]" {
707				sendDone()
708				return
709			}
710			var chunk struct {
711				Choices []struct {
712					Index int `json:"index"`
713					Delta struct {
714						Content          string `json:"content"`
715						ReasoningContent string `json:"reasoning_content"`
716						ToolCalls        []struct {
717							Index     int             `json:"index"`
718							ID        string          `json:"id"`
719							Type      string          `json:"type"`
720							Name      string          `json:"name"`
721							Arguments json.RawMessage `json:"arguments"`
722							Function  struct {
723								Name      string `json:"name"`
724								Arguments string `json:"arguments"`
725							} `json:"function"`
726						} `json:"tool_calls"`
727					} `json:"delta"`
728					FinishReason string `json:"finish_reason"`
729				} `json:"choices"`
730				Usage *struct {
731					PromptTokens        int `json:"prompt_tokens"`
732					CompletionTokens    int `json:"completion_tokens"`
733					PromptTokensDetails struct {
734						CachedTokens int `json:"cached_tokens"`
735					} `json:"prompt_tokens_details"`
736					CompletionTokensDetails *struct {
737						ReasoningTokens int `json:"reasoning_tokens"`
738					} `json:"completion_tokens_details"`
739				} `json:"usage"`
740				Error *struct {
741					Message string `json:"message"`
742					Type    string `json:"type"`
743				} `json:"error"`
744			}
745			if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
746				continue
747			}
748			if chunk.Error != nil {
749				stop = StopError
750				finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
751				sendDone()
752				return
753			}
754			if chunk.Usage != nil {
755				usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
756				if usage.InputTokens < 0 {
757					usage.InputTokens = chunk.Usage.PromptTokens
758				}
759				usage.OutputTokens = chunk.Usage.CompletionTokens
760				usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
761				if details := chunk.Usage.CompletionTokensDetails; details != nil {
762					usage.ReasoningTokens = details.ReasoningTokens
763					usage.ReasoningTokensKnown = true
764				}
765			}
766			for _, ch := range chunk.Choices {
767				if ch.Delta.ReasoningContent != "" {
768					reasoningBuf.WriteString(ch.Delta.ReasoningContent)
769				}
770				if ch.Delta.Content != "" {
771					appendText(ch.Delta.Content)
772					out <- EventTextDelta{Delta: ch.Delta.Content}
773				}
774				for _, tc := range ch.Delta.ToolCalls {
775					t := getOrCreateTool(tc.Index)
776					if tc.ID != "" {
777						t.toolID = tc.ID
778					}
779					if isOpenRouterServerToolType(tc.Type) {
780						t.server = true
781						if tc.Name != "" {
782							t.toolName = tc.Name
783						} else if t.toolName == "" {
784							t.toolName = tc.Type
785						}
786						if len(tc.Arguments) > 0 {
787							t.toolArgs.Write(tc.Arguments)
788						}
789					}
790					if tc.Function.Name != "" {
791						t.toolName = tc.Function.Name
792						if isOpenRouterServerToolType(tc.Function.Name) {
793							t.server = true
794						}
795					}
796					if !t.announced && t.toolID != "" && t.toolName != "" {
797						t.announced = true
798						out <- EventToolStart{ID: t.toolID, Name: t.toolName}
799					}
800					if tc.Function.Arguments != "" {
801						t.toolArgs.WriteString(tc.Function.Arguments)
802						if t.announced {
803							out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
804						}
805					}
806				}
807				switch ch.FinishReason {
808				case "stop":
809					stop = StopEnd
810				case "length":
811					stop = StopLength
812				case "tool_calls", "function_call":
813					stop = StopToolUse
814					hasClientTool := false
815					for _, b := range blocks {
816						if b.kind == "tool_use" && b.announced {
817							out <- EventToolEnd{ID: b.toolID}
818							if !b.server {
819								hasClientTool = true
820							}
821						}
822					}
823					if !hasClientTool {
824						// OpenRouter executed every tool server-side; the
825						// client must not send tool_result messages.
826						stop = StopEnd
827					}
828				}
829			}
830		}
831	}
832}

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