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";
11
12import {
13 clampPercent,
14 makeUnavailableUsageLimits,
15 makeUsageLimits,
16} from "@t3tools/provider-core/server/usageLimits";
17
18const SESSION_MINS = 5 * 60;
19const WEEK_MINS = 7 * 24 * 60;
20
21const WINDOWS: Readonly<
22 Record<string, Pick<ServerProviderUsageWindow, "kind" | "label" | "windowDurationMins">>
23> = {
24 five_hour: { kind: "session", label: "Session", windowDurationMins: SESSION_MINS },
25 seven_day: { kind: "weekly", label: "Weekly", windowDurationMins: WEEK_MINS },
26};
27
28/**
29 * The streamed event names the overage-included bucket by type
30 * (`seven_day_overage_included`), while `get_usage` names it by the model's
31 * `display_name`. Which model that is changes over time, so the probe records
32 * the name it saw and the event mapper reuses it; the mid-turn update then
33 * lands on the row the probe drew instead of opening a second one.
34 */
35const OVERAGE_INCLUDED_EVENT_TYPE = "seven_day_overage_included";
36
37export interface ClaudeScopedLimitNames {
38 readonly overageIncluded: string | undefined;
39}
40
41export const makeClaudeScopedLimitNames = Ref.make<ClaudeScopedLimitNames>({
42 overageIncluded: undefined,
43});
44
45function scopedWindowId(displayName: string): string {
46 return `seven_day_${displayName.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`;
47}
48
49function scopedWindow(
50 displayName: string,
51 usedPercent: number,
52 resetsAt: string | undefined,
53): ServerProviderUsageWindow {
54 return {
55 id: scopedWindowId(displayName),
56 kind: "weekly",
57 label: `Weekly · ${displayName}`,
58 windowDurationMins: WEEK_MINS,
59 usedPercent: clampPercent(usedPercent),
60 ...(resetsAt ? { resetsAt } : {}),
61 };
62}
63
64/**
65 * `model_scoped` shipped in the CLI after the SDK typings we pin, so it is
66 * read structurally until the `.d.ts` catches up.
67 */
68interface ModelScopedWindow {
69 readonly display_name: string;
70 readonly utilization: number | null;
71 readonly resets_at: string | null;
72}
73
74function readModelScoped(rateLimits: object): ReadonlyArray<ModelScopedWindow> {
75 const raw = (rateLimits as { readonly model_scoped?: unknown }).model_scoped;
76 if (!Array.isArray(raw)) return [];
77 return raw.filter(
78 (entry): entry is ModelScopedWindow =>
79 typeof entry === "object" &&
80 entry !== null &&
81 typeof (entry as ModelScopedWindow).display_name === "string",
82 );
83}
84
85function isoFromEpochSeconds(value: number | undefined): string | undefined {
86 if (value === undefined || !Number.isFinite(value) || value <= 0) return undefined;
87 const dt = DateTime.make(value * 1000);
88 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
89}
90
91function isoFromString(value: string | null | undefined): string | undefined {
92 if (!value) return undefined;
93 const dt = DateTime.make(value);
94 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
95}
96
97function makeWindow(
98 id: keyof typeof WINDOWS & string,
99 usedPercent: number,
100 resetsAt: string | undefined,
101): ServerProviderUsageWindow {
102 const window = WINDOWS[id]!;
103 return {
104 id,
105 ...window,
106 usedPercent: clampPercent(usedPercent),
107 ...(resetsAt ? { resetsAt } : {}),
108 };
109}
110
111/**
112 * Utilization is a 0–1 fraction on the streamed event. An overage-included
113 * event before any probe has named the bucket is dropped: guessing a name
114 * would draw a row the next probe cannot reconcile.
115 */
116export function claudeRateLimitEventToUpdate(
117 info: SDKRateLimitInfo,
118 names: ClaudeScopedLimitNames,
119): ProviderUsageLimitsUpdate | undefined {
120 const type: string | undefined = info.rateLimitType;
121 if (!type || typeof info.utilization !== "number") {
122 return undefined;
123 }
124 const usedPercent = info.utilization * 100;
125 const resetsAt = isoFromEpochSeconds(info.resetsAt);
126 if (type in WINDOWS) {
127 return { windows: [makeWindow(type, usedPercent, resetsAt)] };
128 }
129 if (type === OVERAGE_INCLUDED_EVENT_TYPE && names.overageIncluded) {
130 return { windows: [scopedWindow(names.overageIncluded, usedPercent, resetsAt)] };
131 }
132 return undefined;
133}
134
135/**
136 * Percentages on the `get_usage` response are already 0–100.
137 */
138export function claudeUsageResponseToLimits(input: {
139 readonly response: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
140 readonly checkedAt: string;
141}): { readonly limits: ServerProviderUsageLimits; readonly names: ClaudeScopedLimitNames } {
142 const { response, checkedAt } = input;
143 if (!response.rate_limits_available || !response.rate_limits) {
144 return {
145 limits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }),
146 names: { overageIncluded: undefined },
147 };
148 }
149 const windows: ServerProviderUsageWindow[] = [];
150 for (const id of Object.keys(WINDOWS)) {
151 const window = response.rate_limits[id as "five_hour" | "seven_day"];
152 if (!window || typeof window.utilization !== "number") continue;
153 windows.push(makeWindow(id, window.utilization, isoFromString(window.resets_at)));
154 }
155 // The CLI filters `model_scoped` to the overage-included allowlist, which
156 // today holds one model; the first entry is the one the event refers to.
157 let overageIncluded: string | undefined;
158 for (const entry of readModelScoped(response.rate_limits)) {
159 if (typeof entry.utilization !== "number") continue;
160 windows.push(
161 scopedWindow(entry.display_name, entry.utilization, isoFromString(entry.resets_at)),
162 );
163 overageIncluded ??= entry.display_name;
164 }
165 return {
166 limits: makeUsageLimits({ checkedAt, windows }),
167 names: { overageIncluded },
168 };
169}
170
171export const recordClaudeUsageResponse = (
172 namesRef: Ref.Ref<ClaudeScopedLimitNames>,
173 input: Parameters<typeof claudeUsageResponseToLimits>[0],
174): Effect.Effect<ServerProviderUsageLimits> => {
175 const { limits, names } = claudeUsageResponseToLimits(input);
176 return Ref.set(namesRef, names).pipe(Effect.as(limits));
177};