@effect/ai-amazon-bedrock 0.17.0 → 4.1.5

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 (186) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/README.md +76 -3
  4. package/ai-docs/README.md +44 -0
  5. package/ai-docs/package.json +36 -0
  6. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  7. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  8. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  9. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  10. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  11. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  12. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  13. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  14. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  16. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  17. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  18. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  19. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  20. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  21. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  22. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  23. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  24. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  25. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  26. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  27. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  28. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  29. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  30. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  31. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  32. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  33. package/ai-docs/src/03_stream/index.md +4 -0
  34. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  35. package/ai-docs/src/04_integration/index.md +5 -0
  36. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  37. package/ai-docs/src/05_batching/index.md +3 -0
  38. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  39. package/ai-docs/src/06_schedule/index.md +3 -0
  40. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  41. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  42. package/ai-docs/src/07_datetime/index.md +5 -0
  43. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  44. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  45. package/ai-docs/src/08_observability/index.md +7 -0
  46. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  47. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  48. package/ai-docs/src/09_testing/index.md +1 -0
  49. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  50. package/ai-docs/src/10_predicate/index.md +9 -0
  51. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  52. package/ai-docs/src/40_sql/index.md +6 -0
  53. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  54. package/ai-docs/src/50_http-client/index.md +3 -0
  55. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  56. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  57. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  61. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  63. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  66. package/ai-docs/src/51_http-server/index.md +3 -0
  67. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  68. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  69. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  70. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  71. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  72. package/ai-docs/src/52_graphql/index.md +6 -0
  73. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  74. package/ai-docs/src/60_child-process/index.md +3 -0
  75. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  76. package/ai-docs/src/70_cli/index.md +5 -0
  77. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  78. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  79. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  80. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  81. package/ai-docs/src/71_ai/index.md +5 -0
  82. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  83. package/ai-docs/src/80_cluster/index.md +4 -0
  84. package/ai-docs/src/index.md +10 -0
  85. package/ai-docs/tsconfig.json +28 -0
  86. package/dist/AmazonBedrockClient.d.ts +227 -0
  87. package/dist/AmazonBedrockClient.d.ts.map +1 -0
  88. package/dist/AmazonBedrockClient.js +281 -0
  89. package/dist/AmazonBedrockClient.js.map +1 -0
  90. package/dist/AmazonBedrockConfig.d.ts +76 -0
  91. package/dist/AmazonBedrockConfig.d.ts.map +1 -0
  92. package/dist/AmazonBedrockConfig.js +41 -0
  93. package/dist/AmazonBedrockConfig.js.map +1 -0
  94. package/dist/AmazonBedrockLanguageModel.d.ts +315 -0
  95. package/dist/AmazonBedrockLanguageModel.d.ts.map +1 -0
  96. package/dist/AmazonBedrockLanguageModel.js +997 -0
  97. package/dist/AmazonBedrockLanguageModel.js.map +1 -0
  98. package/dist/AmazonBedrockSchema.d.ts +918 -0
  99. package/dist/AmazonBedrockSchema.d.ts.map +1 -0
  100. package/dist/AmazonBedrockSchema.js +536 -0
  101. package/dist/AmazonBedrockSchema.js.map +1 -0
  102. package/dist/index.d.ts +25 -0
  103. package/dist/index.d.ts.map +1 -0
  104. package/dist/{esm/index.js → index.js} +13 -12
  105. package/dist/index.js.map +1 -0
  106. package/dist/internal/errors.d.ts +2 -0
  107. package/dist/internal/errors.d.ts.map +1 -0
  108. package/dist/internal/errors.js +185 -0
  109. package/dist/internal/errors.js.map +1 -0
  110. package/dist/internal/eventStream.d.ts +2 -0
  111. package/dist/internal/eventStream.d.ts.map +1 -0
  112. package/dist/internal/eventStream.js +180 -0
  113. package/dist/internal/eventStream.js.map +1 -0
  114. package/dist/internal/sigv4.d.ts +2 -0
  115. package/dist/internal/sigv4.d.ts.map +1 -0
  116. package/dist/internal/sigv4.js +115 -0
  117. package/dist/internal/sigv4.js.map +1 -0
  118. package/dist/{dts/internal → internal}/utilities.d.ts.map +1 -1
  119. package/dist/internal/utilities.js +17 -0
  120. package/dist/internal/utilities.js.map +1 -0
  121. package/package.json +45 -84
  122. package/src/AmazonBedrockClient.ts +447 -263
  123. package/src/AmazonBedrockConfig.ts +55 -40
  124. package/src/AmazonBedrockLanguageModel.ts +957 -929
  125. package/src/AmazonBedrockSchema.ts +526 -970
  126. package/src/index.ts +15 -14
  127. package/src/internal/errors.ts +207 -0
  128. package/src/internal/eventStream.ts +208 -0
  129. package/src/internal/sigv4.ts +154 -0
  130. package/src/internal/utilities.ts +15 -17
  131. package/AmazonBedrockClient/package.json +0 -6
  132. package/AmazonBedrockConfig/package.json +0 -6
  133. package/AmazonBedrockLanguageModel/package.json +0 -6
  134. package/AmazonBedrockSchema/package.json +0 -6
  135. package/AmazonBedrockTool/package.json +0 -6
  136. package/EventStreamEncoding/package.json +0 -6
  137. package/dist/cjs/AmazonBedrockClient.js +0 -191
  138. package/dist/cjs/AmazonBedrockClient.js.map +0 -1
  139. package/dist/cjs/AmazonBedrockConfig.js +0 -30
  140. package/dist/cjs/AmazonBedrockConfig.js.map +0 -1
  141. package/dist/cjs/AmazonBedrockLanguageModel.js +0 -1051
  142. package/dist/cjs/AmazonBedrockLanguageModel.js.map +0 -1
  143. package/dist/cjs/AmazonBedrockSchema.js +0 -800
  144. package/dist/cjs/AmazonBedrockSchema.js.map +0 -1
  145. package/dist/cjs/AmazonBedrockTool.js +0 -53
  146. package/dist/cjs/AmazonBedrockTool.js.map +0 -1
  147. package/dist/cjs/EventStreamEncoding.js +0 -86
  148. package/dist/cjs/EventStreamEncoding.js.map +0 -1
  149. package/dist/cjs/index.js +0 -20
  150. package/dist/cjs/index.js.map +0 -1
  151. package/dist/cjs/internal/utilities.js +0 -27
  152. package/dist/cjs/internal/utilities.js.map +0 -1
  153. package/dist/dts/AmazonBedrockClient.d.ts +0 -95
  154. package/dist/dts/AmazonBedrockClient.d.ts.map +0 -1
  155. package/dist/dts/AmazonBedrockConfig.d.ts +0 -47
  156. package/dist/dts/AmazonBedrockConfig.d.ts.map +0 -1
  157. package/dist/dts/AmazonBedrockLanguageModel.d.ts +0 -147
  158. package/dist/dts/AmazonBedrockLanguageModel.d.ts.map +0 -1
  159. package/dist/dts/AmazonBedrockSchema.d.ts +0 -1875
  160. package/dist/dts/AmazonBedrockSchema.d.ts.map +0 -1
  161. package/dist/dts/AmazonBedrockTool.d.ts +0 -206
  162. package/dist/dts/AmazonBedrockTool.d.ts.map +0 -1
  163. package/dist/dts/EventStreamEncoding.d.ts +0 -16
  164. package/dist/dts/EventStreamEncoding.d.ts.map +0 -1
  165. package/dist/dts/index.d.ts +0 -25
  166. package/dist/dts/index.d.ts.map +0 -1
  167. package/dist/esm/AmazonBedrockClient.js +0 -179
  168. package/dist/esm/AmazonBedrockClient.js.map +0 -1
  169. package/dist/esm/AmazonBedrockConfig.js +0 -22
  170. package/dist/esm/AmazonBedrockConfig.js.map +0 -1
  171. package/dist/esm/AmazonBedrockLanguageModel.js +0 -1040
  172. package/dist/esm/AmazonBedrockLanguageModel.js.map +0 -1
  173. package/dist/esm/AmazonBedrockSchema.js +0 -731
  174. package/dist/esm/AmazonBedrockSchema.js.map +0 -1
  175. package/dist/esm/AmazonBedrockTool.js +0 -45
  176. package/dist/esm/AmazonBedrockTool.js.map +0 -1
  177. package/dist/esm/EventStreamEncoding.js +0 -78
  178. package/dist/esm/EventStreamEncoding.js.map +0 -1
  179. package/dist/esm/index.js.map +0 -1
  180. package/dist/esm/internal/utilities.js +0 -19
  181. package/dist/esm/internal/utilities.js.map +0 -1
  182. package/dist/esm/package.json +0 -4
  183. package/index/package.json +0 -6
  184. package/src/AmazonBedrockTool.ts +0 -273
  185. package/src/EventStreamEncoding.ts +0 -118
  186. /package/dist/{dts/internal → internal}/utilities.d.ts +0 -0
