Open History to see the last commit
1import type { SDKControlGetUsageResponse, SDKRateLimitInfo } from "@anthropic-ai/claude-agent-sdk";
2import type {
3 ProviderUsageLimitsUpdate,
4 ServerProviderUsageLimits,
5 ServerProviderUsageWindow,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Ref from "effect/Ref";
11import * as Schema from "effect/Schema";
12
13import {
14 clampPercent,
15 makeUnavailableUsageLimits,
16 makeUsageLimits,
17} from "@t3tools/provider-core/server/usageLimits";
18
19const SESSION_MINS = 5 * 60;
20const WEEK_MINS = 7 * 24 * 60;
21
22const WINDOWS: Readonly<
23 Record<string, Pick<ServerProviderUsageWindow, "kind" | "label" | "windowDurationMins">>
24> = {
25 five_hour: { kind: "session", label: "Session", windowDurationMins: SESSION_MINS },
26 seven_day: { kind: "weekly", label: "Weekly", windowDurationMins: WEEK_MINS },
27};
28
29/**
30 * The streamed event names the overage-included bucket by type
31 * (`seven_day_overage_included`), while `get_usage` names it by the model's
32 * `display_name`. Which model that is changes over time, so the probe records
33 * the name it saw and the event mapper reuses it; the mid-turn update then
34 * lands on the row the probe drew instead of opening a second one.
35 */
36const OVERAGE_INCLUDED_EVENT_TYPE = "seven_day_overage_included";
37
38// The SDK does not yet type the spend budget returned by `get_usage`.
39const SpendMoney = Schema.Struct({
40 amount_minor: Schema.Natural,
41 currency: Schema.NonEmptyString,
42 exponent: Schema.Natural,
43});
44const decodeSpendBudget = Schema.decodeUnknownOption(
45 Schema.Struct({ enabled: Schema.Boolean, used: SpendMoney, limit: SpendMoney }),
46);
47
48export interface ClaudeScopedLimitNames {
49 readonly overageIncluded: string | undefined;
50}
51
52export const makeClaudeScopedLimitNames = Ref.make<ClaudeScopedLimitNames>({
53 overageIncluded: undefined,
54});
55
56function scopedWindowId(displayName: string): string {
57 return `seven_day_${displayName.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`;
58}
59
60function scopedWindow(
61 displayName: string,
62 usedPercent: number,
63 resetsAt: string | undefined,
64): ServerProviderUsageWindow {
65 return {
66 id: scopedWindowId(displayName),
67 kind: "weekly",
68 label: `Weekly · ${displayName}`,
69 windowDurationMins: WEEK_MINS,
70 usedPercent: clampPercent(usedPercent),
71 ...(resetsAt ? { resetsAt } : {}),
72 };
73}
74
75function percentFromAmounts(used: number | null | undefined, limit: number | null | undefined) {
76 if (
77 typeof used !== "number" ||
78 typeof limit !== "number" ||
79 !Number.isFinite(used) ||
80 !Number.isFinite(limit) ||
81 used < 0 ||
82 limit <= 0
83 ) {
84 return undefined;
85 }
86 const percent = (used / limit) * 100;
87 return Number.isFinite(percent) ? clampPercent(percent) : undefined;
88}
89
90function readSpendPercent(rateLimits: NonNullable<SDKControlGetUsageResponse["rate_limits"]>) {
91 const spend = Option.getOrUndefined(
92 decodeSpendBudget((rateLimits as { readonly spend?: unknown }).spend),
93 );
94 // Minor-unit ratios require matching currency and scale; spend.percent is rounded.
95 if (
96 spend?.enabled &&
97 spend.used.currency.trim().length > 0 &&
98 spend.used.currency.trim() === spend.limit.currency.trim() &&
99 spend.used.exponent === spend.limit.exponent
100 ) {
101 const percent = percentFromAmounts(spend.used.amount_minor, spend.limit.amount_minor);
102 if (percent !== undefined) return percent;
103 }
104
105 const extra = rateLimits.extra_usage;
106 if (extra?.is_enabled !== true) return undefined;
107 const percent = percentFromAmounts(extra.used_credits, extra.monthly_limit) ?? extra.utilization;
108 return typeof percent === "number" && Number.isFinite(percent) && percent >= 0
109 ? clampPercent(percent)
110 : undefined;
111}
112
113/**
114 * `model_scoped` shipped in the CLI after the SDK typings we pin, so it is
115 * read structurally until the `.d.ts` catches up.
116 */
117interface ModelScopedWindow {
118 readonly display_name: string;
119 readonly utilization: number | null;
120 readonly resets_at: string | null;
121}
122
123function readModelScoped(rateLimits: object): ReadonlyArray<ModelScopedWindow> {
124 const raw = (rateLimits as { readonly model_scoped?: unknown }).model_scoped;
125 if (!Array.isArray(raw)) return [];
126 return raw.filter(
127 (entry): entry is ModelScopedWindow =>
128 typeof entry === "object" &&
129 entry !== null &&
130 typeof (entry as ModelScopedWindow).display_name === "string",
131 );
132}
133
134function isoFromEpochSeconds(value: number | undefined): string | undefined {
135 if (value === undefined || !Number.isFinite(value) || value <= 0) return undefined;
136 const dt = DateTime.make(value * 1000);
137 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
138}
139
140function isoFromString(value: string | null | undefined): string | undefined {
141 if (!value) return undefined;
142 const dt = DateTime.make(value);
143 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
144}
145
146function makeWindow(
147 id: keyof typeof WINDOWS & string,
148 usedPercent: number,
149 resetsAt: string | undefined,
150): ServerProviderUsageWindow {
151 const window = WINDOWS[id]!;
152 return {
153 id,
154 ...window,
155 usedPercent: clampPercent(usedPercent),
156 ...(resetsAt ? { resetsAt } : {}),
157 };
158}
159
160/**
161 * Utilization is a 0–1 fraction on the streamed event. An overage-included
162 * event before any probe has named the bucket is dropped: guessing a name
163 * would draw a row the next probe cannot reconcile.
164 */
165export function claudeRateLimitEventToUpdate(
166 info: SDKRateLimitInfo,
167 names: ClaudeScopedLimitNames,
168): ProviderUsageLimitsUpdate | undefined {
169 const type: string | undefined = info.rateLimitType;
170 if (!type || typeof info.utilization !== "number") {
171 return undefined;
172 }
173 const usedPercent = info.utilization * 100;
174 const resetsAt = isoFromEpochSeconds(info.resetsAt);
175 if (type in WINDOWS) {
176 return { windows: [makeWindow(type, usedPercent, resetsAt)] };
177 }
178 if (type === OVERAGE_INCLUDED_EVENT_TYPE && names.overageIncluded) {
179 return { windows: [scopedWindow(names.overageIncluded, usedPercent, resetsAt)] };
180 }
181 return undefined;
182}
183
184/**
185 * Percentages on the `get_usage` response are already 0–100.
186 */
187export function claudeUsageResponseToLimits(input: {
188 readonly response: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
189 readonly checkedAt: string;
190}): { readonly limits: ServerProviderUsageLimits; readonly names: ClaudeScopedLimitNames } {
191 const { response, checkedAt } = input;
192 if (!response.rate_limits_available || !response.rate_limits) {
193 return {
194 limits: makeUnavailableUsageLimits({
195 checkedAt,
196 reason: response.rate_limits_available ? "probeFailed" : "unsupported",
197 }),
198 names: { overageIncluded: undefined },
199 };
200 }
201 const windows: ServerProviderUsageWindow[] = [];
202 for (const id of Object.keys(WINDOWS)) {
203 const window = response.rate_limits[id as "five_hour" | "seven_day"];
204 if (!window || typeof window.utilization !== "number") continue;
205 windows.push(makeWindow(id, window.utilization, isoFromString(window.resets_at)));
206 }
207 // The CLI filters `model_scoped` to the overage-included allowlist, which
208 // today holds one model; the first entry is the one the event refers to.
209 let overageIncluded: string | undefined;
210 for (const entry of readModelScoped(response.rate_limits)) {
211 if (typeof entry.utilization !== "number") continue;
212 windows.push(
213 scopedWindow(entry.display_name, entry.utilization, isoFromString(entry.resets_at)),
214 );
215 overageIncluded ??= entry.display_name;
216 }
217 const spendPercent = readSpendPercent(response.rate_limits);
218 if (spendPercent !== undefined) {
219 windows.push({
220 id: "monthly_spend",
221 kind: "monthly",
222 label: "Monthly spend",
223 usedPercent: spendPercent,
224 });
225 }
226 return {
227 limits: makeUsageLimits({ checkedAt, windows }),
228 names: { overageIncluded },
229 };
230}
231
232export const recordClaudeUsageResponse = (
233 namesRef: Ref.Ref<ClaudeScopedLimitNames>,
234 input: Parameters<typeof claudeUsageResponseToLimits>[0],
235): Effect.Effect<ServerProviderUsageLimits> => {
236 const { limits, names } = claudeUsageResponseToLimits(input);
237 return Ref.set(namesRef, names).pipe(Effect.as(limits));
238};