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