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