@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 305 lines 10.8 KB
Raw
1 import { AnthropicClient } from "@effect/ai-anthropic"
2 import * as Errors from "@effect/ai-anthropic/internal/errors"
3 import { assert, describe, it } from "@effect/vitest"
4 import { Context, Duration, Effect, Layer, Redacted, type Schema } from "effect"
5 import { HttpClient, type HttpClientError, type HttpClientRequest, HttpClientResponse } from "effect/http"
6
7 describe("AnthropicClient", () => {
8 it.effect("maps a gateway 400 without an Anthropic error envelope", () =>
9 Effect.gen(function*() {
10 const client = yield* AnthropicClient.AnthropicClient
11 const error = yield* client.createMessage({
12 payload: {
13 model: "claude-sonnet-4-20250514",
14 max_tokens: 1,
15 messages: [{ role: "user", content: "hello" }]
16 }
17 }).pipe(Effect.flip)
18
19 assert.strictEqual(error.reason._tag, "InvalidRequestError")
20 if (error.reason._tag !== "InvalidRequestError") return
21 assert.include(error.reason.description ?? "", "HTTP 400")
22 assert.include(error.reason.description ?? "", "gateway rejected request")
23 assert.strictEqual(error.reason.http?.response?.status, 400)
24 }).pipe(Effect.provide(makeTestLayer({
25 _tag: "Json",
26 status: 400,
27 body: { error: { message: "gateway rejected request" } }
28 }))))
29
30 it.effect("maps a gateway 429 without an Anthropic error envelope and preserves retry-after", () =>
31 Effect.gen(function*() {
32 const client = yield* AnthropicClient.AnthropicClient
33 const error = yield* client.createMessage({
34 payload: {
35 model: "claude-sonnet-4-20250514",
36 max_tokens: 1,
37 messages: [{ role: "user", content: "hello" }]
38 }
39 }).pipe(Effect.flip)
40
41 assert.strictEqual(error.reason._tag, "RateLimitError")
42 if (error.reason._tag !== "RateLimitError") return
43 assert.strictEqual(Duration.toMillis(error.reason.retryAfter!), 3000)
44 assert.strictEqual(error.reason.http?.response?.status, 429)
45 }).pipe(Effect.provide(makeTestLayer({
46 _tag: "Json",
47 status: 429,
48 headers: { "retry-after": "3" },
49 body: { error: { message: "gateway rate limit" } }
50 }))))
51
52 it.effect.each([
53 { name: "ignores a negative Retry-After", header: "-5", expected: undefined },
54 { name: "ignores a non-finite Retry-After", header: "Infinity", expected: undefined },
55 { name: "honors an HTTP-date Retry-After", header: "Thu, 01 Jan 1970 00:00:30 GMT", expected: 30_000 }
56 ])("$name", ({ expected, header }) =>
57 Effect.gen(function*() {
58 const client = yield* AnthropicClient.AnthropicClient
59 const error = yield* client.createMessage({
60 payload: {
61 model: "claude-sonnet-4-20250514",
62 max_tokens: 1,
63 messages: [{ role: "user", content: "hello" }]
64 }
65 }).pipe(Effect.flip)
66
67 assert.strictEqual(error.reason._tag, "RateLimitError")
68 if (error.reason._tag !== "RateLimitError") return
69 assert.strictEqual(
70 error.reason.retryAfter === undefined ? undefined : Duration.toMillis(error.reason.retryAfter),
71 expected
72 )
73 }).pipe(Effect.provide(makeTestLayer({
74 _tag: "Json",
75 status: 429,
76 headers: { "retry-after": header },
77 body: { error: { message: "gateway rate limit" } }
78 }))))
79
80 it.effect("maps a 429 Anthropic error envelope with a non-rate-limit type and preserves retry-after", () =>
81 Effect.gen(function*() {
82 const client = yield* AnthropicClient.AnthropicClient
83 const error = yield* client.createMessage({
84 payload: {
85 model: "claude-sonnet-4-20250514",
86 max_tokens: 1,
87 messages: [{ role: "user", content: "hello" }]
88 }
89 }).pipe(Effect.flip)
90
91 assert.strictEqual(error.reason._tag, "RateLimitError")
92 if (error.reason._tag !== "RateLimitError") return
93 assert.strictEqual(Duration.toMillis(error.reason.retryAfter!), 3000)
94 assert.strictEqual(error.reason.http?.response?.status, 429)
95 }).pipe(Effect.provide(makeTestLayer({
96 _tag: "Json",
97 status: 429,
98 headers: { "retry-after": "3" },
99 body: { type: "error", error: { type: "api_error", message: "gateway message" }, request_id: "req-test" }
100 }))))
101
102 it.effect("redacts the API key in AI error context", () =>
103 Effect.gen(function*() {
104 const client = yield* AnthropicClient.AnthropicClient
105
106 const result = yield* client.createMessage({
107 payload: {
108 model: "claude-sonnet-4-20250514",
109 max_tokens: 1,
110 messages: [{ role: "user", content: "hello" }]
111 }
112 }).pipe(Effect.flip)
113
114 assert.strictEqual(result.reason._tag, "InvalidRequestError")
115 const requests = yield* MockHttpClient.requests
116 assert.include(requests[0]?.url, "/v1/messages")
117 assert.notInclude(JSON.stringify(result), "sk-test-key")
118 }).pipe(Effect.provide(makeTestLayer({
119 _tag: "Json",
120 status: 400,
121 body: {
122 type: "error",
123 error: {
124 type: "invalid_request_error",
125 message: "Bad request"
126 },
127 request_id: null
128 }
129 }))))
130
131 it.effect("surfaces the provider message on 401 AuthenticationError", () =>
132 Effect.gen(function*() {
133 const client = yield* AnthropicClient.AnthropicClient
134
135 const result = yield* client.createMessage({
136 payload: {
137 model: "claude-sonnet-4-20250514",
138 max_tokens: 1,
139 messages: [{ role: "user", content: "hello" }]
140 }
141 }).pipe(Effect.flip)
142
143 assert.strictEqual(result.reason._tag, "AuthenticationError")
144 if (result.reason._tag !== "AuthenticationError") {
145 return yield* Effect.die(new Error("Expected AuthenticationError"))
146 }
147 assert.strictEqual(result.reason.kind, "InvalidKey")
148 assert.deepStrictEqual(result.reason.metadata?.anthropic, {
149 errorType: "authentication_error",
150 requestId: "req_anthropic"
151 })
152 assert.strictEqual(
153 result.reason.description,
154 "invalid x-api-key (POST https://api.anthropic.com/v1/messages?beta=true) [type: authentication_error] [requestId: req_anthropic]"
155 )
156 assert.include(result.reason.message, "invalid x-api-key")
157 assert.strictEqual(
158 result.reason.message,
159 "InvalidKey: Verify your API key is correct. invalid x-api-key (POST https://api.anthropic.com/v1/messages?beta=true) [type: authentication_error] [requestId: req_anthropic]"
160 )
161 }).pipe(Effect.provide(makeTestLayer({
162 _tag: "Json",
163 status: 401,
164 body: {
165 type: "error",
166 error: { type: "authentication_error", message: "invalid x-api-key" },
167 request_id: "req_anthropic"
168 }
169 }))))
170
171 it("preserves and truncates a fallback HTTP response", () => {
172 const body = `${"a".repeat(200)}b`
173 const reason = Errors.mapStatusCodeToReason({
174 now: 0,
175 status: 400,
176 headers: {},
177 message: undefined,
178 metadata: { errorType: null, requestId: null },
179 method: "POST",
180 url: "https://api.anthropic.com/v1/messages?beta=true",
181 http: { body }
182 })
183
184 assert.strictEqual(reason._tag, "InvalidRequestError")
185 if (reason._tag !== "InvalidRequestError") {
186 throw new Error("Expected InvalidRequestError")
187 }
188 assert.strictEqual(
189 reason.description,
190 `HTTP 400 (POST https://api.anthropic.com/v1/messages?beta=true) Response: ${"a".repeat(200)}...`
191 )
192 })
193
194 it.effect("surfaces the provider message on 403 AuthenticationError", () =>
195 Effect.gen(function*() {
196 const client = yield* AnthropicClient.AnthropicClient
197
198 const result = yield* client.createMessage({
199 payload: {
200 model: "claude-sonnet-4-20250514",
201 max_tokens: 1,
202 messages: [{ role: "user", content: "hello" }]
203 }
204 }).pipe(Effect.flip)
205
206 assert.strictEqual(result.reason._tag, "AuthenticationError")
207 if (result.reason._tag !== "AuthenticationError") {
208 return yield* Effect.die(new Error("Expected AuthenticationError"))
209 }
210 assert.strictEqual(result.reason.kind, "InsufficientPermissions")
211 assert.include(result.reason.description ?? "", "not available for this account")
212 assert.include(result.reason.message, "not available for this account")
213 }).pipe(Effect.provide(makeTestLayer({
214 _tag: "Json",
215 status: 403,
216 body: {
217 type: "error",
218 error: {
219 type: "permission_error",
220 message: "claude-sonnet-4-20250514 is not available for this account"
221 },
222 request_id: null
223 }
224 }))))
225 })
226
227 type MockResponse =
228 | {
229 readonly _tag: "Json"
230 readonly body: Schema.Json
231 readonly status?: number | undefined
232 readonly headers?: Record<string, string> | undefined
233 }
234 | {
235 readonly _tag: "Sse"
236 readonly events: ReadonlyArray<Schema.Json>
237 readonly status?: number | undefined
238 readonly headers?: Record<string, string> | undefined
239 }
240
241 class MockAnthropicResponse extends Context.Service<MockAnthropicResponse, {
242 readonly response: MockResponse
243 }>()("MockAnthropicResponse") {}
244
245 class MockHttpClient extends Context.Service<MockHttpClient, {
246 readonly requests: Effect.Effect<ReadonlyArray<HttpClientRequest.HttpClientRequest>>
247 }>()("MockHttpClient") {
248 static requests = MockHttpClient.use((client) => client.requests)
249 }
250
251 const makeHttpClientContext = Effect.gen(function*() {
252 const capturedRequests: Array<HttpClientRequest.HttpClientRequest> = []
253 const mock = yield* MockAnthropicResponse
254
255 const httpClient = HttpClient.makeWith(
256 Effect.fnUntraced(function*(requestEffect) {
257 const request = yield* requestEffect
258 capturedRequests.push(request)
259 return makeResponse(request, mock.response)
260 }),
261 Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
262 )
263
264 const mockHttpClient: MockHttpClient["Service"] = {
265 requests: Effect.sync(() => capturedRequests)
266 }
267
268 return Context.make(HttpClient.HttpClient, httpClient).pipe(
269 Context.add(MockHttpClient, mockHttpClient)
270 )
271 })
272
273 const HttpClientLayer = Layer.effectContext(makeHttpClientContext)
274
275 const makeTestLayer = (
276 response: MockResponse,
277 options: AnthropicClient.Options = { apiKey: Redacted.make("sk-test-key") }
278 ) =>
279 AnthropicClient.layer(options).pipe(
280 Layer.provideMerge(HttpClientLayer),
281 Layer.provide(Layer.succeed(MockAnthropicResponse, { response }))
282 )
283
284 const makeResponse = (
285 request: HttpClientRequest.HttpClientRequest,
286 response: MockResponse
287 ): HttpClientResponse.HttpClientResponse => {
288 const contentType = response._tag === "Json"
289 ? "application/json"
290 : "text/event-stream"
291 const body = response._tag === "Json"
292 ? JSON.stringify(response.body)
293 : response.events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")
294
295 return HttpClientResponse.fromWeb(
296 request,
297 new Response(body, {
298 status: response.status ?? 200,
299 headers: {
300 "content-type": contentType,
301 ...response.headers
302 }
303 })
304 )
305 }