v0.2.71 c18646e

amazon_bedrock.go RawHistoryFolder

1package provider
2
3// Amazon Bedrock Converse-Stream client.
4//
5// Endpoint: POST https://bedrock-runtime.{region}.amazonaws.com/model/{id}/converse-stream
6//
7// Auth: two paths supported.
8//
9//   - **Bearer token** via AWS_BEARER_TOKEN_BEDROCK. Modern, simple,
10//     `bedrock:CallWithBearerToken` IAM permission required.
11//   - **SigV4 signing** via AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY
12//     (+ optional AWS_SESSION_TOKEN for temporary credentials, e.g. SSO
13//     or IRSA-issued). Hand-rolled here so we don't pull in aws-sdk-go-v2.
14//
15// If both are present, bearer wins (simpler / fewer moving parts).
16//
17// Wire format: AWS event-stream binary framing. Each message is:
18//
19//	[4-byte total length BE]
20//	[4-byte headers length BE]
21//	[4-byte CRC32 of the 8-byte prelude]
22//	[headers ...]      each = [1B name-length][name][1B value-type][2B value-length][value]
23//	[payload ...]      payload-length = total - headers - 4 (trailer) - 12 (prelude+prelude-crc)
24//	[4-byte CRC32 of message bytes minus trailer]
25//
26// We only consume the stream — never produce it — so we don't validate
27// CRCs (the TLS+TCP transport already protects in-flight bytes). We do
28// validate length-bounds to avoid OOB reads on a hostile / corrupted
29// stream.
30//
31// Event types we care about (from `:event-type` header):
32//   - messageStart        { role: "assistant" }
33//   - contentBlockStart   { contentBlockIndex, start: { toolUse: { toolUseId, name } } }
34//   - contentBlockDelta   { contentBlockIndex, delta: { text?, toolUse?: { input } } }
35//   - contentBlockStop    { contentBlockIndex }
36//   - messageStop         { stopReason }
37//   - metadata            { usage: { inputTokens, outputTokens } }
38
39import (
40	"bytes"
41	"context"
42	"crypto/hmac"
43	"crypto/sha256"
44	"encoding/base64"
45	"encoding/binary"
46	"encoding/hex"
47	"encoding/json"
48	"fmt"
49	"io"
50	"net/http"
51	"net/url"
52	"os"
53	"sort"
54	"strings"
55	"time"
56)
57
58type bedrockClient struct {
59	// Auth mode is determined at construction time. Exactly one of
60	// bearerToken or sigv4 is populated.
61	bearerToken string
62	sigv4       *bedrockSigV4Creds
63
64	region  string
65	baseURL string
66	http    *http.Client
67}
68
69// bedrockSigV4Creds holds the IAM credentials used to sign each request.
70type bedrockSigV4Creds struct {
71	accessKeyID     string
72	secretAccessKey string
73	sessionToken    string // optional; STS / SSO / IRSA temp creds
74}
75
76// NewBedrockClient returns a Bedrock client.
77//
78// Auth resolution (first match wins):
79//
80//  1. apiKey == real bearer-ish string (not "<aws>") -> bearer route.
81//  2. AWS_BEARER_TOKEN_BEDROCK env var -> bearer route.
82//  3. AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY (+ optional
83//     AWS_SESSION_TOKEN) -> SigV4 route.
84//  4. AWS_PROFILE -> read ~/.aws/credentials, take that profile's keys.
85//
86// region defaults to us-east-1 unless AWS_REGION / AWS_DEFAULT_REGION is
87// set or the baseURL embeds a region.
88func NewBedrockClient(apiKey, baseURL string) Client {
89	region := os.Getenv("AWS_REGION")
90	if region == "" {
91		region = os.Getenv("AWS_DEFAULT_REGION")
92	}
93	if region == "" {
94		region = "us-east-1"
95	}
96	if baseURL == "" {
97		baseURL = "https://bedrock-runtime." + region + ".amazonaws.com"
98	}
99	c := &bedrockClient{
100		region:  region,
101		baseURL: strings.TrimRight(baseURL, "/"),
102		http:    &http.Client{Timeout: 0},
103	}
104
105	// Bearer route.
106	token := apiKey
107	if token == "" || token == "<aws>" {
108		token = os.Getenv("AWS_BEARER_TOKEN_BEDROCK")
109	}
110	if token != "" && token != "<aws>" {
111		c.bearerToken = token
112		return c
113	}
114
115	// SigV4 route: env vars first.
116	ak := os.Getenv("AWS_ACCESS_KEY_ID")
117	sk := os.Getenv("AWS_SECRET_ACCESS_KEY")
118	st := os.Getenv("AWS_SESSION_TOKEN")
119	if ak != "" && sk != "" {
120		c.sigv4 = &bedrockSigV4Creds{accessKeyID: ak, secretAccessKey: sk, sessionToken: st}
121		return c
122	}
123
124	// SigV4 route: ~/.aws/credentials via AWS_PROFILE.
125	if profile := os.Getenv("AWS_PROFILE"); profile != "" {
126		if creds, err := readAWSCredentialsFile(profile); err == nil {
127			c.sigv4 = creds
128			return c
129		}
130	}
131
132	return &unimplementedClient{
133		name: "amazon-bedrock",
134		hint: "no Bedrock credentials found (set AWS_BEARER_TOKEN_BEDROCK, AWS_ACCESS_KEY_ID+AWS_SECRET_ACCESS_KEY, or AWS_PROFILE)",
135	}
136}
137
138// readAWSCredentialsFile parses ~/.aws/credentials and returns the
139// access-key/secret-key (and optional session-token) for the named
140// profile. The file is an INI-like format with `[profile]` headers.
141func readAWSCredentialsFile(profile string) (*bedrockSigV4Creds, error) {
142	home, err := os.UserHomeDir()
143	if err != nil {
144		return nil, err
145	}
146	b, err := os.ReadFile(home + "/.aws/credentials")
147	if err != nil {
148		return nil, err
149	}
150	var current string
151	creds := map[string]map[string]string{}
152	for _, line := range strings.Split(string(b), "\n") {
153		line = strings.TrimSpace(line)
154		if line == "" || strings.HasPrefix(line, "#") {
155			continue
156		}
157		if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
158			current = strings.TrimSpace(line[1 : len(line)-1])
159			creds[current] = map[string]string{}
160			continue
161		}
162		if current == "" {
163			continue
164		}
165		eq := strings.IndexByte(line, '=')
166		if eq < 0 {
167			continue
168		}
169		k := strings.TrimSpace(line[:eq])
170		v := strings.TrimSpace(line[eq+1:])
171		creds[current][k] = v
172	}
173	p, ok := creds[profile]
174	if !ok {
175		return nil, fmt.Errorf("aws profile %q not found in ~/.aws/credentials", profile)
176	}
177	ak := p["aws_access_key_id"]
178	sk := p["aws_secret_access_key"]
179	if ak == "" || sk == "" {
180		return nil, fmt.Errorf("aws profile %q missing aws_access_key_id or aws_secret_access_key", profile)
181	}
182	return &bedrockSigV4Creds{
183		accessKeyID:     ak,
184		secretAccessKey: sk,
185		sessionToken:    p["aws_session_token"],
186	}, nil
187}
188
189func (c *bedrockClient) Name() string { return "amazon-bedrock" }
190
191// ---- request building ----
192
193type bedrockMessage struct {
194	Role    string                   `json:"role"`
195	Content []map[string]interface{} `json:"content"`
196}
197
198// bedrockCachePoint is the Converse API cache checkpoint content block.
199// Appending this to a system or message content array tells Bedrock to
200// create a cache boundary at that position in the prompt prefix.
201var bedrockCachePoint = map[string]interface{}{
202	"cachePoint": map[string]interface{}{"type": "default"},
203}
204
205type bedrockToolSpec struct {
206	ToolSpec struct {
207		Name        string `json:"name"`
208		Description string `json:"description,omitempty"`
209		InputSchema struct {
210			JSON json.RawMessage `json:"json"`
211		} `json:"inputSchema"`
212	} `json:"toolSpec"`
213}
214
215type bedrockRequest struct {
216	Messages        []bedrockMessage         `json:"messages"`
217	System          []map[string]interface{} `json:"system,omitempty"`
218	InferenceConfig struct {
219		MaxTokens   int      `json:"maxTokens,omitempty"`
220		Temperature *float32 `json:"temperature,omitempty"`
221	} `json:"inferenceConfig,omitempty"`
222	ToolConfig *struct {
223		Tools []bedrockToolSpec `json:"tools"`
224	} `json:"toolConfig,omitempty"`
225}
226
227func normalizeBedrockToolResults(msgs []Message) []Message {
228	resultByID := map[string]ToolResultBlock{}
229	for _, m := range msgs {
230		for _, c := range m.Content {
231			if tr, ok := c.(ToolResultBlock); ok {
232				if _, exists := resultByID[tr.CallID]; !exists {
233					resultByID[tr.CallID] = tr
234				}
235			}
236		}
237	}
238
239	out := make([]Message, 0, len(msgs))
240	for _, m := range msgs {
241		copy := m
242		copy.Content = nil
243		var toolCalls []ToolCallBlock
244		for _, c := range m.Content {
245			switch v := c.(type) {
246			case ToolResultBlock:
247				// Bedrock requires toolResult blocks immediately after the
248				// assistant toolUse they answer. Reinsert them from the
249				// assistant pass below instead of preserving their original
250				// location, which may be separated by user text in active
251				// sessions.
252				continue
253			case ToolCallBlock:
254				toolCalls = append(toolCalls, v)
255			}
256			copy.Content = append(copy.Content, c)
257		}
258		if len(copy.Content) > 0 {
259			out = append(out, copy)
260		}
261		if m.Role != RoleAssistant || len(toolCalls) == 0 {
262			continue
263		}
264
265		results := make([]Content, 0, len(toolCalls))
266		for _, tc := range toolCalls {
267			if tr, ok := resultByID[tc.ID]; ok {
268				results = append(results, tr)
269				continue
270			}
271			results = append(results, ToolResultBlock{
272				CallID:  tc.ID,
273				IsError: true,
274				Content: []Content{TextBlock{Text: "tool call did not complete before the next user message"}},
275			})
276		}
277		out = append(out, Message{Role: RoleTool, Content: results, Time: m.Time})
278	}
279	return out
280}
281
282// bedrockModelSupportsCaching reports whether the resolved model ID
283// supports explicit prompt caching via cachePoint markers on Bedrock.
284// We use PriceCacheWrite > 0 as a proxy: every Bedrock-hosted Claude
285// model with a write price in the catalog supports cachePoint markers.
286// Nova models use automatic caching and don't need explicit markers.
287func bedrockModelSupportsCaching(modelID string) bool {
288	// Strip geo prefix (us./eu./apac./au./global.) before catalog lookup.
289	for _, p := range bedrockGeoPrefixes {
290		if strings.HasPrefix(modelID, p+".") {
291			modelID = modelID[len(p)+1:]
292			break
293		}
294	}
295	if m, err := FindModel("amazon-bedrock", modelID); err == nil {
296		return m.PriceCacheWrite > 0
297	}
298	// Unknown model: enable for Anthropic Claude families — cachePoint is
299	// silently ignored by the API if the model doesn't support it.
300	return strings.HasPrefix(modelID, "anthropic.claude-")
301}
302
303// bedrockMessagesHaveToolBlocks reports whether any message in msgs
304// contains a toolUse or toolResult content block. Bedrock's Converse API
305// rejects the request with HTTP 400 if those block types are present but
306// toolConfig is absent.
307func bedrockMessagesHaveToolBlocks(msgs []bedrockMessage) bool {
308	for _, m := range msgs {
309		for _, c := range m.Content {
310			if _, ok := c["toolUse"]; ok {
311				return true
312			}
313			if _, ok := c["toolResult"]; ok {
314				return true
315			}
316		}
317	}
318	return false
319}
320
321func (c *bedrockClient) buildRequest(req Request) (*bedrockRequest, error) {
322	out := &bedrockRequest{}
323
324	// Resolve the model ID as it will appear on the wire so the caching
325	// check operates on the same ID used for FindModel.
326	resolvedModel := resolveBedrockInferenceProfileID(req.Model, c.region)
327	caching := bedrockModelSupportsCaching(resolvedModel)
328
329	if req.System != "" {
330		sysBlock := map[string]interface{}{"text": req.System}
331		if caching {
332			// Append cachePoint after the system text so the stable system
333			// prompt is cached as the first breakpoint.
334			out.System = []map[string]interface{}{sysBlock, bedrockCachePoint}
335		} else {
336			out.System = []map[string]interface{}{sysBlock}
337		}
338	}
339	out.InferenceConfig.Temperature = req.Temperature
340	out.InferenceConfig.MaxTokens = req.MaxTokens
341	if out.InferenceConfig.MaxTokens == 0 {
342		out.InferenceConfig.MaxTokens = 4096
343	}
344	for _, m := range normalizeBedrockToolResults(req.Messages) {
345		role := string(m.Role)
346		if role == "tool" {
347			role = "user"
348		}
349		bm := bedrockMessage{Role: role}
350		for _, c := range m.Content {
351			switch v := c.(type) {
352			case TextBlock:
353				bm.Content = append(bm.Content, map[string]interface{}{"text": v.Text})
354			case ToolCallBlock:
355				var input map[string]interface{}
356				_ = json.Unmarshal(v.Arguments, &input)
357				if input == nil {
358					input = map[string]interface{}{}
359				}
360				bm.Content = append(bm.Content, map[string]interface{}{
361					"toolUse": map[string]interface{}{
362						"toolUseId": v.ID, "name": v.Name, "input": input,
363					},
364				})
365			case ImageBlock:
366				data, mime := anthShrinkImageBytesIfTooBig(v.Data, v.MimeType)
367				// Bedrock Converse uses the bare format name (jpeg/png/gif/webp).
368				imgFmt := strings.TrimPrefix(mime, "image/")
369				bm.Content = append(bm.Content, map[string]interface{}{
370					"image": map[string]interface{}{
371						"format": imgFmt,
372						"source": map[string]interface{}{
373							"bytes": base64.StdEncoding.EncodeToString(data),
374						},
375					},
376				})
377			case ToolResultBlock:
378				var resultContent []map[string]interface{}
379				for _, inner := range v.Content {
380					switch iv := inner.(type) {
381					case TextBlock:
382						resultContent = append(resultContent, map[string]interface{}{"text": iv.Text})
383					case ImageBlock:
384						data, mime := anthShrinkImageBytesIfTooBig(iv.Data, iv.MimeType)
385						imgFmt := strings.TrimPrefix(mime, "image/")
386						resultContent = append(resultContent, map[string]interface{}{
387							"image": map[string]interface{}{
388								"format": imgFmt,
389								"source": map[string]interface{}{
390									"bytes": base64.StdEncoding.EncodeToString(data),
391								},
392							},
393						})
394					}
395				}
396				status := "success"
397				if v.IsError {
398					status = "error"
399				}
400				bm.Content = append(bm.Content, map[string]interface{}{
401					"toolResult": map[string]interface{}{
402						"toolUseId": v.CallID,
403						"content":   resultContent,
404						"status":    status,
405					},
406				})
407			}
408		}
409		if len(bm.Content) == 0 {
410			continue
411		}
412		out.Messages = append(out.Messages, bm)
413	}
414	if len(req.Tools) > 0 {
415		tc := struct {
416			Tools []bedrockToolSpec `json:"tools"`
417		}{}
418		for _, t := range req.Tools {
419			var ts bedrockToolSpec
420			ts.ToolSpec.Name = t.Name
421			ts.ToolSpec.Description = t.Description
422			ts.ToolSpec.InputSchema.JSON = t.Schema
423			tc.Tools = append(tc.Tools, ts)
424		}
425		out.ToolConfig = &tc
426	} else if bedrockMessagesHaveToolBlocks(out.Messages) {
427		// Bedrock requires toolConfig to be present whenever the message
428		// history contains toolUse or toolResult content blocks, even if
429		// the current request does not intend to call any tools (e.g. the
430		// /btw side-chat sends the frozen main transcript which may include
431		// prior tool turns). Inject a stub tool so the API accepts the
432		// request; it will never be invoked since no tool_use stop reason
433		// can be triggered when the real tool list is empty.
434		var stub bedrockToolSpec
435		stub.ToolSpec.Name = "_placeholder"
436		stub.ToolSpec.Description = "placeholder required by Bedrock when tool history is present"
437		stub.ToolSpec.InputSchema.JSON = json.RawMessage(`{"type":"object","properties":{}}`)
438		out.ToolConfig = &struct {
439			Tools []bedrockToolSpec `json:"tools"`
440		}{Tools: []bedrockToolSpec{stub}}
441	}
442
443	if caching {
444		// Tag the last user message with a cachePoint. This extends the
445		// cached prefix to cover the full conversation history up to the
446		// current turn, so the next turn reads that history cheaply.
447		bedrockTagLastUserCache(out.Messages)
448	}
449
450	return out, nil
451}
452
453// bedrockTagLastUserCache appends a cachePoint block to the last user
454// message in the Bedrock message list. It is the Bedrock equivalent of
455// Anthropic's cache_control:{type:"ephemeral"} on the last user message.
456func bedrockTagLastUserCache(msgs []bedrockMessage) {
457	for i := len(msgs) - 1; i >= 0; i-- {
458		if msgs[i].Role == "user" {
459			msgs[i].Content = append(msgs[i].Content, bedrockCachePoint)
460			return
461		}
462	}
463}
464
465// resolveBedrockInferenceProfileID maps a bare foundation-model ID to
466// its region-matched cross-region inference-profile ID.
467//
468// Several newer Bedrock models (Anthropic Claude 4.x, DeepSeek, etc.)
469// cannot be invoked with on-demand throughput by their plain
470// foundation-model ID; Bedrock returns HTTP 400 demanding "the ID or
471// ARN of an inference profile that contains this model". The profile
472// ID is the same model ID with a geographic prefix (us/eu/apac/...).
473//
474// We only rewrite IDs that (a) lack an existing geo prefix and (b)
475// belong to a model family that requires a profile. IDs that already
476// carry a prefix (e.g. "eu.anthropic...", "global.anthropic...") or
477// fully-qualified ARNs are returned unchanged, so explicit user
478// choices and custom application inference profiles still work.
479func resolveBedrockInferenceProfileID(modelID, region string) string {
480	if modelID == "" {
481		return modelID
482	}
483	// ARNs are already inference-profile references; leave untouched.
484	if strings.HasPrefix(modelID, "arn:") {
485		return modelID
486	}
487	// Already geo-prefixed (us. / eu. / apac. / ap. / us-gov. / global.)?
488	if bedrockHasGeoPrefix(modelID) {
489		return modelID
490	}
491	if !bedrockRequiresInferenceProfile(modelID) {
492		return modelID
493	}
494	prefix := bedrockGeoPrefixForRegion(region)
495	if prefix == "" {
496		return modelID
497	}
498	return prefix + "." + modelID
499}
500
501// bedrockGeoPrefixes are the cross-region inference-profile geo
502// prefixes Bedrock uses. A model ID that starts with one of these
503// (followed by a dot) is already a profile reference.
504var bedrockGeoPrefixes = []string{"us-gov", "us", "eu", "apac", "ap", "global", "au"}
505
506func bedrockHasGeoPrefix(modelID string) bool {
507	for _, p := range bedrockGeoPrefixes {
508		if strings.HasPrefix(modelID, p+".") {
509			return true
510		}
511	}
512	return false
513}
514
515// bedrockRequiresInferenceProfile reports whether a bare
516// foundation-model ID is one of the families AWS only exposes through
517// a cross-region inference profile for on-demand throughput.
518func bedrockRequiresInferenceProfile(modelID string) bool {
519	switch {
520	case strings.HasPrefix(modelID, "anthropic.claude-"):
521		return true
522	case strings.HasPrefix(modelID, "deepseek."):
523		return true
524	default:
525		return false
526	}
527}
528
529// bedrockGeoPrefixForRegion maps an AWS region to the geo prefix used
530// by its cross-region inference profiles. Returns "" when the region
531// has no known mapping, in which case the model ID is left unchanged.
532func bedrockGeoPrefixForRegion(region string) string {
533	switch {
534	case region == "":
535		return "us"
536	case strings.HasPrefix(region, "us-gov-"):
537		return "us-gov"
538	case strings.HasPrefix(region, "us-"):
539		return "us"
540	case strings.HasPrefix(region, "eu-"):
541		return "eu"
542	case strings.HasPrefix(region, "ap-"):
543		return "apac"
544	case strings.HasPrefix(region, "ca-"):
545		return "us"
546	case strings.HasPrefix(region, "sa-"):
547		return "us"
548	default:
549		return "us"
550	}
551}
552
553func (c *bedrockClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
554	wire, err := c.buildRequest(req)
555	if err != nil {
556		return nil, err
557	}
558	body, err := json.Marshal(wire)
559	if err != nil {
560		return nil, err
561	}
562	modelID := resolveBedrockInferenceProfileID(req.Model, c.region)
563	url := c.baseURL + "/model/" + modelID + "/converse-stream"
564	httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
565	if err != nil {
566		return nil, err
567	}
568	httpReq.Header.Set("content-type", "application/json")
569	httpReq.Header.Set("accept", "application/vnd.amazon.eventstream")
570	if c.bearerToken != "" {
571		httpReq.Header.Set("authorization", "Bearer "+c.bearerToken)
572	} else if c.sigv4 != nil {
573		if err := signSigV4(httpReq, body, "bedrock", c.region, c.sigv4, time.Now().UTC()); err != nil {
574			return nil, fmt.Errorf("bedrock: sigv4 sign: %w", err)
575		}
576	} else {
577		return nil, fmt.Errorf("bedrock: no auth configured")
578	}
579	resp, err := c.http.Do(httpReq)
580	if err != nil {
581		return nil, fmt.Errorf("bedrock: %w", err)
582	}
583	if resp.StatusCode != http.StatusOK {
584		b, _ := io.ReadAll(resp.Body)
585		resp.Body.Close()
586		msg := strings.TrimSpace(string(b))
587		// A 403 on the bearer route is almost always a region mismatch:
588		// short-term Bedrock API keys are scoped to the region of the
589		// console session that minted them, but zot defaults to
590		// us-east-1. Surface the resolved region and the fix so the user
591		// is not left guessing why a freshly-copied key is "invalid".
592		if resp.StatusCode == http.StatusForbidden && c.bearerToken != "" {
593			return nil, fmt.Errorf(
594				"bedrock: http 403 (region=%s): %s\nhint: Bedrock API keys are region-scoped. If your key was created in another region, set AWS_REGION (e.g. AWS_REGION=eu-central-1) or pass --base-url https://bedrock-runtime.<region>.amazonaws.com",
595				c.region, msg)
596		}
597		return nil, fmt.Errorf("bedrock: http %d: %s", resp.StatusCode, msg)
598	}
599	out := make(chan Event, 16)
600	go c.runStream(ctx, resp, req, out)
601	return out, nil
602}
603
604func (c *bedrockClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
605	defer close(out)
606	defer resp.Body.Close()
607
608	out <- EventStart{Provider: "amazon-bedrock", Model: req.Model}
609
610	// State accumulated across deltas.
611	contentBlocks := map[int]*bedrockBlockState{}
612	stop := StopEnd
613	finalMsg := Message{Role: RoleAssistant, Time: time.Now()}
614	var usage Usage
615
616	for {
617		if ctx.Err() != nil {
618			stop = StopAborted
619			break
620		}
621		evt, err := readEventStreamMessage(resp.Body)
622		if err != nil {
623			if err == io.EOF {
624				break
625			}
626			out <- EventDone{Stop: StopError, Err: err, Message: finalMsg}
627			return
628		}
629		eventType := evt.headerString(":event-type")
630		if eventType == "" {
631			eventType = bedrockEventTypeFromPayload(evt.payload)
632		}
633		messageType := evt.headerString(":message-type")
634		if messageType == "exception" {
635			out <- EventDone{Stop: StopError, Err: fmt.Errorf("bedrock exception (%s): %s", evt.headerString(":exception-type"), string(evt.payload)), Message: finalMsg}
636			return
637		}
638		switch eventType {
639		case "messageStart":
640			// nothing to do; role is always "assistant"
641		case "contentBlockStart":
642			var d struct {
643				ContentBlockIndex int `json:"contentBlockIndex"`
644				Start             struct {
645					ToolUse *struct {
646						ToolUseID string `json:"toolUseId"`
647						Name      string `json:"name"`
648					} `json:"toolUse"`
649				} `json:"start"`
650			}
651			if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockStart", &d); err != nil {
652				continue
653			}
654			st := &bedrockBlockState{}
655			contentBlocks[d.ContentBlockIndex] = st
656			if d.Start.ToolUse != nil {
657				st.isToolUse = true
658				st.toolID = d.Start.ToolUse.ToolUseID
659				st.toolName = d.Start.ToolUse.Name
660				out <- EventToolStart{ID: st.toolID, Name: st.toolName}
661			}
662		case "contentBlockDelta":
663			var d struct {
664				ContentBlockIndex int `json:"contentBlockIndex"`
665				Delta             struct {
666					Text    string `json:"text"`
667					ToolUse *struct {
668						Input string `json:"input"`
669					} `json:"toolUse"`
670				} `json:"delta"`
671			}
672			if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockDelta", &d); err != nil {
673				continue
674			}
675			st := contentBlocks[d.ContentBlockIndex]
676			if st == nil {
677				st = &bedrockBlockState{}
678				contentBlocks[d.ContentBlockIndex] = st
679			}
680			if d.Delta.Text != "" {
681				st.text.WriteString(d.Delta.Text)
682				out <- EventTextDelta{Delta: d.Delta.Text}
683			}
684			if d.Delta.ToolUse != nil && d.Delta.ToolUse.Input != "" {
685				st.toolArgs.WriteString(d.Delta.ToolUse.Input)
686				out <- EventToolArgs{ID: st.toolID, Delta: d.Delta.ToolUse.Input}
687			}
688		case "contentBlockStop":
689			var d struct {
690				ContentBlockIndex int `json:"contentBlockIndex"`
691			}
692			if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockStop", &d); err != nil {
693				continue
694			}
695			st := contentBlocks[d.ContentBlockIndex]
696			if st == nil {
697				continue
698			}
699			if st.isToolUse {
700				args := st.toolArgs.String()
701				if args == "" {
702					args = "{}"
703				}
704				finalMsg.Content = append(finalMsg.Content, ToolCallBlock{
705					ID: st.toolID, Name: st.toolName, Arguments: json.RawMessage(args),
706				})
707				out <- EventToolEnd{ID: st.toolID}
708			} else if st.text.Len() > 0 {
709				finalMsg.Content = append(finalMsg.Content, TextBlock{Text: st.text.String()})
710			}
711		case "messageStop":
712			var d struct {
713				StopReason string `json:"stopReason"`
714			}
715			_ = unmarshalBedrockEventPayload(evt.payload, "messageStop", &d)
716			switch d.StopReason {
717			case "tool_use":
718				stop = StopToolUse
719			case "end_turn":
720				stop = StopEnd
721			case "max_tokens":
722				stop = StopLength
723			default:
724				stop = StopEnd
725			}
726		case "metadata":
727			var d struct {
728				Usage struct {
729					InputTokens           int `json:"inputTokens"`
730					OutputTokens          int `json:"outputTokens"`
731					CacheReadInputTokens  int `json:"cacheReadInputTokens"`
732					CacheWriteInputTokens int `json:"cacheWriteInputTokens"`
733				} `json:"usage"`
734			}
735			if err := unmarshalBedrockEventPayload(evt.payload, "metadata", &d); err == nil {
736				usage.InputTokens = d.Usage.InputTokens
737				usage.OutputTokens = d.Usage.OutputTokens
738				usage.CacheReadTokens = d.Usage.CacheReadInputTokens
739				usage.CacheWriteTokens = d.Usage.CacheWriteInputTokens
740				if m, err := FindModel("amazon-bedrock", req.Model); err == nil {
741					usage.CostUSD = ComputeCost(m, usage)
742				}
743				out <- EventUsage{Usage: usage}
744			}
745		}
746	}
747	out <- EventDone{Stop: stop, Message: finalMsg}
748}
749
750type bedrockBlockState struct {
751	isToolUse bool
752	toolID    string
753	toolName  string
754	toolArgs  strings.Builder
755	text      strings.Builder
756}
757
758func bedrockEventTypeFromPayload(payload []byte) string {
759	var outer map[string]json.RawMessage
760	if err := json.Unmarshal(payload, &outer); err != nil {
761		return ""
762	}
763	for _, name := range []string{"messageStart", "contentBlockStart", "contentBlockDelta", "contentBlockStop", "messageStop", "metadata"} {
764		if _, ok := outer[name]; ok {
765			return name
766		}
767	}
768	return ""
769}
770
771func unmarshalBedrockEventPayload(payload []byte, eventType string, dst any) error {
772	var outer map[string]json.RawMessage
773	if err := json.Unmarshal(payload, &outer); err == nil {
774		if wrapped, ok := outer[eventType]; ok {
775			return json.Unmarshal(wrapped, dst)
776		}
777	}
778	if err := json.Unmarshal(payload, dst); err != nil {
779		return fmt.Errorf("bedrock: parse %s payload: %w", eventType, err)
780	}
781	return nil
782}
783
784// ---- event-stream binary framing parser ----
785
786type eventStreamMessage struct {
787	headers map[string]string
788	payload []byte
789}
790
791func (m *eventStreamMessage) headerString(name string) string { return m.headers[name] }
792
793// readEventStreamMessage reads one event-stream message from r. Returns
794// io.EOF when the stream is finished cleanly.
795func readEventStreamMessage(r io.Reader) (*eventStreamMessage, error) {
796	var prelude [8]byte
797	if _, err := io.ReadFull(r, prelude[:]); err != nil {
798		return nil, err
799	}
800	totalLen := binary.BigEndian.Uint32(prelude[0:4])
801	headersLen := binary.BigEndian.Uint32(prelude[4:8])
802	if totalLen < 16 || headersLen > totalLen-16 {
803		return nil, fmt.Errorf("bedrock: malformed event-stream prelude (total=%d headers=%d)", totalLen, headersLen)
804	}
805	// Skip prelude CRC (4 bytes); we don't validate.
806	var preludeCRC [4]byte
807	if _, err := io.ReadFull(r, preludeCRC[:]); err != nil {
808		return nil, err
809	}
810	headersBuf := make([]byte, headersLen)
811	if _, err := io.ReadFull(r, headersBuf); err != nil {
812		return nil, err
813	}
814	payloadLen := int(totalLen) - 16 - int(headersLen)
815	payload := make([]byte, payloadLen)
816	if _, err := io.ReadFull(r, payload); err != nil {
817		return nil, err
818	}
819	var trailer [4]byte
820	if _, err := io.ReadFull(r, trailer[:]); err != nil {
821		return nil, err
822	}
823	// Parse headers.
824	hdrs := map[string]string{}
825	i := 0
826	for i < len(headersBuf) {
827		if i+1 > len(headersBuf) {
828			break
829		}
830		nameLen := int(headersBuf[i])
831		i++
832		if i+nameLen > len(headersBuf) {
833			return nil, fmt.Errorf("bedrock: header name overflow")
834		}
835		name := string(headersBuf[i : i+nameLen])
836		i += nameLen
837		if i+1 > len(headersBuf) {
838			return nil, fmt.Errorf("bedrock: header value-type missing")
839		}
840		valueType := headersBuf[i]
841		i++
842		// Type 7 = string with 2-byte length. Type 6 = byte-array similar.
843		// Other types (bool/int/long/timestamp/uuid) we treat as opaque
844		// strings since bedrock's event-type headers are always type 7.
845		switch valueType {
846		case 7, 6:
847			if i+2 > len(headersBuf) {
848				return nil, fmt.Errorf("bedrock: header value length missing")
849			}
850			vLen := int(binary.BigEndian.Uint16(headersBuf[i : i+2]))
851			i += 2
852			if i+vLen > len(headersBuf) {
853				return nil, fmt.Errorf("bedrock: header value overflow")
854			}
855			hdrs[name] = string(headersBuf[i : i+vLen])
856			i += vLen
857		case 0: // bool true
858			hdrs[name] = "true"
859		case 1: // bool false
860			hdrs[name] = "false"
861		case 2: // byte
862			if i+1 > len(headersBuf) {
863				return nil, fmt.Errorf("bedrock: header byte missing")
864			}
865			i++
866		case 3: // int16
867			if i+2 > len(headersBuf) {
868				return nil, fmt.Errorf("bedrock: header int16 missing")
869			}
870			i += 2
871		case 4: // int32
872			if i+4 > len(headersBuf) {
873				return nil, fmt.Errorf("bedrock: header int32 missing")
874			}
875			i += 4
876		case 5: // int64
877			if i+8 > len(headersBuf) {
878				return nil, fmt.Errorf("bedrock: header int64 missing")
879			}
880			i += 8
881		case 8: // timestamp (int64)
882			if i+8 > len(headersBuf) {
883				return nil, fmt.Errorf("bedrock: header timestamp missing")
884			}
885			i += 8
886		case 9: // uuid (16 bytes)
887			if i+16 > len(headersBuf) {
888				return nil, fmt.Errorf("bedrock: header uuid missing")
889			}
890			i += 16
891		default:
892			return nil, fmt.Errorf("bedrock: unknown header value-type %d", valueType)
893		}
894	}
895	return &eventStreamMessage{headers: hdrs, payload: payload}, nil
896}
897
898// ---- SigV4 signing ----
899//
900// AWS Signature Version 4. Implemented from scratch so we don't pull in
901// aws-sdk-go-v2 (large transitive dep tree just for one signer). The
902// algorithm is documented at:
903//   https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
904//
905// Steps:
906//
907//   1. Build the canonical request: method + path + canonical query +
908//      canonical headers + signed headers + payload-hash.
909//   2. Build the string-to-sign: algorithm + amz-date + credential scope +
910//      sha256(canonical request).
911//   3. Derive the signing key by chaining HMAC-SHA256:
912//      kSecret -> kDate -> kRegion -> kService -> kSigning
913//   4. signature = HMAC-SHA256(kSigning, stringToSign)
914//   5. Authorization header: AWS4-HMAC-SHA256 Credential=..., SignedHeaders=..., Signature=...
915//
916// Payload hash is sha256 of the JSON body. For Bedrock's streaming
917// endpoint this works because the request body is fully buffered before
918// the call — we don't need the streaming-payload variant.
919
920func sigHMAC(key, msg []byte) []byte {
921	m := hmac.New(sha256.New, key)
922	m.Write(msg)
923	return m.Sum(nil)
924}
925
926func sigSHA256Hex(b []byte) string {
927	h := sha256.Sum256(b)
928	return hex.EncodeToString(h[:])
929}
930
931func signSigV4(req *http.Request, payload []byte, service, region string, creds *bedrockSigV4Creds, now time.Time) error {
932	amzDate := now.Format("20060102T150405Z")
933	shortDate := now.Format("20060102")
934	credentialScope := shortDate + "/" + region + "/" + service + "/aws4_request"
935
936	// Required headers.
937	req.Header.Set("host", req.URL.Host)
938	req.Header.Set("x-amz-date", amzDate)
939	if creds.sessionToken != "" {
940		req.Header.Set("x-amz-security-token", creds.sessionToken)
941	}
942	payloadHash := sigSHA256Hex(payload)
943	req.Header.Set("x-amz-content-sha256", payloadHash)
944
945	// Canonical headers: lowercase name, trimmed value, sorted by name,
946	// each on its own line ending with \n.
947	var names []string
948	values := map[string]string{}
949	for k, vs := range req.Header {
950		lower := strings.ToLower(k)
951		// Skip authorization (we're computing it) and any
952		// connection-specific headers.
953		if lower == "authorization" {
954			continue
955		}
956		names = append(names, lower)
957		values[lower] = strings.Join(vs, ",")
958	}
959	// host is special — it's not in req.Header by default; set above.
960	sort.Strings(names)
961	var canonHdrs strings.Builder
962	for _, n := range names {
963		canonHdrs.WriteString(n)
964		canonHdrs.WriteByte(':')
965		canonHdrs.WriteString(strings.TrimSpace(values[n]))
966		canonHdrs.WriteByte('\n')
967	}
968	signedHeaders := strings.Join(names, ";")
969
970	// Canonical query string: keys sorted by name, each key and value
971	// URI-escaped (RFC 3986).
972	q := req.URL.Query()
973	var qKeys []string
974	for k := range q {
975		qKeys = append(qKeys, k)
976	}
977	sort.Strings(qKeys)
978	var canonQuery strings.Builder
979	for i, k := range qKeys {
980		if i > 0 {
981			canonQuery.WriteByte('&')
982		}
983		canonQuery.WriteString(url.QueryEscape(k))
984		canonQuery.WriteByte('=')
985		canonQuery.WriteString(url.QueryEscape(q.Get(k)))
986	}
987
988	// Canonical request.
989	canonReq := req.Method + "\n" +
990		canonicalSigV4Path(req.URL.Path) + "\n" +
991		canonQuery.String() + "\n" +
992		canonHdrs.String() + "\n" +
993		signedHeaders + "\n" +
994		payloadHash
995
996	// String to sign.
997	stringToSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n" + sigSHA256Hex([]byte(canonReq))
998
999	// Signing key.
1000	kDate := sigHMAC([]byte("AWS4"+creds.secretAccessKey), []byte(shortDate))
1001	kRegion := sigHMAC(kDate, []byte(region))
1002	kService := sigHMAC(kRegion, []byte(service))
1003	kSigning := sigHMAC(kService, []byte("aws4_request"))
1004
1005	// Signature.
1006	signature := hex.EncodeToString(sigHMAC(kSigning, []byte(stringToSign)))
1007
1008	// Authorization header.
1009	auth := "AWS4-HMAC-SHA256 " +
1010		"Credential=" + creds.accessKeyID + "/" + credentialScope + ", " +
1011		"SignedHeaders=" + signedHeaders + ", " +
1012		"Signature=" + signature
1013	req.Header.Set("Authorization", auth)
1014	return nil
1015}
1016
1017// canonicalSigV4Path returns the path with each segment URI-encoded
1018// according to SigV4 rules (everything except unreserved chars
1019// A-Za-z0-9-_.~ and / between segments). Bedrock model IDs contain
1020// dots, colons, and slashes; the colons must be percent-encoded.
1021func canonicalSigV4Path(p string) string {
1022	if p == "" {
1023		return "/"
1024	}
1025	segments := strings.Split(p, "/")
1026	for i, s := range segments {
1027		segments[i] = sigV4EncodeSegment(s)
1028	}
1029	return strings.Join(segments, "/")
1030}
1031
1032func sigV4EncodeSegment(s string) string {
1033	var b strings.Builder
1034	for i := 0; i < len(s); i++ {
1035		c := s[i]
1036		// Unreserved per RFC 3986.
1037		if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
1038			c == '-' || c == '_' || c == '.' || c == '~' {
1039			b.WriteByte(c)
1040			continue
1041		}
1042		fmt.Fprintf(&b, "%%%02X", c)
1043	}
1044	return b.String()
1045}

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