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

claudeResetCredits.ts

270 lines10.1 KB

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