Open History to see the last commit
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 }
80}
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 };
123}
124
125const readJson = Effect.fn("claudeResetCredits.readJson")(function* <S extends Schema.Top>(
126 schema: S,
127 file: string,
128) {
129 const fs = yield* FileSystem.FileSystem;
130 return yield* fs.readFileString(file).pipe(
131 Effect.catchTags({
132 PlatformError: (error) =>
133 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
134 }),
135 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),
136 );
137});
138
139const readAccessToken = Effect.fn("claudeResetCredits.readAccessToken")(function* (
140 configDir: string,
141) {
142 if ((yield* HostProcess.Platform) === "darwin") return undefined;
143 const path = yield* Path.Path;
144 const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));
145 return credentials.claudeAiOauth?.accessToken?.trim() || undefined;
146});
147
148const withClaudeHeaders = (token: string, version: string) =>
149 HttpClientRequest.setHeaders({
150 authorization: `Bearer ${token}`,
151 "anthropic-beta": "oauth-2025-04-20",
152 "user-agent": `claude-cli/${version} (external, cli)`,
153 });
154
155export const readClaudeResetCredits = Effect.fn("readClaudeResetCredits")(
156 function* (configDir: string, version: string) {
157 const token = yield* readAccessToken(configDir);
158 if (!token) return undefined;
159 const client = yield* HttpClient.HttpClient;
160 const response = yield* client.execute(
161 HttpClientRequest.get(`${API_BASE}/api/oauth/usage`, {
162 urlParams: { cedar_ember: "1", skip_spend: "1" },
163 }).pipe(withClaudeHeaders(token, version)),
164 );
165 const body = yield* HttpClientResponse.schemaBodyJson(UsageResponse)(
166 yield* HttpClientResponse.filterStatusOk(response),
167 );
168 return claudeResetCreditsToContract(
169 body.cedar_ember,
170 DateTime.toEpochMillis(yield* DateTime.now),
171 );
172 },
173 Effect.timeout("10 seconds"),
174 Effect.orElseSucceed(() => undefined),
175);
176
177export const readClaudeOrganizationId = (accountConfigPath: string) =>
178 readJson(Config, accountConfigPath).pipe(
179 Effect.map((config) => config.oauthAccount?.organizationUuid?.trim() || undefined),
180 Effect.orElseSucceed(() => undefined),
181 );
182
183export const claudeAccountConfigPath = Effect.fn("claudeAccountConfigPath")(function* (
184 configDir: string | undefined,
185) {
186 const path = yield* Path.Path;
187 return configDir
188 ? path.join(configDir, ".claude.json")
189 : path.join(yield* HostProcess.HomeDirectory, ".claude.json");
190});
191
192const CLAIM_OUTCOMES = {
193 reset: "reset",
194 not_limited: "nothingToReset",
195 already_used: "alreadyRedeemed",
196 ineligible: "noCredit",
197} as const satisfies Record<string, ProviderConsumeResetCreditOutcome>;
198
199/**
200 * `requestId` is the idempotency key: a retry with the same id is the same
201 * claim.
202 */
203export const consumeClaudeResetCredit = Effect.fn("consumeClaudeResetCredit")(function* (input: {
204 readonly configDir: string;
205 readonly accountConfigPath: string;
206 readonly version: string;
207 readonly grantId: string;
208 readonly requestId: string;
209}) {
210 if (!GRANT_ID.test(input.grantId) || !REQUEST_ID.test(input.requestId)) {
211 return yield* new ClaudeResetCreditError({ reason: "malformedCredit" });
212 }
213 const token = yield* readAccessToken(input.configDir).pipe(
214 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "loginUnreadable", cause })),
215 );
216 const config = yield* readJson(Config, input.accountConfigPath).pipe(
217 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "accountUnreadable", cause })),
218 );
219 const organization = config.oauthAccount?.organizationUuid?.trim();
220 if (!token || !organization) {
221 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
222 }
223 const client = yield* HttpClient.HttpClient;
224 const response = yield* client
225 .execute(
226 HttpClientRequest.post(
227 new URL(
228 `/api/organizations/${encodeURIComponent(organization)}/reset_rate_limits`,
229 API_BASE,
230 ),
231 ).pipe(
232 withClaudeHeaders(token, input.version),
233 HttpClientRequest.bodyJsonUnsafe({
234 program: PROGRAM,
235 grant_id: input.grantId,
236 request_id: input.requestId,
237 }),
238 ),
239 )
240 .pipe(
241 Effect.timeout("25 seconds"),
242 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
243 );
244 if (response.status === 429) {
245 return yield* new ClaudeResetCreditError({ reason: "rateLimited" });
246 }
247 if (response.status === 401 || response.status === 403) {
248 return yield* new ClaudeResetCreditError({ reason: "signedOut" });
249 }
250 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
251 Effect.flatMap(HttpClientResponse.schemaBodyJson(ClaimResponse)),
252 Effect.timeout("25 seconds"),
253 Effect.mapError((cause) => new ClaudeResetCreditError({ reason: "requestFailed", cause })),
254 );
255 if (body.result === "cooldown") {
256 return yield* new ClaudeResetCreditError({ reason: "coolingDown" });
257 }
258 // Claude could not say whether the claim landed, so, like the CLI, keep the
259 // request id and let the retry ask about the same claim.
260 if (body.result === "unavailable") {
261 return yield* new ClaudeResetCreditError({ reason: "unconfirmed" });
262 }
263 return CLAIM_OUTCOMES[body.result];
264});