v0.11.5 c4261b5

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"
138	Function oaiToolCallFn `json:"function"`
139}
140
141type oaiMessage struct {
142	Role       string        `json:"role"`
143	Content    interface{}   `json:"content,omitempty"` // string or []block
144	Name       string        `json:"name,omitempty"`
145	ToolCalls  []oaiToolCall `json:"tool_calls,omitempty"`
146	ToolCallID string        `json:"tool_call_id,omitempty"`
147	Tools      []oaiTool     `json:"tools,omitempty"`
148	// ReasoningContent carries the model's chain-of-thought summary
149	// alongside an assistant tool-call message. Required by Kimi's
150	// chat completions endpoint when thinking is enabled and the
151	// assistant message contains a tool call; OpenAI ignores it.
152	ReasoningContent string `json:"reasoning_content,omitempty"`
153}
154
155type oaiTool struct {
156	Type     string `json:"type"` // "function"
157	Function struct {
158		Name        string          `json:"name"`
159		Description string          `json:"description,omitempty"`
160		Parameters  json.RawMessage `json:"parameters"`
161	} `json:"function"`
162}
163
164type oaiStreamOptions struct {
165	IncludeUsage bool `json:"include_usage"`
166}
167
168type oaiRequest struct {
169	Model            string            `json:"model"`
170	Messages         []oaiMessage      `json:"messages"`
171	Tools            []oaiTool         `json:"tools,omitempty"`
172	ToolChoice       string            `json:"tool_choice,omitempty"`
173	Stream           bool              `json:"stream"`
174	StreamOptions    *oaiStreamOptions `json:"stream_options,omitempty"`
175	Temperature      *float32          `json:"temperature,omitempty"`
176	MaxTokens        *int              `json:"max_tokens,omitempty"`
177	MaxCompletionTok *int              `json:"max_completion_tokens,omitempty"`
178	ReasoningEffort  string            `json:"reasoning_effort,omitempty"`
179	ServiceTier      string            `json:"service_tier,omitempty"`
180}
181
182// ---- request building ----
183
184func (c *openaiClient) buildRequest(req Request) (*oaiRequest, error) {
185	if err := ValidateFastMode(c.Name(), req.FastMode); err != nil {
186		return nil, err
187	}
188	// The OpenAI wire client is shared by many providers, so prefer its own
189	// provider namespace before falling back to a provider-agnostic lookup.
190	m, err := FindModel(c.Name(), req.Model)
191	if err != nil {
192		m, err = FindModel("", req.Model)
193	}
194	if err != nil {
195		// Unknown model: use sensible defaults so local/custom
196		// models still work without a catalog entry.
197		m = Model{
198			ID:            req.Model,
199			ContextWindow: 32768,
200			MaxOutput:     8192,
201		}
202	}
203	reasoning := ClampReasoningForModel(m, req.Reasoning)
204	out := &oaiRequest{
205		Model:         req.Model,
206		Stream:        true,
207		StreamOptions: &oaiStreamOptions{IncludeUsage: true},
208		Temperature:   req.Temperature,
209	}
210	if req.FastMode {
211		out.ServiceTier = fastModeServiceTier
212	}
213
214	maxTok := req.MaxTokens
215	if maxTok <= 0 {
216		maxTok = m.MaxOutput
217	}
218	// Clamp max_tokens so output plus a minimum input reservation fits
219	// within the context window. Some providers (OpenRouter) enforce
220	// input + max_output <= context_length and reject requests where the
221	// total exceeds it. Reserving headroom guarantees the system prompt,
222	// first message, and tool definitions have room.
223	//
224	// The cap is derived from the context window, never from MaxOutput:
225	// MaxOutput is already the output ceiling, so subtracting from it
226	// would shrink every model's budget even when its output comfortably
227	// fits the window. We only lower maxTok when ContextWindow - reserve
228	// is actually tighter than the requested budget, which is exactly the
229	// pathological case (e.g. a model whose MaxOutput equals its window).
230	//
231	// The reserve is proportional (window/8, capped at 4096) rather than a
232	// flat 4096 so small-window models aren't over-penalized: a flat 4096
233	// would halve gpt-4's 8192 budget, while window/8 reserves a sensible
234	// 1024 there and still tops out at 4096 for large contexts.
235	//
236	// Some providers (OpenRouter) report inflated model-level context
237	// windows (e.g. 1000000) while the serving provider enforces a much
238	// tighter limit (e.g. 262144). Discovery already prefers the serving
239	// provider's smaller context_length, so m.ContextWindow is the real
240	// limit by the time we get here.
241	if m.ContextWindow > 0 {
242		reserve := m.ContextWindow / 8
243		const maxReserve = 4096
244		if reserve > maxReserve {
245			reserve = maxReserve
246		}
247		clamped := m.ContextWindow - reserve
248		if clamped < 1 {
249			clamped = 1
250		}
251		if maxTok > clamped {
252			maxTok = clamped
253		}
254	}
255	if m.Reasoning {
256		if maxTok > 0 {
257			out.MaxCompletionTok = &maxTok
258		}
259		effort := OpenAIReasoningEffort(reasoning)
260		if usesAdaptiveThinking(m) {
261			// Some gateways expose adaptive-thinking Anthropic models through
262			// the OpenAI-compatible chat-completions wire. They accept the
263			// same reasoning_effort knob, including the top "xhigh" tier;
264			// don't clamp zut's "maximum" to "high" for those models.
265			effort = OpenAICompatAnthropicEffort(reasoning)
266		}
267		if effort != "" {
268			out.ReasoningEffort = effort
269		}
270	} else if maxTok > 0 {
271		// Omit max_tokens when unknown (some discovered models don't
272		// advertise an output cap) so the server applies its own default
273		// instead of receiving an invalid max_tokens: 0.
274		out.MaxTokens = &maxTok
275	}
276
277	if req.System != "" {
278		out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
279	}
280
281	deferredMode := isKimiDeferredModel(req.Model)
282	toolByName := make(map[string]Tool, len(req.Tools))
283	for _, t := range req.Tools {
284		toolByName[t.Name] = t
285	}
286	activatedTools := activatedToolNames(req.Messages)
287
288	// DeepSeek's chat-completions API rejects the multimodal content
289	// schema (parts arrays containing image_url). Force every user/tool
290	// message to a plain string and silently drop image blocks for
291	// this provider so historical sessions with screenshots still replay.
292	textOnly := c.name == "deepseek"
293
294	req.Messages = RepairOrphanedToolResults(req.Messages)
295	for _, msg := range req.Messages {
296		switch msg.Role {
297		case RoleUser:
298			content := buildOAIUserContent(msg.Content, textOnly)
299			out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
300		case RoleAssistant:
301			am := oaiMessage{Role: "assistant"}
302			var text strings.Builder
303			var reasoning strings.Builder
304			for _, b := range msg.Content {
305				switch v := b.(type) {
306				case TextBlock:
307					if strings.TrimSpace(v.Text) == "" {
308						continue
309					}
310					if text.Len() > 0 {
311						text.WriteString("\n")
312					}
313					text.WriteString(v.Text)
314				case ToolCallBlock:
315					args := v.Arguments
316					if len(args) == 0 || !json.Valid(args) {
317						args = json.RawMessage("{}")
318					}
319					am.ToolCalls = append(am.ToolCalls, oaiToolCall{
320						ID:   v.ID,
321						Type: "function",
322						Function: oaiToolCallFn{
323							Name:      v.Name,
324							Arguments: string(args),
325						},
326					})
327				case ReasoningBlock:
328					if v.Summary != "" {
329						if reasoning.Len() > 0 {
330							reasoning.WriteString("\n")
331						}
332						reasoning.WriteString(v.Summary)
333					}
334				}
335			}
336			if text.Len() > 0 {
337				am.Content = text.String()
338			}
339			if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
340				am.ReasoningContent = reasoning.String()
341			}
342			// Kimi rejects assistant messages with neither visible text nor
343			// tool calls ("assistant must not be empty"). This can happen when
344			// a previous stream produced only reasoning_content, which zut keeps
345			// internally for provider replay but cannot send back as standalone
346			// assistant content on OpenAI-compatible chat-completions APIs.
347			if am.Content == nil && len(am.ToolCalls) == 0 {
348				continue
349			}
350			out.Messages = append(out.Messages, am)
351		case RoleTool:
352			// Each ToolResultBlock becomes its own tool message. Preserve
353			// image blocks for vision-capable OpenAI models instead of
354			// flattening the tool output to plain text.
355			for _, b := range msg.Content {
356				if tr, ok := b.(ToolResultBlock); ok {
357					content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
358					out.Messages = append(out.Messages, oaiMessage{
359						Role:       "tool",
360						ToolCallID: tr.CallID,
361						Content:    content,
362					})
363				}
364			}
365		}
366		if deferredMode {
367			var loaded []oaiTool
368			for _, name := range msg.AddedToolNames {
369				if t, ok := toolByName[name]; ok && t.Deferred {
370					loaded = append(loaded, makeOAITool(t))
371				}
372			}
373			if len(loaded) > 0 {
374				out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
375			}
376		}
377	}
378
379	for _, t := range req.Tools {
380		if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
381			continue
382		}
383		out.Tools = append(out.Tools, makeOAITool(t))
384	}
385	if len(out.Tools) > 0 {
386		out.ToolChoice = "auto"
387	}
388
389	return out, nil
390}
391
392func isKimiDeferredModel(model string) bool {
393	model = strings.ToLower(model)
394	return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
395}
396
397func makeOAITool(t Tool) oaiTool {
398	var tool oaiTool
399	tool.Type = "function"
400	tool.Function.Name = t.Name
401	tool.Function.Description = t.Description
402	tool.Function.Parameters = t.Schema
403	return tool
404}
405
406func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
407	hasImage := false
408	for _, b := range blocks {
409		if _, ok := b.(ImageBlock); ok {
410			hasImage = true
411			break
412		}
413	}
414	if textOnly || !hasImage {
415		var sb strings.Builder
416		for _, b := range blocks {
417			if tb, ok := b.(TextBlock); ok {
418				if sb.Len() > 0 {
419					sb.WriteString("\n")
420				}
421				sb.WriteString(tb.Text)
422			}
423		}
424		return sb.String()
425	}
426	return buildOAIContentBlocks(blocks, false)
427}
428
429func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
430	hasImage := false
431	for _, b := range blocks {
432		if _, ok := b.(ImageBlock); ok {
433			hasImage = true
434			break
435		}
436	}
437	if textOnly || !hasImage {
438		var sb strings.Builder
439		for _, b := range blocks {
440			if tb, ok := b.(TextBlock); ok {
441				if sb.Len() > 0 {
442					sb.WriteString("\n")
443				}
444				sb.WriteString(tb.Text)
445			}
446		}
447		if isError && sb.Len() > 0 {
448			sb.WriteString(" [error]")
449		}
450		return sb.String()
451	}
452	return buildOAIContentBlocks(blocks, isError)
453}
454
455func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
456	var arr []interface{}
457	for _, b := range blocks {
458		switch v := b.(type) {
459		case TextBlock:
460			arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
461		case ImageBlock:
462			var img oaiContentImage
463			img.Type = "image_url"
464			img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
465			arr = append(arr, img)
466		}
467	}
468	if isError {
469		arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
470	}
471	return arr
472}
473
474// ---- streaming ----
475
476func (c *openaiClient) chatCompletionsURL() string {
477	if c.chatCompletionsPath != "" {
478		return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
479	}
480	return chatCompletionsURL(c.baseURL)
481}
482
483func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
484	endpoint := c.chatCompletionsURL()
485	wire, err := c.buildRequest(req)
486	if err != nil {
487		return nil, err
488	}
489	body, err := json.Marshal(wire)
490	if err != nil {
491		return nil, err
492	}
493	newReq := func() (*http.Request, error) {
494		httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
495		if err != nil {
496			return nil, err
497		}
498		httpReq.Header.Set("content-type", "application/json")
499		httpReq.Header.Set("accept", "text/event-stream")
500		httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
501		for k, v := range c.headers {
502			httpReq.Header.Set(k, v)
503		}
504		return httpReq, nil
505	}
506
507	resp, err := doStreamWithRetry(ctx, c.http, newReq, req.Lifecycle)
508	if err != nil {
509		return nil, fmt.Errorf("%s: %w", c.Name(), err)
510	}
511	if resp.StatusCode != http.StatusOK {
512		b, _ := io.ReadAll(resp.Body)
513		resp.Body.Close()
514		return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
515	}
516
517	out := make(chan Event, 16)
518	go c.runStream(ctx, resp, req, out)
519	return out, nil
520}
521
522func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
523	defer close(out)
524	defer resp.Body.Close()
525
526	model, _ := FindModel("", req.Model)
527	out <- EventStart{Model: req.Model, Provider: c.Name()}
528
529	raw := make(chan sseEvent, 16)
530	go readSSE(resp.Body, raw)
531
532	// Interleaved block tracking: text and tool_calls preserve their
533	// emission order so the assistant message renders in the same order
534	// the model produced it. The builder fires one kind of block at a
535	// time — incoming text deltas after a tool_call split into a fresh
536	// text block; subsequent tool_calls each get their own slot.
537	type blockEntry struct {
538		kind      string // "text" | "tool_use"
539		textBuf   strings.Builder
540		toolID    string
541		toolName  string
542		toolArgs  strings.Builder
543		announced bool
544	}
545	var (
546		blocks       []*blockEntry
547		currentText  *blockEntry             // most-recent text block, nil if none
548		toolByIdx    = map[int]*blockEntry{} // openai tool_call index -> block
549		reasoningBuf strings.Builder
550		usage        Usage
551		stop         = StopEnd
552		finalErr     error
553	)
554
555	appendText := func(delta string) {
556		if currentText == nil {
557			currentText = &blockEntry{kind: "text"}
558			blocks = append(blocks, currentText)
559		}
560		currentText.textBuf.WriteString(delta)
561	}
562
563	getOrCreateTool := func(idx int) *blockEntry {
564		if t, ok := toolByIdx[idx]; ok {
565			return t
566		}
567		t := &blockEntry{kind: "tool_use"}
568		toolByIdx[idx] = t
569		blocks = append(blocks, t)
570		// A new tool block breaks the current text block. Subsequent text
571		// deltas will start a fresh text block after this tool.
572		currentText = nil
573		return t
574	}
575
576	assembleMsg := func() Message {
577		content := []Content{}
578		for _, b := range blocks {
579			switch b.kind {
580			case "text":
581				if b.textBuf.Len() > 0 {
582					content = append(content, TextBlock{Text: b.textBuf.String()})
583				}
584			case "tool_use":
585				args := b.toolArgs.String()
586				if args == "" || !json.Valid([]byte(args)) {
587					args = "{}"
588				}
589				content = append(content, ToolCallBlock{
590					ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
591				})
592			}
593		}
594		if reasoningBuf.Len() > 0 {
595			content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
596		}
597		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
598	}
599
600	sendDone := func() {
601		usage.CostUSD = ComputeCost(model, usage)
602		out <- EventUsage{Usage: usage}
603		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
604	}
605
606	for {
607		select {
608		case <-ctx.Done():
609			stop = StopAborted
610			finalErr = ctx.Err()
611			sendDone()
612			return
613		case ev, ok := <-raw:
614			if !ok {
615				sendDone()
616				return
617			}
618			if ev.Data == "[DONE]" {
619				sendDone()
620				return
621			}
622			var chunk struct {
623				Choices []struct {
624					Index int `json:"index"`
625					Delta struct {
626						Content          string `json:"content"`
627						ReasoningContent string `json:"reasoning_content"`
628						ToolCalls        []struct {
629							Index    int    `json:"index"`
630							ID       string `json:"id"`
631							Type     string `json:"type"`
632							Function struct {
633								Name      string `json:"name"`
634								Arguments string `json:"arguments"`
635							} `json:"function"`
636						} `json:"tool_calls"`
637					} `json:"delta"`
638					FinishReason string `json:"finish_reason"`
639				} `json:"choices"`
640				Usage *struct {
641					PromptTokens        int `json:"prompt_tokens"`
642					CompletionTokens    int `json:"completion_tokens"`
643					PromptTokensDetails struct {
644						CachedTokens int `json:"cached_tokens"`
645					} `json:"prompt_tokens_details"`
646					CompletionTokensDetails *struct {
647						ReasoningTokens int `json:"reasoning_tokens"`
648					} `json:"completion_tokens_details"`
649				} `json:"usage"`
650				Error *struct {
651					Message string `json:"message"`
652					Type    string `json:"type"`
653				} `json:"error"`
654			}
655			if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
656				continue
657			}
658			if chunk.Error != nil {
659				stop = StopError
660				finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
661				sendDone()
662				return
663			}
664			if chunk.Usage != nil {
665				usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
666				if usage.InputTokens < 0 {
667					usage.InputTokens = chunk.Usage.PromptTokens
668				}
669				usage.OutputTokens = chunk.Usage.CompletionTokens
670				usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
671				if details := chunk.Usage.CompletionTokensDetails; details != nil {
672					usage.ReasoningTokens = details.ReasoningTokens
673					usage.ReasoningTokensKnown = true
674				}
675			}
676			for _, ch := range chunk.Choices {
677				if ch.Delta.ReasoningContent != "" {
678					reasoningBuf.WriteString(ch.Delta.ReasoningContent)
679				}
680				if ch.Delta.Content != "" {
681					appendText(ch.Delta.Content)
682					out <- EventTextDelta{Delta: ch.Delta.Content}
683				}
684				for _, tc := range ch.Delta.ToolCalls {
685					t := getOrCreateTool(tc.Index)
686					if tc.ID != "" {
687						t.toolID = tc.ID
688					}
689					if tc.Function.Name != "" {
690						t.toolName = tc.Function.Name
691					}
692					if !t.announced && t.toolID != "" && t.toolName != "" {
693						t.announced = true
694						out <- EventToolStart{ID: t.toolID, Name: t.toolName}
695					}
696					if tc.Function.Arguments != "" {
697						t.toolArgs.WriteString(tc.Function.Arguments)
698						if t.announced {
699							out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
700						}
701					}
702				}
703				switch ch.FinishReason {
704				case "stop":
705					stop = StopEnd
706				case "length":
707					stop = StopLength
708				case "tool_calls", "function_call":
709					stop = StopToolUse
710					for _, b := range blocks {
711						if b.kind == "tool_use" && b.announced {
712							out <- EventToolEnd{ID: b.toolID}
713						}
714					}
715				}
716			}
717		}
718	}
719}

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