@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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