@ai-sdk/amazon-bedrock 5.0.127 → 5.0.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ let _ai_sdk_provider = require("@ai-sdk/provider");
4
4
  let _ai_sdk_provider_utils = require("@ai-sdk/provider-utils");
5
5
  let aws4fetch = require("aws4fetch");
6
6
  //#region src/version.ts
7
- const VERSION = "5.0.127";
7
+ const VERSION = "5.0.129";
8
8
  //#endregion
9
9
  //#region src/amazon-bedrock-sigv4-fetch.ts
10
10
  /**
@@ -73,7 +73,9 @@ function createApiKeyFetchFunction(apiKey, fetch) {
73
73
  const effectiveFetch = fetch ?? globalThis.fetch;
74
74
  const originalHeaders = (0, _ai_sdk_provider_utils.normalizeHeaders)(init?.headers);
75
75
  const headersWithUserAgent = (0, _ai_sdk_provider_utils.withUserAgentSuffix)(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, (0, _ai_sdk_provider_utils.getRuntimeEnvironmentUserAgent)());
76
- const finalHeaders = (0, _ai_sdk_provider_utils.combineHeaders)(headersWithUserAgent, { Authorization: `Bearer ${apiKey}` });
76
+ const resolvedApiKey = await (0, _ai_sdk_provider_utils.resolve)(apiKey);
77
+ if (typeof apiKey !== "string" && (typeof resolvedApiKey !== "string" || !resolvedApiKey.trim())) throw new _ai_sdk_provider.LoadAPIKeyError({ message: "Amazon Bedrock API key must be a non-empty string." });
78
+ const finalHeaders = (0, _ai_sdk_provider_utils.combineHeaders)(headersWithUserAgent, { Authorization: `Bearer ${typeof apiKey === "string" ? resolvedApiKey : resolvedApiKey.trim()}` });
77
79
  return effectiveFetch(input, {
78
80
  ...init,
79
81
  headers: finalHeaders
@@ -88,11 +90,11 @@ function createApiKeyFetchFunction(apiKey, fetch) {
88
90
  * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).
89
91
  */
