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