@effect/ai-cloudflare 0.0.0 → 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 (105) hide show
  1. package/AGENTS.md +410 -0
  2. package/CLAUDE.md +410 -0
  3. package/LICENSE +21 -0
  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 +110 -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/60_child-process/10_working-with-child-processes.ts +117 -0
  68. package/ai-docs/src/60_child-process/index.md +3 -0
  69. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  70. package/ai-docs/src/70_cli/index.md +5 -0
  71. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  72. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  73. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  74. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  75. package/ai-docs/src/71_ai/index.md +5 -0
  76. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  77. package/ai-docs/src/80_cluster/index.md +4 -0
  78. package/ai-docs/src/index.md +10 -0
  79. package/ai-docs/tsconfig.json +24 -0
  80. package/dist/CloudflareClient.d.ts +79 -0
  81. package/dist/CloudflareClient.d.ts.map +1 -0
  82. package/dist/CloudflareClient.js +86 -0
  83. package/dist/CloudflareClient.js.map +1 -0
  84. package/dist/CloudflareDecisionModel.d.ts +49 -0
  85. package/dist/CloudflareDecisionModel.d.ts.map +1 -0
  86. package/dist/CloudflareDecisionModel.js +122 -0
  87. package/dist/CloudflareDecisionModel.js.map +1 -0
  88. package/dist/CloudflareSchema.d.ts +186 -0
  89. package/dist/CloudflareSchema.d.ts.map +1 -0
  90. package/dist/CloudflareSchema.js +128 -0
  91. package/dist/CloudflareSchema.js.map +1 -0
  92. package/dist/index.d.ts +19 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +20 -0
  95. package/dist/index.js.map +1 -0
  96. package/dist/internal/errors.d.ts +7 -0
  97. package/dist/internal/errors.d.ts.map +1 -0
  98. package/dist/internal/errors.js +109 -0
  99. package/dist/internal/errors.js.map +1 -0
  100. package/package.json +47 -9
  101. package/src/CloudflareClient.ts +149 -0
  102. package/src/CloudflareDecisionModel.ts +111 -0
  103. package/src/CloudflareSchema.ts +131 -0
  104. package/src/index.ts +23 -0
  105. package/src/internal/errors.ts +101 -0