package/src/index.ts CHANGED
@@ -1,29 +1,30 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * @stability unstable
3
+ * @since 4.0.0
3
4
  */
4
- export * as AmazonBedrockClient from "./AmazonBedrockClient.js"
5
5
 
6
- /**
7
- * @since 1.0.0
8
- */
9
- export * as AmazonBedrockConfig from "./AmazonBedrockConfig.js"
6
+ // @barrel
10
7
 
11
8
  /**
12
- * @since 1.0.0
9
+ * @stability unstable
10
+ * @since 4.0.0
13
11
  */
14
- export * as AmazonBedrockLanguageModel from "./AmazonBedrockLanguageModel.js"
12
+ export * as AmazonBedrockClient from "./AmazonBedrockClient.ts"
15
13
 
16
14
  /**
17
- * @since 1.0.0
15
+ * @stability unstable
16
+ * @since 4.0.0
18
17
  */
19
- export * as AmazonBedrockSchema from "./AmazonBedrockSchema.js"
18
+ export * as AmazonBedrockConfig from "./AmazonBedrockConfig.ts"
20
19
 
21
20
  /**
22
- * @since 1.0.0
21
+ * @stability unstable
22
+ * @since 4.0.0
23
23
  */
24
- export * as AmazonBedrockTool from "./AmazonBedrockTool.js"
24
+ export * as AmazonBedrockLanguageModel from "./AmazonBedrockLanguageModel.ts"
25
25
 
