v0.1.35 0a670c0

anthropic.go RawHistoryFolder

1package provider
2
3import (
4	"bytes"
5	"context"
6	"encoding/base64"
7	"encoding/json"
8	"fmt"
9	"io"
10	"net/http"
11	"os"
12	"strings"
13	"time"
14)
15
16const anthropicDefaultBaseURL = "https://api.anthropic.com"
17const anthropicAPIVersion = "2023-06-01"
18
19// Stealth identity used when talking to Anthropic via subscription OAuth.
20// These values mimic the official Claude Code CLI so Anthropic's edge
21// accepts the request; diverging from them causes 429 rate_limit_error
22// or 403 on the very first request.
23const (
24	claudeCodeVersion  = "2.1.75"
25	claudeCodeIdentity = "You are Claude Code, Anthropic's official CLI for Claude."
26)
27
28// Claude Code's canonical tool casing. When running under OAuth we must
29// advertise tool names that match this list (case-insensitive lookup),
30// because Anthropic's backend cross-checks them.
31var claudeCodeToolNames = map[string]string{
32	"read":  "Read",
33	"write": "Write",
34	"edit":  "Edit",
35	"bash":  "Bash",
36	"grep":  "Grep",
37	"glob":  "Glob",
38}
39
40func toClaudeCodeToolName(name string) string {
41	if cc, ok := claudeCodeToolNames[strings.ToLower(name)]; ok {
42		return cc
43	}
44	return name
45}
46
47func fromClaudeCodeToolName(name string, tools []Tool) string {
48	lower := strings.ToLower(name)
49	for _, t := range tools {
50		if strings.ToLower(t.Name) == lower {
51			return t.Name
52		}
53	}
54	return name
55}
56
57// anthropicClient implements Client against the Anthropic Messages API.
58type anthropicClient struct {
59	apiKey   string
60	baseURL  string
61	oauthTok string // when non-empty, send Bearer auth instead of x-api-key
62	http     *http.Client
63}
64
65// NewAnthropic creates an Anthropic client using an API key. baseURL may be empty.
66func NewAnthropic(apiKey, baseURL string) Client {
67	if baseURL == "" {
68		baseURL = anthropicDefaultBaseURL
69	}
70	return &anthropicClient{
71		apiKey:  apiKey,
72		baseURL: strings.TrimRight(baseURL, "/"),
73		http:    &http.Client{Timeout: 0},
74	}
75}
76
77// NewAnthropicOAuth creates an Anthropic client using a subscription OAuth access token.
78func NewAnthropicOAuth(accessToken, baseURL string) Client {
79	if baseURL == "" {
80		baseURL = anthropicDefaultBaseURL
81	}
82	return &anthropicClient{
83		oauthTok: accessToken,
84		baseURL:  strings.TrimRight(baseURL, "/"),
85		http:     &http.Client{Timeout: 0},
86	}
87}
88
89func (c *anthropicClient) Name() string { return "anthropic" }
90
91// ---- wire types ----
92
93type anthTextBlock struct {
94	Type         string         `json:"type"` // "text"
95	Text         string         `json:"text"`
96	CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
97}
98
99type anthImageSource struct {
100	Type      string `json:"type"` // "base64"
101	MediaType string `json:"media_type"`
102	Data      string `json:"data"`
103}
104
105type anthImageBlock struct {
106	Type         string          `json:"type"` // "image"
107	Source       anthImageSource `json:"source"`
108	CacheControl *anthCacheCtrl  `json:"cache_control,omitempty"`
109}
110
111type anthToolUseBlock struct {
112	Type         string          `json:"type"` // "tool_use"
113	ID           string          `json:"id"`
114	Name         string          `json:"name"`
115	Input        json.RawMessage `json:"input"`
116	CacheControl *anthCacheCtrl  `json:"cache_control,omitempty"`
117}
118
119type anthToolResultBlock struct {
120	Type         string          `json:"type"` // "tool_result"
121	ToolUseID    string          `json:"tool_use_id"`
122	Content      json.RawMessage `json:"content"` // string or array of blocks
123	IsError      bool            `json:"is_error,omitempty"`
124	CacheControl *anthCacheCtrl  `json:"cache_control,omitempty"`
125}
126
127type anthCacheCtrl struct {
128	Type string `json:"type"` // "ephemeral"
129	TTL  string `json:"ttl,omitempty"`
130}
131
132type anthMessage struct {
133	Role    string        `json:"role"`
134	Content []interface{} `json:"content"`
135}
136
137type anthSystemBlock struct {
138	Type         string         `json:"type"` // "text"
139	Text         string         `json:"text"`
140	CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
141}
142
143type anthTool struct {
144	Name         string          `json:"name"`
145	Description  string          `json:"description,omitempty"`
146	InputSchema  json.RawMessage `json:"input_schema"`
147	CacheControl *anthCacheCtrl  `json:"cache_control,omitempty"`
148}
149
150type anthThinking struct {
151	Type         string `json:"type"` // "enabled"
152	BudgetTokens int    `json:"budget_tokens"`
153}
154
155type anthRequest struct {
156	Model       string            `json:"model"`
157	MaxTokens   int               `json:"max_tokens"`
158	System      []anthSystemBlock `json:"system,omitempty"`
159	Messages    []anthMessage     `json:"messages"`
160	Tools       []anthTool        `json:"tools,omitempty"`
161	Temperature *float32          `json:"temperature,omitempty"`
162	Thinking    *anthThinking     `json:"thinking,omitempty"`
163	Stream      bool              `json:"stream"`
164}
165
166// ---- request building ----
167
168func (c *anthropicClient) buildRequest(req Request) (*anthRequest, error) {
169	m, err := FindModel("anthropic", req.Model)
170	if err != nil {
171		return nil, err
172	}
173	maxTok := req.MaxTokens
174	if maxTok <= 0 {
175		maxTok = m.MaxOutput
176	}
177
178	out := &anthRequest{
179		Model:       req.Model,
180		MaxTokens:   maxTok,
181		Temperature: req.Temperature,
182		Stream:      true,
183	}
184
185	// System prompt assembly differs between api-key and OAuth modes.
186	// OAuth requests MUST begin with the Claude Code identity line or
187	// Anthropic rejects them (429 rate_limit_error with zero tokens used).
188	//
189	// Cache budget: anthropic caps cache_control to 4 breakpoints per
190	// request. We spend them on:
191	//   1. claude-code identity (OAuth only; stable forever)
192	//   2. user system prompt   (changes per-session at most)
193	//   3. last tool definition (tools change rarely)
194	//   4. last message block   (advances every turn)
195	//
196	// The identity line gets its OWN cache_control so the prefix
197	// [identity] is cacheable independently of the user system
198	// prompt. Without that, the cache prefix starts after block 2
199	// and any drift in the user prompt (e.g. the Current date
200	// line flipping at midnight) invalidates everything, including
201	// the 17 identity tokens we have to re-send every request
202	// forever.
203	if c.oauthTok != "" {
204		out.System = []anthSystemBlock{{
205			Type:         "text",
206			Text:         claudeCodeIdentity,
207			CacheControl: &anthCacheCtrl{Type: "ephemeral"},
208		}}
209		if req.System != "" {
210			out.System = append(out.System, anthSystemBlock{
211				Type:         "text",
212				Text:         req.System,
213				CacheControl: &anthCacheCtrl{Type: "ephemeral"},
214			})
215		}
216	} else if req.System != "" {
217		out.System = []anthSystemBlock{{
218			Type:         "text",
219			Text:         req.System,
220			CacheControl: &anthCacheCtrl{Type: "ephemeral"},
221		}}
222	}
223
224	if req.Reasoning != "" && m.Reasoning {
225		budget := anthropicReasoningBudget(req.Reasoning)
226		if budget > 0 {
227			out.Thinking = &anthThinking{Type: "enabled", BudgetTokens: budget}
228			// Reasoning requires max_tokens > budget.
229			if out.MaxTokens <= budget {
230				out.MaxTokens = budget + 4096
231			}
232		}
233	}
234
235	for _, t := range req.Tools {
236		name := t.Name
237		if c.oauthTok != "" {
238			name = toClaudeCodeToolName(name)
239		}
240		out.Tools = append(out.Tools, anthTool{
241			Name:        name,
242			Description: t.Description,
243			InputSchema: t.Schema,
244		})
245	}
246	// Cache the last tool definition (applies cache breakpoint to the whole tools array).
247	if n := len(out.Tools); n > 0 {
248		out.Tools[n-1].CacheControl = &anthCacheCtrl{Type: "ephemeral"}
249	}
250
251	// Convert messages. Anthropic's wire format has only "user" and
252	// "assistant" roles; tool_result blocks live inside user messages.
253	//
254	// CRITICAL: tool_result blocks go into their OWN new user
255	// message, they are NOT merged into the preceding user message.
256	// Merging would mutate the prior user message's content array
257	// between turn N and turn N+1: turn N caches the prefix ending at
258	// [user: "read sample.ts"], turn N+1 sends
259	// [user: "read sample.ts" + tool_result=...] which is a
260	// different block sequence, busting the cache prefix match.
261	// Anthropic's API happily accepts consecutive user messages, and
262	// emitting them separately keeps each message bit-stable across
263	// turns, so the cache prefix matches for the entire history up
264	// to the newest block.
265	for _, msg := range req.Messages {
266		renameTools := c.oauthTok != ""
267		switch msg.Role {
268		case RoleUser:
269			out.Messages = append(out.Messages, anthMessage{
270				Role:    "user",
271				Content: convertAnthContent(msg.Content, renameTools),
272			})
273		case RoleTool:
274			out.Messages = append(out.Messages, anthMessage{
275				Role:    "user",
276				Content: convertAnthContent(msg.Content, renameTools),
277			})
278		case RoleAssistant:
279			out.Messages = append(out.Messages, anthMessage{
280				Role:    "assistant",
281				Content: convertAnthContent(msg.Content, renameTools),
282			})
283		}
284	}
285
286	// Tag the LAST user message with cache_control. Spends the 4th
287	// breakpoint. For prefixes under ~1024 tokens (Anthropic's
288	// minimum cacheable block size for Opus), no cache is written.
289	tagLastUserCache(out.Messages)
290
291	return out, nil
292}
293
294// tagLastUserCache marks the last block of the most recent user
295// message. One marker; combined with identity + systemPrompt +
296// last-tool, spends Anthropic's 4-breakpoint budget.
297func tagLastUserCache(msgs []anthMessage) {
298	for i := len(msgs) - 1; i >= 0; i-- {
299		if msgs[i].Role == "user" {
300			markLastBlockEphemeral(msgs[i].Content)
301			return
302		}
303	}
304}
305
306// markLastBlockEphemeral sets CacheControl on the last entry in blocks
307// regardless of whether it's a text, image, tool_use, or tool_result.
308// Each block type carries its own CacheControl pointer so we type-
309// switch + reassign the slice element.
310func markLastBlockEphemeral(blocks []interface{}) {
311	if len(blocks) == 0 {
312		return
313	}
314	i := len(blocks) - 1
315	cc := &anthCacheCtrl{Type: "ephemeral"}
316	switch v := blocks[i].(type) {
317	case anthTextBlock:
318		v.CacheControl = cc
319		blocks[i] = v
320	case anthImageBlock:
321		v.CacheControl = cc
322		blocks[i] = v
323	case anthToolUseBlock:
324		v.CacheControl = cc
325		blocks[i] = v
326	case anthToolResultBlock:
327		v.CacheControl = cc
328		blocks[i] = v
329	}
330}
331
332func anthropicReasoningBudget(level string) int {
333	switch strings.ToLower(level) {
334	case "low":
335		return 2048
336	case "medium":
337		return 8192
338	case "high":
339		return 16384
340	default:
341		return 0
342	}
343}
344
345func convertAnthContent(blocks []Content, renameTools bool) []interface{} {
346	out := make([]interface{}, 0, len(blocks))
347	for _, b := range blocks {
348		switch v := b.(type) {
349		case TextBlock:
350			if v.Text == "" {
351				continue
352			}
353			out = append(out, anthTextBlock{Type: "text", Text: v.Text})
354		case ImageBlock:
355			out = append(out, anthImageBlock{
356				Type: "image",
357				Source: anthImageSource{
358					Type:      "base64",
359					MediaType: v.MimeType,
360					Data:      base64.StdEncoding.EncodeToString(v.Data),
361				},
362			})
363		case ToolCallBlock:
364			args := v.Arguments
365			if len(args) == 0 {
366				args = json.RawMessage("{}")
367			}
368			name := v.Name
369			if renameTools {
370				name = toClaudeCodeToolName(name)
371			}
372			out = append(out, anthToolUseBlock{
373				Type: "tool_use", ID: v.ID, Name: name, Input: args,
374			})
375		case ToolResultBlock:
376			// Flatten content to a string if all text; else array of blocks.
377			content, _ := anthBuildToolResultContent(v.Content)
378			out = append(out, anthToolResultBlock{
379				Type:      "tool_result",
380				ToolUseID: v.CallID,
381				Content:   content,
382				IsError:   v.IsError,
383			})
384		}
385	}
386	return out
387}
388
389func anthBuildToolResultContent(blocks []Content) (json.RawMessage, error) {
390	onlyText := true
391	var sb strings.Builder
392	for _, b := range blocks {
393		if tb, ok := b.(TextBlock); ok {
394			if sb.Len() > 0 {
395				sb.WriteString("\n")
396			}
397			sb.WriteString(tb.Text)
398		} else {
399			onlyText = false
400			break
401		}
402	}
403	if onlyText {
404		if sb.Len() == 0 {
405			return json.Marshal("")
406		}
407		return json.Marshal(sb.String())
408	}
409	// Array form: text + image blocks.
410	arr := make([]interface{}, 0, len(blocks))
411	for _, b := range blocks {
412		switch v := b.(type) {
413		case TextBlock:
414			arr = append(arr, anthTextBlock{Type: "text", Text: v.Text})
415		case ImageBlock:
416			arr = append(arr, anthImageBlock{
417				Type: "image",
418				Source: anthImageSource{
419					Type:      "base64",
420					MediaType: v.MimeType,
421					Data:      base64.StdEncoding.EncodeToString(v.Data),
422				},
423			})
424		}
425	}
426	return json.Marshal(arr)
427}
428
429// ---- streaming ----
430
431func (c *anthropicClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
432	wire, err := c.buildRequest(req)
433	if err != nil {
434		return nil, err
435	}
436	body, err := json.Marshal(wire)
437	if err != nil {
438		return nil, err
439	}
440
441	// Optional debug dump: when $ZOT_DEBUG_ANTHROPIC is a file path
442	// we append every outgoing request body to it, one JSON object
443	// per line. Useful for diffing turn N vs turn N+1 to understand
444	// why the cache prefix isn't matching.
445	if dump := os.Getenv("ZOT_DEBUG_ANTHROPIC"); dump != "" {
446		if f, derr := os.OpenFile(dump, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); derr == nil {
447			_, _ = f.Write(body)
448			_, _ = f.Write([]byte{'\n'})
449			_ = f.Close()
450		}
451	}
452
453	httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/v1/messages", bytes.NewReader(body))
454	if err != nil {
455		return nil, err
456	}
457	httpReq.Header.Set("content-type", "application/json")
458	httpReq.Header.Set("anthropic-version", anthropicAPIVersion)
459	if c.oauthTok != "" {
460		// Claude-Code-shaped request: identical headers and values as the
461		// official CLI. Any drift triggers Anthropic's anti-abuse check and
462		// rate-limits (or outright blocks) the request.
463		httpReq.Header.Set("accept", "application/json")
464		httpReq.Header.Set("authorization", "Bearer "+c.oauthTok)
465		httpReq.Header.Set("anthropic-beta", "claude-code-20250219,oauth-2025-04-20,fine-grained-tool-streaming-2025-05-14")
466		httpReq.Header.Set("anthropic-dangerous-direct-browser-access", "true")
467		httpReq.Header.Set("user-agent", "claude-cli/"+claudeCodeVersion)
468		httpReq.Header.Set("x-app", "cli")
469		// Remove x-api-key entirely by NOT setting it.
470	} else {
471		httpReq.Header.Set("accept", "text/event-stream")
472		httpReq.Header.Set("x-api-key", c.apiKey)
473	}
474
475	resp, err := c.http.Do(httpReq)
476	if err != nil {
477		return nil, fmt.Errorf("anthropic: %w", err)
478	}
479	if resp.StatusCode != http.StatusOK {
480		b, _ := io.ReadAll(resp.Body)
481		resp.Body.Close()
482		return nil, fmt.Errorf("anthropic: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
483	}
484
485	out := make(chan Event, 16)
486	go c.runStream(ctx, resp, req, out)
487	return out, nil
488}
489
490func (c *anthropicClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
491	defer close(out)
492	defer resp.Body.Close()
493
494	model, _ := FindModel("anthropic", req.Model)
495	out <- EventStart{Model: req.Model, Provider: "anthropic"}
496
497	raw := make(chan sseEvent, 16)
498	go readSSE(resp.Body, raw)
499
500	// State for assembling the assistant message. Blocks are indexed
501	// by their `index` field from Anthropic so we can preserve the
502	// interleaved order the model emitted them in (text may come
503	// before OR after tool_use; mixing both happens frequently).
504	type blockEntry struct {
505		kind     string // "text" | "tool_use"
506		textBuf  strings.Builder
507		toolCall ToolCallBlock
508		toolArgs strings.Builder
509	}
510	var (
511		blocks     = map[int]*blockEntry{}
512		blockOrder []int // insertion order of indexes
513		activeIdx  = -1
514		usage      Usage
515		stop       StopReason = StopEnd
516		finalErr   error
517	)
518	_ = activeIdx // read-only indicator used for legacy parity
519
520	registerBlock := func(idx int, kind string) *blockEntry {
521		if be, ok := blocks[idx]; ok {
522			return be
523		}
524		be := &blockEntry{kind: kind}
525		blocks[idx] = be
526		blockOrder = append(blockOrder, idx)
527		return be
528	}
529
530	assembleMsg := func() Message {
531		content := []Content{}
532		for _, idx := range blockOrder {
533			be := blocks[idx]
534			switch be.kind {
535			case "text":
536				if be.textBuf.Len() > 0 {
537					content = append(content, TextBlock{Text: be.textBuf.String()})
538				}
539			case "tool_use":
540				tc := be.toolCall
541				args := be.toolArgs.String()
542				if args == "" {
543					args = "{}"
544				}
545				tc.Arguments = json.RawMessage(args)
546				content = append(content, tc)
547			}
548		}
549		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
550	}
551
552	sendDone := func() {
553		usage.CostUSD = ComputeCost(model, usage)
554		out <- EventUsage{Usage: usage}
555		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
556	}
557
558	for {
559		select {
560		case <-ctx.Done():
561			stop = StopAborted
562			finalErr = ctx.Err()
563			sendDone()
564			return
565		case ev, ok := <-raw:
566			if !ok {
567				sendDone()
568				return
569			}
570			// Parse event payload based on event: type.
571			var payload map[string]json.RawMessage
572			if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil {
573				continue
574			}
575			switch ev.Event {
576			case "content_block_start":
577				var idx int
578				if b, ok := payload["index"]; ok {
579					_ = json.Unmarshal(b, &idx)
580				}
581				var block struct {
582					Type  string          `json:"type"`
583					ID    string          `json:"id"`
584					Name  string          `json:"name"`
585					Text  string          `json:"text"`
586					Input json.RawMessage `json:"input"`
587				}
588				if b, ok := payload["content_block"]; ok {
589					_ = json.Unmarshal(b, &block)
590				}
591				activeIdx = idx
592				switch block.Type {
593				case "tool_use":
594					name := block.Name
595					if c.oauthTok != "" {
596						name = fromClaudeCodeToolName(name, req.Tools)
597					}
598					be := registerBlock(idx, "tool_use")
599					be.toolCall = ToolCallBlock{ID: block.ID, Name: name}
600					out <- EventToolStart{ID: block.ID, Name: name}
601				case "text":
602					registerBlock(idx, "text")
603				case "thinking":
604					// not surfaced
605				}
606			case "content_block_delta":
607				var idx int
608				if b, ok := payload["index"]; ok {
609					_ = json.Unmarshal(b, &idx)
610				}
611				var d struct {
612					Type        string `json:"type"`
613					Text        string `json:"text"`
614					PartialJSON string `json:"partial_json"`
615					Thinking    string `json:"thinking"`
616				}
617				if b, ok := payload["delta"]; ok {
618					_ = json.Unmarshal(b, &d)
619				}
620				switch d.Type {
621				case "text_delta":
622					if be, ok := blocks[idx]; ok && be.kind == "text" {
623						be.textBuf.WriteString(d.Text)
624					}
625					out <- EventTextDelta{Delta: d.Text}
626				case "input_json_delta":
627					if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
628						be.toolArgs.WriteString(d.PartialJSON)
629						out <- EventToolArgs{ID: be.toolCall.ID, Delta: d.PartialJSON}
630					}
631				case "thinking_delta":
632					// Not surfaced in v1.
633				}
634			case "content_block_stop":
635				var idx int
636				if b, ok := payload["index"]; ok {
637					_ = json.Unmarshal(b, &idx)
638				}
639				if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
640					out <- EventToolEnd{ID: be.toolCall.ID}
641				}
642				activeIdx = -1
643			case "message_start":
644				var m struct {
645					Message struct {
646						Usage struct {
647							InputTokens              int `json:"input_tokens"`
648							OutputTokens             int `json:"output_tokens"`
649							CacheReadInputTokens     int `json:"cache_read_input_tokens"`
650							CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
651						} `json:"usage"`
652					} `json:"message"`
653				}
654				_ = json.Unmarshal([]byte(ev.Data), &m)
655				// Anthropic sends cumulative values on message_start and
656				// again on message_delta (refreshed), so assign, don't
657				// accumulate. Accumulating doubles cache_creation_input
658				// which can be 50-70% of cost.
659				usage.InputTokens = m.Message.Usage.InputTokens
660				usage.OutputTokens = m.Message.Usage.OutputTokens
661				usage.CacheReadTokens = m.Message.Usage.CacheReadInputTokens
662				usage.CacheWriteTokens = m.Message.Usage.CacheCreationInputTokens
663			case "message_delta":
664				var m struct {
665					Delta struct {
666						StopReason string `json:"stop_reason"`
667					} `json:"delta"`
668					Usage struct {
669						InputTokens              int `json:"input_tokens"`
670						OutputTokens             int `json:"output_tokens"`
671						CacheReadInputTokens     int `json:"cache_read_input_tokens"`
672						CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
673					} `json:"usage"`
674				}
675				_ = json.Unmarshal([]byte(ev.Data), &m)
676				// Refresh usage from the latest cumulative totals
677				// Anthropic provides. Only apply non-zero fields in case
678				// a given delta only carries output tokens.
679				if m.Usage.InputTokens > 0 {
680					usage.InputTokens = m.Usage.InputTokens
681				}
682				if m.Usage.OutputTokens > 0 {
683					usage.OutputTokens = m.Usage.OutputTokens
684				}
685				if m.Usage.CacheReadInputTokens > 0 {
686					usage.CacheReadTokens = m.Usage.CacheReadInputTokens
687				}
688				if m.Usage.CacheCreationInputTokens > 0 {
689					usage.CacheWriteTokens = m.Usage.CacheCreationInputTokens
690				}
691				switch m.Delta.StopReason {
692				case "end_turn", "stop_sequence":
693					stop = StopEnd
694				case "max_tokens":
695					stop = StopLength
696				case "tool_use":
697					stop = StopToolUse
698				}
699			case "message_stop":
700				sendDone()
701				return
702			case "error":
703				var e struct {
704					Error struct {
705						Type    string `json:"type"`
706						Message string `json:"message"`
707					} `json:"error"`
708				}
709				_ = json.Unmarshal([]byte(ev.Data), &e)
710				stop = StopError
711				finalErr = fmt.Errorf("anthropic %s: %s", e.Error.Type, e.Error.Message)
712				sendDone()
713				return
714			}
715			_ = activeIdx
716		}
717	}
718}

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