@h-rig/pi-ai 0.0.6-alpha.23

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.
Files changed (218) hide show
  1. package/README.md +1391 -0
  2. package/dist/api-registry.d.ts +20 -0
  3. package/dist/api-registry.d.ts.map +1 -0
  4. package/dist/api-registry.js +44 -0
  5. package/dist/api-registry.js.map +1 -0
  6. package/dist/bedrock-provider.d.ts +5 -0
  7. package/dist/bedrock-provider.d.ts.map +1 -0
  8. package/dist/bedrock-provider.js +6 -0
  9. package/dist/bedrock-provider.js.map +1 -0
  10. package/dist/cli.d.ts +3 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +130 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/env-api-keys.d.ts +18 -0
  15. package/dist/env-api-keys.d.ts.map +1 -0
  16. package/dist/env-api-keys.js +181 -0
  17. package/dist/env-api-keys.js.map +1 -0
  18. package/dist/image-models.d.ts +10 -0
  19. package/dist/image-models.d.ts.map +1 -0
  20. package/dist/image-models.generated.d.ts +485 -0
  21. package/dist/image-models.generated.d.ts.map +1 -0
  22. package/dist/image-models.generated.js +487 -0
  23. package/dist/image-models.generated.js.map +1 -0
  24. package/dist/image-models.js +23 -0
  25. package/dist/image-models.js.map +1 -0
  26. package/dist/images-api-registry.d.ts +14 -0
  27. package/dist/images-api-registry.d.ts.map +1 -0
  28. package/dist/images-api-registry.js +22 -0
  29. package/dist/images-api-registry.js.map +1 -0
  30. package/dist/images.d.ts +4 -0
  31. package/dist/images.d.ts.map +1 -0
  32. package/dist/images.js +14 -0
  33. package/dist/images.js.map +1 -0
  34. package/dist/index.d.ts +32 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +20 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/models.d.ts +18 -0
  39. package/dist/models.d.ts.map +1 -0
  40. package/dist/models.generated.d.ts +18411 -0
  41. package/dist/models.generated.d.ts.map +1 -0
  42. package/dist/models.generated.js +16944 -0
  43. package/dist/models.generated.js.map +1 -0
  44. package/dist/models.js +71 -0
  45. package/dist/models.js.map +1 -0
  46. package/dist/oauth.d.ts +2 -0
  47. package/dist/oauth.d.ts.map +1 -0
  48. package/dist/oauth.js +2 -0
  49. package/dist/oauth.js.map +1 -0
  50. package/dist/providers/amazon-bedrock.d.ts +38 -0
  51. package/dist/providers/amazon-bedrock.d.ts.map +1 -0
  52. package/dist/providers/amazon-bedrock.js +826 -0
  53. package/dist/providers/amazon-bedrock.js.map +1 -0
  54. package/dist/providers/anthropic.d.ts +71 -0
  55. package/dist/providers/anthropic.d.ts.map +1 -0
  56. package/dist/providers/anthropic.js +959 -0
  57. package/dist/providers/anthropic.js.map +1 -0
  58. package/dist/providers/azure-openai-responses.d.ts +15 -0
  59. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  60. package/dist/providers/azure-openai-responses.js +221 -0
  61. package/dist/providers/azure-openai-responses.js.map +1 -0
  62. package/dist/providers/cloudflare.d.ts +13 -0
  63. package/dist/providers/cloudflare.d.ts.map +1 -0
  64. package/dist/providers/cloudflare.js +26 -0
  65. package/dist/providers/cloudflare.js.map +1 -0
  66. package/dist/providers/faux.d.ts +56 -0
  67. package/dist/providers/faux.d.ts.map +1 -0
  68. package/dist/providers/faux.js +368 -0
  69. package/dist/providers/faux.js.map +1 -0
  70. package/dist/providers/github-copilot-headers.d.ts +8 -0
  71. package/dist/providers/github-copilot-headers.d.ts.map +1 -0
  72. package/dist/providers/github-copilot-headers.js +29 -0
  73. package/dist/providers/github-copilot-headers.js.map +1 -0
  74. package/dist/providers/google-shared.d.ts +70 -0
  75. package/dist/providers/google-shared.d.ts.map +1 -0
  76. package/dist/providers/google-shared.js +329 -0
  77. package/dist/providers/google-shared.js.map +1 -0
  78. package/dist/providers/google-vertex.d.ts +15 -0
  79. package/dist/providers/google-vertex.d.ts.map +1 -0
  80. package/dist/providers/google-vertex.js +442 -0
  81. package/dist/providers/google-vertex.js.map +1 -0
  82. package/dist/providers/google.d.ts +13 -0
  83. package/dist/providers/google.d.ts.map +1 -0
  84. package/dist/providers/google.js +402 -0
  85. package/dist/providers/google.js.map +1 -0
  86. package/dist/providers/images/openrouter.d.ts +3 -0
  87. package/dist/providers/images/openrouter.d.ts.map +1 -0
  88. package/dist/providers/images/openrouter.js +128 -0
  89. package/dist/providers/images/openrouter.js.map +1 -0
  90. package/dist/providers/images/register-builtins.d.ts +4 -0
  91. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  92. package/dist/providers/images/register-builtins.js +34 -0
  93. package/dist/providers/images/register-builtins.js.map +1 -0
  94. package/dist/providers/mistral.d.ts +25 -0
  95. package/dist/providers/mistral.d.ts.map +1 -0
  96. package/dist/providers/mistral.js +534 -0
  97. package/dist/providers/mistral.js.map +1 -0
  98. package/dist/providers/openai-codex-responses.d.ts +30 -0
  99. package/dist/providers/openai-codex-responses.d.ts.map +1 -0
  100. package/dist/providers/openai-codex-responses.js +1171 -0
  101. package/dist/providers/openai-codex-responses.js.map +1 -0
  102. package/dist/providers/openai-completions.d.ts +19 -0
  103. package/dist/providers/openai-completions.d.ts.map +1 -0
  104. package/dist/providers/openai-completions.js +976 -0
  105. package/dist/providers/openai-completions.js.map +1 -0
  106. package/dist/providers/openai-prompt-cache.d.ts +3 -0
  107. package/dist/providers/openai-prompt-cache.d.ts.map +1 -0
  108. package/dist/providers/openai-prompt-cache.js +10 -0
  109. package/dist/providers/openai-prompt-cache.js.map +1 -0
  110. package/dist/providers/openai-responses-shared.d.ts +18 -0
  111. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  112. package/dist/providers/openai-responses-shared.js +496 -0
  113. package/dist/providers/openai-responses-shared.js.map +1 -0
  114. package/dist/providers/openai-responses.d.ts +13 -0
  115. package/dist/providers/openai-responses.d.ts.map +1 -0
  116. package/dist/providers/openai-responses.js +234 -0
  117. package/dist/providers/openai-responses.js.map +1 -0
  118. package/dist/providers/register-builtins.d.ts +35 -0
  119. package/dist/providers/register-builtins.d.ts.map +1 -0
  120. package/dist/providers/register-builtins.js +254 -0
  121. package/dist/providers/register-builtins.js.map +1 -0
  122. package/dist/providers/simple-options.d.ts +8 -0
  123. package/dist/providers/simple-options.d.ts.map +1 -0
  124. package/dist/providers/simple-options.js +42 -0
  125. package/dist/providers/simple-options.js.map +1 -0
  126. package/dist/providers/transform-messages.d.ts +8 -0
  127. package/dist/providers/transform-messages.d.ts.map +1 -0
  128. package/dist/providers/transform-messages.js +184 -0
  129. package/dist/providers/transform-messages.js.map +1 -0
  130. package/dist/session-resources.d.ts +4 -0
  131. package/dist/session-resources.d.ts.map +1 -0
  132. package/dist/session-resources.js +22 -0
  133. package/dist/session-resources.js.map +1 -0
  134. package/dist/stream.d.ts +8 -0
  135. package/dist/stream.d.ts.map +1 -0
  136. package/dist/stream.js +39 -0
  137. package/dist/stream.js.map +1 -0
  138. package/dist/types.d.ts +516 -0
  139. package/dist/types.d.ts.map +1 -0
  140. package/dist/types.js +2 -0
  141. package/dist/types.js.map +1 -0
  142. package/dist/utils/abort-signals.d.ts +6 -0
  143. package/dist/utils/abort-signals.d.ts.map +1 -0
  144. package/dist/utils/abort-signals.js +34 -0
  145. package/dist/utils/abort-signals.js.map +1 -0
  146. package/dist/utils/diagnostics.d.ts +19 -0
  147. package/dist/utils/diagnostics.d.ts.map +1 -0
  148. package/dist/utils/diagnostics.js +25 -0
  149. package/dist/utils/diagnostics.js.map +1 -0
  150. package/dist/utils/event-stream.d.ts +21 -0
  151. package/dist/utils/event-stream.d.ts.map +1 -0
  152. package/dist/utils/event-stream.js +81 -0
  153. package/dist/utils/event-stream.js.map +1 -0
  154. package/dist/utils/hash.d.ts +3 -0
  155. package/dist/utils/hash.d.ts.map +1 -0
  156. package/dist/utils/hash.js +14 -0
  157. package/dist/utils/hash.js.map +1 -0
  158. package/dist/utils/headers.d.ts +2 -0
  159. package/dist/utils/headers.d.ts.map +1 -0
  160. package/dist/utils/headers.js +8 -0
  161. package/dist/utils/headers.js.map +1 -0
  162. package/dist/utils/json-parse.d.ts +16 -0
  163. package/dist/utils/json-parse.d.ts.map +1 -0
  164. package/dist/utils/json-parse.js +113 -0
  165. package/dist/utils/json-parse.js.map +1 -0
  166. package/dist/utils/node-http-proxy.d.ts +10 -0
  167. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  168. package/dist/utils/node-http-proxy.js +97 -0
  169. package/dist/utils/node-http-proxy.js.map +1 -0
  170. package/dist/utils/oauth/anthropic.d.ts +25 -0
  171. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  172. package/dist/utils/oauth/anthropic.js +335 -0
  173. package/dist/utils/oauth/anthropic.js.map +1 -0
  174. package/dist/utils/oauth/device-code.d.ts +21 -0
  175. package/dist/utils/oauth/device-code.d.ts.map +1 -0
  176. package/dist/utils/oauth/device-code.js +56 -0
  177. package/dist/utils/oauth/device-code.js.map +1 -0
  178. package/dist/utils/oauth/github-copilot.d.ts +30 -0
  179. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  180. package/dist/utils/oauth/github-copilot.js +280 -0
  181. package/dist/utils/oauth/github-copilot.js.map +1 -0
  182. package/dist/utils/oauth/index.d.ts +58 -0
  183. package/dist/utils/oauth/index.d.ts.map +1 -0
  184. package/dist/utils/oauth/index.js +122 -0
  185. package/dist/utils/oauth/index.js.map +1 -0
  186. package/dist/utils/oauth/oauth-page.d.ts +3 -0
  187. package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
  188. package/dist/utils/oauth/oauth-page.js +105 -0
  189. package/dist/utils/oauth/oauth-page.js.map +1 -0
  190. package/dist/utils/oauth/openai-codex.d.ts +43 -0
  191. package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
  192. package/dist/utils/oauth/openai-codex.js +487 -0
  193. package/dist/utils/oauth/openai-codex.js.map +1 -0
  194. package/dist/utils/oauth/pkce.d.ts +13 -0
  195. package/dist/utils/oauth/pkce.d.ts.map +1 -0
  196. package/dist/utils/oauth/pkce.js +31 -0
  197. package/dist/utils/oauth/pkce.js.map +1 -0
  198. package/dist/utils/oauth/types.d.ts +64 -0
  199. package/dist/utils/oauth/types.d.ts.map +1 -0
  200. package/dist/utils/oauth/types.js +2 -0
  201. package/dist/utils/oauth/types.js.map +1 -0
  202. package/dist/utils/overflow.d.ts +57 -0
  203. package/dist/utils/overflow.d.ts.map +1 -0
  204. package/dist/utils/overflow.js +154 -0
  205. package/dist/utils/overflow.js.map +1 -0
  206. package/dist/utils/sanitize-unicode.d.ts +22 -0
  207. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  208. package/dist/utils/sanitize-unicode.js +26 -0
  209. package/dist/utils/sanitize-unicode.js.map +1 -0
  210. package/dist/utils/typebox-helpers.d.ts +17 -0
  211. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  212. package/dist/utils/typebox-helpers.js +21 -0
  213. package/dist/utils/typebox-helpers.js.map +1 -0
  214. package/dist/utils/validation.d.ts +18 -0
  215. package/dist/utils/validation.d.ts.map +1 -0
  216. package/dist/utils/validation.js +281 -0
  217. package/dist/utils/validation.js.map +1 -0
  218. package/package.json +93 -0