26
26
  /**
27
- * @since 1.0.0
27
+ * @stability unstable
28
+ * @since 4.0.0
28
29
  */
29
- export * as EventStreamEncoding from "./EventStreamEncoding.js"
30
+ export * as AmazonBedrockSchema from "./AmazonBedrockSchema.ts"
@@ -0,0 +1,207 @@
1
+ import * as AiError from "effect/ai/AiError"
2
+ import * as Effect from "effect/Effect"
3
+ import type * as HttpClientError from "effect/http/HttpClientError"
4
+ import * as Option from "effect/Option"
5
+ import * as Predicate from "effect/Predicate"
6
+ import * as Redactable from "effect/Redactable"
7
+ import * as Schema from "effect/Schema"
8
+ import type { EventStreamError } from "./eventStream.ts"
9
+
10
+ const module = "AmazonBedrockClient"
11
+
12
+ /**
13
+ * An `AiError` of the client module.
14
+ *
15
+ * @internal
16
+ */
17
+ export const make = (method: string, reason: AiError.AiErrorReason): AiError.AiError =>
18
+ AiError.make({ module, method, reason })
19
+
20
+ // =============================================================================
21
+ // Error Mappers
22
+ // =============================================================================
23
+
24
+ /** @internal */
25
+ export const mapSchemaError = (error: Schema.SchemaError, method: string): AiError.AiError =>
26
+ make(method, AiError.InvalidResponseError.fromSchemaError(error))
27
+
28
+ /** @internal */
29
+ export const mapEventStreamError = (error: EventStreamError, method: string): AiError.AiError =>
30
+ make(method, new AiError.InvalidResponseError({ description: error.description }))
31
+
32
+ /**
33
+ * Maps an exception frame of a ConverseStream response, such as a
34
+ * `throttlingException`, to the reason its REST counterpart would have.
35
+ *
36
+ * @internal
37
+ */
38
+ export const mapStreamException = (
39
+ exceptionType: string,
40
+ message: string | undefined,
41
+ method: string
42
+ ): AiError.AiError => {
43
+ const description = Predicate.isUndefined(message) ? exceptionType : `${exceptionType}: ${message}`
44
+ return make(
45
+ method,
46
+ exceptionType === "throttlingException"
47
+ ? new AiError.RateLimitError({})
48
+ : exceptionType === "validationException"
49
+ ? new AiError.InvalidRequestError({ description })
50
+ : new AiError.InternalProviderError({ description })
51
+ )
52
+ }
53
+
54
+ /** @internal */
55
+ export const mapHttpClientError = (
56
+ error: HttpClientError.HttpClientError,
57
+ method: string
58
+ ): Effect.Effect<never, AiError.AiError> => {
59
+ const reason = error.reason
60
+ switch (reason._tag) {
61
+ case "TransportError":
62
+ case "EncodeError":
63
+ case "InvalidUrlError": {
64
+ return Effect.fail(make(method, AiError.NetworkError.fromRequestError(reason)))
65
+ }
66
+ case "StatusCodeError": {
67
+ return mapStatusCodeError(reason, method)
68
+ }
69
+ case "DecodeError":
70
+ case "EmptyBodyError": {
71
+ return Effect.fail(make(
72
+ method,
73
+ new AiError.InvalidOutputError({
74
+ description: reason.description ??
75
+ (reason._tag === "DecodeError" ? "Failed to decode response" : "Response body was empty")
76
+ })
77
+ ))
78
+ }
79
+ }
80
+ }
81
+
82
+ // Bedrock REST errors are flat `{ "message": "..." }` bodies (AWS uses both
83
+ // casings), with the exception type in the `x-amzn-errortype` header.
84
+ const BedrockErrorBody = Schema.fromJsonString(Schema.Struct({
85
+ message: Schema.optional(Schema.String),
86
+ Message: Schema.optional(Schema.String)
87
+ }))
88
+
89
+ const decodeErrorBody = Schema.decodeUnknownOption(BedrockErrorBody)
90
+
91
+ const mapStatusCodeError = Effect.fnUntraced(function*(
92
+ error: HttpClientError.StatusCodeError,
93
+ method: string
94
+ ) {
95
+ const { description, request, response } = error
96
+
97
+ let body: string | undefined = description
98
+ if (!description?.startsWith("{")) {
99
+ const responseBody = yield* Effect.option(response.text)
100
+ if (Option.isSome(responseBody) && responseBody.value) {
101
+ body = responseBody.value
102
+ }
103
+ }
104
+
105
+ const decoded = decodeErrorBody(body)
106
+ const message = Option.isSome(decoded) ? decoded.value.message ?? decoded.value.Message : undefined
107
+
108
+ return yield* make(
109
+ method,
110
+ mapStatusCodeToReason({
111
+ status: response.status,
112
+ requestMethod: request.method,
113
+ url: request.url,
114
+ message,
115
+ // AWS sends the exception shape as `Name:http://internal.amazon.com/coral/...`.
116
+ errorType: response.headers["x-amzn-errortype"]?.split(":")[0],
117
+ http: {
118
+ response: {
119
+ status: response.status,
120
+ headers: Redactable.redact(response.headers) as Record<string, string>
121
+ },
122
+ body
123
+ }
124
+ })
125
+ )
126
+ })
127
+
128
+ // =============================================================================
129
+ // HTTP Status Code
130
+ // =============================================================================
131
+
132
+ /**
133
+ * Bedrock answers 403 for several unrelated problems: a bad key, an expired
134
+ * session token and a model the account is not entitled to all arrive as 403.
135
+ * The exception shape in `x-amzn-errortype` distinguishes them.
136
+ */
137
+ const authenticationKinds: Record<string, AiError.AuthenticationError["kind"]> = {
138
+ AccessDeniedException: "InsufficientPermissions",
139
+ ExpiredTokenException: "ExpiredKey",
140
+ IncompleteSignatureException: "InvalidKey",
141
+ InvalidSignatureException: "InvalidKey",
142
+ MissingAuthenticationTokenException: "MissingKey",
143
+ UnrecognizedClientException: "InvalidKey"
144
+ }
145
+
146
+ const mapStatusCodeToReason = ({ errorType, http, message, requestMethod, status, url }: {
147
+ readonly requestMethod: string
148
+ readonly url: string
149
+ readonly status: number
150
+ readonly message: string | undefined
151
+ readonly errorType: string | undefined
152
+ readonly http: typeof AiError.HttpContext.Type
153
+ }): AiError.AiErrorReason => {
154
+ // AWS sends this with a 400, but the request is well formed: the account
155
+ // has used up a quota.
156
+ if (errorType === "ServiceQuotaExceededException") {
157
+ return new AiError.QuotaExhaustedError({ http })
158
+ }
159
+
160
+ const describe = (text: string | undefined): string | undefined =>
161
+ Predicate.isUndefined(errorType) ? text : Predicate.isUndefined(text) ? errorType : `${errorType}: ${text}`
162
+
163
+ switch (status) {
164
+ case 400:
165
+ case 404:
166
+ case 422: {
167
+ const summary = message ?? `HTTP ${status}`
168
+ return new AiError.InvalidRequestError({
169
+ description: describe(`${summary} (${requestMethod} ${url})`),
170
+ http
171
+ })
172
+ }
173
+ case 401:
174
+ case 403: {
175
+ return new AiError.AuthenticationError({
176
+ kind: (Predicate.isNotUndefined(errorType) ? authenticationKinds[errorType] : undefined)
177
+ ?? (status === 401 ? "InvalidKey" : "InsufficientPermissions"),
178
+ description: describe(message),
179
+ http
180
+ })
181
+ }
182
+ case 408:
183
+ case 424: {
184
+ // ModelTimeoutException and ModelErrorException: the model failed to
185
+ // answer in time, or answered with an error.
186
+ return new AiError.InternalProviderError({
187
+ description: describe(message) ?? "Model error",
188
+ http
189
+ })
190
+ }
191
+ case 429: {
192
+ return new AiError.RateLimitError({ http })
193
+ }
194
+ default: {
195
+ if (status >= 500) {
196
+ return new AiError.InternalProviderError({
197
+ description: describe(message) ?? "Server error",
198
+ http
199
+ })
200
+ }
201
+ return new AiError.UnknownError({
202
+ description: describe(message),
203
+ http
204
+ })
205
+ }
206
+ }
207
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Decodes the `application/vnd.amazon.eventstream` binary framing that the
3
+ * Bedrock ConverseStream endpoint uses.
4
+ *
5
+ * **Wire format**
6
+ *
7
+ * Each frame is laid out as
8
+ * `[totalLength u32][headersLength u32][preludeCrc u32][headers][payload][messageCrc u32]`,
9
+ * all big-endian. The prelude CRC covers the first 8 bytes and the message
10
+ * CRC covers everything before it. Headers are a sequence of
11
+ * `[nameLength u8][name][valueType u8][value]` entries; only string headers
12
+ * (`:message-type`, `:event-type`, `:exception-type`, ...) matter here.
13
+ *
14
+ * Adapted from the decoder of `@wmaurer/effect-ai-amazon-bedrock` (MIT,
15
+ * Copyright (c) 2026 Wayne Maurer), with CRC validation added.
16
+ *
17
+ * @see https://docs.aws.amazon.com/lexv2/latest/dg/event-stream-encoding.html
18
+ */
19
+ import * as Bytes from "effect/Bytes"
20
+ import * as Effect from "effect/Effect"
21
+ import * as Schema from "effect/Schema"
22
+ import * as Stream from "effect/Stream"
23
+
24
+ /**
25
+ * A frame that cannot be decoded.
26
+ *
27
+ * @internal
28
+ */
29
+ export class EventStreamError extends Schema.TaggedError<EventStreamError>(
30
+ "@effect/ai-amazon-bedrock/internal/eventStream/EventStreamError"
31
+ )("EventStreamError", {
32
+ description: Schema.String
33
+ }) {}
34
+
35
+ /**
36
+ * A decoded frame: its string headers and its raw payload.
37
+ *
38
+ * @internal
39
+ */
40
+ export interface Frame {
41
+ readonly headers: Record<string, string>
42
+ readonly payload: Uint8Array
43
+ }
44
+
45
+ const textDecoder = new TextDecoder()
46
+
47
+ const crcTable = (() => {
48
+ const table = new Int32Array(256)
49
+ for (let n = 0; n < 256; n++) {
50
+ let c = n
51
+ for (let k = 0; k < 8; k++) {
52
+ c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1
53
+ }
54
+ table[n] = c
55
+ }
56
+ return table
57
+ })()
58
+
59
+ const crc32 = (bytes: Uint8Array): number => {
60
+ let crc = -1
61
+ for (let i = 0; i < bytes.length; i++) {
62
+ crc = crcTable[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8)
63
+ }
64
+ return (crc ^ -1) >>> 0
65
+ }
66
+
67
+ const malformed = (description: string) => new EventStreamError({ description })
68
+
69
+ /** Prelude (12 bytes) plus message CRC (4 bytes). */
70
+ const minimumFrameLength = 16
71
+
72
+ /** The byte length of each fixed-size header value type, by type code. */
73
+ const fixedHeaderValueLengths: Record<number, number> = {
74
+ 0: 0, // bool true
75
+ 1: 0, // bool false
76
+ 2: 1, // byte
77
+ 3: 2, // short
78
+ 4: 4, // integer
79
+ 5: 8, // long
80
+ 8: 8, // timestamp
81
+ 9: 16 // uuid
82
+ }
83
+
84
+ const decodeHeaders = (bytes: Uint8Array): Record<string, string> => {
85
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
86
+ const headers: Record<string, string> = {}
87
+ let offset = 0
88
+ // Claims the next `length` bytes and returns where they start.
89
+ const take = (length: number): number => {
90
+ if (offset + length > bytes.length) {
91
+ throw malformed("An event stream header runs past the end of the headers block")
92
+ }
93
+ const start = offset
94
+ offset += length
95
+ return start
96
+ }
97
+ while (offset < bytes.length) {
98
+ const nameLength = view.getUint8(take(1))
99
+ const nameStart = take(nameLength)
100
+ const name = textDecoder.decode(bytes.subarray(nameStart, nameStart + nameLength))
101
+ const valueType = view.getUint8(take(1))
102
+ switch (valueType) {
103
+ // byte array
104
+ case 6: {
105
+ take(view.getUint16(take(2), false))
106
+ break
107
+ }
108
+ // string
109
+ case 7: {
110
+ const valueLength = view.getUint16(take(2), false)
111
+ const valueStart = take(valueLength)
112
+ headers[name] = textDecoder.decode(bytes.subarray(valueStart, valueStart + valueLength))
113
+ break
114
+ }
115
+ default: {
116
+ const length = fixedHeaderValueLengths[valueType]
117
+ if (length === undefined) {
118
+ throw malformed(`An event stream header has the unknown value type ${valueType}`)
119
+ }
120
+ take(length)
121
+ }
122
+ }
123
+ }
124
+ return headers
125
+ }
126
+
127
+ /**
128
+ * Takes every complete frame off the front of `buffer`. Returns the frames and
129
+ * the bytes left over, or throws an `EventStreamError`.
130
+ */
131
+ const takeFrames = (buffer: Uint8Array): [frames: Array<Frame>, rest: Uint8Array] => {
132
+ const frames: Array<Frame> = []
133
+ while (buffer.length >= 4) {
134
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
135
+ const totalLength = view.getUint32(0, false)
136
+ if (totalLength < minimumFrameLength) {
137
+ throw malformed(`An event stream frame declares a total length of ${totalLength} bytes, below the minimum of 16`)
138
+ }
139
+ if (buffer.length < totalLength) {
140
+ break
141
+ }
142
+ const headersLength = view.getUint32(4, false)
143
+ if (minimumFrameLength + headersLength > totalLength) {
144
+ throw malformed(
145
+ `An event stream frame declares ${headersLength} bytes of headers in a frame of ${totalLength} bytes`
146
+ )
147
+ }
148
+ if (crc32(buffer.subarray(0, 8)) !== view.getUint32(8, false)) {
149
+ throw malformed("The prelude CRC of an event stream frame does not match")
150
+ }
151
+ if (crc32(buffer.subarray(0, totalLength - 4)) !== view.getUint32(totalLength - 4, false)) {
152
+ throw malformed("The message CRC of an event stream frame does not match")
153
+ }
154
+ const headersEnd = 12 + headersLength
155
+ frames.push({
156
+ headers: decodeHeaders(buffer.subarray(12, headersEnd)),
157
+ payload: buffer.slice(headersEnd, totalLength - 4)
158
+ })
159
+ buffer = buffer.subarray(totalLength)
160
+ }
161
+ return [frames, buffer]
162
+ }
163
+
164
+ /**
165
+ * Decodes a stream of bytes into event stream frames. A stream that ends in
166
+ * the middle of a frame fails with an `EventStreamError`.
167
+ *
168
+ * @internal
169
+ */
170
+ export const decode = <E>(bytes: Stream.Stream<Uint8Array, E>): Stream.Stream<Frame, E | EventStreamError> =>
171
+ Stream.suspend(() => {
172
+ let buffer: Uint8Array = new Uint8Array(0)
173
+ const frames = bytes.pipe(
174
+ Stream.mapEffect((chunk) =>
175
+ Effect.try({
176
+ try: () => {
177
+ const [frames, rest] = takeFrames(buffer.length === 0 ? chunk : Bytes.concat([buffer, chunk]))
178
+ buffer = rest
179
+ return frames
180
+ },
181
+ catch: (error) =>
182
+ error instanceof EventStreamError
183
+ ? error
184
+ : malformed(
185
+ `An event stream frame could not be decoded: ${error instanceof Error ? error.message : String(error)}`
186
+ )
187
+ })
188
+ ),
189
+ Stream.flattenIterable
190
+ )
191
+ const trailing = Stream.suspend(() =>
192
+ buffer.length === 0
193
+ ? Stream.empty
194
+ : Stream.fail(malformed(`The event stream ended with ${buffer.length} bytes of an incomplete frame`))
195
+ )
196
+ return Stream.concat(frames, trailing)
197
+ })
198
+
199
+ /**
200
+ * Parses the JSON payload of a frame.
201
+ *
202
+ * @internal
203
+ */
204
+ export const parseJsonPayload = (frame: Frame): Effect.Effect<unknown, EventStreamError> =>
205
+ Effect.try({
206
+ try: () => JSON.parse(textDecoder.decode(frame.payload)) as unknown,
207
+ catch: () => malformed(`The payload of an event stream frame is not JSON: ${textDecoder.decode(frame.payload)}`)
208
+ })
@@ -0,0 +1,154 @@
1
+ import * as Clock from "effect/Clock"
2
+ import * as Digest from "effect/crypto/Digest"
3
+ import * as Mac from "effect/crypto/Mac"
4
+ import * as Effect from "effect/Effect"
5
+ import * as Hex from "effect/encoding/Hex"
6
+ import type * as HttpBody from "effect/http/HttpBody"
7
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
8
+ import * as Url from "effect/http/Url"
9
+ import * as Result from "effect/Result"
10
+
11
+ /**
12
+ * The credentials a request is signed with.
13
+ *
14
+ * @internal
15
+ */
16
+ export interface SigningCredentials {
17
+ readonly accessKeyId: string
18
+ readonly secretAccessKey: string
19
+ readonly sessionToken: string | undefined
20
+ }
21
+
22
+ const encoder = new TextEncoder()
23
+
24
+ /** Percent-encodes a string per RFC 3986, as SigV4 requires. */
25
+ const encodeRfc3986 = (value: string): string =>
26
+ encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
27
+
28
+ const service = "bedrock"
29
+
30
+ /** `YYYYMMDD'T'HHMMSS'Z'`, the SigV4 timestamp format. */
31
+ const formatAmzDate = (date: Date): string => date.toISOString().replace(/[-:]|\.\d{3}/g, "")
32
+
33
+ /**
34
+ * The bytes of the request body, for the payload hash.
35
+ */
36
+ const bodyBytes = (body: HttpBody.HttpBody): Effect.Effect<Uint8Array> => {
37
+ switch (body._tag) {
38
+ case "Empty": {
39
+ return Effect.succeed(new Uint8Array(0))
40
+ }
41
+ case "Uint8Array": {
42
+ return Effect.succeed(body.body)
43
+ }
44
+ case "Raw": {
45
+ if (typeof body.body === "string") {
46
+ return Effect.succeed(encoder.encode(body.body))
47
+ }
48
+ if (body.body instanceof Uint8Array) {
49
+ return Effect.succeed(body.body)
50
+ }
51
+ if (body.body instanceof ArrayBuffer) {
52
+ return Effect.succeed(new Uint8Array(body.body))
53
+ }
54
+ break
55
+ }
56
+ }
57
+ return Effect.die(new Error(`AmazonBedrockClient cannot sign a request with a body of type '${body._tag}'`))
58
+ }
59
+
60
+ /**
61
+ * Signs `request` with AWS Signature Version 4 for the Bedrock Runtime
62
+ * service, adding the `authorization`, `x-amz-date` and, with a session
63
+ * token, `x-amz-security-token` headers.
64
+ *
65
+ * **Details**
66
+ *
67
+ * The signed headers are `host`, `x-amz-date`, `content-type` when present
68
+ * and `x-amz-security-token` when present. The canonical URI and query come
69
+ * from the URL the transport sends, `url` with `urlParams` appended. Path
70
+ * segments are encoded a second time in the canonical URI, as the service does
71
+ * for every API but S3. The timestamp comes from the Effect `Clock`, and
72
+ * SHA-256 and HMAC run on the given `Digest` and `Mac` services.
73
+ *
74
+ * @internal
75
+ */
76
+ export const sign = (
77
+ request: HttpClientRequest.HttpClientRequest,
78
+ options: {
79
+ readonly region: string
80
+ readonly credentials: SigningCredentials
81
+ readonly digest: Digest.Digest["Service"]
82
+ readonly mac: Mac.Mac["Service"]
83
+ }
84
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest> =>
85
+ Effect.gen(function*() {
86
+ const { digest, mac } = options
87
+ // Signing keys are never empty, so a `CryptoError` means the `Mac`
88
+ // service has no HMAC-SHA-256, which is a defect.
89
+ const hmac = (key: Uint8Array, data: string): Effect.Effect<Uint8Array> =>
90
+ Mac.key(Mac.hmacSha256, key).pipe(
91
+ Effect.flatMap((key) => mac.sign(key, encoder.encode(data))),
92
+ Effect.orDie
93
+ )
94
+ const { accessKeyId, secretAccessKey, sessionToken } = options.credentials
95
+ const amzDate = formatAmzDate(new Date(yield* Clock.currentTimeMillis))
96
+ const date = amzDate.slice(0, 8)
97
+ const urlResult = Url.make(request.url, request.urlParams, undefined)
98
+ if (Result.isFailure(urlResult)) {
99
+ // The transport fails the request with an `InvalidUrlError` before sending it.
100
+ return request
101
+ }
102
+ const url = urlResult.success
103
+
104
+ // The headers this signer adds, which are also signed.
105
+ const amzHeaders: Record<string, string> = {
106
+ "x-amz-date": amzDate,
107
+ ...(sessionToken !== undefined ? { "x-amz-security-token": sessionToken } : {})
108
+ }
109
+ const headers: Record<string, string> = { host: url.host, ...amzHeaders }
110
+ const contentType = request.headers["content-type"]
111
+ if (contentType !== undefined) {
112
+ headers["content-type"] = contentType.trim().replace(/\s+/g, " ")
113
+ }
114
+ const signedHeaderNames = Object.keys(headers).sort()
115
+ const canonicalHeaders = signedHeaderNames.map((name) => `${name}:${headers[name]}\n`).join("")
116
+ const signedHeaders = signedHeaderNames.join(";")
117
+
118
+ const canonicalUri = url.pathname.split("/").map(encodeRfc3986).join("/")
119
+ const canonicalQuery = Array.from(url.searchParams.entries())
120
+ .map(([key, value]) => [encodeRfc3986(key), encodeRfc3986(value)] as const)
121
+ .sort(([a, av], [b, bv]) => a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0)
122
+ .map(([key, value]) => `${key}=${value}`)
123
+ .join("&")
124
+ const payloadHash = yield* digest.digestHex(Digest.sha256, yield* bodyBytes(request.body))
125
+
126
+ const canonicalRequest = [
127
+ request.method,
128
+ canonicalUri,
129
+ canonicalQuery,
130
+ canonicalHeaders,
131
+ signedHeaders,
132
+ payloadHash
133
+ ].join("\n")
134
+
135
+ const scope = `${date}/${options.region}/${service}/aws4_request`
136
+ const stringToSign = [
137
+ "AWS4-HMAC-SHA256",
138
+ amzDate,
139
+ scope,
140
+ yield* digest.digestHex(Digest.sha256, encoder.encode(canonicalRequest))
141
+ ].join("\n")
142
+
143
+ const kDate = yield* hmac(encoder.encode(`AWS4${secretAccessKey}`), date)
144
+ const kRegion = yield* hmac(kDate, options.region)
145
+ const kService = yield* hmac(kRegion, service)
146
+ const kSigning = yield* hmac(kService, "aws4_request")
147
+ const signature = Hex.encode(yield* hmac(kSigning, stringToSign))
148
+
149
+ return HttpClientRequest.setHeaders(request, {
150
+ authorization:
151
+ `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
152
+ ...amzHeaders
153
+ })
154
+ })
@@ -1,24 +1,22 @@
1
- import type * as Response from "@effect/ai/Response"
2
- import * as Predicate from "effect/Predicate"
3
- import type { StopReason } from "../AmazonBedrockSchema.js"
1
+ import type * as Response from "effect/ai/Response"
4
2
 
5
- /** @internal */
6
- export const ProviderOptionsKey = "@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/ProviderOptions"
7
-
8
- /** @internal */
9
- export const ProviderMetadataKey = "@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/ProviderMetadata"
10
-
11
- const finishReasonMap: Record<StopReason, Response.FinishReason> = {
12
- content_filtered: "content-filter",
3
+ const finishReasonMap: Record<string, Response.FinishReason> = {
13
4
  end_turn: "stop",
14
- guardrail_intervened: "content-filter",
15
- max_tokens: "length",
16
5
  stop_sequence: "stop",
17
- tool_use: "tool-calls"
6
+ tool_use: "tool-calls",
7
+ max_tokens: "length",
8
+ model_context_window_exceeded: "length",
9
+ guardrail_intervened: "content-filter",
10
+ content_filtered: "content-filter",
11
+ malformed_model_output: "error",
12
+ malformed_tool_use: "error"
18
13
  }
19
14
 
20
15
  /** @internal */
21
- export const resolveFinishReason = (stopReason: StopReason): Response.FinishReason => {
22
- const reason = finishReasonMap[stopReason]
23
- return Predicate.isUndefined(reason) ? "unknown" : reason
16
+ export const resolveFinishReason = (
17
+ stopReason: string,
18
+ isJsonResponse: boolean = false
19
+ ): Response.FinishReason => {
20
+ const reason = Object.hasOwn(finishReasonMap, stopReason) ? finishReasonMap[stopReason] : "other"
21
+ return isJsonResponse && reason === "tool-calls" ? "stop" : reason
24
22
  }
@@ -1,6 +0,0 @@
1
- {
2
- "sideEffects": [],
3
- "main": "../dist/cjs/AmazonBedrockClient.js",
4
- "module": "../dist/esm/AmazonBedrockClient.js",
5
- "types": "../dist/dts/AmazonBedrockClient.d.ts"
6
- }
@@ -1,6 +0,0 @@
1
- {
2
- "sideEffects": [],
3
- "main": "../dist/cjs/AmazonBedrockConfig.js",
4
- "module": "../dist/esm/AmazonBedrockConfig.js",
5
- "types": "../dist/dts/AmazonBedrockConfig.d.ts"
6
- }
@@ -1,6 +0,0 @@
1
- {
2
- "sideEffects": [],
3
- "main": "../dist/cjs/AmazonBedrockLanguageModel.js",
4
- "module": "../dist/esm/AmazonBedrockLanguageModel.js",
5
- "types": "../dist/dts/AmazonBedrockLanguageModel.d.ts"
6
- }
@@ -1,6 +0,0 @@
1
- {
2
- "sideEffects": [],
3
- "main": "../dist/cjs/AmazonBedrockSchema.js",
4
- "module": "../dist/esm/AmazonBedrockSchema.js",
5
- "types": "../dist/dts/AmazonBedrockSchema.d.ts"
6
- }
@@ -1,6 +0,0 @@
1
- {
2
- "sideEffects": [],
3
- "main": "../dist/cjs/AmazonBedrockTool.js",
4
- "module": "../dist/esm/AmazonBedrockTool.js",
5
- "types": "../dist/dts/AmazonBedrockTool.d.ts"
6
- }