Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

claudeResetCredits.ts

258 lines9.4 KB

1import type {
2 ProviderConsumeResetCreditOutcome,
3 ServerProviderResetCredits,
4} from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
13​
14const API_BASE = "https://api.anthropic.com";
15const PROGRAM = "cedar_ember";
16const GRANT_ID = /^[a-z0-9_-]{1,40}$/;
17const REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/;
18const COMPLETE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
19​
20const Credentials = Schema.Struct({
21 claudeAiOauth: Schema.optional(Schema.Struct({ accessToken: Schema.optional(Schema.String) })),
22});
23const Config = Schema.Struct({
24 oauthAccount: Schema.optional(
25 Schema.Struct({ organizationUuid: Schema.optional(Schema.String) }),
26 ),
27});
28const Grant = Schema.Struct({
29 id: Schema.String.check(Schema.isPattern(GRANT_ID)),
30 resets_left: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
31 ends_at: Schema.optional(Schema.NullOr(Schema.String)),
32 paused: Schema.optional(Schema.Boolean),
33 usable_now: Schema.optional(Schema.Boolean),
34});
35const decodeGrant = Schema.decodeUnknownOption(Grant);
36const CedarEmber = Schema.Struct({
37 eligible: Schema.Boolean,
38 grants: Schema.optional(Schema.Array(Schema.Unknown)),
39 next_grant_id: Schema.optional(Schema.NullOr(Schema.String)),
40});
41const UsageResponse = Schema.Struct({
42 cedar_ember: Schema.optional(Schema.NullOr(Schema.Unknown)),
43});
44const decodeCedarEmber = Schema.decodeUnknownOption(CedarEmber);
45const ClaimResponse = Schema.Struct({
46 result: Schema.Literals([
47 "reset",
48 "already_used",
49 "not_limited",
50 "cooldown",
51 "ineligible",
52 "unavailable",
53 ]),
54});
55​
56const RESET_CREDIT_FAILURES = {
57 malformedCredit: "Claude returned a malformed reset credit.",
58 loginUnreadable: "Claude could not read its login.",
59 accountUnreadable: "Claude could not read its account.",
60 signedOut: "Sign in to Claude again to redeem resets.",
61 rateLimited: "Claude is rate limiting resets. Try again soon.",
62 coolingDown: "Claude resets are cooling down. Try again later.",
63 unconfirmed:
64 "Claude could not confirm the reset. If you are still limited in a moment, try again.",
65 requestFailed: "Claude could not redeem the reset.",
66} as const;
67​
68class ClaudeResetCreditError extends Schema.TaggedError<ClaudeResetCreditError>()(
69 "ClaudeResetCreditError",
70 {
71 reason: Schema.Literals(
72 Object.keys(RESET_CREDIT_FAILURES) as Array<keyof typeof RESET_CREDIT_FAILURES>,
73 ),
74 cause: Schema.optional(Schema.Defect()),
75 },
76) {
77 override get message(): string {
78 return RESET_CREDIT_FAILURES[this.reason];
79 }
81​
82const isClaudeResetCreditError = Schema.is(ClaudeResetCreditError);
83​
84/** Retry unanswered or unconfirmed claims with the same request ID. */
85export const isSettledClaudeResetCreditFailure = (error: unknown) =>
86 isClaudeResetCreditError(error) &&
87 error.reason !== "requestFailed" &&
88 error.reason !== "unconfirmed";
89​
90const isFutureTimestamp = (value: string, nowMs: number) => {
91 if (!COMPLETE_TIMESTAMP.test(value)) return false;
92 const [year, month, day] = value.slice(0, 10).split("-").map(Number);
93 return (
94 Date.parse(value) > nowMs && Date.UTC(year!, month! - 1, day!) <= Date.UTC(year!, month!, 0)
95 );
96};
97​
98export function claudeResetCreditsToContract(
99 block: unknown,
100 nowMs: number,
101): ServerProviderResetCredits | undefined {
102 const parsed = decodeCedarEmber(block);
103 if (Option.isNone(parsed) || !parsed.value.eligible) return undefined;
104 const live = (parsed.value.grants ?? [])
105 .flatMap((raw) => Option.toArray(decodeGrant(raw)))
106 .filter(
107 (grant) =>
108 !grant.paused &&
109 grant.usable_now &&
110 (grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)),
111 );
112 const next = live.find((grant) => grant.id === parsed.value.next_grant_id);
113 const nextExpiresAt = next?.ends_at ? DateTime.make(next.ends_at) : Option.none();
114 return {
115 availableCount: next ? live.reduce((sum, grant) => sum + grant.resets_left, 0) : 0,
116 ...(Option.isSome(nextExpiresAt)
117 ? { nextExpiresAt: DateTime.formatIso(nextExpiresAt.value) }
118 : {}),
119 ...(next ? { nextCreditId: next.id } : {}),
120 };
122​
123const readJson = Effect.fn("claudeResetCredits.readJson")(function* <S extends Schema.Top>(
124 schema: S,
125 file: string,
126) {
127 const fs = yield* FileSystem.FileSystem;
128 return yield* fs.readFileString(file).pipe(
129 Effect.catchTags({
130 PlatformError: (error) =>
131 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
132 }),
133 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),
134 );
135});
136​
137const readAccessToken = Effect.fn("claudeResetCredits.readAccessToken")(function* (
138 configDir: string,
139) {
140 if ((yield* HostProcess.Platform) === "darwin") return undefined;
141 const path = yield* Path.Path;
142 const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));
143 return credentials.claudeAiOauth?.accessToken?.trim() || undefined;
144});
145​
146const withClaudeHeaders = (token: string, version: string) =>
147 HttpClientRequest.setHeaders({
148 authorization: `Bearer ${token}`,
149 "anthropic-beta": "oauth-2025-04-20",
150 "user-agent": `claude-cli/${version} (external, cli)`,
151 });
152​
153export const readClaudeResetCredits = Effect.fn("readClaudeResetCredits")(
154 function* (configDir: string, version: string) {
155 const token = yield* readAccessToken(configDir);
156 if (!token) return undefined;
157 const client = yield* HttpClient.HttpClient;
158 const response = yield* client.execute(
159 HttpClientRequest.get(`${API_BASE}/api/oauth/usage`, {
160 urlParams: { cedar_ember: "1", skip_spend: "1" },
161 }).pipe(withClaudeHeaders(token, version)),
162 );
163 const body = yield* HttpClientResponse.schemaBodyJson(UsageResponse)(
164 yield* HttpClientResponse.filterStatusOk(response),
165 );
166 return claudeResetCreditsToContract(
167 body.cedar_ember,
168 DateTime.toEpochMillis(yield* DateTime.now),
169 );
170 },
171 Effect.timeout("10 seconds"),
172 Effect.orElseSucceed(() => undefined),
173);
174​
175export const readClaudeOrganizationId = (accountConfigPath: string) =>
176 readJson(Config, accountConfigPath).pipe(
177 Effect.map((config) => config.oauthAccount?.organizationUuid?.trim() || undefined),
178 Effect.orElseSucceed(() => undefined),
179 );
180​
181export const claudeAccountConfigPath = Effect.fn("claudeAccountConfigPath")(function* (
182 configDir: string | undefined,
183) {
184 const path = yield* Path.Path;
185 return configDir
186 ? path.join(configDir, ".claude.json")
187 : path.join(yield* HostProcess.HomeDirectory, ".claude.json");
188});
189​
190const CLAIM_OUTCOMES = {
191 reset: "reset",
192 not_limited: "nothingToReset",
193 already_used: "alreadyRedeemed",
194 ineligible: "noCredit",
195} as const satisfies Record<string, ProviderConsumeResetCreditOutcome>;
196​
197/** requestId is the claim's idempotency key. */
198export const consumeClaudeResetCredit = Effect.fn("consumeClaudeResetCredit")(function* (input: {
199 readonly configDir: string;
200 readonly accountConfigPath: string;
201 readonly version: string;
202 readonly grantId: string;
203 readonly requestId: string;
204}) {
205 if (!GRANT_ID.test(input.grantId) || !REQUEST_ID.test(input.requestId)) {
206 return yield* new ClaudeResetCreditError({ reason: "malformedCredit" });
207 }
208 const token = yield* readAccessToken(input.configDir).pipe(
209 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "loginUnreadable", cause })),
210 );
211 const config = yield* readJson(Config, input.accountConfigPath).pipe(
212 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "accountUnreadable", cause })),
213 );
214 const organization = config.oauthAccount?.organizationUuid?.trim();
215 if (!token || !organization) {
216 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
217 }
218 const client = yield* HttpClient.HttpClient;
219 const response = yield* client
220 .execute(
221 HttpClientRequest.post(
222 new URL(
223 `/api/organizations/${encodeURIComponent(organization)}/reset_rate_limits`,
224 API_BASE,
225 ),
226 ).pipe(
227 withClaudeHeaders(token, input.version),
228 HttpClientRequest.bodyJsonUnsafe({
229 program: PROGRAM,
230 grant_id: input.grantId,
231 request_id: input.requestId,
232 }),
233 ),
234 )
235 .pipe(
236 Effect.timeout("25 seconds"),
237 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
238 );
239 if (response.status === 429) {
240 return yield* new ClaudeResetCreditError({ reason: "rateLimited" });
241 }
242 if (response.status === 401 || response.status === 403) {
243 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
244 }
245 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
246 Effect.flatMap(HttpClientResponse.schemaBodyJson(ClaimResponse)),
247 Effect.timeout("25 seconds"),
248 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
249 );
250 if (body.result === "cooldown") {
251 return yield* new ClaudeResetCreditError({ reason: "coolingDown" });
252 }
253 // Unknown outcomes retain the request ID so retries address the same claim.
254 if (body.result === "unavailable") {
255 return yield* new ClaudeResetCreditError({ reason: "unconfirmed" });
256 }
257 return CLAIM_OUTCOMES[body.result];
258});