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

claudeResetCredits.ts

261 lines9.5 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/**
85 * An unanswered or unconfirmed claim retries with the same request id.
86 */
87export const isSettledClaudeResetCreditFailure = (error: unknown) =>
88 isClaudeResetCreditError(error) &&
89 error.reason !== "requestFailed" &&
90 error.reason !== "unconfirmed";
91​
92const isFutureTimestamp = (value: string, nowMs: number) => {
93 if (!COMPLETE_TIMESTAMP.test(value)) return false;
94 const [year, month, day] = value.slice(0, 10).split("-").map(Number);
95 return (
96 Date.parse(value) > nowMs && Date.UTC(year!, month! - 1, day!) <= Date.UTC(year!, month!, 0)
97 );
98};
99​
100export function claudeResetCreditsToContract(
101 block: unknown,
102 nowMs: number,
103): ServerProviderResetCredits | undefined {
104 const parsed = decodeCedarEmber(block);
105 if (Option.isNone(parsed) || !parsed.value.eligible) return undefined;
106 const live = (parsed.value.grants ?? [])
107 .flatMap((raw) => Option.toArray(decodeGrant(raw)))
108 .filter(
109 (grant) =>
110 !grant.paused &&
111 grant.usable_now &&
112 (grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)),
113 );
114 const next = live.find((grant) => grant.id === parsed.value.next_grant_id);
115 const nextExpiresAt = next?.ends_at ? DateTime.make(next.ends_at) : Option.none();
116 return {
117 availableCount: next ? live.reduce((sum, grant) => sum + grant.resets_left, 0) : 0,
118 ...(Option.isSome(nextExpiresAt)
119 ? { nextExpiresAt: DateTime.formatIso(nextExpiresAt.value) }
120 : {}),
121 ...(next ? { nextCreditId: next.id } : {}),
122 };
124​
125const readJson = <S extends Schema.Top>(schema: S, file: string) =>
126 Effect.gen(function* () {
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 = (configDir: string) =>
138 Effect.gen(function* () {
139 if ((yield* HostProcess.Platform) === "darwin") return undefined;
140 const path = yield* Path.Path;
141 const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));
142 return credentials.claudeAiOauth?.accessToken?.trim() || undefined;
143 });
144​
145const withClaudeHeaders = (token: string, version: string) =>
146 HttpClientRequest.setHeaders({
147 authorization: `Bearer ${token}`,
148 "anthropic-beta": "oauth-2025-04-20",
149 "user-agent": `claude-cli/${version} (external, cli)`,
150 });
151​
152export const readClaudeResetCredits = Effect.fn("readClaudeResetCredits")(
153 function* (configDir: string, version: string) {
154 const token = yield* readAccessToken(configDir);
155 if (!token) return undefined;
156 const client = yield* HttpClient.HttpClient;
157 const response = yield* client.execute(
158 HttpClientRequest.get(`${API_BASE}/api/oauth/usage`, {
159 urlParams: { cedar_ember: "1", skip_spend: "1" },
160 }).pipe(withClaudeHeaders(token, version)),
161 );
162 const body = yield* HttpClientResponse.schemaBodyJson(UsageResponse)(
163 yield* HttpClientResponse.filterStatusOk(response),
164 );
165 return claudeResetCreditsToContract(
166 body.cedar_ember,
167 DateTime.toEpochMillis(yield* DateTime.now),
168 );
169 },
170 Effect.timeout("10 seconds"),
171 Effect.orElseSucceed(() => undefined),
172);
173​
174export const readClaudeOrganizationId = (accountConfigPath: string) =>
175 readJson(Config, accountConfigPath).pipe(
176 Effect.map((config) => config.oauthAccount?.organizationUuid?.trim() || undefined),
177 Effect.orElseSucceed(() => undefined),
178 );
179​
180export const claudeAccountConfigPath = Effect.fn("claudeAccountConfigPath")(function* (
181 configDir: string | undefined,
182) {
183 const path = yield* Path.Path;
184 return configDir
185 ? path.join(configDir, ".claude.json")
186 : path.join(yield* HostProcess.HomeDirectory, ".claude.json");
187});
188​
189const CLAIM_OUTCOMES = {
190 reset: "reset",
191 not_limited: "nothingToReset",
192 already_used: "alreadyRedeemed",
193 ineligible: "noCredit",
194} as const satisfies Record<string, ProviderConsumeResetCreditOutcome>;
195​
196/**
197 * `requestId` is the idempotency key: a retry with the same id is the same
198 * claim.
199 */
200export const consumeClaudeResetCredit = Effect.fn("consumeClaudeResetCredit")(function* (input: {
201 readonly configDir: string;
202 readonly accountConfigPath: string;
203 readonly version: string;
204 readonly grantId: string;
205 readonly requestId: string;
206}) {
207 if (!GRANT_ID.test(input.grantId) || !REQUEST_ID.test(input.requestId)) {
208 return yield* new ClaudeResetCreditError({ reason: "malformedCredit" });
209 }
210 const token = yield* readAccessToken(input.configDir).pipe(
211 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "loginUnreadable", cause })),
212 );
213 const config = yield* readJson(Config, input.accountConfigPath).pipe(
214 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "accountUnreadable", cause })),
215 );
216 const organization = config.oauthAccount?.organizationUuid?.trim();
217 if (!token || !organization) {
218 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
219 }
220 const client = yield* HttpClient.HttpClient;
221 const response = yield* client
222 .execute(
223 HttpClientRequest.post(
224 new URL(
225 `/api/organizations/${encodeURIComponent(organization)}/reset_rate_limits`,
226 API_BASE,
227 ),
228 ).pipe(
229 withClaudeHeaders(token, input.version),
230 HttpClientRequest.bodyJsonUnsafe({
231 program: PROGRAM,
232 grant_id: input.grantId,
233 request_id: input.requestId,
234 }),
235 ),
236 )
237 .pipe(
238 Effect.timeout("25 seconds"),
239 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
240 );
241 if (response.status === 429) {
242 return yield* new ClaudeResetCreditError({ reason: "rateLimited" });
243 }
244 if (response.status === 401 || response.status === 403) {
245 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
246 }
247 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
248 Effect.flatMap(HttpClientResponse.schemaBodyJson(ClaimResponse)),
249 Effect.timeout("25 seconds"),
250 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
251 );
252 if (body.result === "cooldown") {
253 return yield* new ClaudeResetCreditError({ reason: "coolingDown" });
254 }
255 // Claude could not say whether the claim landed, so, like the CLI, keep the
256 // request id and let the retry ask about the same claim.
257 if (body.result === "unavailable") {
258 return yield* new ClaudeResetCreditError({ reason: "unconfirmed" });
259 }
260 return CLAIM_OUTCOMES[body.result];
261});