Skip to content

feat(core): add Amazon Bedrock provider with AWS credential chain auth - #4895

Merged
sailist merged 4 commits into
mainfrom
feat-361-11-12-bedrock-provider-client
Nov 13, 2026
Merged

sailist merged 4 commits into
mainfrom
feat-361-11-12-bedrock-provider-client

Conversation

@sailist

@sailist sailist commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Resolve #3965. Users who authenticate to AWS through the standard credential chain (SSO, shared config, instance roles) should be able to use Amazon Bedrock models without configuring a long-lived Bedrock API key.

This PR adds a bedrock provider that generates short-lived bearer tokens from the ambient AWS credential chain. It also isolates Bedrock's Anthropic client construction inside the Bedrock provider instead of adding Bedrock-specific bearer detection to the shared Anthropic protocol.

Bug Reproduction Steps

N/A (feature PR)

Root Cause

N/A (feature PR)

Code Changes

Core idea. When no api_key, api_key_env, or AWS_BEARER_TOKEN_BEDROCK is configured, the CLI uses @aws/bedrock-token-generator and the ambient AWS credential chain to mint a short-lived bearer token. The token is cached, refreshed before expiry, and regenerated after a 401. Explicit credentials retain their existing precedence.

providers.<name>.env
        |
        +--> region / profile --> AWS credential chain --> cached Bedrock token
        |
        +--> model ID --> Anthropic / OpenAI / OpenAI Responses route

Static or generated credential --> ordinary { apiKey }
                                       |
                       +---------------+---------------+
                       |                               |
                OpenAI protocols              Bedrock Anthropic requester
                (normal Bearer)               (provider-owned authToken mapping)

Key decisions

  • Provider-owned Anthropic authentication. bedrockAnthropicProtocol derives from anthropicProtocol.with({ client }). Only the Bedrock requester maps the credential to the Anthropic SDK's authToken; the shared Anthropic client keeps its existing x-api-key and custom-header behavior. There is no Bearer == apiKey heuristic.
  • One credential representation. Static keys and generated tokens both use the existing { apiKey } credential shape. No parallel Bedrock credential header convention is introduced.
  • Protocol inference per model. anthropic.* uses Anthropic Messages, openai.gpt-oss* uses Chat Completions, other openai.* uses Responses, and moonshotai.* / moonshot.* uses Chat Completions. Unknown vendors default to Chat Completions, with an explicit per-model protocol override.
  • Region-safe endpoints. The default endpoint is derived from AWS_REGION / AWS_DEFAULT_REGION. Missing explicit region configuration fails with a configuration error instead of allowing a credential to be sent to a protocol client's default public host.
  • Existing configuration surfaces. Node SDK, kap-server REST writes, and legacy migration accept bedrock. REST model writes also accept the optional protocol field. Existing single-protocol providers retain their endpoint-env fallback when a model overrides the protocol.

Reading guide

  • packages/core/src/llm/builtin/provider/bedrock/credentials.ts — token caching, coalescing, expiry, 401 recovery, and credential-chain error propagation.
  • packages/core/src/llm/builtin/provider/bedrock/routing.ts — protocol inference, inference-profile prefix handling, capabilities, and region endpoints.
  • packages/core/src/llm/builtin/provider/bedrock/anthropic.ts — Bedrock-only Anthropic client and requester.
  • packages/agent-core-v2/src/llm-adapter/model/model-auth.ts — auth-material, protocol, and endpoint resolution.
  • packages/agent-core-v2/src/llm-adapter/provider/provider-definition.ts — the three Bedrock registrations.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Amazon Bedrock with ambient AWS credentials Not supported Supported through type = "bedrock"; no long-lived key is required N/A — new capability Configure an explicit Bedrock key to bypass the ambient chain
Bedrock model wire protocol Not supported Inferred per model, with an optional per-model override N/A — new capability Set protocol on the model alias
Bedrock region resolution Not supported Region is required from provider env or the shell; missing region fails explicitly N/A — new capability Set AWS_REGION or AWS_DEFAULT_REGION
Provider-type allowlists Accepted six provider types Also accept bedrock in Node SDK, kap-server, and migration Existing providers keep their previous behavior N/A — additive enum member
Provider REST model writes No per-model protocol field Optional anthropic / openai / openai_responses override is persisted Older clients never send the field and see no behavior change Omit protocol to use inference
Ambient-credential provider status No ambient provider type Bedrock reports connected when an ambient credential route is configured This is a configuration check, not a credential ping Use has_api_key: false + type: bedrock to distinguish it from stored-key providers
Anthropic and Anthropic-compatible providers apiKey maps to x-api-key; independent custom Authorization headers are preserved Unchanged Existing Anthropic providers and dual-auth gateways No behavior change; the shared client has no Bedrock branch

Affected modules and coverage

  • Core Bedrock provider: token lifecycle, concurrent resolution, credential errors, model routing, capabilities, and real Anthropic SDK header mapping are covered without contacting AWS.
  • v2 model/auth/catalog paths: static-key precedence, Region/Profile resolution, protocol overrides, missing-region errors, ambient readiness, and provider status are covered in existing test cases.
  • Node SDK and kap-server: Bedrock parsing plus create/replace protocol round-trips are covered in existing test cases.
  • Test count is unchanged: one Bedrock test was added while two adjacent ready-resolution cases were consolidated.
  • Verification includes focused Vitest suites, package typechecks, import-boundary and lint checks, CLI and native JS bundle checks, VitePress build, and an end-to-end built-CLI request against a local fake Bedrock SSE server using temporary dummy AWS credentials. No real AWS account or paid Bedrock request is used by ordinary tests.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 41611f6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T08:22:02.104042Z 41611f6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@41611f6