@@ -0,0 +1,128 @@
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
+ * A classification question.
10
+ *
11
+ * @stability unstable
12
+ * @category schemas
13
+ * @since 4.0.0
14
+ */
15
+ export const ChoiceQuestion = /*#__PURE__*/Schema.Struct({
16
+ type: /*#__PURE__*/Schema.Literal("choice"),
17
+ instructions: Schema.String,
18
+ criteria: /*#__PURE__*/Schema.Record(Schema.String, Schema.String)
19
+ });
20
+ /**
21
+ * An ordered rating question.
22
+ *
23
+ * @stability unstable
24
+ * @category schemas
25
+ * @since 4.0.0
26
+ */
27
+ export const ScoreQuestion = /*#__PURE__*/Schema.Struct({
28
+ type: /*#__PURE__*/Schema.Literal("score"),
29
+ instructions: Schema.String,
30
+ criteria: /*#__PURE__*/Schema.Array(Schema.String)
31
+ });
32
+ /**
33
+ * A probability question.
34
+ *
35
+ * @stability unstable
36
+ * @category schemas
37
+ * @since 4.0.0
38
+ */
39
+ export const NoulQuestion = /*#__PURE__*/Schema.Struct({
40
+ type: /*#__PURE__*/Schema.Literal("noul"),
41
+ instructions: Schema.String,
42
+ criteria: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Struct({
43
+ false: Schema.String,
44
+ true: Schema.String
45
+ }))
46
+ });
47
+ /**
48
+ * A Clef classification, rating, or probability question.
49
+ *
50
+ * @stability unstable
51
+ * @category schemas
52
+ * @since 4.0.0
53
+ */
54
+ export const Question = /*#__PURE__*/Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestion]);
55
+ /**
56
+ * A batch of questions about text or JSON state.
57
+ *
58
+ * @stability unstable
59
+ * @category schemas
60
+ * @since 4.0.0
61
+ */
62
+ export const DecisionsRequest = /*#__PURE__*/Schema.Struct({
63
+ model: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literals(["clef", "clef-flash"]), Schema.StringForLiteralAutocomplete]),
64
+ state: Schema.Json,
65
+ questions: /*#__PURE__*/Schema.Record(Schema.String, Question)
66
+ });
67
+ /**
68
+ * A classification distribution.
69
+ *
70
+ * @stability unstable
71
+ * @category schemas
72
+ * @since 4.0.0
73
+ */
74
+ export const ChoiceAnswer = /*#__PURE__*/Schema.Struct({
75
+ type: /*#__PURE__*/Schema.Literal("choice"),
76
+ choice: Schema.String,
77
+ probabilities: /*#__PURE__*/Schema.Record(Schema.String, Schema.Number),
78
+ confidence: Schema.Number
79
+ });
80
+ /**
81
+ * A zero-based rating and index-keyed distribution.
82
+ *
83
+ * @stability unstable
84
+ * @category schemas
85
+ * @since 4.0.0
86
+ */
87
+ export const ScoreAnswer = /*#__PURE__*/Schema.Struct({
88
+ type: /*#__PURE__*/Schema.Literal("score"),
89
+ score: Schema.Number,
90
+ probabilities: /*#__PURE__*/Schema.Record(Schema.String, Schema.Number),
91
+ confidence: Schema.Number,
92
+ legend: /*#__PURE__*/Schema.Record(Schema.String, Schema.String)
93
+ });
94
+ /**
95
+ * A Bernoulli probability.
96
+ *
97
+ * @stability unstable
98
+ * @category schemas
99
+ * @since 4.0.0
100
+ */
101
+ export const NoulAnswer = /*#__PURE__*/Schema.Struct({
102
+ type: /*#__PURE__*/Schema.Literal("noul"),
103
+ noul: Schema.Number
104
+ });
105
+ /**
106
+ * A Clef classification, rating, or probability answer.
107
+ *
108
+ * @stability unstable
109
+ * @category schemas
110
+ * @since 4.0.0
111
+ */
112
+ export const Answer = /*#__PURE__*/Schema.Union([ChoiceAnswer, ScoreAnswer, NoulAnswer]);
113
+ /**
114
+ * Answers and token usage for a batch.
115
+ *
116
+ * @stability unstable
117
+ * @category schemas
118
+ * @since 4.0.0
119
+ */
120
+ export const DecisionsResponse = /*#__PURE__*/Schema.Struct({
121
+ model: Schema.String,
122
+ answers: /*#__PURE__*/Schema.Record(Schema.String, Answer),
123
+ usage: /*#__PURE__*/Schema.Struct({
124
+ input_tokens: Schema.Int,
125
+ output_tokens: Schema.Int
126
+ })
127
+ });
128
+ //# sourceMappingURL=CloudflareSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareSchema.js","names":[],"sources":["../src/CloudflareSchema.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;AAMA,OAAO,KAAK,MAAM,MAAM,eAAe;AAEvC;;;;;;;AAOA,OAAO,MAAM,cAAc,gBAAG,MAAM,CAAC,MAAM,CAAC;EAC1C,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC;EAC9B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM;CACrD,CAAC;AAEF;;;;;;;AAOA,OAAO,MAAM,aAAa,gBAAG,MAAM,CAAC,MAAM,CAAC;EACzC,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;EAC7B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM;CACrC,CAAC;AAEF;;;;;;;AAOA,OAAO,MAAM,YAAY,gBAAG,MAAM,CAAC,MAAM,CAAC;EACxC,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;EAC5B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,QAAQ,cAAC,MAAM,CAAC,MAAM,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC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MAAM,UAAU,gBAAG,MAAM,CAAC,MAAM,CAAC;EAAE,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;EAAE,IAAI,EAAE,MAAM,CAAC;AAAM,CAAE,CAAC;AAE9F;;;;;;;AAOA,OAAO,MAAM,MAAM,gBAAG,MAAM,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;AAE3E;;;;;;;AAOA,OAAO,MAAM,iBAAiB,gBAAG,MAAM,CAAC,MAAM,CAAC;EAC7C,KAAK,EAAE,MAAM,CAAC,MAAM;EACpB,OAAO,eAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;EAC7C,KAAK,eAAE,MAAM,CAAC,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC,GAAG;IACxB,aAAa,EAAE,MAAM,CAAC;GACvB;CACF,CAAC","ignoreList":[]}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+ /**
5
+ * @stability unstable
6
+ * @since 4.0.0
7
+ */
8
+ export * as CloudflareClient from "./CloudflareClient.ts";
9
+ /**
10
+ * @stability unstable
11
+ * @since 4.0.0
12
+ */
13
+ export * as CloudflareDecisionModel from "./CloudflareDecisionModel.ts";
14
+ /**
15
+ * @stability unstable
16
+ * @since 4.0.0
17
+ */
18
+ export * as CloudflareSchema from "./CloudflareSchema.ts";
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH;;;GAGG;AACH,OAAO,KAAK,gBAAgB,MAAM,uBAAuB,CAAA;AAEzD;;;GAGG;AACH,OAAO,KAAK,uBAAuB,MAAM,8BAA8B,CAAA;AAEvE;;;GAGG;AACH,OAAO,KAAK,gBAAgB,MAAM,uBAAuB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+ // @barrel
5
+ /**
6
+ * @stability unstable
7
+ * @since 4.0.0
8
+ */
9
+ export * as CloudflareClient from "./CloudflareClient.js";
10
+ /**
11
+ * @stability unstable
12
+ * @since 4.0.0
13
+ */
14
+ export * as CloudflareDecisionModel from "./CloudflareDecisionModel.js";
15
+ /**
16
+ * @stability unstable
17
+ * @since 4.0.0
18
+ */
19
+ export * as CloudflareSchema from "./CloudflareSchema.js";
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAIA;AAEA;;;;AAIA,OAAO,KAAK,gBAAgB,MAAM,uBAAuB;AAEzD;;;;AAIA,OAAO,KAAK,uBAAuB,MAAM,8BAA8B;AAEvE;;;;AAIA,OAAO,KAAK,gBAAgB,MAAM,uBAAuB","ignoreList":[]}
@@ -0,0 +1,7 @@
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 type * as HttpClientResponse from "effect/http/HttpClientResponse";
5
+ export declare const mapResponseError: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<never, AiError.AiError, never>;
6
+ export declare const mapHttpClientError: (error: HttpClientError.HttpClientError) => Effect.Effect<never, AiError.AiError, never>;
7
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/internal/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,mBAAmB,CAAA;AAE5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,eAAe,MAAM,6BAA6B,CAAA;AAEnE,OAAO,KAAK,KAAK,kBAAkB,MAAM,gCAAgC,CAAA;AA+BzE,eAAO,MAAM,gBAAgB,mGAqC5B,CAAA;AAED,eAAO,MAAM,kBAAkB,0FAyB9B,CAAA"}
@@ -0,0 +1,109 @@
1
+ import * as AiError from "effect/ai/AiError";
2
+ import * as Duration from "effect/Duration";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Num from "effect/Number";
5
+ import * as Option from "effect/Option";
6
+ import * as Redactable from "effect/Redactable";
7
+ import * as Schema from "effect/Schema";
8
+ const requestDetails = request => ({
9
+ method: request.method,
10
+ url: request.url,
11
+ urlParams: Array.from(request.urlParams),
12
+ hash: Option.getOrUndefined(request.hash),
13
+ headers: Redactable.redact(request.headers)
14
+ });
15
+ const ErrorBody = /*#__PURE__*/Schema.Struct({
16
+ errors: /*#__PURE__*/Schema.Array(/*#__PURE__*/Schema.Struct({
17
+ code: Schema.Number,
18
+ message: Schema.String
19
+ }))
20
+ });
21
+ const decodeErrorBody = /*#__PURE__*/Schema.decodeUnknownOption(ErrorBody);
22
+ const retryAfter = raw => {
23
+ if (raw === undefined || raw.trim() === "") return undefined;
24
+ const seconds = Option.getOrUndefined(Num.parse(raw));
25
+ if (seconds !== undefined) return Number.isFinite(seconds) && seconds >= 0 ? Duration.seconds(seconds) : undefined;
26
+ const date = Date.parse(raw);
27
+ return Number.isNaN(date) ? undefined : Duration.millis(Math.max(0, date - Date.now()));
28
+ };
29
+ const fail = reason => Effect.fail(AiError.make({
30
+ module: "CloudflareClient",
31
+ method: "createDecisions",
32
+ reason
33
+ }));
34
+ export const mapResponseError = /*#__PURE__*/Effect.fnUntraced(function* (response) {
35
+ const {
36
+ request,
37
+ status
38
+ } = response;
39
+ const body = yield* response.text.pipe(Effect.orElseSucceed(() => undefined));
40
+ const parsed = yield* Effect.try(() => JSON.parse(body ?? "")).pipe(Effect.orElseSucceed(() => undefined));
41
+ const details = Option.getOrUndefined(decodeErrorBody(parsed));
42
+ const http = {
43
+ request: requestDetails(request),
44
+ response: {
45
+ status,
46
+ headers: Redactable.redact(response.headers)
47
+ },
48
+ body
49
+ };
50
+ const description = AiError.buildErrorDescription({
51
+ status,
52
+ method: request.method,
53
+ url: request.url,
54
+ body,
55
+ message: details?.errors.map(error => error.message).join("; "),
56
+ errorCode: details?.errors[0]?.code,
57
+ requestId: response.headers["cf-ray"]
58
+ });
59
+ if (status === 429) {
60
+ return yield* fail(new AiError.RateLimitError({
61
+ retryAfter: retryAfter(response.headers["retry-after"]),
62
+ http,
63
+ metadata: {
64
+ cloudflare: {
65
+ rayId: response.headers["cf-ray"] ?? null,
66
+ errors: details?.errors ?? []
67
+ }
68
+ }
69
+ }));
70
+ }
71
+ if (status === 404 || status === 422) {
72
+ return yield* fail(new AiError.InvalidRequestError({
73
+ description,
74
+ http
75
+ }));
76
+ }
77
+ if (status >= 200 && status < 300) {
78
+ return yield* fail(new AiError.InternalProviderError({
79
+ description,
80
+ http
81
+ }));
82
+ }
83
+ return yield* fail(AiError.reasonFromHttpStatus({
84
+ status,
85
+ description,
86
+ http
87
+ }));
88
+ });
89
+ export const mapHttpClientError = /*#__PURE__*/Effect.fnUntraced(function* (error) {
90
+ const source = error.reason;
91
+ switch (source._tag) {
92
+ case "TransportError":
93
+ case "EncodeError":
94
+ case "InvalidUrlError":
95
+ return yield* fail(new AiError.NetworkError({
96
+ reason: source._tag,
97
+ description: source.description,
98
+ request: requestDetails(source.request)
99
+ }));
100
+ case "DecodeError":
101
+ case "EmptyBodyError":
102
+ return yield* fail(new AiError.InvalidOutputError({
103
+ description: source.description ?? "Failed to decode Cloudflare response"
104
+ }));
105
+ case "StatusCodeError":
106
+ return yield* mapResponseError(source.response);
107
+ }
108
+ });
109
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/internal/errors.ts"],"sourcesContent":[null],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,mBAAmB;AAC5C,OAAO,KAAK,QAAQ,MAAM,iBAAiB;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe;AAIvC,OAAO,KAAK,GAAG,MAAM,eAAe;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E,MAAM,CAAC,IAAI;QACnB,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,OAAO;OACvC,CAAC,CACH;IACH,KAAK,aAAa;IAClB,KAAK,gBAAgB;MACnB,OAAO,OAAO,IAAI,CAChB,IAAI,OAAO,CAAC,kBAAkB,CAAC;QAC7B,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI;OACpC,CAAC,CACH;IACH,KAAK,iBAAiB;MACpB,OAAO,OAAO,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC;EACnD;AACF,CAAC,CACF","ignoreList":[]}
package/package.json CHANGED
@@ -1,13 +1,9 @@
1
1
  {
2
2
  "name": "@effect/ai-cloudflare",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for @effect/ai-cloudflare",
5
- "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ],
3
+ "version": "4.0.1",
4
+ "type": "module",
10
5
  "license": "MIT",
6
+ "description": "A Cloudflare Workers AI decision provider for Effect",
11
7
  "homepage": "https://effect.website",
12
8
  "repository": {
13
9
  "type": "git",
@@ -17,7 +13,49 @@
17
13
  "bugs": {
18
14
  "url": "https://github.com/Effect-TS/effect/issues"
19
15
  },
16
+ "tags": [
17
+ "typescript",
18
+ "ai",
19
+ "cloudflare"
20
+ ],
21
+ "keywords": [
22
+ "typescript",
23
+ "ai",
24
+ "cloudflare"
25
+ ],
26
+ "sideEffects": [],
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": "./dist/index.js",
30
+ "./*": "./dist/*.js",
31
+ "./internal/*": null,
32
+ "./index": null,
33
+ "./*/index": null
34
+ },
35
+ "files": [
36
+ "src/**/*.ts",
37
+ "dist/**/*.js",
38
+ "dist/**/*.js.map",
39
+ "dist/**/*.d.ts",
40
+ "dist/**/*.d.ts.map",
41
+ "AGENTS.md",
42
+ "CLAUDE.md",
43
+ "ai-docs/**/*"
44
+ ],
20
45
  "publishConfig": {
21
- "access": "public"
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "devDependencies": {
50
+ "effect": "^4.0.1"
51
+ },
52
+ "peerDependencies": {
53
+ "effect": "^4.0.1"
54
+ },
55
+ "scripts": {
56
+ "codegen": "effect-utils codegen",
57
+ "build": "tsc -b tsconfig.json && pnpm babel",
58
+ "babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
59
+ "check": "tsc -b tsconfig.json"
22
60
  }
23
- }
61
+ }
@@ -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))