90
92
  function createBedrockMantle(options = {}) {
91
- const rawApiKey = (0, _ai_sdk_provider_utils.loadOptionalSetting)({
93
+ const rawApiKey = typeof options.apiKey === "string" || options.apiKey == null ? (0, _ai_sdk_provider_utils.loadOptionalSetting)({
92
94
  settingValue: options.apiKey,
93
95
  environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
94
- });
95
- const apiKey = rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : void 0;
96
+ }) : options.apiKey;
97
+ const apiKey = typeof rawApiKey === "string" ? rawApiKey.trim() || void 0 : rawApiKey;
96
98
  const fetchFunction = apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
97
99
  const region = (0, _ai_sdk_provider_utils.loadSetting)({
98
100
  settingValue: options.region,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["combineHeaders","normalizeHeaders","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","AwsV4Signer","loadOptionalSetting","loadSetting","withoutTrailingSlash","isValidHostnamePart","InvalidArgumentError","withUserAgentSuffix","OpenAIChatLanguageModel","OpenAIResponsesLanguageModel","NoSuchModelError"],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.ts"],"sourcesContent":["// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n combineHeaders,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: string,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${apiKey}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: string;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string | undefined>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey = loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n });\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.responses = createResponsesModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;;AAEA,MAAa,UAAA;;;;;;;;;;;ACuBb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,mBAAA,GAAkBA,uBAAAA,eAAAA,EAAAA,GACtBC,uBAAAA,iBAAAA,CAAiB,SAAS,OAAO,IAAA,GACjCA,uBAAAA,iBAAAA,CAAiB,MAAM,OAAO,CAChC;EACA,MAAM,wBAAA,GAAuBC,uBAAAA,oBAAAA,CAC3B,iBACA,yBAAyB,YAAA,GACzBC,uBAAAA,+BAAAA,CAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ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CAAiC;CACnC,CAAC;CAEH,MAAM,WAAW,SAAU,SAAmC;EAC5D,IAAI,YACF,MAAM,IAAI,MACR,0EACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,OAAO;CAChB,SAAS,YAAY;CAErB,SAAS,kBAAkB,YAAoB;EAC7C,MAAM,IAAIC,iBAAAA,iBAAiB;GAAE;GAAS,WAAW;EAAiB,CAAC;CACrE;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAIA,iBAAAA,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,gBAAgB,oBAAoB"}
1
+ {"version":3,"file":"index.cjs","names":["combineHeaders","normalizeHeaders","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","AwsV4Signer","resolve","LoadAPIKeyError","loadOptionalSetting","loadSetting","withoutTrailingSlash","isValidHostnamePart","InvalidArgumentError","withUserAgentSuffix","OpenAIChatLanguageModel","OpenAIResponsesLanguageModel","NoSuchModelError"],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.ts"],"sourcesContent":["// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { LoadAPIKeyError } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n resolve,\n type Resolvable,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: Resolvable<string>,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const resolvedApiKey = await resolve(apiKey);\n if (\n typeof apiKey !== 'string' &&\n (typeof resolvedApiKey !== 'string' || !resolvedApiKey.trim())\n ) {\n throw new LoadAPIKeyError({\n message: 'Amazon Bedrock API key must be a non-empty string.',\n });\n }\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${typeof apiKey === 'string' ? resolvedApiKey : resolvedApiKey.trim()}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * A callback is resolved before each request and must return a non-empty key.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string | undefined>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey =\n typeof options.apiKey === 'string' || options.apiKey == null\n ? loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n })\n : options.apiKey;\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.responses = createResponsesModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;;AAEA,MAAa,UAAA;;;;;;;;;;;AC0Bb,SAAgB,yBACd,gBAGA,OACA,UA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"@ai-sdk/provider-utils";
2
+ import { FetchFunction, Resolvable } from "@ai-sdk/provider-utils";
3
3
  //#region src/amazon-bedrock-sigv4-fetch.d.ts
4
4
  interface AmazonBedrockCredentials {
5
5
  region: string;
@@ -47,10 +47,11 @@ interface BedrockMantleProviderSettings {
47
47
  region?: string;
48
48
  /**
49
49
  * API key for authenticating requests using Bearer token authentication.
50
+ * A callback is resolved before each request and must return a non-empty key.
50
51
  * When provided, this will be used instead of AWS SigV4 authentication.
51
52
  * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
52
53
  */
53
- apiKey?: string;
54
+ apiKey?: Resolvable<string>;
54
55
  /**
55
56
  * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the
56
57
  * `AWS_ACCESS_KEY_ID` environment variable.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAUiB;EACf;EACA;EACA;EACA;;;;KCdU;KAOA;KAKA,uBACR,2BACA;;;UCea,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;EAOA;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAiLU,eAAa"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAaiB;EACf;EACA;EACA;EACA;;;;KCjBU;KAOA;KAKA,uBACR,2BACA;;;UCgBa,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;;EAQA,SAAS;;;;;EAMT;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAoLU,eAAa"}
@@ -1,5 +1,5 @@
1
1
  import { LanguageModelV4, ProviderV4 } from "@ai-sdk/provider";
2
- import { FetchFunction } from "@ai-sdk/provider-utils";
2
+ import { FetchFunction, Resolvable } from "@ai-sdk/provider-utils";
3
3
  //#region src/amazon-bedrock-sigv4-fetch.d.ts
4
4
  interface AmazonBedrockCredentials {
5
5
  region: string;
@@ -47,10 +47,11 @@ interface BedrockMantleProviderSettings {
47
47
  region?: string;
48
48
  /**
49
49
  * API key for authenticating requests using Bearer token authentication.
50
+ * A callback is resolved before each request and must return a non-empty key.
50
51
  * When provided, this will be used instead of AWS SigV4 authentication.
51
52
  * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
52
53
  */
53
- apiKey?: string;
54
+ apiKey?: Resolvable<string>;
54
55
  /**
55
56
  * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the
56
57
  * `AWS_ACCESS_KEY_ID` environment variable.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAUiB;EACf;EACA;EACA;EACA;;;;KCdU;KAOA;KAKA,uBACR,2BACA;;;UCea,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;EAOA;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAiLU,eAAa"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAaiB;EACf;EACA;EACA;EACA;;;;KCjBU;KAOA;KAKA,uBACR,2BACA;;;UCgBa,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;;EAQA,SAAS;;;;;EAMT;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAoLU,eAAa"}
@@ -1,9 +1,9 @@
1
1
  import { OpenAIChatLanguageModel, OpenAIResponsesLanguageModel } from "@ai-sdk/openai/internal";
2
- import { InvalidArgumentError, NoSuchModelError } from "@ai-sdk/provider";
3
- import { combineHeaders, getRuntimeEnvironmentUserAgent, isValidHostnamePart, loadOptionalSetting, loadSetting, normalizeHeaders, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
2
+ import { InvalidArgumentError, LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
3
+ import { combineHeaders, getRuntimeEnvironmentUserAgent, isValidHostnamePart, loadOptionalSetting, loadSetting, normalizeHeaders, resolve, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
4
4
  import { AwsV4Signer } from "aws4fetch";
5
5
  //#region src/version.ts
6
- const VERSION = "5.0.127";
6
+ const VERSION = "5.0.129";
7
7
  //#endregion
8
8
  //#region src/amazon-bedrock-sigv4-fetch.ts
9
9
  /**
@@ -72,7 +72,9 @@ function createApiKeyFetchFunction(apiKey, fetch) {
72
72
  const effectiveFetch = fetch ?? globalThis.fetch;
73
73
  const originalHeaders = normalizeHeaders(init?.headers);
74
74
  const headersWithUserAgent = withUserAgentSuffix(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, getRuntimeEnvironmentUserAgent());
75
- const finalHeaders = combineHeaders(headersWithUserAgent, { Authorization: `Bearer ${apiKey}` });
75
+ const resolvedApiKey = await resolve(apiKey);
76
+ if (typeof apiKey !== "string" && (typeof resolvedApiKey !== "string" || !resolvedApiKey.trim())) throw new LoadAPIKeyError({ message: "Amazon Bedrock API key must be a non-empty string." });
77
+ const finalHeaders = combineHeaders(headersWithUserAgent, { Authorization: `Bearer ${typeof apiKey === "string" ? resolvedApiKey : resolvedApiKey.trim()}` });
76
78
  return effectiveFetch(input, {
77
79
  ...init,
78
80
  headers: finalHeaders
@@ -87,11 +89,11 @@ function createApiKeyFetchFunction(apiKey, fetch) {
87
89
  * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).
88
90
  */
89
91
  function createBedrockMantle(options = {}) {
90
- const rawApiKey = loadOptionalSetting({
92
+ const rawApiKey = typeof options.apiKey === "string" || options.apiKey == null ? loadOptionalSetting({
91
93
  settingValue: options.apiKey,
92
94
  environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
93
- });
94
- const apiKey = rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : void 0;
95
+ }) : options.apiKey;
96
+ const apiKey = typeof rawApiKey === "string" ? rawApiKey.trim() || void 0 : rawApiKey;
95
97
  const fetchFunction = apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
96
98
  const region = loadSetting({
97
99
  settingValue: options.region,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.ts"],"sourcesContent":["// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n combineHeaders,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: string,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${apiKey}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: string;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string | undefined>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey = loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n });\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.responses = createResponsesModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;AAEA,MAAa,UAAA;;;;;;;;;;;ACuBb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,kBAAkB,eACtB,iBAAiB,SAAS,OAAO,GACjC,iBAAiB,MAAM,OAAO,CAChC;EACA,MAAM,uBAAuB,oBAC3B,iBACA,yBAAyB,WACzB,+BAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ,KAAA;EACxD,IAAI,kBAAkB,KAAA,KAAa,WAAW,QAAQ,SAAS,MAC7D,IAAI;GACF,gBAAgB,MAAM,QAAQ,MAAM,CAAC,CAAC,KAAK;EAC7C,QAAQ,CAAC;EAKX,KAFwB,MAAM,UAAU,SAAS,OAAA,EAE5B,YAAY,MAAM,UAAU,CAAC,eAChD,OAAO,eAAe,OAAO;GAC3B,GAAG;GACH,SAAS;EACX,CAAC;EAGH,MAAM,MACJ,OAAO,UAAU,WACb,QACA,iBAAiB,MACf,MAAM,OACN,MAAM;EAEd,MAAM,OAAO,kBAAkB,aAAa;EAC5C,MAAM,cAAc,MAAM,eAAe;EAezC,MAAM,gBAAgB,MAAM,IAdT,YAAY;GAC7B;GACA,QAAQ;GACR,SAAS,OAAO,QAAQ,oBAAoB,CAAC,CAAC,QAAQ,GAAG,WACvD,QAAQ,KAAK,CACf;GACA;GACA,QAAQ,YAAY;GACpB,aAAa,YAAY;GACzB,iBAAiB,YAAY;GAC7B,cAAc,YAAY;GAC1B;EACF,CAEiC,CAAC,CAAC,KAAK;EACxC,MAAM,gBAAgB,iBAAiB,cAAc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I,wBAAwB,SAAS;EACnC,UAAU;EACV;EACA,SAAS;EACT,OAAO;CACT,CAAC;CAEH,MAAM,wBAAwB,YAC5B,IAAI,6BAA6B,SAAS;EACxC,UAAU;EACV;EACA,SAAS;EACT,OAAO;EACP,iCAAiC;CACnC,CAAC;CAEH,MAAM,WAAW,SAAU,SAAmC;EAC5D,IAAI,YACF,MAAM,IAAI,MACR,0EACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,OAAO;CAChB,SAAS,YAAY;CAErB,SAAS,kBAAkB,YAAoB;EAC7C,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAiB,CAAC;CACrE;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,gBAAgB,oBAAoB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.ts"],"sourcesContent":["// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { LoadAPIKeyError } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n resolve,\n type Resolvable,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: Resolvable<string>,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const resolvedApiKey = await resolve(apiKey);\n if (\n typeof apiKey !== 'string' &&\n (typeof resolvedApiKey !== 'string' || !resolvedApiKey.trim())\n ) {\n throw new LoadAPIKeyError({\n message: 'Amazon Bedrock API key must be a non-empty string.',\n });\n }\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${typeof apiKey === 'string' ? resolvedApiKey : resolvedApiKey.trim()}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * A callback is resolved before each request and must return a non-empty key.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string | undefined>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey =\n typeof options.apiKey === 'string' || options.apiKey == null\n ? loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n })\n : options.apiKey;\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.responses = createResponsesModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;AAEA,MAAa,UAAA;;;;;;;;;;;AC0Bb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,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MAAM,wBAAwB,YAC5B,IAAI,6BAA6B,SAAS;EACxC,UAAU;EACV;EACA,SAAS;EACT,OAAO;EACP,iCAAiC;CACnC,CAAC;CAEH,MAAM,WAAW,SAAU,SAAmC;EAC5D,IAAI,YACF,MAAM,IAAI,MACR,0EACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,OAAO;CAChB,SAAS,YAAY;CAErB,SAAS,kBAAkB,YAAoB;EAC7C,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAiB,CAAC;CACrE;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,gBAAgB,oBAAoB"}
@@ -213,7 +213,12 @@ You can use the following optional settings to customize the Amazon Bedrock prov
213
213
  Optional. The AWS credential provider chain that you want to use for the API calls.
214
214
  It uses the specified credentials by default.
215
215
 
216
- - **apiKey** _string_
216
+ - **apiKey** _string | PromiseLike&lt;string&gt; | (() =&gt; string | PromiseLike&lt;string&gt;)_
217
+
218
+ Pass a callback to resolve the API key before each request. The callback can
219
+ return a string or a promise; token caching and renewal are handled by the caller.
220
+ A callback or promise selects API key authentication and must resolve to a
221
+ non-empty string; lookup failures do not switch authentication methods.
217
222
 
218
223
  Optional. API key for authenticating requests using Bearer token authentication.
219
224
  When provided, this will be used instead of AWS SigV4 authentication.
@@ -683,7 +688,7 @@ Amazon Bedrock supports model creator-specific reasoning features:
683
688
  - Anthropic (e.g. `claude-sonnet-4-5-20250929`): enable via the `reasoningConfig` provider option and specifying a thinking budget in tokens (minimum: `1024`, maximum: `64000`).
684
689
  - Amazon (e.g. `us.amazon.nova-2-lite-v1:0`): enable via the `reasoningConfig` provider option and specifying a maximum reasoning effort level (`'low' | 'medium' | 'high'`).
685
690
 
686
- You can also use the top-level `reasoning` parameter. For Amazon Nova 2, `'xhigh'` and `'max'` are mapped to `'high'` with a compatibility warning. Anthropic and OpenAI effort mappings preserve `'max'`.
691
+ You can also use the top-level `reasoning` parameter.
687
692
 
688
693
  Bedrock combines partial `providerOptions.amazonBedrock.reasoningConfig` with
689
694
  portable reasoning, preserving explicit values and deriving missing fields for
@@ -1634,7 +1639,12 @@ You can use the following optional settings to customize the Bedrock Anthropic p
1634
1639
  used. If either key is taken from the environment, omitting `sessionToken`
1635
1640
  allows `AWS_SESSION_TOKEN`.
1636
1641
 
1637
- - **apiKey** _string_
1642
+ - **apiKey** _string | PromiseLike&lt;string&gt; | (() =&gt; string | PromiseLike&lt;string&gt;)_
1643
+
1644
+ Pass a callback to resolve the API key before each request. The callback can
1645
+ return a string or a promise; token caching and renewal are handled by the caller.
1646
+ A callback or promise selects API key authentication and must resolve to a
1647
+ non-empty string; lookup failures do not switch authentication methods.
1638
1648
 
1639
1649
  API key for authenticating requests using Bearer token authentication.
1640
1650
  When provided, this will be used instead of AWS SigV4 authentication.
@@ -1951,7 +1961,12 @@ You can use the following optional settings to customize the Bedrock Mantle prov
1951
1961
  Optional. The AWS session token that you want to use for the API calls.
1952
1962
  It uses the `AWS_SESSION_TOKEN` environment variable by default.
1953
1963
 
1954
- - **apiKey** _string_
1964
+ - **apiKey** _string | PromiseLike&lt;string&gt; | (() =&gt; string | PromiseLike&lt;string&gt;)_
1965
+
1966
+ Pass a callback to resolve the API key before each request. The callback can
1967
+ return a string or a promise; token caching and renewal are handled by the caller.
1968
+ A callback or promise selects API key authentication and must resolve to a
1969
+ non-empty string; lookup failures do not switch authentication methods.
1955
1970
 
1956
1971
  API key for authenticating requests using Bearer token authentication.
1957
1972
  When provided, this will be used instead of AWS SigV4 authentication.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/amazon-bedrock",
3
- "version": "5.0.127",
3
+ "version": "5.0.129",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -41,10 +41,10 @@
41
41
  }
42
42
  },
43
43
  "dependencies": {
44
- "@ai-sdk/anthropic": "4.0.91",
45
- "@ai-sdk/openai": "4.0.104",
46
- "@ai-sdk/provider": "4.0.34",
47
- "@ai-sdk/provider-utils": "5.0.70",
44
+ "@ai-sdk/anthropic": "4.0.93",
45
+ "@ai-sdk/openai": "4.0.106",
46
+ "@ai-sdk/provider": "4.0.35",
47
+ "@ai-sdk/provider-utils": "5.0.72",
48
48
  "@smithy/eventstream-codec": "^4.3.3",
49
49
  "@smithy/util-utf8": "^4.3.3",
50
50
  "aws4fetch": "^1.0.20"
@@ -335,17 +335,15 @@ export class AmazonBedrockChatLanguageModel implements LanguageModelV4 {
335
335
  }
336
336
  }
337
337
 
338
- if (hasExplicitDisabledThinking || thinkingType === 'adaptive') {
339
- warnings.push({
340
- type: hasExplicitDisabledThinking ? 'unsupported' : 'compatibility',
341
- feature: hasExplicitDisabledThinking
342
- ? 'providerOptions.amazonBedrock.reasoningConfig'
343
- : 'reasoning',
344
- details:
345
- `thinking cannot be disabled for ${this.modelId}. ` +
346
- `Using '${thinkingType}' thinking instead.`,
347
- });
348
- }
338
+ warnings.push({
339
+ type: hasExplicitDisabledThinking ? 'unsupported' : 'compatibility',
340
+ feature: hasExplicitDisabledThinking
341
+ ? 'providerOptions.amazonBedrock.reasoningConfig'
342
+ : 'reasoning',
343
+ details:
344
+ `thinking cannot be disabled for ${this.modelId}. ` +
345
+ `Using '${thinkingType}' thinking instead.`,
346
+ });
349
347
  }
350
348
 
351
349
  const effort =
@@ -1721,27 +1719,38 @@ export {
1721
1719
  type AmazonBedrockReasoningMetadata,
1722
1720
  } from './amazon-bedrock-reasoning-metadata';
1723
1721
 
1724
- const amazonBedrockReasoningEffortMap: Partial<
1725
- Record<string, 'low' | 'medium' | 'high' | 'max'>
1726
- > = {
1727
- minimal: 'low',
1722
+ // Effort maps only list the supported levels. Other levels are mapped to the
1723
+ // closest supported level by mapReasoningToProviderEffort.
1724
+ const amazonBedrockReasoningEffortMap = {
1728
1725
  low: 'low',
1729
1726
  medium: 'medium',
1730
1727
  high: 'high',
1731
- xhigh: 'max',
1732
1728
  max: 'max',
1733
- };
1729
+ } as const;
1734
1730
 
1735
- const amazonNovaReasoningEffortMap: Partial<
1736
- Record<string, 'low' | 'medium' | 'high'>
1737
- > = {
1738
- minimal: 'low',
1731
+ const amazonNovaReasoningEffortMap = {
1739
1732
  low: 'low',
1740
1733
  medium: 'medium',
1741
1734
  high: 'high',
1742
- xhigh: 'high',
1743
- max: 'high',
1744
- };
1735
+ } as const;
1736
+
1737
+ const openAIGptOssReasoningEffortMap = {
1738
+ low: 'low',
1739
+ medium: 'medium',
1740
+ high: 'high',
1741
+ } as const;
1742
+
1743
+ // The reasoning efforts of other OpenAI models are not known, so reasoning
1744
+ // values are sent directly.
1745
+ const openAIReasoningEffortMap = {
1746
+ none: 'none',
1747
+ minimal: 'minimal',
1748
+ low: 'low',
1749
+ medium: 'medium',
1750
+ high: 'high',
1751
+ xhigh: 'xhigh',
1752
+ max: 'max',
1753
+ } as const;
1745
1754
 
1746
1755
  function isNova2ReasoningModel(modelId: string): boolean {
1747
1756
  return modelId.includes('amazon.nova-2-lite-v1:0');
@@ -1779,7 +1788,6 @@ function resolveAmazonBedrockReasoningConfig({
1779
1788
  return result;
1780
1789
  }
1781
1790
 
1782
- const hasPortableReasoning = reasoning !== 'none';
1783
1791
  const isNovaReasoningModel = isNova2ReasoningModel(modelId);
1784
1792
  const supportsPortableReasoning =
1785
1793
  isOpenAIModel || isNovaReasoningModel || reasoningConfig != null;
@@ -1794,7 +1802,12 @@ function resolveAmazonBedrockReasoningConfig({
1794
1802
  reasoningConfig?.maxReasoningEffort ??
1795
1803
  mapReasoningToProviderEffort({
1796
1804
  reasoning,
1797
- effortMap: amazonBedrockReasoningEffortMap,
1805
+ effortMap: {
1806
+ ...amazonBedrockReasoningEffortMap,
1807
+ ...(capabilities.supportsXhighEffort && {
1808
+ xhigh: 'xhigh' as const,
1809
+ }),
1810
+ },
1798
1811
  warnings,
1799
1812
  });
1800
1813
  result.reasoningConfig = {
@@ -1811,25 +1824,34 @@ function resolveAmazonBedrockReasoningConfig({
1811
1824
  maxReasoningBudget: capabilities.maxOutputTokens,
1812
1825
  warnings,
1813
1826
  });
1814
- if (budgetTokens != null) {
1815
- result.reasoningConfig = {
1816
- ...reasoningConfig,
1817
- type: reasoningConfig?.type ?? 'enabled',
1818
- budgetTokens,
1819
- };
1820
- }
1827
+ result.reasoningConfig = {
1828
+ ...reasoningConfig,
1829
+ type: reasoningConfig?.type ?? 'enabled',
1830
+ budgetTokens,
1831
+ };
1821
1832
  }
1822
- } else if (hasPortableReasoning) {
1833
+ } else if (reasoning === 'none' && isNovaReasoningModel) {
1834
+ // Nova 2 reasoning is disabled unless a reasoning effort is sent, so
1835
+ // there is nothing to add.
1836
+ } else {
1823
1837
  if (supportsPortableReasoning) {
1824
1838
  const effort =
1825
1839
  reasoningConfig?.maxReasoningEffort ??
1826
- mapReasoningToProviderEffort({
1840
+ // OpenAI efforts such as 'none' are sent as `reasoning_effort` even
1841
+ // though they are not accepted in the reasoningConfig provider option.
1842
+ (mapReasoningToProviderEffort({
1827
1843
  reasoning,
1828
1844
  effortMap: isNovaReasoningModel
1829
1845
  ? amazonNovaReasoningEffortMap
1830
- : amazonBedrockReasoningEffortMap,
1846
+ : isOpenAIModel
1847
+ ? modelId.includes('openai.gpt-oss-')
1848
+ ? openAIGptOssReasoningEffortMap
1849
+ : openAIReasoningEffortMap
1850
+ : amazonBedrockReasoningEffortMap,
1831
1851
  warnings,
1832
- });
1852
+ }) as NonNullable<
1853
+ AmazonBedrockLanguageModelChatOptions['reasoningConfig']
1854
+ >['maxReasoningEffort']);
1833
1855
  result.reasoningConfig = {
1834
1856
  ...reasoningConfig,
1835
1857
  ...(isNovaReasoningModel && {
@@ -12,6 +12,7 @@ import {
12
12
  loadSetting,
13
13
  withUserAgentSuffix,
14
14
  type FetchFunction,
15
+ type Resolvable,
15
16
  } from '@ai-sdk/provider-utils';
16
17
  import { AmazonBedrockChatLanguageModel } from './amazon-bedrock-chat-language-model';
17
18
  import type {
@@ -44,6 +45,7 @@ export interface AmazonBedrockProviderSettings {
44
45
 
45
46
  /**
46
47
  * API key for authenticating requests using Bearer token authentication.
48
+ * A callback is resolved before each request and must return a non-empty key.
47
49
  * When provided, this will be used instead of AWS SigV4 authentication.
48
50
  * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
49
51
  *
@@ -65,7 +67,7 @@ export interface AmazonBedrockProviderSettings {
65
67
  * If neither `apiKey` nor `AWS_BEARER_TOKEN_BEDROCK` environment variable is set,
66
68
  * the provider will fall back to AWS SigV4 authentication using AWS credentials.
67
69
  */
68
- apiKey?: string;
70
+ apiKey?: Resolvable<string>;
69
71
 
70
72
  /**
71
73
  * The AWS access key ID to use for the Bedrock provider. Defaults to the value of the
@@ -193,15 +195,18 @@ export function createAmazonBedrock(
193
195
  options: AmazonBedrockProviderSettings = {},
194
196
  ): AmazonBedrockProvider {
195
197
  // Check for API key authentication first
196
- const rawApiKey = loadOptionalSetting({
197
- settingValue: options.apiKey,
198
- environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
199
- });
198
+ const rawApiKey =
199
+ typeof options.apiKey === 'string' || options.apiKey == null
200
+ ? loadOptionalSetting({
201
+ settingValue: options.apiKey,
202
+ environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
203
+ })
204
+ : options.apiKey;
200
205
 
201
206
  // FIX 1: Validate API key to ensure proper fallback to SigV4
202
207
  // Only use API key if it's a non-empty, non-whitespace string
203
208
  const apiKey =
204
- rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;
209
+ typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;
205
210
 
206
211
  // Use API key authentication if available, otherwise fall back to SigV4
207
212
  const fetchFunction = apiKey