@@ -0,0 +1,826 @@
1
+ import { BedrockRuntimeClient, BedrockRuntimeServiceException, StopReason as BedrockStopReason, CachePointType, CacheTTL, ConversationRole, ConverseStreamCommand, ImageFormat, ToolResultStatus, } from "@aws-sdk/client-bedrock-runtime";
2
+ import { NodeHttpHandler } from "@smithy/node-http-handler";
3
+ import { calculateCost } from "../models.js";
4
+ import { AssistantMessageEventStream } from "../utils/event-stream.js";
5
+ import { parseStreamingJson } from "../utils/json-parse.js";
6
+ import { createHttpProxyAgentsForTarget } from "../utils/node-http-proxy.js";
7
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
8
+ import { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from "./simple-options.js";
9
+ import { transformMessages } from "./transform-messages.js";
10
+ const EMPTY_TEXT_PLACEHOLDER = "<empty>";
11
+ export const streamBedrock = (model, context, options = {}) => {
12
+ const stream = new AssistantMessageEventStream();
13
+ (async () => {
14
+ const output = {
15
+ role: "assistant",
16
+ content: [],
17
+ api: "bedrock-converse-stream",
18
+ provider: model.provider,
19
+ model: model.id,
20
+ usage: {
21
+ input: 0,
22
+ output: 0,
23
+ cacheRead: 0,
24
+ cacheWrite: 0,
25
+ totalTokens: 0,
26
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
27
+ },
28
+ stopReason: "stop",
29
+ timestamp: Date.now(),
30
+ };
31
+ const blocks = output.content;
32
+ const config = {
33
+ profile: options.profile,
34
+ };
35
+ const configuredRegion = getConfiguredBedrockRegion(options);
36
+ const hasConfiguredProfile = hasConfiguredBedrockProfile();
37
+ const endpointRegion = getStandardBedrockEndpointRegion(model.baseUrl);
38
+ const useExplicitEndpoint = shouldUseExplicitBedrockEndpoint(model.baseUrl, configuredRegion, hasConfiguredProfile);
39
+ // Only pin standard AWS Bedrock runtime endpoints when no region/profile is configured.
40
+ // This preserves custom endpoints (VPC/proxy) from #3402 without forcing built-in
41
+ // catalog defaults such as us-east-1 to override AWS_REGION/AWS_PROFILE.
42
+ if (useExplicitEndpoint) {
43
+ config.endpoint = model.baseUrl;
44
+ }
45
+ // Resolve bearer token for Bedrock API key auth.
46
+ const bearerToken = options.bearerToken || process.env.AWS_BEARER_TOKEN_BEDROCK || undefined;
47
+ const useBearerToken = bearerToken !== undefined && process.env.AWS_BEDROCK_SKIP_AUTH !== "1";
48
+ // in Node.js/Bun environment only
49
+ if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
50
+ // Region resolution: explicit option > env vars > SDK default chain.
51
+ // When AWS_PROFILE is set, we leave region undefined so the SDK can
52
+ // resovle it from aws profile configs. Otherwise fall back to us-east-1.
53
+ if (configuredRegion) {
54
+ config.region = configuredRegion;
55
+ }
56
+ else if (endpointRegion && useExplicitEndpoint) {
57
+ config.region = endpointRegion;
58
+ }
59
+ else if (!hasConfiguredProfile) {
60
+ config.region = "us-east-1";
61
+ }
62
+ // Support proxies that don't need authentication
63
+ if (process.env.AWS_BEDROCK_SKIP_AUTH === "1") {
64
+ config.credentials = {
65
+ accessKeyId: "dummy-access-key",
66
+ secretAccessKey: "dummy-secret-key",
67
+ };
68
+ }
69
+ const proxyAgents = createHttpProxyAgentsForTarget(model.baseUrl);
70
+ if (proxyAgents) {
71
+ // Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based
72
+ // on `http2` module and has no support for http agent.
73
+ // Use NodeHttpHandler to support HTTP(S) proxy agents.
74
+ config.requestHandler = new NodeHttpHandler(proxyAgents);
75
+ }
76
+ else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === "1") {
77
+ // Some custom endpoints require HTTP/1.1 instead of HTTP/2
78
+ config.requestHandler = new NodeHttpHandler();
79
+ }
80
+ }
81
+ else {
82
+ // Non-Node environment (browser): fall back to us-east-1 since
83
+ // there's no config file resolution available.
84
+ config.region =
85
+ configuredRegion || (endpointRegion && useExplicitEndpoint ? endpointRegion : undefined) || "us-east-1";
86
+ }
87
+ if (useBearerToken) {
88
+ config.token = { token: bearerToken };
89
+ config.authSchemePreference = ["httpBearerAuth"];
90
+ }
91
+ try {
92
+ const client = new BedrockRuntimeClient(config);
93
+ if (options.headers && Object.keys(options.headers).length > 0) {
94
+ addCustomHeadersMiddleware(client, options.headers);
95
+ }
96
+ const cacheRetention = resolveCacheRetention(options.cacheRetention);
97
+ const inferenceMaxTokens = options.maxTokens ?? (isAnthropicClaudeModel(model) ? model.maxTokens : undefined);
98
+ let commandInput = {
99
+ modelId: model.id,
100
+ messages: convertMessages(context, model, cacheRetention),
101
+ system: buildSystemPrompt(context.systemPrompt, model, cacheRetention),
102
+ inferenceConfig: {
103
+ ...(inferenceMaxTokens !== undefined && { maxTokens: inferenceMaxTokens }),
104
+ ...(options.temperature !== undefined && { temperature: options.temperature }),
105
+ },
106
+ toolConfig: convertToolConfig(context.tools, options.toolChoice),
107
+ additionalModelRequestFields: buildAdditionalModelRequestFields(model, options),
108
+ ...(options.requestMetadata !== undefined && { requestMetadata: options.requestMetadata }),
109
+ };
110
+ const nextCommandInput = await options?.onPayload?.(commandInput, model);
111
+ if (nextCommandInput !== undefined) {
112
+ commandInput = nextCommandInput;
113
+ }
114
+ const command = new ConverseStreamCommand(commandInput);
115
+ const response = await client.send(command, { abortSignal: options.signal });
116
+ if (response.$metadata.httpStatusCode !== undefined) {
117
+ const responseHeaders = {};
118
+ if (response.$metadata.requestId) {
119
+ responseHeaders["x-amzn-requestid"] = response.$metadata.requestId;
120
+ }
121
+ await options?.onResponse?.({ status: response.$metadata.httpStatusCode, headers: responseHeaders }, model);
122
+ }
123
+ for await (const item of response.stream) {
124
+ if (item.messageStart) {
125
+ if (item.messageStart.role !== ConversationRole.ASSISTANT) {
126
+ throw new Error("Unexpected assistant message start but got user message start instead");
127
+ }
128
+ stream.push({ type: "start", partial: output });
129
+ }
130
+ else if (item.contentBlockStart) {
131
+ handleContentBlockStart(item.contentBlockStart, blocks, output, stream);
132
+ }
133
+ else if (item.contentBlockDelta) {
134
+ handleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);
135
+ }
136
+ else if (item.contentBlockStop) {
137
+ handleContentBlockStop(item.contentBlockStop, blocks, output, stream);
138
+ }
139
+ else if (item.messageStop) {
140
+ output.stopReason = mapStopReason(item.messageStop.stopReason);
141
+ }
142
+ else if (item.metadata) {
143
+ handleMetadata(item.metadata, model, output);
144
+ }
145
+ else if (item.internalServerException) {
146
+ throw item.internalServerException;
147
+ }
148
+ else if (item.modelStreamErrorException) {
149
+ throw item.modelStreamErrorException;
150
+ }
151
+ else if (item.validationException) {
152
+ throw item.validationException;
153
+ }
154
+ else if (item.throttlingException) {
155
+ throw item.throttlingException;
156
+ }
157
+ else if (item.serviceUnavailableException) {
158
+ throw item.serviceUnavailableException;
159
+ }
160
+ }
161
+ if (options.signal?.aborted) {
162
+ throw new Error("Request was aborted");
163
+ }
164
+ if (output.stopReason === "error" || output.stopReason === "aborted") {
165
+ throw new Error("An unknown error occurred");
166
+ }
167
+ stream.push({ type: "done", reason: output.stopReason, message: output });
168
+ stream.end();
169
+ }
170
+ catch (error) {
171
+ for (const block of output.content) {
172
+ delete block.index;
173
+ // partialJson is only a streaming scratch buffer; never persist it.
174
+ delete block.partialJson;
175
+ }
176
+ output.stopReason = options.signal?.aborted ? "aborted" : "error";
177
+ output.errorMessage = formatBedrockError(error);
178
+ stream.push({ type: "error", reason: output.stopReason, error: output });
179
+ stream.end();
180
+ }
181
+ })();
182
+ return stream;
183
+ };
184
+ /**
185
+ * Human-readable prefixes for Bedrock SDK exception names.
186
+ * The downstream retry logic in agent-session matches patterns like
187
+ * `server.?error` and `service.?unavailable`, so we preserve the legacy
188
+ * prefix format rather than using the raw SDK exception name.
189
+ */
190
+ const BEDROCK_ERROR_PREFIXES = {
191
+ InternalServerException: "Internal server error",
192
+ ModelStreamErrorException: "Model stream error",
193
+ ValidationException: "Validation error",
194
+ ThrottlingException: "Throttling error",
195
+ ServiceUnavailableException: "Service unavailable",
196
+ };
197
+ /**
198
+ * Format a Bedrock error with a human-readable prefix.
199
+ * AWS SDK exceptions (both from `client.send()` and from stream event items)
200
+ * extend BedrockRuntimeServiceException. We map the `.name` to a stable
201
+ * human-readable prefix so downstream consumers (retry logic, context-overflow
202
+ * detection) can distinguish error categories via simple string matching.
203
+ */
204
+ function formatBedrockError(error) {
205
+ const message = error instanceof Error ? error.message : JSON.stringify(error);
206
+ if (error instanceof BedrockRuntimeServiceException) {
207
+ const prefix = BEDROCK_ERROR_PREFIXES[error.name] ?? error.name;
208
+ return `${prefix}: ${message}`;
209
+ }
210
+ return message;
211
+ }
212
+ /**
213
+ * Header keys that must never be overwritten by caller-supplied headers.
214
+ * `host` and `x-amz-*` participate in the SigV4 canonical request; `authorization`
215
+ * is owned by SigV4 or the bearer-token path (config.token + authSchemePreference).
216
+ * Compared case-insensitively (caller key is lower-cased before lookup).
217
+ */
218
+ const RESERVED_HEADER_EXACT = new Set(["authorization", "host"]);
219
+ function isReservedHeader(key) {
220
+ const lower = key.toLowerCase();
221
+ return lower.startsWith("x-amz-") || RESERVED_HEADER_EXACT.has(lower);
222
+ }
223
+ /**
224
+ * Attach caller-supplied headers to the outgoing Bedrock request via a Smithy
225
+ * `build`-step middleware. The `build` step runs after request serialisation but
226
+ * before SigV4 signing, so injected headers are covered by the signature. Reserved
227
+ * SigV4 / auth headers (`x-amz-*`, `authorization`, `host`) are silently skipped;
228
+ * all other caller headers override any existing same-named header on the request.
229
+ */
230
+ function addCustomHeadersMiddleware(client, headers) {
231
+ const middleware = (next) => async (args) => {
232
+ const request = args.request;
233
+ if (request && typeof request === "object" && "headers" in request) {
234
+ const requestHeaders = request.headers;
235
+ for (const [key, value] of Object.entries(headers)) {
236
+ if (!isReservedHeader(key)) {
237
+ requestHeaders[key] = value;
238
+ }
239
+ }
240
+ }
241
+ return next(args);
242
+ };
243
+ client.middlewareStack.add(middleware, { step: "build", name: "pi-ai-custom-headers", priority: "low" });
244
+ }
245
+ export const streamSimpleBedrock = (model, context, options) => {
246
+ const base = buildBaseOptions(model, options, undefined);
247
+ if (!options?.reasoning) {
248
+ return streamBedrock(model, context, { ...base, reasoning: undefined });
249
+ }
250
+ if (isAnthropicClaudeModel(model)) {
251
+ if (supportsAdaptiveThinking(model.id, model.name)) {
252
+ return streamBedrock(model, context, {
253
+ ...base,
254
+ reasoning: options.reasoning,
255
+ thinkingBudgets: options.thinkingBudgets,
256
+ });
257
+ }
258
+ // Undefined means the caller did not request an output cap; let the helper use the model cap.
259
+ // Do not coerce to 0 here, or the thinking budget would become the entire maxTokens value.
260
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
261
+ return streamBedrock(model, context, {
262
+ ...base,
263
+ maxTokens: adjusted.maxTokens,
264
+ reasoning: options.reasoning,
265
+ thinkingBudgets: {
266
+ ...(options.thinkingBudgets || {}),
267
+ [clampReasoning(options.reasoning)]: adjusted.thinkingBudget,
268
+ },
269
+ });
270
+ }
271
+ return streamBedrock(model, context, {
272
+ ...base,
273
+ reasoning: options.reasoning,
274
+ thinkingBudgets: options.thinkingBudgets,
275
+ });
276
+ };
277
+ function handleContentBlockStart(event, blocks, output, stream) {
278
+ const index = event.contentBlockIndex;
279
+ const start = event.start;
280
+ if (start?.toolUse) {
281
+ const block = {
282
+ type: "toolCall",
283
+ id: start.toolUse.toolUseId || "",
284
+ name: start.toolUse.name || "",
285
+ arguments: {},
286
+ partialJson: "",
287
+ index,
288
+ };
289
+ output.content.push(block);
290
+ stream.push({ type: "toolcall_start", contentIndex: blocks.length - 1, partial: output });
291
+ }
292
+ }
293
+ function handleContentBlockDelta(event, blocks, output, stream) {
294
+ const contentBlockIndex = event.contentBlockIndex;
295
+ const delta = event.delta;
296
+ let index = blocks.findIndex((b) => b.index === contentBlockIndex);
297
+ let block = blocks[index];
298
+ if (delta?.text !== undefined) {
299
+ // If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks
300
+ if (!block) {
301
+ const newBlock = { type: "text", text: "", index: contentBlockIndex };
302
+ output.content.push(newBlock);
303
+ index = blocks.length - 1;
304
+ block = blocks[index];
305
+ stream.push({ type: "text_start", contentIndex: index, partial: output });
306
+ }
307
+ if (block.type === "text") {
308
+ block.text += delta.text;
309
+ stream.push({ type: "text_delta", contentIndex: index, delta: delta.text, partial: output });
310
+ }
311
+ }
312
+ else if (delta?.toolUse && block?.type === "toolCall") {
313
+ block.partialJson = (block.partialJson || "") + (delta.toolUse.input || "");
314
+ block.arguments = parseStreamingJson(block.partialJson);
315
+ stream.push({ type: "toolcall_delta", contentIndex: index, delta: delta.toolUse.input || "", partial: output });
316
+ }
317
+ else if (delta?.reasoningContent) {
318
+ let thinkingBlock = block;
319
+ let thinkingIndex = index;
320
+ if (!thinkingBlock) {
321
+ const newBlock = { type: "thinking", thinking: "", thinkingSignature: "", index: contentBlockIndex };
322
+ output.content.push(newBlock);
323
+ thinkingIndex = blocks.length - 1;
324
+ thinkingBlock = blocks[thinkingIndex];
325
+ stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output });
326
+ }
327
+ if (thinkingBlock?.type === "thinking") {
328
+ if (delta.reasoningContent.text) {
329
+ thinkingBlock.thinking += delta.reasoningContent.text;
330
+ stream.push({
331
+ type: "thinking_delta",
332
+ contentIndex: thinkingIndex,
333
+ delta: delta.reasoningContent.text,
334
+ partial: output,
335
+ });
336
+ }
337
+ if (delta.reasoningContent.signature) {
338
+ thinkingBlock.thinkingSignature =
339
+ (thinkingBlock.thinkingSignature || "") + delta.reasoningContent.signature;
340
+ }
341
+ }
342
+ }
343
+ }
344
+ function handleMetadata(event, model, output) {
345
+ if (event.usage) {
346
+ output.usage.input = event.usage.inputTokens || 0;
347
+ output.usage.output = event.usage.outputTokens || 0;
348
+ output.usage.cacheRead = event.usage.cacheReadInputTokens || 0;
349
+ output.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;
350
+ output.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;
351
+ calculateCost(model, output.usage);
352
+ }
353
+ }
354
+ function handleContentBlockStop(event, blocks, output, stream) {
355
+ const index = blocks.findIndex((b) => b.index === event.contentBlockIndex);
356
+ const block = blocks[index];
357
+ if (!block)
358
+ return;
359
+ delete block.index;
360
+ switch (block.type) {
361
+ case "text":
362
+ stream.push({ type: "text_end", contentIndex: index, content: block.text, partial: output });
363
+ break;
364
+ case "thinking":
365
+ stream.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: output });
366
+ break;
367
+ case "toolCall":
368
+ block.arguments = parseStreamingJson(block.partialJson);
369
+ // Finalize in-place and strip the scratch buffer so replay only
370
+ // carries parsed arguments.
371
+ delete block.partialJson;
372
+ stream.push({ type: "toolcall_end", contentIndex: index, toolCall: block, partial: output });
373
+ break;
374
+ }
375
+ }
376
+ /**
377
+ * Check if the model supports adaptive thinking (Opus 4.6+, Sonnet 4.6).
378
+ * Checks both model ID and model name to support application inference profiles
379
+ * whose ARNs don't contain the model name.
380
+ */
381
+ function getModelMatchCandidates(modelId, modelName) {
382
+ const values = modelName ? [modelId, modelName] : [modelId];
383
+ return values.flatMap((value) => {
384
+ const lower = value.toLowerCase();
385
+ return [lower, lower.replace(/[\s_.:]+/g, "-")];
386
+ });
387
+ }
388
+ function supportsAdaptiveThinking(modelId, modelName) {
389
+ const candidates = getModelMatchCandidates(modelId, modelName);
390
+ return candidates.some((s) => s.includes("opus-4-6") || s.includes("opus-4-7") || s.includes("opus-4-8") || s.includes("sonnet-4-6"));
391
+ }
392
+ function supportsNativeXhighEffort(model) {
393
+ const candidates = getModelMatchCandidates(model.id, model.name);
394
+ return candidates.some((s) => s.includes("opus-4-7") || s.includes("opus-4-8"));
395
+ }
396
+ function mapThinkingLevelToEffort(model, level) {
397
+ if (level === "xhigh" && supportsNativeXhighEffort(model))
398
+ return "xhigh";
399
+ const mapped = level ? model.thinkingLevelMap?.[level] : undefined;
400
+ if (typeof mapped === "string")
401
+ return mapped;
402
+ switch (level) {
403
+ case "minimal":
404
+ case "low":
405
+ return "low";
406
+ case "medium":
407
+ return "medium";
408
+ case "high":
409
+ return "high";
410
+ default:
411
+ return "high";
412
+ }
413
+ }
414
+ /**
415
+ * Resolve cache retention preference.
416
+ * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
417
+ */
418
+ function resolveCacheRetention(cacheRetention) {
419
+ if (cacheRetention) {
420
+ return cacheRetention;
421
+ }
422
+ if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
423
+ return "long";
424
+ }
425
+ return "short";
426
+ }
427
+ /**
428
+ * Check if the model is an Anthropic Claude model on Bedrock.
429
+ * Checks both model ID and model name to support application inference profiles
430
+ * whose ARNs don't contain the model name.
431
+ */
432
+ function isAnthropicClaudeModel(model) {
433
+ const id = model.id.toLowerCase();
434
+ const name = model.name?.toLowerCase() ?? "";
435
+ return (id.includes("anthropic.claude") ||
436
+ id.includes("anthropic/claude") ||
437
+ name.includes("anthropic.claude") ||
438
+ name.includes("anthropic/claude") ||
439
+ name.includes("claude"));
440
+ }
441
+ /**
442
+ * Check if the model supports prompt caching.
443
+ * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models
444
+ *
445
+ * For base models and system-defined inference profiles the model ID / ARN
446
+ * contains the model name, so we can decide locally.
447
+ *
448
+ * For application inference profiles (whose ARNs don't contain the model name),
449
+ * also checks model.name which is user-controlled via models.json or registerProvider.
450
+ * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.
451
+ * Amazon Nova models have automatic caching and don't need explicit cache points.
452
+ */
453
+ function supportsPromptCaching(model) {
454
+ const candidates = getModelMatchCandidates(model.id, model.name);
455
+ const hasClaudeRef = candidates.some((s) => s.includes("claude"));
456
+ if (!hasClaudeRef) {
457
+ // Application inference profiles don't contain the model name in the ARN.
458
+ // Allow users to force cache points via environment variable.
459
+ if (typeof process !== "undefined" && process.env.AWS_BEDROCK_FORCE_CACHE === "1")
460
+ return true;
461
+ return false;
462
+ }
463
+ // Claude 4.x models (opus-4, sonnet-4, haiku-4)
464
+ if (candidates.some((s) => s.includes("-4-")))
465
+ return true;
466
+ // Claude 3.7 Sonnet
467
+ if (candidates.some((s) => s.includes("claude-3-7-sonnet")))
468
+ return true;
469
+ // Claude 3.5 Haiku
470
+ if (candidates.some((s) => s.includes("claude-3-5-haiku")))
471
+ return true;
472
+ return false;
473
+ }
474
+ /**
475
+ * Check if the model supports thinking signatures in reasoningContent.
476
+ * Only Anthropic Claude models support the signature field.
477
+ * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:
478
+ * "This model doesn't support the reasoningContent.reasoningText.signature field"
479
+ *
480
+ * Checks both model ID and model name to support application inference profiles.
481
+ */
482
+ function supportsThinkingSignature(model) {
483
+ return isAnthropicClaudeModel(model);
484
+ }
485
+ function buildSystemPrompt(systemPrompt, model, cacheRetention) {
486
+ if (!systemPrompt)
487
+ return undefined;
488
+ const blocks = [{ text: sanitizeSurrogates(systemPrompt) }];
489
+ // Add cache point for supported Claude models when caching is enabled
490
+ if (cacheRetention !== "none" && supportsPromptCaching(model)) {
491
+ blocks.push({
492
+ cachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === "long" ? { ttl: CacheTTL.ONE_HOUR } : {}) },
493
+ });
494
+ }
495
+ return blocks;
496
+ }
497
+ function normalizeToolCallId(id) {
498
+ const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, "_");
499
+ return sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
500
+ }
501
+ function createNonBlankTextBlock(text) {
502
+ const sanitized = sanitizeSurrogates(text);
503
+ return sanitized.trim().length === 0 ? undefined : { text: sanitized };
504
+ }
505
+ function createRequiredTextBlock(text) {
506
+ return createNonBlankTextBlock(text) ?? { text: EMPTY_TEXT_PLACEHOLDER };
507
+ }
508
+ function convertToolResultContent(content) {
509
+ const result = [];
510
+ for (const c of content) {
511
+ if (c.type === "image") {
512
+ result.push({ image: createImageBlock(c.mimeType, c.data) });
513
+ }
514
+ else {
515
+ const textBlock = createNonBlankTextBlock(c.text);
516
+ if (textBlock)
517
+ result.push(textBlock);
518
+ }
519
+ }
520
+ if (result.length === 0)
521
+ result.push({ text: EMPTY_TEXT_PLACEHOLDER });
522
+ return result;
523
+ }
524
+ function convertMessages(context, model, cacheRetention) {
525
+ const result = [];
526
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
527
+ for (let i = 0; i < transformedMessages.length; i++) {
528
+ const m = transformedMessages[i];
529
+ switch (m.role) {
530
+ case "user": {
531
+ const content = [];
532
+ if (typeof m.content === "string") {
533
+ content.push(createRequiredTextBlock(m.content));
534
+ }
535
+ else {
536
+ for (const c of m.content) {
537
+ switch (c.type) {
538
+ case "text": {
539
+ const textBlock = createNonBlankTextBlock(c.text);
540
+ if (textBlock)
541
+ content.push(textBlock);
542
+ break;
543
+ }
544
+ case "image":
545
+ content.push({ image: createImageBlock(c.mimeType, c.data) });
546
+ break;
547
+ default:
548
+ continue;
549
+ }
550
+ }
551
+ if (content.length === 0)
552
+ content.push({ text: EMPTY_TEXT_PLACEHOLDER });
553
+ }
554
+ result.push({
555
+ role: ConversationRole.USER,
556
+ content,
557
+ });
558
+ break;
559
+ }
560
+ case "assistant": {
561
+ // Skip assistant messages with empty content (e.g., from aborted requests)
562
+ // Bedrock rejects messages with empty content arrays
563
+ if (m.content.length === 0) {
564
+ continue;
565
+ }
566
+ const contentBlocks = [];
567
+ for (const c of m.content) {
568
+ switch (c.type) {
569
+ case "text": {
570
+ // Skip empty text blocks
571
+ const textBlock = createNonBlankTextBlock(c.text);
572
+ if (!textBlock)
573
+ continue;
574
+ contentBlocks.push(textBlock);
575
+ break;
576
+ }
577
+ case "toolCall":
578
+ contentBlocks.push({
579
+ toolUse: { toolUseId: c.id, name: c.name, input: c.arguments },
580
+ });
581
+ break;
582
+ case "thinking": {
583
+ // Skip empty thinking blocks
584
+ const thinking = sanitizeSurrogates(c.thinking);
585
+ if (thinking.trim().length === 0)
586
+ continue;
587
+ // Only Anthropic models support the signature field in reasoningText.
588
+ // For other models, we omit the signature to avoid errors like:
589
+ // "This model doesn't support the reasoningContent.reasoningText.signature field"
590
+ if (supportsThinkingSignature(model)) {
591
+ // Signatures arrive after thinking deltas. If a partial or externally
592
+ // persisted message lacks a signature, Bedrock rejects the replayed
593
+ // reasoning block. Fall back to plain text, matching Anthropic.
594
+ if (!c.thinkingSignature || c.thinkingSignature.trim().length === 0) {
595
+ contentBlocks.push({ text: thinking });
596
+ }
597
+ else {
598
+ contentBlocks.push({
599
+ reasoningContent: {
600
+ reasoningText: {
601
+ text: thinking,
602
+ signature: c.thinkingSignature,
603
+ },
604
+ },
605
+ });
606
+ }
607
+ }
608
+ else {
609
+ contentBlocks.push({
610
+ reasoningContent: {
611
+ reasoningText: { text: thinking },
612
+ },
613
+ });
614
+ }
615
+ break;
616
+ }
617
+ default:
618
+ continue;
619
+ }
620
+ }
621
+ // Skip if all content blocks were filtered out
622
+ if (contentBlocks.length === 0) {
623
+ continue;
624
+ }
625
+ result.push({
626
+ role: ConversationRole.ASSISTANT,
627
+ content: contentBlocks,
628
+ });
629
+ break;
630
+ }
631
+ case "toolResult": {
632
+ // Collect all consecutive toolResult messages into a single user message
633
+ // Bedrock requires all tool results to be in one message
634
+ const toolResults = [];
635
+ // Add current tool result with all content blocks combined
636
+ toolResults.push({
637
+ toolResult: {
638
+ toolUseId: m.toolCallId,
639
+ content: convertToolResultContent(m.content),
640
+ status: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,
641
+ },
642
+ });
643
+ // Look ahead for consecutive toolResult messages
644
+ let j = i + 1;
645
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
646
+ const nextMsg = transformedMessages[j];
647
+ toolResults.push({
648
+ toolResult: {
649
+ toolUseId: nextMsg.toolCallId,
650
+ content: convertToolResultContent(nextMsg.content),
651
+ status: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,
652
+ },
653
+ });
654
+ j++;
655
+ }
656
+ // Skip the messages we've already processed
657
+ i = j - 1;
658
+ result.push({
659
+ role: ConversationRole.USER,
660
+ content: toolResults,
661
+ });
662
+ break;
663
+ }
664
+ default:
665
+ continue;
666
+ }
667
+ }
668
+ // Add cache point to the last user message for supported Claude models when caching is enabled
669
+ if (cacheRetention !== "none" && supportsPromptCaching(model) && result.length > 0) {
670
+ const lastMessage = result[result.length - 1];
671
+ if (lastMessage.role === ConversationRole.USER && lastMessage.content) {
672
+ lastMessage.content.push({
673
+ cachePoint: {
674
+ type: CachePointType.DEFAULT,
675
+ ...(cacheRetention === "long" ? { ttl: CacheTTL.ONE_HOUR } : {}),
676
+ },
677
+ });
678
+ }
679
+ }
680
+ return result;
681
+ }
682
+ function convertToolConfig(tools, toolChoice) {
683
+ if (!tools?.length || toolChoice === "none")
684
+ return undefined;
685
+ const bedrockTools = tools.map((tool) => ({
686
+ toolSpec: {
687
+ name: tool.name,
688
+ description: tool.description,
689
+ inputSchema: { json: tool.parameters },
690
+ },
691
+ }));
692
+ let bedrockToolChoice;
693
+ switch (toolChoice) {
694
+ case "auto":
695
+ bedrockToolChoice = { auto: {} };
696
+ break;
697
+ case "any":
698
+ bedrockToolChoice = { any: {} };
699
+ break;
700
+ default:
701
+ if (toolChoice?.type === "tool") {
702
+ bedrockToolChoice = { tool: { name: toolChoice.name } };
703
+ }
704
+ }
705
+ return { tools: bedrockTools, toolChoice: bedrockToolChoice };
706
+ }
707
+ function mapStopReason(reason) {
708
+ switch (reason) {
709
+ case BedrockStopReason.END_TURN:
710
+ case BedrockStopReason.STOP_SEQUENCE:
711
+ return "stop";
712
+ case BedrockStopReason.MAX_TOKENS:
713
+ case BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:
714
+ return "length";
715
+ case BedrockStopReason.TOOL_USE:
716
+ return "toolUse";
717
+ default:
718
+ return "error";
719
+ }
720
+ }
721
+ function getConfiguredBedrockRegion(options) {
722
+ if (typeof process === "undefined") {
723
+ return options.region;
724
+ }
725
+ return options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || undefined;
726
+ }
727
+ function hasConfiguredBedrockProfile() {
728
+ if (typeof process === "undefined") {
729
+ return false;
730
+ }
731
+ return Boolean(process.env.AWS_PROFILE);
732
+ }
733
+ function getStandardBedrockEndpointRegion(baseUrl) {
734
+ if (!baseUrl) {
735
+ return undefined;
736
+ }
737
+ try {
738
+ const { hostname } = new URL(baseUrl);
739
+ const match = hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/);
740
+ return match?.[1];
741
+ }
742
+ catch {
743
+ return undefined;
744
+ }
745
+ }
746
+ function shouldUseExplicitBedrockEndpoint(baseUrl, configuredRegion, hasConfiguredProfile) {
747
+ const endpointRegion = getStandardBedrockEndpointRegion(baseUrl);
748
+ if (!endpointRegion) {
749
+ return true;
750
+ }
751
+ return !configuredRegion && !hasConfiguredProfile;
752
+ }
753
+ function isGovCloudBedrockTarget(model, options) {
754
+ const region = getConfiguredBedrockRegion(options);
755
+ if (region?.toLowerCase().startsWith("us-gov-")) {
756
+ return true;
757
+ }
758
+ const modelId = model.id.toLowerCase();
759
+ return modelId.startsWith("us-gov.") || modelId.startsWith("arn:aws-us-gov:");
760
+ }
761
+ function buildAdditionalModelRequestFields(model, options) {
762
+ if (!options.reasoning || !model.reasoning) {
763
+ return undefined;
764
+ }
765
+ if (isAnthropicClaudeModel(model)) {
766
+ // GovCloud Bedrock currently rejects the Claude thinking.display field.
767
+ // Omit it there until the GovCloud Converse schema catches up.
768
+ const display = isGovCloudBedrockTarget(model, options) ? undefined : (options.thinkingDisplay ?? "summarized");
769
+ const result = supportsAdaptiveThinking(model.id, model.name)
770
+ ? {
771
+ thinking: { type: "adaptive", ...(display !== undefined ? { display } : {}) },
772
+ output_config: { effort: mapThinkingLevelToEffort(model, options.reasoning) },
773
+ }
774
+ : (() => {
775
+ const defaultBudgets = {
776
+ minimal: 1024,
777
+ low: 2048,
778
+ medium: 8192,
779
+ high: 16384,
780
+ xhigh: 16384, // Claude doesn't support xhigh, clamp to high
781
+ };
782
+ // Custom budgets override defaults (xhigh not in ThinkingBudgets, use high)
783
+ const level = options.reasoning === "xhigh" ? "high" : options.reasoning;
784
+ const budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];
785
+ return {
786
+ thinking: {
787
+ type: "enabled",
788
+ budget_tokens: budget,
789
+ ...(display !== undefined ? { display } : {}),
790
+ },
791
+ };
792
+ })();
793
+ if (!supportsAdaptiveThinking(model.id, model.name) && (options.interleavedThinking ?? true)) {
794
+ result.anthropic_beta = ["interleaved-thinking-2025-05-14"];
795
+ }
796
+ return result;
797
+ }
798
+ return undefined;
799
+ }
800
+ function createImageBlock(mimeType, data) {
801
+ let format;
802
+ switch (mimeType) {
803
+ case "image/jpeg":
804
+ case "image/jpg":
805
+ format = ImageFormat.JPEG;
806
+ break;
807
+ case "image/png":
808
+ format = ImageFormat.PNG;
809
+ break;
810
+ case "image/gif":
811
+ format = ImageFormat.GIF;
812
+ break;
813
+ case "image/webp":
814
+ format = ImageFormat.WEBP;
815
+ break;
816
+ default:
817
+ throw new Error(`Unknown image type: ${mimeType}`);
818
+ }
819
+ const binaryString = atob(data);
820
+ const bytes = new Uint8Array(binaryString.length);
821
+ for (let i = 0; i < binaryString.length; i++) {
822
+ bytes[i] = binaryString.charCodeAt(i);
823
+ }
824
+ return { source: { bytes }, format };
825
+ }
826
+ //# sourceMappingURL=amazon-bedrock.js.map