npx https://pkg.pr.new/@moonshot-ai/kimi-code@41611f6

commit: 41611f6

@github-actions

Copy link
Copy Markdown
Contributor

❌ Nix build failed

Hash mismatch in pnpmDeps:

Hash
specified sha256-Jo/qTBS8SwKNTmSnwTjxBjlwmJ6GpnfyzB6r0iiihSY=
got sha256-QOHwKZaAAU4OG9MEvNEWh0DViOvkAaqlVSlYMHUltbE=

Please update flake.nix with the got hash.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d23ef3d0b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

}
return { apiKey: cached.token };
},
canRecover: (error) => errorStatusCode(error) === 401,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Handle Bedrock's 403 token-expiry response

When the ambient AWS credentials are temporary, such as SSO, an assumed role, or an instance role, AWS limits the generated key to the underlying session lifetime even though this provider caches it for 11 hours 45 minutes. After that shorter lifetime expires, Bedrock returns ExpiredTokenException with HTTP 403, not 401 (AWS Common Errors); this predicate therefore prevents credentialRecovery from invalidating the cached token, and every request continues failing until the local TTL elapses or the process restarts. Recognize the expired-token 403 specifically, or derive the cache lifetime from the source credential expiration.

Useful? React with 👍 / 👎.

Comment on lines +219 to +220
const env = { ...process.env, ...provider.env };
const baseUrl = resolveBedrockBaseUrl(protocol, env);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use the same region for the endpoint and token

When [providers.<id>.env] sets only AWS_DEFAULT_REGION while the process already has AWS_REGION, auth resolution selects the configured default region for token generation, but this per-key merge retains the shell's AWS_REGION; bedrockRegionOf then prefers that value when constructing the endpoint. The resulting token and endpoint belong to different regions, and Bedrock API keys are region-scoped (AWS API keys), so every request fails with a credential-scope error. Resolve the effective region once with the provider table taking precedence over both shell region variables, and use it for both token generation and endpoint construction.

Useful? React with 👍 / 👎.


export type BedrockWireProtocol = 'anthropic' | 'openai' | 'openai_responses';

const GEO_INFERENCE_PROFILE_PREFIX_RE = /^(?:[a-z]{2}|apac|global)$/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recognize GovCloud inference-profile prefixes

For Bedrock models addressed through a GovCloud inference profile such as us-gov.openai..., this expression does not recognize the us-gov prefix, so it is never stripped and protocol inference falls through to the default Chat Completions route. AWS documents us-gov. profile IDs for OpenAI GPT models on the Responses API (Bedrock Responses API); these models are consequently sent to the wrong API and fail unless every alias manually supplies a protocol override. Include us-gov among the recognized geographic prefixes.

Useful? React with 👍 / 👎.

RealKai42
RealKai42 previously approved these changes Nov 13, 2026
@sailist
sailist force-pushed the feat-361-11-12-bedrock-provider-client branch from 6d23ef3 to 41611f6 Compare November 13, 2026 08:14
@sailist
sailist merged commit 88e3c20 into main Nov 13, 2026
16 checks passed
@sailist
sailist deleted the feat-361-11-12-bedrock-provider-client branch November 13, 2026 08:20

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 41611f6bb9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

'openai',
'openai_responses',
'anthropic',
'bedrock',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allow REST clients to supply the Bedrock region

When desktop or web clients create a bedrock provider through POST /api/v1/providers, this enum accepts the type, but the create/replace request schemas expose no provider env, region, or profile field, and the route persists only the type, key, and base URL. Unless the server process already has AWS_REGION, these clients cannot configure the documented ambient AWS credential flow, and model construction fails when resolveEndpointBaseUrl cannot derive a regional endpoint; named-profile SSO is similarly unavailable unless AWS_PROFILE was set before launching the server. Add REST fields for the Bedrock region/profile and persist them into the provider environment.

AGENTS.md reference: AGENTS.md:L123-L125

Useful? React with 👍 / 👎.

alias.displayName = entry.display_name !== undefined ? entry.display_name : undefined;
alias.capabilities =
entry.capabilities !== undefined ? [...entry.capabilities] : undefined;
alias.protocol = entry.protocol;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve protocol overrides across provider replacement

When a Bedrock model needs an explicit protocol override, such as the documented Kimi Responses configuration, neither modelCatalogItemSchema nor the provider response exposes that protocol to desktop/web clients. A client therefore cannot round-trip it when editing the provider, and this assignment clears the existing alias.protocol whenever the replacement payload omits the unknowable field, silently rerouting the model to the inferred API. Expose protocol in the model read contract or preserve the previous value when it is omitted.

AGENTS.md reference: AGENTS.md:L123-L125

Useful? React with 👍 / 👎.

Comment on lines +31 to +34
case 'openai':
return getOpenAILegacyModelCapability(vendorModel);
case 'openai_responses':
return getOpenAIResponsesModelCapability(vendorModel);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add Bedrock capability metadata for Kimi models

For the documented global.moonshotai.kimi-k3 configuration, vendorModel becomes kimi-k3, but getOpenAILegacyModelCapability recognizes only OpenAI model-name families and returns undefined. The catalog consequently records image_in and thinking as false; image attachments are replaced as unsupported and the thinking controls are disabled even though AWS documents Kimi K3 as supporting vision, configurable reasoning, and client-side tools. Add Bedrock-specific capability/profile metadata for this advertised family rather than delegating it to the generic OpenAI name table. AWS Kimi K3 model card

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AWS credential chain support for Kimi models on Amazon Bedrock

3 participants