The best way to control Claude Code, Codex and more from any computer or phone

main
ts 189 lines 8.23 KB
Raw
1 import * as CloudflareClient from "@effect/ai-cloudflare/CloudflareClient"
2 import { assert, describe, it } from "@effect/vitest"
3 import { Config, ConfigProvider, Duration, Effect, Layer, Redacted } from "effect"
4 import * as HttpClient from "effect/http/HttpClient"
5 import * as HttpClientError from "effect/http/HttpClientError"
6 import * as HttpClientRequest from "effect/http/HttpClientRequest"
7 import * as HttpClientResponse from "effect/http/HttpClientResponse"
8
9 const payload = {
10 model: "clef-flash",
11 state: "Checkout is down",
12 questions: { urgent: { type: "noul", instructions: "Does this need immediate attention?" } }
13 } as const
14
15 const result = {
16 model: "clef-flash",
17 answers: { urgent: { type: "noul", noul: 0.99 } },
18 usage: { input_tokens: 120, output_tokens: 0 }
19 } as const
20
21 const httpLayer = (
22 handler: (
23 request: HttpClientRequest.HttpClientRequest
24 ) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>
25 ) =>
26 Layer.succeed(
27 HttpClient.HttpClient,
28 HttpClient.makeWith(
29 Effect.flatMap(handler),
30 Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
31 )
32 )
33
34 const clientLayer = (
35 response: (request: HttpClientRequest.HttpClientRequest) => Response,
36 options?: Partial<CloudflareClient.Options>
37 ) =>
38 CloudflareClient.layer({ accountId: "test-account", apiKey: Redacted.make("test-token"), ...options }).pipe(
39 Layer.provide(httpLayer((request) => Effect.succeed(HttpClientResponse.fromWeb(request, response(request)))))
40 )
41
42 const createDecisions = Effect.gen(function*() {
43 const client = yield* CloudflareClient.CloudflareClient
44 return yield* client.createDecisions(payload)
45 })
46
47 describe("CloudflareClient", () => {
48 it.effect("posts decisions to the account model endpoint and unwraps the result envelope", () =>
49 Effect.gen(function*() {
50 const response = yield* createDecisions
51 assert.deepStrictEqual(response, result)
52 }).pipe(Effect.provide(clientLayer((request) => {
53 assert.strictEqual(request.method, "POST")
54 assert.strictEqual(
55 request.url,
56 "https://api.cloudflare.com/client/v4/accounts/test-account/ai/run/@cf/cloudflare/clef-flash"
57 )
58 assert.strictEqual(request.headers.authorization, "Bearer test-token")
59 assert.strictEqual(request.headers["cf-aig-gateway-id"], undefined)
60 assert.strictEqual(request.body._tag, "Uint8Array")
61 if (request.body._tag === "Uint8Array") {
62 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(request.body.body)), payload)
63 }
64 return Response.json({ success: true, result, errors: [], messages: [] })
65 }))))
66
67 it.effect("routes requests through the configured AI Gateway", () =>
68 createDecisions.pipe(
69 Effect.provide(clientLayer((request) => {
70 assert.strictEqual(request.headers["cf-aig-gateway-id"], "test-gateway")
71 return Response.json({ success: true, result })
72 }, { gatewayId: "test-gateway" }))
73 ))
74
75 it.effect("layerConfig reads Cloudflare credentials and AI Gateway configuration from the environment", () =>
76 createDecisions.pipe(
77 Effect.provide(CloudflareClient.layerConfig({
78 apiUrl: Config.String("TEST_API_URL"),
79 transformClient: HttpClient.mapRequest(HttpClientRequest.setHeader("x-test", "configured"))
80 })),
81 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({
82 env: {
83 CLOUDFLARE_ACCOUNT_ID: "configured-account",
84 CLOUDFLARE_API_TOKEN: "configured-token",
85 CLOUDFLARE_AI_GATEWAY_ID: "configured-gateway",
86 TEST_API_URL: "https://example.com/api"
87 }
88 }))),
89 Effect.provide(httpLayer((request) => {
90 assert.strictEqual(
91 request.url,
92 "https://example.com/api/accounts/configured-account/ai/run/@cf/cloudflare/clef-flash"
93 )
94 assert.strictEqual(request.headers.authorization, "Bearer configured-token")
95 assert.strictEqual(request.headers["cf-aig-gateway-id"], "configured-gateway")
96 assert.strictEqual(request.headers["x-test"], "configured")
97 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ success: true, result })))
98 }))
99 ))
100
101 describe("error mapping", () => {
102 for (
103 const [status, tag] of [
104 [401, "AuthenticationError"],
105 [404, "InvalidRequestError"],
106 [422, "InvalidRequestError"],
107 [200, "InternalProviderError"]
108 ] as const
109 ) {
110 it.effect(`maps a failure envelope with HTTP ${status} to ${tag}`, () =>
111 Effect.gen(function*() {
112 const error = yield* Effect.flip(createDecisions)
113 assert.strictEqual(error.module, "CloudflareClient")
114 assert.strictEqual(error.method, "createDecisions")
115 assert.strictEqual(error.reason._tag, tag)
116 if ("http" in error.reason) {
117 assert.strictEqual(error.reason.http?.response?.status, status)
118 assert.notInclude(JSON.stringify(error.reason), "test-token")
119 }
120 if ("description" in error.reason) {
121 assert.include(error.reason.description, "Request failed")
122 assert.include(error.reason.description, "3040")
123 assert.include(error.reason.description, "test-ray")
124 }
125 }).pipe(Effect.provide(clientLayer(() =>
126 Response.json(
127 { success: false, result: null, errors: [{ code: 3040, message: "Request failed" }] },
128 { status, headers: { "cf-ray": "test-ray" } }
129 )
130 ))))
131 }
132
133 it.effect("maps a failure envelope without errors with HTTP 200 to InternalProviderError", () =>
134 Effect.gen(function*() {
135 const error = yield* Effect.flip(createDecisions)
136 assert.strictEqual(error.reason._tag, "InternalProviderError")
137 }).pipe(Effect.provide(clientLayer(() => Response.json({ success: false, result: null })))))
138
139 it.effect("maps 429 to RateLimitError with Retry-After and Cloudflare metadata", () =>
140 Effect.gen(function*() {
141 const error = yield* Effect.flip(createDecisions)
142 assert.strictEqual(error.reason._tag, "RateLimitError")
143 if (error.reason._tag === "RateLimitError") {
144 assert.strictEqual(Duration.toMillis(error.reason.retryAfter!), 2000)
145 assert.deepStrictEqual(error.reason.metadata, {
146 cloudflare: { rayId: "test-ray", errors: [{ code: 3040, message: "Request failed" }] }
147 })
148 }
149 }).pipe(Effect.provide(clientLayer(() =>
150 Response.json(
151 { success: false, result: null, errors: [{ code: 3040, message: "Request failed" }] },
152 { status: 429, headers: { "cf-ray": "test-ray", "retry-after": "2" } }
153 )
154 ))))
155
156 it.effect("maps a non-JSON failure body by HTTP status", () =>
157 Effect.gen(function*() {
158 const error = yield* Effect.flip(createDecisions)
159 assert.strictEqual(error.reason._tag, "InternalProviderError")
160 if (error.reason._tag === "InternalProviderError") {
161 assert.include(error.reason.description, "Bad gateway")
162 }
163 }).pipe(Effect.provide(clientLayer(() => new Response("Bad gateway", { status: 502 })))))
164
165 it.effect("maps a success body without a result envelope to a non-retryable InvalidResponseError", () =>
166 Effect.gen(function*() {
167 const error = yield* Effect.flip(createDecisions)
168 assert.strictEqual(error.reason._tag, "InvalidResponseError")
169 }).pipe(Effect.provide(clientLayer(() => Response.json(result)))))
170
171 it.effect("maps TransportError to NetworkError", () => {
172 const failures: Array<HttpClientError.HttpClientError> = []
173 return Effect.gen(function*() {
174 const error = yield* Effect.flip(createDecisions)
175 assert.strictEqual(error.reason._tag, "NetworkError")
176 assert.strictEqual(error.reason._tag === "NetworkError" && error.reason.cause, failures[0])
177 }).pipe(
178 Effect.provide(CloudflareClient.layer({ accountId: "test-account", apiKey: Redacted.make("test-token") })),
179 Effect.provide(httpLayer((request) => {
180 const error = new HttpClientError.HttpClientError({
181 reason: new HttpClientError.TransportError({ request, cause: new Error("Connection refused") })
182 })
183 failures.push(error)
184 return Effect.fail(error)
185 }))
186 )
187 })
188 })
189 })