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 activeTools := activeToolDefinitions(req.Tools, req.Messages)
415 if len(activeTools) > 0 {
416 tc := struct {
417 Tools []bedrockToolSpec `json:"tools"`
418 }{}
419 for _, t := range activeTools {
420 var ts bedrockToolSpec
421 ts.ToolSpec.Name = t.Name
422 ts.ToolSpec.Description = t.Description
423 ts.ToolSpec.InputSchema.JSON = t.Schema
424 tc.Tools = append(tc.Tools, ts)
425 }
426 out.ToolConfig = &tc
427 } else if bedrockMessagesHaveToolBlocks(out.Messages) {
428 // Bedrock requires toolConfig to be present whenever the message
429 // history contains toolUse or toolResult content blocks, even if
430 // the current request does not intend to call any tools (e.g. the
431 // /btw side-chat sends the frozen main transcript which may include
432 // prior tool turns). Inject a stub tool so the API accepts the
433 // request; it will never be invoked since no tool_use stop reason
434 // can be triggered when the real tool list is empty.
435 var stub bedrockToolSpec
436 stub.ToolSpec.Name = "_placeholder"
437 stub.ToolSpec.Description = "placeholder required by Bedrock when tool history is present"
438 stub.ToolSpec.InputSchema.JSON = json.RawMessage(`{"type":"object","properties":{}}`)
439 out.ToolConfig = &struct {
440 Tools []bedrockToolSpec `json:"tools"`
441 }{Tools: []bedrockToolSpec{stub}}
442 }
443
444 if caching {
445 // Tag the last user message with a cachePoint. This extends the
446 // cached prefix to cover the full conversation history up to the
447 // current turn, so the next turn reads that history cheaply.
448 bedrockTagLastUserCache(out.Messages)
449 }
450
451 return out, nil
452}
453
454// bedrockTagLastUserCache appends a cachePoint block to the last user
455// message in the Bedrock message list. It is the Bedrock equivalent of
456// Anthropic's cache_control:{type:"ephemeral"} on the last user message.
457func bedrockTagLastUserCache(msgs []bedrockMessage) {
458 for i := len(msgs) - 1; i >= 0; i-- {
459 if msgs[i].Role == "user" {
460 msgs[i].Content = append(msgs[i].Content, bedrockCachePoint)
461 return
462 }
463 }
464}
465
466// resolveBedrockInferenceProfileID maps a bare foundation-model ID to
467// its region-matched cross-region inference-profile ID.
468//
469// Several newer Bedrock models (Anthropic Claude 4.x, DeepSeek, etc.)
470// cannot be invoked with on-demand throughput by their plain
471// foundation-model ID; Bedrock returns HTTP 400 demanding "the ID or
472// ARN of an inference profile that contains this model". The profile
473// ID is the same model ID with a geographic prefix (us/eu/apac/...).
474//
475// We only rewrite IDs that (a) lack an existing geo prefix and (b)
476// belong to a model family that requires a profile. IDs that already
477// carry a prefix (e.g. "eu.anthropic...", "global.anthropic...") or
478// fully-qualified ARNs are returned unchanged, so explicit user
479// choices and custom application inference profiles still work.
480func resolveBedrockInferenceProfileID(modelID, region string) string {
481 if modelID == "" {
482 return modelID
483 }
484 // ARNs are already inference-profile references; leave untouched.
485 if strings.HasPrefix(modelID, "arn:") {
486 return modelID
487 }
488 // Already geo-prefixed (us. / eu. / apac. / ap. / us-gov. / global.)?
489 if bedrockHasGeoPrefix(modelID) {
490 return modelID
491 }
492 if !bedrockRequiresInferenceProfile(modelID) {
493 return modelID
494 }
495 prefix := bedrockGeoPrefixForRegion(region)
496 if prefix == "" {
497 return modelID
498 }
499 return prefix + "." + modelID
500}
501
502// bedrockGeoPrefixes are the cross-region inference-profile geo
503// prefixes Bedrock uses. A model ID that starts with one of these
504// (followed by a dot) is already a profile reference.
505var bedrockGeoPrefixes = []string{"us-gov", "us", "eu", "apac", "ap", "global", "au"}
506
507func bedrockHasGeoPrefix(modelID string) bool {
508 for _, p := range bedrockGeoPrefixes {
509 if strings.HasPrefix(modelID, p+".") {
510 return true
511 }
512 }
513 return false
514}
515
516// bedrockRequiresInferenceProfile reports whether a bare
517// foundation-model ID is one of the families AWS only exposes through
518// a cross-region inference profile for on-demand throughput.
519func bedrockRequiresInferenceProfile(modelID string) bool {
520 switch {
521 case strings.HasPrefix(modelID, "anthropic.claude-"):
522 return true
523 case strings.HasPrefix(modelID, "deepseek."):
524 return true
525 default:
526 return false
527 }
528}
529
530// bedrockGeoPrefixForRegion maps an AWS region to the geo prefix used
531// by its cross-region inference profiles. Returns "" when the region
532// has no known mapping, in which case the model ID is left unchanged.
533func bedrockGeoPrefixForRegion(region string) string {
534 switch {
535 case region == "":
536 return "us"
537 case strings.HasPrefix(region, "us-gov-"):
538 return "us-gov"
539 case strings.HasPrefix(region, "us-"):
540 return "us"
541 case strings.HasPrefix(region, "eu-"):
542 return "eu"
543 case strings.HasPrefix(region, "ap-"):
544 return "apac"
545 case strings.HasPrefix(region, "ca-"):
546 return "us"
547 case strings.HasPrefix(region, "sa-"):
548 return "us"
549 default:
550 return "us"
551 }
552}
553
554func (c *bedrockClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
555 wire, err := c.buildRequest(req)
556 if err != nil {
557 return nil, err
558 }
559 body, err := json.Marshal(wire)
560 if err != nil {
561 return nil, err
562 }
563 modelID := resolveBedrockInferenceProfileID(req.Model, c.region)
564 url := c.baseURL + "/model/" + modelID + "/converse-stream"
565 httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
566 if err != nil {
567 return nil, err
568 }
569 httpReq.Header.Set("content-type", "application/json")
570 httpReq.Header.Set("accept", "application/vnd.amazon.eventstream")
571 if c.bearerToken != "" {
572 httpReq.Header.Set("authorization", "Bearer "+c.bearerToken)
573 } else if c.sigv4 != nil {
574 if err := signSigV4(httpReq, body, "bedrock", c.region, c.sigv4, time.Now().UTC()); err != nil {
575 return nil, fmt.Errorf("bedrock: sigv4 sign: %w", err)
576 }
577 } else {
578 return nil, fmt.Errorf("bedrock: no auth configured")
579 }
580 resp, err := c.http.Do(httpReq)
581 if err != nil {
582 return nil, fmt.Errorf("bedrock: %w", err)
583 }
584 if resp.StatusCode != http.StatusOK {
585 b, _ := io.ReadAll(resp.Body)
586 resp.Body.Close()
587 msg := strings.TrimSpace(string(b))
588 // A 403 on the bearer route is almost always a region mismatch:
589 // short-term Bedrock API keys are scoped to the region of the
590 // console session that minted them, but zot defaults to
591 // us-east-1. Surface the resolved region and the fix so the user
592 // is not left guessing why a freshly-copied key is "invalid".
593 if resp.StatusCode == http.StatusForbidden && c.bearerToken != "" {
594 return nil, fmt.Errorf(
595 "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",
596 c.region, msg)
597 }
598 return nil, fmt.Errorf("bedrock: http %d: %s", resp.StatusCode, msg)
599 }
600 out := make(chan Event, 16)
601 go c.runStream(ctx, resp, req, out)
602 return out, nil
603}
604
605func (c *bedrockClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
606 defer close(out)
607 defer resp.Body.Close()
608
609 out <- EventStart{Provider: "amazon-bedrock", Model: req.Model}
610
611 // State accumulated across deltas.
612 contentBlocks := map[int]*bedrockBlockState{}
613 stop := StopEnd
614 finalMsg := Message{Role: RoleAssistant, Time: time.Now()}
615 var usage Usage
616
617 for {
618 if ctx.Err() != nil {
619 stop = StopAborted
620 break
621 }
622 evt, err := readEventStreamMessage(resp.Body)
623 if err != nil {
624 if err == io.EOF {
625 break
626 }
627 out <- EventDone{Stop: StopError, Err: err, Message: finalMsg}
628 return
629 }
630 eventType := evt.headerString(":event-type")
631 if eventType == "" {
632 eventType = bedrockEventTypeFromPayload(evt.payload)
633 }
634 messageType := evt.headerString(":message-type")
635 if messageType == "exception" {
636 out <- EventDone{Stop: StopError, Err: fmt.Errorf("bedrock exception (%s): %s", evt.headerString(":exception-type"), string(evt.payload)), Message: finalMsg}
637 return
638 }
639 switch eventType {
640 case "messageStart":
641 // nothing to do; role is always "assistant"
642 case "contentBlockStart":
643 var d struct {
644 ContentBlockIndex int `json:"contentBlockIndex"`
645 Start struct {
646 ToolUse *struct {
647 ToolUseID string `json:"toolUseId"`
648 Name string `json:"name"`
649 } `json:"toolUse"`
650 } `json:"start"`
651 }
652 if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockStart", &d); err != nil {
653 continue
654 }
655 st := &bedrockBlockState{}
656 contentBlocks[d.ContentBlockIndex] = st
657 if d.Start.ToolUse != nil {
658 st.isToolUse = true
659 st.toolID = d.Start.ToolUse.ToolUseID
660 st.toolName = d.Start.ToolUse.Name
661 out <- EventToolStart{ID: st.toolID, Name: st.toolName}
662 }
663 case "contentBlockDelta":
664 var d struct {
665 ContentBlockIndex int `json:"contentBlockIndex"`
666 Delta struct {
667 Text string `json:"text"`
668 ToolUse *struct {
669 Input string `json:"input"`
670 } `json:"toolUse"`
671 } `json:"delta"`
672 }
673 if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockDelta", &d); err != nil {
674 continue
675 }
676 st := contentBlocks[d.ContentBlockIndex]
677 if st == nil {
678 st = &bedrockBlockState{}
679 contentBlocks[d.ContentBlockIndex] = st
680 }
681 if d.Delta.Text != "" {
682 st.text.WriteString(d.Delta.Text)
683 out <- EventTextDelta{Delta: d.Delta.Text}
684 }
685 if d.Delta.ToolUse != nil && d.Delta.ToolUse.Input != "" {
686 st.toolArgs.WriteString(d.Delta.ToolUse.Input)
687 out <- EventToolArgs{ID: st.toolID, Delta: d.Delta.ToolUse.Input}
688 }
689 case "contentBlockStop":
690 var d struct {
691 ContentBlockIndex int `json:"contentBlockIndex"`
692 }
693 if err := unmarshalBedrockEventPayload(evt.payload, "contentBlockStop", &d); err != nil {
694 continue
695 }
696 st := contentBlocks[d.ContentBlockIndex]
697 if st == nil {
698 continue
699 }
700 if st.isToolUse {
701 args := st.toolArgs.String()
702 if args == "" {
703 args = "{}"
704 }
705 finalMsg.Content = append(finalMsg.Content, ToolCallBlock{
706 ID: st.toolID, Name: st.toolName, Arguments: json.RawMessage(args),
707 })
708 out <- EventToolEnd{ID: st.toolID}
709 } else if st.text.Len() > 0 {
710 finalMsg.Content = append(finalMsg.Content, TextBlock{Text: st.text.String()})
711 }
712 case "messageStop":
713 var d struct {
714 StopReason string `json:"stopReason"`
715 }
716 _ = unmarshalBedrockEventPayload(evt.payload, "messageStop", &d)
717 switch d.StopReason {
718 case "tool_use":
719 stop = StopToolUse
720 case "end_turn":
721 stop = StopEnd
722 case "max_tokens":
723 stop = StopLength
724 default:
725 stop = StopEnd
726 }
727 case "metadata":
728 var d struct {
729 Usage struct {
730 InputTokens int `json:"inputTokens"`
731 OutputTokens int `json:"outputTokens"`
732 CacheReadInputTokens int `json:"cacheReadInputTokens"`
733 CacheWriteInputTokens int `json:"cacheWriteInputTokens"`
734 } `json:"usage"`
735 }
736 if err := unmarshalBedrockEventPayload(evt.payload, "metadata", &d); err == nil {
737 usage.InputTokens = d.Usage.InputTokens
738 usage.OutputTokens = d.Usage.OutputTokens
739 usage.CacheReadTokens = d.Usage.CacheReadInputTokens
740 usage.CacheWriteTokens = d.Usage.CacheWriteInputTokens
741 if m, err := FindModel("amazon-bedrock", req.Model); err == nil {
742 usage.CostUSD = ComputeCost(m, usage)
743 }
744 out <- EventUsage{Usage: usage}
745 }
746 }
747 }
748 out <- EventDone{Stop: stop, Message: finalMsg}
749}
750
751type bedrockBlockState struct {
752 isToolUse bool
753 toolID string
754 toolName string
755 toolArgs strings.Builder
756 text strings.Builder
757}
758
759func bedrockEventTypeFromPayload(payload []byte) string {
760 var outer map[string]json.RawMessage
761 if err := json.Unmarshal(payload, &outer); err != nil {
762 return ""
763 }
764 for _, name := range []string{"messageStart", "contentBlockStart", "contentBlockDelta", "contentBlockStop", "messageStop", "metadata"} {
765 if _, ok := outer[name]; ok {
766 return name
767 }
768 }
769 return ""
770}
771
772func unmarshalBedrockEventPayload(payload []byte, eventType string, dst any) error {
773 var outer map[string]json.RawMessage
774 if err := json.Unmarshal(payload, &outer); err == nil {
775 if wrapped, ok := outer[eventType]; ok {
776 return json.Unmarshal(wrapped, dst)
777 }
778 }
779 if err := json.Unmarshal(payload, dst); err != nil {
780 return fmt.Errorf("bedrock: parse %s payload: %w", eventType, err)
781 }
782 return nil
783}
784
785// ---- event-stream binary framing parser ----
786
787type eventStreamMessage struct {
788 headers map[string]string
789 payload []byte
790}
791
792func (m *eventStreamMessage) headerString(name string) string { return m.headers[name] }
793
794// readEventStreamMessage reads one event-stream message from r. Returns
795// io.EOF when the stream is finished cleanly.
796func readEventStreamMessage(r io.Reader) (*eventStreamMessage, error) {
797 var prelude [8]byte
798 if _, err := io.ReadFull(r, prelude[:]); err != nil {
799 return nil, err
800 }
801 totalLen := binary.BigEndian.Uint32(prelude[0:4])
802 headersLen := binary.BigEndian.Uint32(prelude[4:8])
803 if totalLen < 16 || headersLen > totalLen-16 {
804 return nil, fmt.Errorf("bedrock: malformed event-stream prelude (total=%d headers=%d)", totalLen, headersLen)
805 }
806 // Skip prelude CRC (4 bytes); we don't validate.
807 var preludeCRC [4]byte
808 if _, err := io.ReadFull(r, preludeCRC[:]); err != nil {
809 return nil, err
810 }
811 headersBuf := make([]byte, headersLen)
812 if _, err := io.ReadFull(r, headersBuf); err != nil {
813 return nil, err
814 }
815 payloadLen := int(totalLen) - 16 - int(headersLen)
816 payload := make([]byte, payloadLen)
817 if _, err := io.ReadFull(r, payload); err != nil {
818 return nil, err
819 }
820 var trailer [4]byte
821 if _, err := io.ReadFull(r, trailer[:]); err != nil {
822 return nil, err
823 }
824 // Parse headers.
825 hdrs := map[string]string{}
826 i := 0
827 for i < len(headersBuf) {
828 if i+1 > len(headersBuf) {
829 break
830 }
831 nameLen := int(headersBuf[i])
832 i++
833 if i+nameLen > len(headersBuf) {
834 return nil, fmt.Errorf("bedrock: header name overflow")
835 }
836 name := string(headersBuf[i : i+nameLen])
837 i += nameLen
838 if i+1 > len(headersBuf) {
839 return nil, fmt.Errorf("bedrock: header value-type missing")
840 }
841 valueType := headersBuf[i]
842 i++
843 // Type 7 = string with 2-byte length. Type 6 = byte-array similar.
844 // Other types (bool/int/long/timestamp/uuid) we treat as opaque
845 // strings since bedrock's event-type headers are always type 7.
846 switch valueType {
847 case 7, 6:
848 if i+2 > len(headersBuf) {
849 return nil, fmt.Errorf("bedrock: header value length missing")
850 }
851 vLen := int(binary.BigEndian.Uint16(headersBuf[i : i+2]))
852 i += 2
853 if i+vLen > len(headersBuf) {
854 return nil, fmt.Errorf("bedrock: header value overflow")
855 }
856 hdrs[name] = string(headersBuf[i : i+vLen])
857 i += vLen
858 case 0: // bool true
859 hdrs[name] = "true"
860 case 1: // bool false
861 hdrs[name] = "false"
862 case 2: // byte
863 if i+1 > len(headersBuf) {
864 return nil, fmt.Errorf("bedrock: header byte missing")
865 }
866 i++
867 case 3: // int16
868 if i+2 > len(headersBuf) {
869 return nil, fmt.Errorf("bedrock: header int16 missing")
870 }
871 i += 2
872 case 4: // int32
873 if i+4 > len(headersBuf) {
874 return nil, fmt.Errorf("bedrock: header int32 missing")
875 }
876 i += 4
877 case 5: // int64
878 if i+8 > len(headersBuf) {
879 return nil, fmt.Errorf("bedrock: header int64 missing")
880 }
881 i += 8
882 case 8: // timestamp (int64)
883 if i+8 > len(headersBuf) {
884 return nil, fmt.Errorf("bedrock: header timestamp missing")
885 }
886 i += 8
887 case 9: // uuid (16 bytes)
888 if i+16 > len(headersBuf) {
889 return nil, fmt.Errorf("bedrock: header uuid missing")
890 }
891 i += 16
892 default:
893 return nil, fmt.Errorf("bedrock: unknown header value-type %d", valueType)
894 }
895 }
896 return &eventStreamMessage{headers: hdrs, payload: payload}, nil
897}
898
899// ---- SigV4 signing ----
900//
901// AWS Signature Version 4. Implemented from scratch so we don't pull in
902// aws-sdk-go-v2 (large transitive dep tree just for one signer). The
903// algorithm is documented at:
904// https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
905//
906// Steps:
907//
908// 1. Build the canonical request: method + path + canonical query +
909// canonical headers + signed headers + payload-hash.
910// 2. Build the string-to-sign: algorithm + amz-date + credential scope +
911// sha256(canonical request).
912// 3. Derive the signing key by chaining HMAC-SHA256:
913// kSecret -> kDate -> kRegion -> kService -> kSigning
914// 4. signature = HMAC-SHA256(kSigning, stringToSign)
915// 5. Authorization header: AWS4-HMAC-SHA256 Credential=..., SignedHeaders=..., Signature=...
916//
917// Payload hash is sha256 of the JSON body. For Bedrock's streaming
918// endpoint this works because the request body is fully buffered before
919// the call — we don't need the streaming-payload variant.
920
921func sigHMAC(key, msg []byte) []byte {
922 m := hmac.New(sha256.New, key)
923 m.Write(msg)
924 return m.Sum(nil)
925}
926
927func sigSHA256Hex(b []byte) string {
928 h := sha256.Sum256(b)
929 return hex.EncodeToString(h[:])
930}
931
932func signSigV4(req *http.Request, payload []byte, service, region string, creds *bedrockSigV4Creds, now time.Time) error {
933 amzDate := now.Format("20060102T150405Z")
934 shortDate := now.Format("20060102")
935 credentialScope := shortDate + "/" + region + "/" + service + "/aws4_request"
936
937 // Required headers.
938 req.Header.Set("host", req.URL.Host)
939 req.Header.Set("x-amz-date", amzDate)
940 if creds.sessionToken != "" {
941 req.Header.Set("x-amz-security-token", creds.sessionToken)
942 }
943 payloadHash := sigSHA256Hex(payload)
944 req.Header.Set("x-amz-content-sha256", payloadHash)
945
946 // Canonical headers: lowercase name, trimmed value, sorted by name,
947 // each on its own line ending with \n.
948 var names []string
949 values := map[string]string{}
950 for k, vs := range req.Header {
951 lower := strings.ToLower(k)
952 // Skip authorization (we're computing it) and any
953 // connection-specific headers.
954 if lower == "authorization" {
955 continue
956 }
957 names = append(names, lower)
958 values[lower] = strings.Join(vs, ",")
959 }
960 // host is special — it's not in req.Header by default; set above.
961 sort.Strings(names)
962 var canonHdrs strings.Builder
963 for _, n := range names {
964 canonHdrs.WriteString(n)
965 canonHdrs.WriteByte(':')
966 canonHdrs.WriteString(strings.TrimSpace(values[n]))
967 canonHdrs.WriteByte('\n')
968 }
969 signedHeaders := strings.Join(names, ";")
970
971 // Canonical query string: keys sorted by name, each key and value
972 // URI-escaped (RFC 3986).
973 q := req.URL.Query()
974 var qKeys []string
975 for k := range q {
976 qKeys = append(qKeys, k)
977 }
978 sort.Strings(qKeys)
979 var canonQuery strings.Builder
980 for i, k := range qKeys {
981 if i > 0 {
982 canonQuery.WriteByte('&')
983 }
984 canonQuery.WriteString(url.QueryEscape(k))
985 canonQuery.WriteByte('=')
986 canonQuery.WriteString(url.QueryEscape(q.Get(k)))
987 }
988
989 // Canonical request.
990 canonReq := req.Method + "\n" +
991 canonicalSigV4Path(req.URL.Path) + "\n" +
992 canonQuery.String() + "\n" +
993 canonHdrs.String() + "\n" +
994 signedHeaders + "\n" +
995 payloadHash
996
997 // String to sign.
998 stringToSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n" + sigSHA256Hex([]byte(canonReq))
999
1000 // Signing key.
1001 kDate := sigHMAC([]byte("AWS4"+creds.secretAccessKey), []byte(shortDate))
1002 kRegion := sigHMAC(kDate, []byte(region))
1003 kService := sigHMAC(kRegion, []byte(service))
1004 kSigning := sigHMAC(kService, []byte("aws4_request"))
1005
1006 // Signature.
1007 signature := hex.EncodeToString(sigHMAC(kSigning, []byte(stringToSign)))
1008
1009 // Authorization header.
1010 auth := "AWS4-HMAC-SHA256 " +
1011 "Credential=" + creds.accessKeyID + "/" + credentialScope + ", " +
1012 "SignedHeaders=" + signedHeaders + ", " +
1013 "Signature=" + signature
1014 req.Header.Set("Authorization", auth)
1015 return nil
1016}
1017
1018// canonicalSigV4Path returns the path with each segment URI-encoded
1019// according to SigV4 rules (everything except unreserved chars
1020// A-Za-z0-9-_.~ and / between segments). Bedrock model IDs contain
1021// dots, colons, and slashes; the colons must be percent-encoded.
1022func canonicalSigV4Path(p string) string {
1023 if p == "" {
1024 return "/"
1025 }
1026 segments := strings.Split(p, "/")
1027 for i, s := range segments {
1028 segments[i] = sigV4EncodeSegment(s)
1029 }
1030 return strings.Join(segments, "/")
1031}
1032
1033func sigV4EncodeSegment(s string) string {
1034 var b strings.Builder
1035 for i := 0; i < len(s); i++ {
1036 c := s[i]
1037 // Unreserved per RFC 3986.
1038 if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
1039 c == '-' || c == '_' || c == '.' || c == '~' {
1040 b.WriteByte(c)
1041 continue
1042 }
1043 fmt.Fprintf(&b, "%%%02X", c)
1044 }
1045 return b.String()
1046}