@effect/ai-cloudflare 0.0.0-stage → 4.0.1

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 (106) hide show
  1. package/AGENTS.md +410 -0
  2. package/CLAUDE.md +410 -0
  3. package/LICENSE +21 -0
  4. package/README.md +43 -2
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  69. package/ai-docs/src/60_child-process/index.md +3 -0
  70. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  71. package/ai-docs/src/70_cli/index.md +5 -0
  72. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  73. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  74. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  75. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  76. package/ai-docs/src/71_ai/index.md +5 -0
  77. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  78. package/ai-docs/src/80_cluster/index.md +4 -0
  79. package/ai-docs/src/index.md +10 -0
  80. package/ai-docs/tsconfig.json +24 -0
  81. package/dist/CloudflareClient.d.ts +79 -0
  82. package/dist/CloudflareClient.d.ts.map +1 -0
  83. package/dist/CloudflareClient.js +86 -0
  84. package/dist/CloudflareClient.js.map +1 -0
  85. package/dist/CloudflareDecisionModel.d.ts +49 -0
  86. package/dist/CloudflareDecisionModel.d.ts.map +1 -0
  87. package/dist/CloudflareDecisionModel.js +122 -0
  88. package/dist/CloudflareDecisionModel.js.map +1 -0
  89. package/dist/CloudflareSchema.d.ts +186 -0
  90. package/dist/CloudflareSchema.d.ts.map +1 -0
  91. package/dist/CloudflareSchema.js +128 -0
  92. package/dist/CloudflareSchema.js.map +1 -0
  93. package/dist/index.d.ts +19 -0
  94. package/dist/index.d.ts.map +1 -0
  95. package/dist/index.js +20 -0
  96. package/dist/index.js.map +1 -0
  97. package/dist/internal/errors.d.ts +7 -0
  98. package/dist/internal/errors.d.ts.map +1 -0
  99. package/dist/internal/errors.js +109 -0
  100. package/dist/internal/errors.js.map +1 -0
  101. package/package.json +58 -3
  102. package/src/CloudflareClient.ts +149 -0
  103. package/src/CloudflareDecisionModel.ts +111 -0
  104. package/src/CloudflareSchema.ts +131 -0
  105. package/src/index.ts +23 -0
  106. package/src/internal/errors.ts +101 -0
