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