@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 315 lines 10.1 KB
Raw
1 import * as AiError from "effect/ai/AiError"
2 import * as Clock from "effect/Clock"
3 import type * as Duration from "effect/Duration"
4 import * as Effect from "effect/Effect"
5 import type * as Sse from "effect/encoding/Sse"
6 import { dual } from "effect/Function"
7 import * as Headers from "effect/http/Headers"
8 import type * as HttpClientError from "effect/http/HttpClientError"
9 import type * as HttpClientResponse from "effect/http/HttpClientResponse"
10 import * as Number from "effect/Number"
11 import * as Option from "effect/Option"
12 import * as Predicate from "effect/Predicate"
13 import * as Redactable from "effect/Redactable"
14 import * as Result from "effect/Result"
15 import * as Schema from "effect/Schema"
16 import type { OpenAiErrorMetadata } from "../OpenAiError.ts"
17
18 // =============================================================================
19 // OpenAI Error Body Schema
20 // =============================================================================
21
22 /** @internal */
23 export const OpenAiErrorBody = Schema.Struct({
24 error: Schema.Struct({
25 message: Schema.String,
26 type: Schema.optional(Schema.NullOr(Schema.String)),
27 param: Schema.optional(Schema.NullOr(Schema.String)),
28 code: Schema.optional(Schema.NullOr(Schema.String))
29 })
30 })
31
32 const OpenAiCompatibleErrorBody = Schema.Struct({
33 error: Schema.String,
34 code: Schema.optional(Schema.String)
35 })
36
37 // =============================================================================
38 // Error Mappers
39 // =============================================================================
40
41 /** @internal */
42 export const mapSchemaError = dual<
43 (method: string) => (error: Schema.SchemaError) => AiError.AiError,
44 (error: Schema.SchemaError, method: string) => AiError.AiError
45 >(2, (error, method) =>
46 AiError.make({
47 module: "OpenAiClient",
48 method,
49 reason: AiError.InvalidResponseError.fromSchemaError(error)
50 }))
51
52 /** @internal */
53 export const mapSseError = dual<
54 (method: string) => (error: Sse.SseError) => AiError.AiError,
55 (error: Sse.SseError, method: string) => AiError.AiError
56 >(2, (error, method) =>
57 AiError.make({
58 module: "OpenAiClient",
59 method,
60 reason: new AiError.InvalidResponseError({ description: error.message })
61 }))
62
63 /** @internal */
64 export const mapHttpClientError = dual<
65 (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect<never, AiError.AiError>,
66 (error: HttpClientError.HttpClientError, method: string) => Effect.Effect<never, AiError.AiError>
67 >(2, (error, method) => {
68 const reason = error.reason
69 switch (reason._tag) {
70 case "TransportError":
71 case "EncodeError":
72 case "InvalidUrlError": {
73 return Effect.fail(AiError.make({
74 module: "OpenAiClient",
75 method,
76 reason: AiError.NetworkError.fromHttpClientError(
77 error as HttpClientError.HttpClientError & { readonly reason: typeof reason }
78 )
79 }))
80 }
81 case "StatusCodeError": {
82 return mapStatusCodeError(reason, method)
83 }
84 case "DecodeError": {
85 return Effect.fail(AiError.make({
86 module: "OpenAiClient",
87 method,
88 reason: new AiError.InvalidOutputError({
89 description: reason.description ?? "Failed to decode response"
90 })
91 }))
92 }
93 case "EmptyBodyError": {
94 return Effect.fail(AiError.make({
95 module: "OpenAiClient",
96 method,
97 reason: new AiError.InvalidOutputError({
98 description: reason.description ?? "Response body was empty"
99 })
100 }))
101 }
102 }
103 })
104
105 /** @internal */
106 const mapStatusCodeError = Effect.fnUntraced(function*(
107 error: HttpClientError.StatusCodeError,
108 method: string
109 ) {
110 const { request, response, description } = error
111 const status = response.status
112 const headers = response.headers as Record<string, string>
113 const requestId = headers["x-request-id"]
114
115 // Try to get the actual response body. The description from filterStatusOk
116 // is often just "non 2xx status code", so try reading from response.text
117 let body: string | undefined = description
118 if (!description || !description.startsWith("{")) {
119 const responseBody = yield* Effect.option(response.text)
120 if (Option.isSome(responseBody) && responseBody.value) {
121 body = responseBody.value
122 }
123 }
124
125 // Try to parse the body as JSON to extract error details
126 let json: unknown = undefined
127 // @effect-diagnostics effect/tryCatchInEffectGen:off
128 try {
129 json = Predicate.isNotUndefined(body) ? JSON.parse(body) : undefined
130 } catch {
131 json = undefined
132 }
133 const decoded = Schema.decodeUnknownOption(OpenAiErrorBody)(json)
134 const compatibleDecoded = Schema.decodeUnknownOption(OpenAiCompatibleErrorBody)(json)
135 const message = Option.isSome(decoded)
136 ? decoded.value.error.message
137 : Option.isSome(compatibleDecoded)
138 ? compatibleDecoded.value.error
139 : undefined
140 const errorCode = Option.isSome(decoded)
141 ? decoded.value.error.code ?? null
142 : Option.isSome(compatibleDecoded)
143 ? compatibleDecoded.value.code ?? null
144 : null
145
146 const now = yield* Clock.currentTimeMillis
147 const reason = mapStatusCodeToReason({
148 now,
149 status,
150 method: request.method,
151 url: request.url,
152 headers,
153 message,
154 http: buildHttpContext({ response, body }),
155 metadata: {
156 errorCode,
157 errorType: Option.isSome(decoded) ? decoded.value.error.type ?? null : null,
158 requestId: requestId ?? null
159 }
160 })
161
162 return yield* AiError.make({ module: "OpenAiClient", method, reason })
163 })
164
165 // =============================================================================
166 // Rate Limits
167 // =============================================================================
168
169 const retryAfterFromHeader = (raw: string, now: number): Duration.Duration | undefined => {
170 const retryAfter = Headers.parseRetryAfter(raw)
171 return Result.isSuccess(retryAfter) ? Headers.retryAfterDelay(retryAfter.success, now) : undefined
172 }
173
174 /** @internal */
175 export const parseRateLimitHeaders = (headers: Record<string, string>, now: number) => {
176 const retryAfterRaw = headers["retry-after"]
177 // an invalid Retry-After is treated as absent
178 const retryAfter = retryAfterRaw === undefined ? undefined : retryAfterFromHeader(retryAfterRaw, now)
179 const remainingRaw = headers["x-ratelimit-remaining-requests"]
180 const remaining = Predicate.isNotUndefined(remainingRaw)
181 ? Option.getOrNull(Number.parse(remainingRaw))
182 : null
183 return {
184 retryAfter,
185 limit: headers["x-ratelimit-limit-requests"] ?? null,
186 remaining,
187 resetRequests: headers["x-ratelimit-reset-requests"] ?? null,
188 resetTokens: headers["x-ratelimit-reset-tokens"] ?? null
189 }
190 }
191
192 // =============================================================================
193 // HTTP Context
194 // =============================================================================
195
196 /** @internal */
197 export const buildHttpContext = (params: {
198 readonly response?: HttpClientResponse.HttpClientResponse
199 readonly body?: string | undefined
200 }): typeof AiError.HttpContext.Type => ({
201 response: Predicate.isNotUndefined(params.response)
202 ? {
203 status: params.response.status,
204 headers: Redactable.redact(params.response.headers) as Record<string, string>
205 }
206 : undefined,
207 body: params.body
208 })
209
210 // =============================================================================
211 // HTTP Status Code
212 // =============================================================================
213
214 /** @internal */
215 export const mapStatusCodeToReason = ({ status, method, url, headers, message, metadata, http, now }: {
216 readonly status: number
217 /** Current time in epoch milliseconds, used to measure a Retry-After date. */
218 readonly now: number
219 readonly method: string
220 readonly url: string
221 readonly headers: Record<string, string>
222 readonly message: string | undefined
223 readonly metadata: OpenAiErrorMetadata
224 readonly http: typeof AiError.HttpContext.Type
225 }): AiError.AiErrorReason => {
226 const errorDescription = AiError.buildErrorDescription({
227 status,
228 message,
229 method,
230 url,
231 errorCode: metadata.errorCode,
232 errorType: metadata.errorType,
233 requestId: metadata.requestId,
234 body: http.body
235 })
236
237 switch (status) {
238 case 400:
239 return new AiError.InvalidRequestError({
240 description: errorDescription,
241 metadata: { openai: metadata },
242 http
243 })
244 case 401:
245 return new AiError.AuthenticationError({
246 kind: "InvalidKey",
247 description: errorDescription,
248 metadata: { openai: metadata },
249 http
250 })
251 case 403:
252 return new AiError.AuthenticationError({
253 kind: "InsufficientPermissions",
254 description: errorDescription,
255 metadata: { openai: metadata },
256 http
257 })
258 case 404:
259 return new AiError.InvalidRequestError({
260 description: errorDescription,
261 metadata: { openai: metadata },
262 http
263 })
264 case 409:
265 case 422:
266 return new AiError.InvalidRequestError({
267 description: errorDescription,
268 metadata: { openai: metadata },
269 http
270 })
271 case 402:
272 return new AiError.QuotaExhaustedError({
273 metadata: { openai: metadata },
274 http
275 })
276 case 429: {
277 // Best-effort detection: OpenAI returns insufficient_quota for billing/quota issues
278 if (
279 metadata.errorCode === "insufficient_quota" ||
280 metadata.errorType === "insufficient_quota" ||
281 metadata.errorCode === "billing_insufficient_balance" ||
282 metadata.errorType === "billing_insufficient_balance"
283 ) {
284 return new AiError.QuotaExhaustedError({
285 metadata: { openai: metadata },
286 http
287 })
288 }
289 const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers, now)
290 return new AiError.RateLimitError({
291 retryAfter,
292 metadata: {
293 openai: {
294 ...metadata,
295 ...rateLimitMetadata
296 }
297 },
298 http
299 })
300 }
301 default:
302 if (status >= 500) {
303 return new AiError.InternalProviderError({
304 description: message ?? "Server error",
305 metadata: { openai: metadata },
306 http
307 })
308 }
309 return new AiError.UnknownError({
310 description: message,
311 metadata: { openai: metadata },
312 http
313 })
314 }
315 }