The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** Instances sharing a login directory share credits; serialize redemptions on that directory. */ |
| 2 | import type { ProviderConsumeResetCreditOutcome, ServerProvider } from "@t3tools/contracts"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import type * as PlatformError from "effect/PlatformError"; |
| 8 | import * as Ref from "effect/Ref"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Semaphore from "effect/Semaphore"; |
| 11 | |
| 12 | interface AccountRedemptionState { |
| 13 | readonly lock: Semaphore.Semaphore; |
| 14 | readonly pendingKey: Ref.Ref<string | null>; |
| 15 | } |
| 16 | |
| 17 | export class ResetCreditCoordinator extends Context.Service< |
| 18 | ResetCreditCoordinator, |
| 19 | { |
| 20 | /** Reuse the idempotency key until an outcome or settled failure; timeouts keep it for retry. */ |
| 21 | readonly redeem: <E, R>( |
| 22 | accountKey: string, |
| 23 | consume: (idempotencyKey: string) => Effect.Effect<ProviderConsumeResetCreditOutcome, E, R>, |
| 24 | isSettled?: (error: E) => boolean, |
| 25 | ) => Effect.Effect<ProviderConsumeResetCreditOutcome, E | PlatformError.PlatformError, R>; |
| 26 | } |
| 27 | >()("t3/provider/resetCreditCoordinator") {} |
| 28 | |
| 29 | /** @public */ |
| 30 | export const make = Effect.gen(function* () { |
| 31 | const random = yield* SecureRandom.SecureRandom; |
| 32 | const statesRef = yield* Ref.make<ReadonlyMap<string, AccountRedemptionState>>(new Map()); |
| 33 | |
| 34 | // Create account locks atomically so concurrent first redemptions cannot use separate locks. |
| 35 | const stateFor = Effect.fn("ResetCreditCoordinator.stateFor")(function* (accountKey: string) { |
| 36 | const existing = (yield* Ref.get(statesRef)).get(accountKey); |
| 37 | if (existing) return existing; |
| 38 | const candidate = { |
| 39 | lock: yield* Semaphore.make(1), |
| 40 | pendingKey: yield* Ref.make<string | null>(null), |
| 41 | }; |
| 42 | return yield* Ref.modify(statesRef, (states) => { |
| 43 | const current = states.get(accountKey); |
| 44 | if (current) return [current, states] as const; |
| 45 | const next = new Map(states); |
| 46 | next.set(accountKey, candidate); |
| 47 | return [candidate, next] as const; |
| 48 | }); |
| 49 | }); |
| 50 | |
| 51 | const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn( |
| 52 | "resetCreditCoordinator.redeem", |
| 53 | )(function* (accountKey, consume, isSettled) { |
| 54 | const state = yield* stateFor(accountKey); |
| 55 | return yield* state.lock.withPermits(1)( |
| 56 | Effect.gen(function* () { |
| 57 | const existing = yield* Ref.get(state.pendingKey); |
| 58 | const idempotencyKey = existing ?? (yield* random.uuidV4()); |
| 59 | yield* Ref.set(state.pendingKey, idempotencyKey); |
| 60 | const outcome = yield* consume(idempotencyKey).pipe( |
| 61 | Effect.tapError((error) => |
| 62 | isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void, |
| 63 | ), |
| 64 | ); |
| 65 | yield* Ref.set(state.pendingKey, null); |
| 66 | return outcome; |
| 67 | }), |
| 68 | ); |
| 69 | }); |
| 70 | |
| 71 | return { redeem } satisfies ResetCreditCoordinator["Service"]; |
| 72 | }); |
| 73 | |
| 74 | type UsageSnapshot = Pick<ServerProvider, "usageLimits">; |
| 75 | |
| 76 | /** |
| 77 | * Re-probe after a redemption; true once a `reset` shows fresh limits. A failed |
| 78 | * usage read republishes the pre-redemption windows, which are known stale after |
| 79 | * a reset, so retry briefly instead of leaving them until the periodic check. |
| 80 | */ |
| 81 | export const refreshAfterRedemption = Effect.fn("resetCreditCoordinator.refreshAfterRedemption")( |
| 82 | function* <R>(input: { |
| 83 | readonly outcome: ProviderConsumeResetCreditOutcome; |
| 84 | readonly getSnapshot: Effect.Effect<UsageSnapshot>; |
| 85 | readonly refresh: Effect.Effect<UsageSnapshot, never, R>; |
| 86 | }) { |
| 87 | const before = (yield* input.getSnapshot).usageLimits?.checkedAt; |
| 88 | const confirmed = ({ usageLimits }: UsageSnapshot) => |
| 89 | input.outcome !== "reset" || |
| 90 | (usageLimits !== undefined && |
| 91 | usageLimits.checkedAt !== before && |
| 92 | usageLimits.unavailable?.reason !== "probeFailed"); |
| 93 | return yield* input.refresh.pipe( |
| 94 | Effect.map(confirmed), |
| 95 | Effect.repeat({ |
| 96 | until: (ok) => ok, |
| 97 | times: 3, |
| 98 | schedule: Schedule.exponential("1 second"), |
| 99 | }), |
| 100 | ); |
| 101 | }, |
| 102 | ); |
| 103 | |
| 104 | export const layer = Layer.effect(ResetCreditCoordinator, make); |
| 105 | |
| 106 | export const layerTest = Layer.effect( |
| 107 | ResetCreditCoordinator, |
| 108 | Effect.gen(function* () { |
| 109 | let counter = 0; |
| 110 | return yield* make.pipe( |
| 111 | Effect.provideService( |
| 112 | SecureRandom.SecureRandom, |
| 113 | SecureRandom.make((size) => { |
| 114 | counter += 1; |
| 115 | return new Uint8Array(size).fill(counter); |
| 116 | }), |
| 117 | ), |
| 118 | ); |
| 119 | }), |
| 120 | ); |