@@ -0,0 +1,149 @@
1
+ /**
2
+ * HTTP client for Cloudflare Clef decisions through Workers AI REST.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as AiError from "effect/ai/AiError"
8
+ import * as Config from "effect/Config"
9
+ import * as Context from "effect/Context"
10
+ import * as Effect from "effect/Effect"
11
+ import { flow, identity } from "effect/Function"
12
+ import * as HttpClient from "effect/http/HttpClient"
13
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
14
+ import * as HttpClientResponse from "effect/http/HttpClientResponse"
15
+ import * as Layer from "effect/Layer"
16
+ import * as Redacted from "effect/Redacted"
17
+ import * as Schema from "effect/Schema"
18
+ import * as CloudflareSchema from "./CloudflareSchema.ts"
19
+ import * as Errors from "./internal/errors.ts"
20
+
21
+ /**
22
+ * Low-level Cloudflare decision operations.
23
+ *
24
+ * @stability unstable
25
+ * @category services
26
+ * @since 4.0.0
27
+ */
28
+ export interface Service {
29
+ readonly client: HttpClient.HttpClient
30
+ readonly createDecisions: (
31
+ request: typeof CloudflareSchema.DecisionsRequest.Encoded
32
+ ) => Effect.Effect<typeof CloudflareSchema.DecisionsResponse.Type, AiError.AiError>
33
+ }
34
+
35
+ /**
36
+ * Cloudflare Workers AI client service.
37
+ *
38
+ * @stability unstable
39
+ * @category services
40
+ * @since 4.0.0
41
+ */
42
+ export class CloudflareClient
43
+ extends Context.Service<CloudflareClient, Service>()("@effect/ai-cloudflare/CloudflareClient")
44
+ {}
45
+
46
+ /**
47
+ * Account, authentication, API base URL, and HTTP customization options.
48
+ *
49
+ * @stability unstable
50
+ * @category options
51
+ * @since 4.0.0
52
+ */
53
+ export interface Options {
54
+ readonly accountId: string
55
+ readonly apiKey: Redacted.Redacted<string>
56
+ readonly apiUrl?: string | undefined
57
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
58
+ }
59
+
60
+ const decodeResponse = HttpClientResponse.schemaBodyJson(Schema.Union([
61
+ Schema.Struct({ success: Schema.Literal(true), result: CloudflareSchema.DecisionsResponse }),
62
+ Schema.Struct({ success: Schema.Literal(false) })
63
+ ]))
64
+
65
+ /**
66
+ * Builds a Cloudflare client without automatic retries.
67
+ *
68
+ * @stability unstable
69
+ * @category constructors
70
+ * @since 4.0.0
71
+ */
72
+ export const make = Effect.fnUntraced(
73
+ function*(options: Options): Effect.fn.Return<Service, never, HttpClient.HttpClient> {
74
+ const base = yield* HttpClient.HttpClient
75
+ const client = base.pipe(
76
+ HttpClient.mapRequest(flow(
77
+ HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.cloudflare.com/client/v4"),
78
+ HttpClientRequest.bearerToken(Redacted.value(options.apiKey)),
79
+ HttpClientRequest.acceptJson
80
+ )),
81
+ HttpClient.filterStatusOk,
82
+ options.transformClient ?? identity
83
+ )
84
+ const path = `/accounts/${encodeURIComponent(options.accountId)}/ai/run/@cf/cloudflare/`
85
+ return CloudflareClient.of({
86
+ client,
87
+ createDecisions: (payload) =>
88
+ HttpClientRequest.bodyJson(HttpClientRequest.post(path + payload.model), payload).pipe(
89
+ Effect.mapError((error) =>
90
+ AiError.make({
91
+ module: "CloudflareClient",
92
+ method: "createDecisions",
93
+ reason: new AiError.InvalidRequestError({ description: String(error) })
94
+ })
95
+ ),
96
+ Effect.flatMap(client.execute),
97
+ Effect.flatMap((response) =>
98
+ decodeResponse(response).pipe(
99
+ Effect.flatMap((body) => body.success ? Effect.succeed(body.result) : Errors.mapResponseError(response))
100
+ )
101
+ ),
102
+ Effect.catchTags({
103
+ HttpClientError: Errors.mapHttpClientError,
104
+ SchemaError: (error) =>
105
+ Effect.fail(AiError.make({
106
+ module: "CloudflareClient",
107
+ method: "createDecisions",
108
+ reason: AiError.InvalidOutputError.fromSchemaError(error)
109
+ }))
110
+ })
111
+ )
112
+ })
113
+ }
114
+ )
115
+
116
+ /**
117
+ * Provides a Cloudflare client from explicit options.
118
+ *
119
+ * @stability unstable
120
+ * @category layers
121
+ * @since 4.0.0
122
+ */
123
+ export const layer = (options: Options): Layer.Layer<CloudflareClient, never, HttpClient.HttpClient> =>
124
+ Layer.effect(CloudflareClient, make(options))
125
+
126
+ /**
127
+ * Provides a client from configuration, defaulting to CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN.
128
+ *
129
+ * @stability unstable
130
+ * @category layers
131
+ * @since 4.0.0
132
+ */
133
+ export const layerConfig = (options?: {
134
+ readonly accountId?: Config.Config<string> | undefined
135
+ readonly apiKey?: Config.Config<Redacted.Redacted<string>> | undefined
136
+ readonly apiUrl?: Config.Config<string> | undefined
137
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
138
+ }): Layer.Layer<CloudflareClient, Config.ConfigError, HttpClient.HttpClient> =>
139
+ Layer.effect(
140
+ CloudflareClient,
141
+ Effect.gen(function*() {
142
+ return yield* make({
143
+ accountId: yield* (options?.accountId ?? Config.String("CLOUDFLARE_ACCOUNT_ID")),
144
+ apiKey: yield* (options?.apiKey ?? Config.Redacted("CLOUDFLARE_API_TOKEN")),
145
+ apiUrl: options?.apiUrl ? yield* options.apiUrl : undefined,
146
+ transformClient: options?.transformClient
147
+ })
148
+ })
149
+ )
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Cloudflare Clef implementation of DecisionModel over Workers AI REST.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as DecisionModel from "effect/ai/DecisionModel"
8
+ import * as AiModel from "effect/ai/Model"
9
+ import * as Effect from "effect/Effect"
10
+ import * as Layer from "effect/Layer"
11
+ import { CloudflareClient } from "./CloudflareClient.ts"
12
+ import type * as CloudflareSchema from "./CloudflareSchema.ts"
13
+
14
+ /**
15
+ * Cloudflare Clef model identifiers.
16
+ *
17
+ * @stability unstable
18
+ * @category models
19
+ * @since 4.0.0
20
+ */
21
+ export type Model = typeof CloudflareSchema.DecisionsRequest.Encoded["model"]
22
+
23
+ /**
24
+ * Creates a decision model with Cloudflare provider metadata.
25
+ *
26
+ * @stability unstable
27
+ * @category constructors
28
+ * @since 4.0.0
29
+ */
30
+ export const model = (
31
+ model: Model
32
+ ): AiModel.Model<"cloudflare", DecisionModel.DecisionModel, CloudflareClient> =>
33
+ AiModel.make("cloudflare", model, layer({ model }))
34
+
35
+ /**
36
+ * Builds a decision service with tolerance for four-decimal probability rounding.
37
+ *
38
+ * @stability unstable
39
+ * @category constructors
40
+ * @since 4.0.0
41
+ */
42
+ export const make = Effect.fnUntraced(
43
+ function*(
44
+ options: { readonly model: Model }
45
+ ): Effect.fn.Return<DecisionModel.DecisionModel, never, CloudflareClient> {
46
+ const client = yield* CloudflareClient
47
+ return yield* DecisionModel.make({
48
+ probabilityPrecision: 4,
49
+ decide: Effect.fnUntraced(function*({ state, decisions }) {
50
+ const questions: Record<string, typeof CloudflareSchema.Question.Encoded> = Object.create(null)
51
+ for (const [key, decision] of Object.entries(decisions)) {
52
+ switch (decision._tag) {
53
+ case "Classify":
54
+ questions[key] = { type: "choice", instructions: decision.instructions, criteria: decision.criteria }
55
+ break
56
+ case "Rate":
57
+ questions[key] = { type: "score", instructions: decision.instructions, criteria: decision.criteria }
58
+ break
59
+ case "Probability":
60
+ questions[key] = { type: "noul", instructions: decision.instructions, criteria: decision.criteria }
61
+ break
62
+ }
63
+ }
64
+ const response = yield* client.createDecisions({ model: options.model, state, questions })
65
+ const answers: Record<string, DecisionModel.ProviderAnswer> = Object.create(null)
66
+ for (const [key, decision] of Object.entries(decisions)) {
67
+ const answer = response.answers[key]
68
+ switch (answer?.type) {
69
+ case "choice":
70
+ answers[key] = {
71
+ _tag: "Classify",
72
+ label: answer.choice,
73
+ probabilities: answer.probabilities,
74
+ confidence: answer.confidence
75
+ }
76
+ break
77
+ case "score": {
78
+ const levels = decision._tag === "Rate" ? decision.criteria : []
79
+ const probabilities: Record<string, number> = Object.create(null)
80
+ for (let index = 0; index < levels.length; index++) {
81
+ const probability = answer.probabilities[String(index)]
82
+ if (probability !== undefined) probabilities[levels[index]] = probability
83
+ }
84
+ answers[key] = { _tag: "Rate", rating: answer.score, probabilities, confidence: answer.confidence }
85
+ break
86
+ }
87
+ case "noul":
88
+ answers[key] = { _tag: "Probability", probability: answer.noul }
89
+ break
90
+ }
91
+ }
92
+ return {
93
+ answers,
94
+ usage: { inputTokens: response.usage.input_tokens, outputTokens: response.usage.output_tokens }
95
+ }
96
+ })
97
+ })
98
+ }
99
+ )
100
+
101
+ /**
102
+ * Provides DecisionModel using an existing CloudflareClient.
103
+ *
104
+ * @stability unstable
105
+ * @category layers
106
+ * @since 4.0.0
107
+ */
108
+ export const layer = (
109
+ options: { readonly model: Model }
110
+ ): Layer.Layer<DecisionModel.DecisionModel, never, CloudflareClient> =>
111
+ Layer.effect(DecisionModel.DecisionModel, make(options))
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Codecs for text and JSON decisions from Cloudflare Clef models.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as Schema from "effect/Schema"
8
+
9
+ /**
10
+ * A classification question.
11
+ *
12
+ * @stability unstable
13
+ * @category schemas
14
+ * @since 4.0.0
15
+ */
16
+ export const ChoiceQuestion = Schema.Struct({
17
+ type: Schema.Literal("choice"),
18
+ instructions: Schema.String,
19
+ criteria: Schema.Record(Schema.String, Schema.String)
20
+ })
21
+
22
+ /**
23
+ * An ordered rating question.
24
+ *
25
+ * @stability unstable
26
+ * @category schemas
27
+ * @since 4.0.0
28
+ */
29
+ export const ScoreQuestion = Schema.Struct({
30
+ type: Schema.Literal("score"),
31
+ instructions: Schema.String,
32
+ criteria: Schema.Array(Schema.String)
33
+ })
34
+
35
+ /**
36
+ * A probability question.
37
+ *
38
+ * @stability unstable
39
+ * @category schemas
40
+ * @since 4.0.0
41
+ */
42
+ export const NoulQuestion = Schema.Struct({
43
+ type: Schema.Literal("noul"),
44
+ instructions: Schema.String,
45
+ criteria: Schema.optional(Schema.Struct({ false: Schema.String, true: Schema.String }))
46
+ })
47
+
48
+ /**
49
+ * A Clef classification, rating, or probability question.
50
+ *
51
+ * @stability unstable
52
+ * @category schemas
53
+ * @since 4.0.0
54
+ */
55
+ export const Question = Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestion])
56
+
57
+ /**
58
+ * A batch of questions about text or JSON state.
59
+ *
60
+ * @stability unstable
61
+ * @category schemas
62
+ * @since 4.0.0
63
+ */
64
+ export const DecisionsRequest = Schema.Struct({
65
+ model: Schema.Union([Schema.Literals(["clef", "clef-flash"]), Schema.StringForLiteralAutocomplete]),
66
+ state: Schema.Json,
67
+ questions: Schema.Record(Schema.String, Question)
68
+ })
69
+
70
+ /**
71
+ * A classification distribution.
72
+ *
73
+ * @stability unstable
74
+ * @category schemas
75
+ * @since 4.0.0
76
+ */
77
+ export const ChoiceAnswer = Schema.Struct({
78
+ type: Schema.Literal("choice"),
79
+ choice: Schema.String,
80
+ probabilities: Schema.Record(Schema.String, Schema.Number),
81
+ confidence: Schema.Number
82
+ })
83
+
84
+ /**
85
+ * A zero-based rating and index-keyed distribution.
86
+ *
87
+ * @stability unstable
88
+ * @category schemas
89
+ * @since 4.0.0
90
+ */
91
+ export const ScoreAnswer = Schema.Struct({
92
+ type: Schema.Literal("score"),
93
+ score: Schema.Number,
94
+ probabilities: Schema.Record(Schema.String, Schema.Number),
95
+ confidence: Schema.Number,
96
+ legend: Schema.Record(Schema.String, Schema.String)
97
+ })
98
+
99
+ /**
100
+ * A Bernoulli probability.
101
+ *
102
+ * @stability unstable
103
+ * @category schemas
104
+ * @since 4.0.0
105
+ */
106
+ export const NoulAnswer = Schema.Struct({ type: Schema.Literal("noul"), noul: Schema.Number })
107
+
108
+ /**
109
+ * A Clef classification, rating, or probability answer.
110
+ *
111
+ * @stability unstable
112
+ * @category schemas
113
+ * @since 4.0.0
114
+ */
115
+ export const Answer = Schema.Union([ChoiceAnswer, ScoreAnswer, NoulAnswer])
116
+
117
+ /**
118
+ * Answers and token usage for a batch.
119
+ *
120
+ * @stability unstable
121
+ * @category schemas
122
+ * @since 4.0.0
123
+ */
124
+ export const DecisionsResponse = Schema.Struct({
125
+ model: Schema.String,
126
+ answers: Schema.Record(Schema.String, Answer),
127
+ usage: Schema.Struct({
128
+ input_tokens: Schema.Int,
129
+ output_tokens: Schema.Int
130
+ })
131
+ })
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+
5
+ // @barrel
6
+
7
+ /**
8
+ * @stability unstable
9
+ * @since 4.0.0
10
+ */
11
+ export * as CloudflareClient from "./CloudflareClient.ts"
12
+
13
+ /**
14
+ * @stability unstable
15
+ * @since 4.0.0
16
+ */
17
+ export * as CloudflareDecisionModel from "./CloudflareDecisionModel.ts"
18
+
19
+ /**
20
+ * @stability unstable
21
+ * @since 4.0.0
22
+ */
23
+ export * as CloudflareSchema from "./CloudflareSchema.ts"
@@ -0,0 +1,101 @@
1
+ import * as AiError from "effect/ai/AiError"
2
+ import * as Duration from "effect/Duration"
3
+ import * as Effect from "effect/Effect"
4
+ import type * as HttpClientError from "effect/http/HttpClientError"
5
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest"
6
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse"
7
+ import * as Num from "effect/Number"
8
+ import * as Option from "effect/Option"
9
+ import * as Redactable from "effect/Redactable"
10
+ import * as Schema from "effect/Schema"
11
+
12
+ const requestDetails = (request: HttpClientRequest.HttpClientRequest) => ({
13
+ method: request.method,
14
+ url: request.url,
15
+ urlParams: Array.from(request.urlParams),
16
+ hash: Option.getOrUndefined(request.hash),
17
+ headers: Redactable.redact(request.headers) as Record<string, string>
18
+ })
19
+
20
+ const ErrorBody = Schema.Struct({
21
+ errors: Schema.Array(Schema.Struct({ code: Schema.Number, message: Schema.String }))
22
+ })
23
+
24
+ const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody)
25
+
26
+ const retryAfter = (raw: string | undefined): Duration.Duration | undefined => {
27
+ if (raw === undefined || raw.trim() === "") return undefined
28
+ const seconds = Option.getOrUndefined(Num.parse(raw))
29
+ if (seconds !== undefined) return Number.isFinite(seconds) && seconds >= 0 ? Duration.seconds(seconds) : undefined
30
+ const date = Date.parse(raw)
31
+ return Number.isNaN(date) ? undefined : Duration.millis(Math.max(0, date - Date.now()))
32
+ }
33
+
34
+ const fail = (reason: AiError.AiErrorReason) =>
35
+ Effect.fail(AiError.make({ module: "CloudflareClient", method: "createDecisions", reason }))
36
+
37
+ export const mapResponseError = Effect.fnUntraced(
38
+ function*(response: HttpClientResponse.HttpClientResponse): Effect.fn.Return<never, AiError.AiError> {
39
+ const { request, status } = response
40
+ const body = yield* response.text.pipe(Effect.orElseSucceed(() => undefined))
41
+ const parsed = yield* Effect.try(() => JSON.parse(body ?? "")).pipe(Effect.orElseSucceed(() => undefined))
42
+ const details = Option.getOrUndefined(decodeErrorBody(parsed))
43
+ const http = {
44
+ request: requestDetails(request),
45
+ response: { status, headers: Redactable.redact(response.headers) as Record<string, string> },
46
+ body
47
+ }
48
+ const description = AiError.buildErrorDescription({
49
+ status,
50
+ method: request.method,
51
+ url: request.url,
52
+ body,
53
+ message: details?.errors.map((error) => error.message).join("; "),
54
+ errorCode: details?.errors[0]?.code,
55
+ requestId: response.headers["cf-ray"]
56
+ })
57
+ if (status === 429) {
58
+ return yield* fail(
59
+ new AiError.RateLimitError({
60
+ retryAfter: retryAfter(response.headers["retry-after"]),
61
+ http,
62
+ metadata: { cloudflare: { rayId: response.headers["cf-ray"] ?? null, errors: details?.errors ?? [] } }
63
+ })
64
+ )
65
+ }
66
+ if (status === 404 || status === 422) {
67
+ return yield* fail(new AiError.InvalidRequestError({ description, http }))
68
+ }
69
+ if (status >= 200 && status < 300) {
70
+ return yield* fail(new AiError.InternalProviderError({ description, http }))
71
+ }
72
+ return yield* fail(AiError.reasonFromHttpStatus({ status, description, http }))
73
+ }
74
+ )
75
+
76
+ export const mapHttpClientError = Effect.fnUntraced(
77
+ function*(error: HttpClientError.HttpClientError): Effect.fn.Return<never, AiError.AiError> {
78
+ const source = error.reason
79
+ switch (source._tag) {
80
+ case "TransportError":
81
+ case "EncodeError":
82
+ case "InvalidUrlError":
83
+ return yield* fail(
84
+ new AiError.NetworkError({
85
+ reason: source._tag,
86
+ description: source.description,
87
+ request: requestDetails(source.request)
88
+ })
89
+ )
90
+ case "DecodeError":
91
+ case "EmptyBodyError":
92
+ return yield* fail(
93
+ new AiError.InvalidOutputError({
94
+ description: source.description ?? "Failed to decode Cloudflare response"
95
+ })
96
+ )
97
+ case "StatusCodeError":
98
+ return yield* mapResponseError(source.response)
99
+ }
100
+ }
101
+ )