The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | type EnvironmentId, |
| 3 | type ModelSelection, |
| 4 | type ServerSettings, |
| 5 | type ProjectId, |
| 6 | resolveProjectProviderInstanceEnabled, |
| 7 | type UsageLimitsReport, |
| 8 | type ProviderInstanceId, |
| 9 | type ProviderConsumeResetCreditInput, |
| 10 | type ServerProviderSlashCommand, |
| 11 | isProviderAvailable, |
| 12 | PROVIDER_DISPLAY_NAMES, |
| 13 | type ServerProvider, |
| 14 | type ServerProviderUsageLimits, |
| 15 | type ServerProviderUsageWindow, |
| 16 | type UsageLimitSourceAccount, |
| 17 | type UsageLimitSourceSnapshot, |
| 18 | type UsageLimitSourceSnapshots, |
| 19 | } from "@t3tools/contracts"; |
| 20 | |
| 21 | import * as DateTime from "effect/DateTime"; |
| 22 | |
| 23 | import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; |
| 24 | |
| 25 | const MINUTE = 60_000; |
| 26 | |
| 27 | export function exhaustedUsageWindow( |
| 28 | provider: ServerProvider | undefined, |
| 29 | now: number, |
| 30 | model?: string, |
| 31 | ) { |
| 32 | const windows = provider?.usageLimits?.windows ?? []; |
| 33 | const exhausted = windows.filter( |
| 34 | (window) => |
| 35 | (window.usedPercent ?? 0) >= 100 && |
| 36 | (model === undefined || window.modelIds === undefined || window.modelIds.includes(model)) && |
| 37 | (model === undefined || |
| 38 | window.providerIds === undefined || |
| 39 | window.providerIds.includes(model.split("/")[0] ?? "")) && |
| 40 | (!window.resetsAt || |
| 41 | !Number.isFinite(Date.parse(window.resetsAt)) || |
| 42 | Date.parse(window.resetsAt) > now), |
| 43 | ); |
| 44 | if (model === undefined) return exhausted[0]; |
| 45 | switch (provider?.driver) { |
| 46 | case "cursor": { |
| 47 | const api = exhausted.find((window) => window.id === "apiPercentUsed"); |
| 48 | const auto = exhausted.find((window) => window.id === "autoPercentUsed"); |
| 49 | return /^(auto|default|grok|composer)/.test(model) ? auto && api : api; |
| 50 | } |
| 51 | case "antigravity": { |
| 52 | const family = model.match(/^(gemini|claude|gpt)-/)?.[1]; |
| 53 | return exhausted.find((window) => { |
| 54 | const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1]; |
| 55 | return ( |
| 56 | pool === undefined || |
| 57 | family === undefined || |
| 58 | pool === family || |
| 59 | (pool === "3p" && (family === "claude" || family === "gpt")) |
| 60 | ); |
| 61 | }); |
| 62 | } |
| 63 | case "codex": { |
| 64 | // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them. |
| 65 | const hasPlanWindows = windows.some( |
| 66 | (window) => window.id === "primary" || window.id === "secondary", |
| 67 | ); |
| 68 | return exhausted.find((window) => window.id !== "individual" || !hasPlanWindows); |
| 69 | } |
| 70 | case "opencode": |
| 71 | return exhausted.find( |
| 72 | (window) => !window.id.startsWith("go_") || model.startsWith("opencode-go/"), |
| 73 | ); |
| 74 | default: |
| 75 | return exhausted[0]; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | export function resolveNewThreadModelSelection(input: { |
| 80 | readonly defaultSelection: ModelSelection | null; |
| 81 | readonly explicitSelection?: ModelSelection | null; |
| 82 | readonly fallbackSelection: ModelSelection | null; |
| 83 | readonly providers: readonly ServerProvider[]; |
| 84 | readonly now: number; |
| 85 | readonly settings?: ServerSettings; |
| 86 | readonly projectId?: ProjectId | null; |
| 87 | }) { |
| 88 | const selection = input.explicitSelection ?? input.defaultSelection; |
| 89 | const unchanged = { selection, fallback: null }; |
| 90 | if (input.explicitSelection || !selection || !input.fallbackSelection) return unchanged; |
| 91 | const provider = input.providers.find((entry) => entry.instanceId === selection.instanceId); |
| 92 | const window = exhaustedUsageWindow(provider, input.now, selection.model); |
| 93 | const fallback = input.providers.find( |
| 94 | (entry) => entry.instanceId === input.fallbackSelection?.instanceId, |
| 95 | ); |
| 96 | if ( |
| 97 | !provider || |
| 98 | !window || |
| 99 | !fallback?.enabled || |
| 100 | !fallback.installed || |
| 101 | fallback.auth.status === "unauthenticated" || |
| 102 | !isProviderAvailable(fallback) || |
| 103 | exhaustedUsageWindow(fallback, input.now, input.fallbackSelection.model) || |
| 104 | (input.settings && |
| 105 | !resolveProjectProviderInstanceEnabled( |
| 106 | input.settings, |
| 107 | input.projectId ?? null, |
| 108 | fallback.instanceId, |
| 109 | )) |
| 110 | ) |
| 111 | return unchanged; |
| 112 | return { |
| 113 | selection: input.fallbackSelection, |
| 114 | fallback: { provider, resetsAt: window.resetsAt ?? null }, |
| 115 | }; |
| 116 | } |
| 117 | |
| 118 | export const CHATGPT_USAGE_URL = "https://chatgpt.com/#settings/Usage"; |
| 119 | export const CHATGPT_USAGE_LIMIT_CODE = "subscription_sharing_usage_limit_exceeded"; |
| 120 | /** A ChatGPT Business admin caps plan use in other apps; only the admin can raise it. */ |
| 121 | export const CHATGPT_WORKSPACE_USAGE_LIMIT_CODE = |
| 122 | "subscription_sharing_workplace_individual_usage_limit_exceeded"; |
| 123 | /** OpenAI's partner guidelines fix this wording; the user sends it to their admin themselves. */ |
| 124 | export const CHATGPT_WORKSPACE_ADMIN_REQUEST = |
| 125 | "I've reached the limit for using my ChatGPT plan in T3 Code. Could you increase our workspace's usage limits so I can continue?\n\nGo to admin.openai.com → Workspace → Usage limits. Thank you!"; |
| 126 | |
| 127 | export function usesChatGptSharing(provider: ServerProvider | null | undefined): boolean { |
| 128 | return provider?.auth.status === "authenticated" && provider.auth.subscriptionSharing === true; |
| 129 | } |
| 130 | |
| 131 | export const CURSOR_USAGE_WINDOWS = [ |
| 132 | { |
| 133 | id: "totalPercentUsed", |
| 134 | label: "Overall", |
| 135 | description: "All usage on your plan this billing cycle.", |
| 136 | }, |
| 137 | { |
| 138 | id: "autoPercentUsed", |
| 139 | label: "Cursor Models", |
| 140 | description: "Grok, Composer, and Auto use this allowance.", |
| 141 | }, |
| 142 | { |
| 143 | id: "apiPercentUsed", |
| 144 | label: "Other Models", |
| 145 | description: "Usage allowance for third-party models such as Claude, GPT, and Gemini.", |
| 146 | }, |
| 147 | ] as const; |
| 148 | |
| 149 | export function cursorUsageWindowDetails(id: string, pool: LimitPool) { |
| 150 | const details = CURSOR_USAGE_WINDOWS.find((window) => window.id === id); |
| 151 | return details && |
| 152 | ((pool.windows.length === 1 && id === "totalPercentUsed") || hasDuplicateCursorTotal(pool)) |
| 153 | ? { ...details, label: null, description: undefined } |
| 154 | : details; |
| 155 | } |
| 156 | |
| 157 | function cursorUsageWindowRank(id: string): number { |
| 158 | const rank = CURSOR_USAGE_WINDOWS.findIndex((window) => window.id === id); |
| 159 | return rank < 0 ? CURSOR_USAGE_WINDOWS.length : rank; |
| 160 | } |
| 161 | |
| 162 | export function providersWithLimits( |
| 163 | providers: readonly ServerProvider[], |
| 164 | ): readonly ServerProvider[] { |
| 165 | return providers.filter( |
| 166 | (provider) => |
| 167 | provider.enabled && |
| 168 | provider.installed && |
| 169 | isProviderAvailable(provider) && |
| 170 | provider.usageLimits !== undefined, |
| 171 | ); |
| 172 | } |
| 173 | |
| 174 | export type LimitPresentations = ReadonlyMap< |
| 175 | EnvironmentId, |
| 176 | { |
| 177 | readonly entry: { readonly target: { readonly label: string } }; |
| 178 | readonly serverConfig: { |
| 179 | readonly providers: readonly ServerProvider[]; |
| 180 | readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined; |
| 181 | } | null; |
| 182 | } |
| 183 | >; |
| 184 | |
| 185 | export function collectExternalUsageLinks( |
| 186 | presentations: LimitPresentations, |
| 187 | accountLabel = (provider: string, environment: string) => `${provider} on ${environment}`, |
| 188 | ) { |
| 189 | const links = new Map< |
| 190 | string, |
| 191 | { |
| 192 | readonly label: string; |
| 193 | readonly url: string; |
| 194 | readonly message: string | undefined; |
| 195 | readonly accounts: readonly string[]; |
| 196 | } |
| 197 | >(); |
| 198 | for (const presentation of presentations.values()) { |
| 199 | for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { |
| 200 | const external = provider.usageLimits?.externalUsage; |
| 201 | if (external && provider.auth.status === "authenticated") { |
| 202 | const account = accountLabel( |
| 203 | provider.displayName ?? provider.instanceId, |
| 204 | presentation.entry.target.label, |
| 205 | ); |
| 206 | links.set(external.url, { |
| 207 | ...external, |
| 208 | message: provider.usageLimits?.unavailable?.message, |
| 209 | accounts: [...new Set([...(links.get(external.url)?.accounts ?? []), account])], |
| 210 | }); |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | return [...links.values()]; |
| 215 | } |
| 216 | |
| 217 | function accountKey( |
| 218 | driver: ServerProvider["driver"], |
| 219 | email: string | undefined, |
| 220 | limits?: ServerProviderUsageLimits, |
| 221 | ): string | null { |
| 222 | const normalizedEmail = email?.trim().toLowerCase(); |
| 223 | if (normalizedEmail) return `${driver}:${normalizedEmail}`; |
| 224 | return limits?.credentialFingerprint |
| 225 | ? `${driver}:credential:${limits.credentialFingerprint}` |
| 226 | : null; |
| 227 | } |
| 228 | |
| 229 | interface AccountReport { |
| 230 | readonly driver: ServerProvider["driver"]; |
| 231 | readonly email?: string | undefined; |
| 232 | readonly workspaceId?: string | undefined; |
| 233 | readonly usageLimits?: ServerProviderUsageLimits | undefined; |
| 234 | } |
| 235 | |
| 236 | const nativeReport = (provider: ServerProvider): AccountReport => ({ |
| 237 | driver: provider.driver, |
| 238 | email: provider.auth.email, |
| 239 | workspaceId: provider.auth.workspaceId, |
| 240 | usageLimits: provider.usageLimits, |
| 241 | }); |
| 242 | |
| 243 | // Include every enabled login, even unreadable workspaces. |
| 244 | function accountKeyResolver(reports: Iterable<AccountReport>) { |
| 245 | const workspaces = new Map<string, Set<string>>(); |
| 246 | for (const report of reports) { |
| 247 | const key = accountKey(report.driver, report.email, report.usageLimits); |
| 248 | if (key && report.workspaceId) { |
| 249 | workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId)); |
| 250 | } |
| 251 | } |
| 252 | return (report: AccountReport): string | null => { |
| 253 | const key = accountKey(report.driver, report.email, report.usageLimits); |
| 254 | if (!key) return null; |
| 255 | if (report.workspaceId) return `${key}:${report.workspaceId}`; |
| 256 | const known = workspaces.get(key); |
| 257 | if (!known) return key; |
| 258 | return known.size === 1 ? `${key}:${[...known][0]}` : null; |
| 259 | }; |
| 260 | } |
| 261 | |
| 262 | const hubAccountName = (account: { readonly id: string }) => account.id.replace(/\.json$/i, ""); |
| 263 | |
| 264 | // Source ids are environment-local, so only a remote endpoint names the same hub across environments. |
| 265 | function hubIdentity(environmentId: EnvironmentId, source: UsageLimitSourceSnapshot): string { |
| 266 | // The server supplies canonical endpoints; native URL polyfills can misparse IPv6 hosts. |
| 267 | const endpoint = source.endpoint; |
| 268 | const host = endpoint?.match(/^https?:\/\/(\[[\da-f:.]+\]|[^:/?#@]+)(?::\d+)?(?:\/|$)/)?.[1]; |
| 269 | const local = |
| 270 | !host || |
| 271 | isLocalLoopbackHost(host) || |
| 272 | isWildcardHost(host) || |
| 273 | // Each machine resolves these to itself too; shared host classification leaves them out. |
| 274 | /\.localhost\.*$|^\[::ffff:(?:127\.|7f[\da-f]{2}:)/i.test(host); |
| 275 | return endpoint && !local ? endpoint : `${environmentId}:${source.id}`; |
| 276 | } |
| 277 | |
| 278 | export interface LimitAccount { |
| 279 | readonly key: string; |
| 280 | readonly driver: ServerProvider["driver"]; |
| 281 | readonly displayName: string | null; |
| 282 | readonly email: string | undefined; |
| 283 | readonly plan: string | undefined; |
| 284 | readonly accentColor: string | undefined; |
| 285 | readonly environments: ReadonlyArray<{ |
| 286 | readonly environmentId: EnvironmentId; |
| 287 | readonly label: string; |
| 288 | }>; |
| 289 | readonly sourceLabel: string | null; |
| 290 | readonly redeem: { |
| 291 | readonly environmentId: EnvironmentId; |
| 292 | readonly input: ProviderConsumeResetCreditInput; |
| 293 | } | null; |
| 294 | readonly limits: ServerProviderUsageLimits; |
| 295 | } |
| 296 | |
| 297 | export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] { |
| 298 | const accounts = new Map<string, LimitAccount>(); |
| 299 | const creditSources = new Map<string, LimitAccount>(); |
| 300 | const hubRedeems = new Map<string, LimitAccount>(); |
| 301 | const planSources = new Map<string, LimitAccount>(); |
| 302 | const merge = (key: string, next: LimitAccount) => { |
| 303 | // Prefer hub redemption to clear its routing cooldown too; displayed balance still follows the freshest read. |
| 304 | const previousHub = hubRedeems.get(key); |
| 305 | if ( |
| 306 | next.redeem && |
| 307 | "sourceId" in next.redeem.input && |
| 308 | (!previousHub || Date.parse(next.limits.checkedAt) > Date.parse(previousHub.limits.checkedAt)) |
| 309 | ) { |
| 310 | hubRedeems.set(key, next); |
| 311 | } |
| 312 | const previousCredit = creditSources.get(key); |
| 313 | if ( |
| 314 | next.limits.resetCredits && |
| 315 | (!previousCredit || |
| 316 | Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt)) |
| 317 | ) { |
| 318 | creditSources.set(key, next); |
| 319 | } |
| 320 | const previousPlan = planSources.get(key); |
| 321 | if ( |
| 322 | next.plan && |
| 323 | (!previousPlan || |
| 324 | Date.parse(next.limits.checkedAt) > Date.parse(previousPlan.limits.checkedAt)) |
| 325 | ) { |
| 326 | planSources.set(key, next); |
| 327 | } |
| 328 | const previous = accounts.get(key); |
| 329 | if (!previous) { |
| 330 | accounts.set(key, next); |
| 331 | return; |
| 332 | } |
| 333 | const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt); |
| 334 | const environments = [ |
| 335 | ...previous.environments, |
| 336 | ...next.environments.filter( |
| 337 | (candidate) => |
| 338 | !previous.environments.some((seen) => seen.environmentId === candidate.environmentId), |
| 339 | ), |
| 340 | ]; |
| 341 | const winner = fresher ? next : previous; |
| 342 | const creditSource = creditSources.get(key); |
| 343 | // A hub e-mail names the account better than the driver's default instance name. |
| 344 | const hubEmail = [previous, next].some( |
| 345 | (account) => account.environments.length === 0 && account.email, |
| 346 | ); |
| 347 | const displayName = previous.displayName ?? next.displayName; |
| 348 | accounts.set(key, { |
| 349 | ...previous, |
| 350 | displayName: |
| 351 | hubEmail && |
| 352 | displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase() |
| 353 | ? null |
| 354 | : displayName, |
| 355 | plan: planSources.get(key)?.plan ?? previous.plan ?? next.plan, |
| 356 | accentColor: previous.accentColor ?? next.accentColor, |
| 357 | environments, |
| 358 | sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel), |
| 359 | redeem: |
| 360 | hubRedeems.get(key)?.redeem ?? |
| 361 | (creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)), |
| 362 | limits: { |
| 363 | ...winner.limits, |
| 364 | ...(creditSource?.limits.resetCredits |
| 365 | ? { resetCredits: creditSource.limits.resetCredits } |
| 366 | : { resetCredits: undefined }), |
| 367 | }, |
| 368 | }); |
| 369 | }; |
| 370 | const resolveKey = accountKeyResolver( |
| 371 | [...presentations.values()].flatMap((presentation) => [ |
| 372 | ...(presentation.serverConfig?.providers ?? []) |
| 373 | .filter((provider) => provider.enabled) |
| 374 | .map(nativeReport), |
| 375 | ...(presentation.serverConfig?.usageLimitSources ?? []).flatMap((source) => source.accounts), |
| 376 | ]), |
| 377 | ); |
| 378 | for (const [environmentId, presentation] of presentations) { |
| 379 | const label = presentation.entry.target.label; |
| 380 | for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { |
| 381 | if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue; |
| 382 | merge(resolveKey(nativeReport(provider)) ?? `${environmentId}:${provider.instanceId}`, { |
| 383 | key: `${environmentId}:${provider.instanceId}`, |
| 384 | driver: provider.driver, |
| 385 | displayName: provider.displayName?.trim() || null, |
| 386 | email: provider.auth.email, |
| 387 | plan: provider.auth.label, |
| 388 | accentColor: provider.accentColor, |
| 389 | environments: [{ environmentId, label }], |
| 390 | sourceLabel: null, |
| 391 | redeem: { environmentId, input: { instanceId: provider.instanceId } }, |
| 392 | limits: provider.usageLimits, |
| 393 | }); |
| 394 | } |
| 395 | } |
| 396 | const labelEnvironment = presentations.size > 1; |
| 397 | for (const [environmentId, presentation] of presentations) { |
| 398 | for (const source of presentation.serverConfig?.usageLimitSources ?? []) { |
| 399 | const sourceLabel = labelEnvironment |
| 400 | ? `${presentation.entry.target.label} · ${source.label}` |
| 401 | : source.label; |
| 402 | for (const account of source.accounts) { |
| 403 | if (limitsNotice(account.usageLimits) !== null) continue; |
| 404 | const resolved = resolveKey(account); |
| 405 | // A resolved account already has an identity; its public key must stay distinct from others'. |
| 406 | const hub = resolved ? `${environmentId}:${source.id}` : hubIdentity(environmentId, source); |
| 407 | const key = `${hub}:${account.id}${account.workspaceId ? `:${account.workspaceId}` : ""}`; |
| 408 | merge(resolved ?? key, { |
| 409 | key, |
| 410 | driver: account.driver, |
| 411 | displayName: account.email ? null : hubAccountName(account), |
| 412 | email: account.email, |
| 413 | plan: account.plan, |
| 414 | accentColor: undefined, |
| 415 | environments: [], |
| 416 | sourceLabel, |
| 417 | redeem: account.usageLimits.resetCredits?.nextCreditId |
| 418 | ? { |
| 419 | environmentId, |
| 420 | input: { |
| 421 | sourceId: source.id, |
| 422 | accountId: account.id, |
| 423 | creditId: account.usageLimits.resetCredits.nextCreditId, |
| 424 | }, |
| 425 | } |
| 426 | : null, |
| 427 | limits: account.usageLimits, |
| 428 | }); |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | return [...accounts.values()]; |
| 433 | } |
| 434 | |
| 435 | export interface LimitPoolMember { |
| 436 | readonly account: LimitAccount; |
| 437 | readonly window: ServerProviderUsageWindow; |
| 438 | readonly refillPercent: number; |
| 439 | } |
| 440 | |
| 441 | export interface LimitPoolWindow { |
| 442 | readonly id: string; |
| 443 | readonly kind: ServerProviderUsageWindow["kind"]; |
| 444 | readonly label: string; |
| 445 | readonly members: readonly LimitPoolMember[]; |
| 446 | readonly columns: ReadonlyArray< |
| 447 | LimitPoolMember | { readonly account: LimitAccount; readonly window: null } |
| 448 | >; |
| 449 | readonly remainingPercent: number; |
| 450 | readonly usedPercent: number; |
| 451 | readonly pace: LimitPace | null; |
| 452 | readonly resets: ReadonlyArray<{ |
| 453 | readonly member: LimitPoolMember; |
| 454 | readonly at: number; |
| 455 | readonly restoresPercent: number; |
| 456 | }>; |
| 457 | } |
| 458 | |
| 459 | export interface LimitPool { |
| 460 | readonly driver: ServerProvider["driver"]; |
| 461 | readonly accounts: readonly LimitAccount[]; |
| 462 | readonly windows: readonly LimitPoolWindow[]; |
| 463 | } |
| 464 | |
| 465 | function hasDuplicateCursorTotal(pool: LimitPool): boolean { |
| 466 | if (pool.windows.length !== 2) return false; |
| 467 | const total = pool.windows.find((window) => window.id === "totalPercentUsed"); |
| 468 | const auto = pool.windows.find((window) => window.id === "autoPercentUsed"); |
| 469 | return ( |
| 470 | total !== undefined && |
| 471 | auto !== undefined && |
| 472 | total.members.length === auto.members.length && |
| 473 | total.members.every(({ account, window }) => |
| 474 | account.limits.windows.some( |
| 475 | (candidate) => |
| 476 | candidate.id === auto.id && |
| 477 | candidate.kind === auto.kind && |
| 478 | candidate.usedPercent === window.usedPercent && |
| 479 | candidate.resetsAt === window.resetsAt, |
| 480 | ), |
| 481 | ) |
| 482 | ); |
| 483 | } |
| 484 | |
| 485 | export function displayLimitWindows(pool: LimitPool) { |
| 486 | if (pool.driver === "antigravity") { |
| 487 | return [...pool.windows].sort( |
| 488 | (left, right) => |
| 489 | Number(!left.id.startsWith("gemini-")) - Number(!right.id.startsWith("gemini-")) || |
| 490 | left.id |
| 491 | .replace(/-(5h|weekly|quota)$/, "") |
| 492 | .localeCompare(right.id.replace(/-(5h|weekly|quota)$/, "")) || |
| 493 | WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind], |
| 494 | ); |
| 495 | } |
| 496 | if (pool.driver !== "cursor") return pool.windows; |
| 497 | const hasAuto = pool.windows.some((window) => window.id === "autoPercentUsed"); |
| 498 | const hasApi = pool.windows.some((window) => window.id === "apiPercentUsed"); |
| 499 | const hideTotal = (hasAuto && hasApi) || hasDuplicateCursorTotal(pool); |
| 500 | return pool.windows |
| 501 | .filter((window) => !hideTotal || window.id !== "totalPercentUsed") |
| 502 | .sort((left, right) => cursorUsageWindowRank(left.id) - cursorUsageWindowRank(right.id)); |
| 503 | } |
| 504 | |
| 505 | const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = { |
| 506 | session: 0, |
| 507 | weekly: 1, |
| 508 | monthly: 2, |
| 509 | other: 3, |
| 510 | }; |
| 511 | |
| 512 | export function collectLimitPools( |
| 513 | accounts: readonly LimitAccount[], |
| 514 | now: number, |
| 515 | ): readonly LimitPool[] { |
| 516 | const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>(); |
| 517 | for (const account of accounts) { |
| 518 | const list = byDriver.get(account.driver); |
| 519 | if (list) list.push(account); |
| 520 | else byDriver.set(account.driver, [account]); |
| 521 | } |
| 522 | return [...byDriver].map(([driver, members]) => { |
| 523 | const orderWindow = members |
| 524 | .flatMap((account) => account.limits.windows) |
| 525 | .sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind])[0]; |
| 526 | const orderReset = (account: LimitAccount) => { |
| 527 | const window = account.limits.windows.find( |
| 528 | (window) => orderWindow && poolKey(driver, window) === poolKey(driver, orderWindow), |
| 529 | ); |
| 530 | return ( |
| 531 | (window ? resetMillis(poolMember(account, window, now).window) : null) ?? |
| 532 | Number.POSITIVE_INFINITY |
| 533 | ); |
| 534 | }; |
| 535 | const sorted = [...members].sort( |
| 536 | (left, right) => |
| 537 | orderReset(left) - orderReset(right) || |
| 538 | accountSortName(left).localeCompare(accountSortName(right)) || |
| 539 | left.key.localeCompare(right.key), |
| 540 | ); |
| 541 | return { driver, accounts: sorted, windows: poolWindows(sorted, now) }; |
| 542 | }); |
| 543 | } |
| 544 | |
| 545 | function accountSortName(account: LimitAccount): string { |
| 546 | return (account.displayName ?? account.email ?? account.key).toLowerCase(); |
| 547 | } |
| 548 | |
| 549 | const CODEX_PLAN_CAPACITY: Record<string, number> = { |
| 550 | "ChatGPT Plus Subscription": 1, |
| 551 | "ChatGPT Pro 100 Subscription": 5, |
| 552 | "ChatGPT Pro 200 Subscription": 20, |
| 553 | }; |
| 554 | // Claude's published plan multipliers describe the session allowance only. |
| 555 | const CLAUDE_SESSION_CAPACITY: Record<string, number> = { Pro: 1, Max: 5, Ultra: 20 }; |
| 556 | |
| 557 | function planCapacity(account: LimitAccount, kind: ServerProviderUsageWindow["kind"]) { |
| 558 | if (!account.plan) return undefined; |
| 559 | if (account.driver === "codex" && (kind === "session" || kind === "weekly")) { |
| 560 | return CODEX_PLAN_CAPACITY[account.plan]; |
| 561 | } |
| 562 | if (account.driver === "claudeAgent" && kind === "session") { |
| 563 | return CLAUDE_SESSION_CAPACITY[account.plan]; |
| 564 | } |
| 565 | return undefined; |
| 566 | } |
| 567 | |
| 568 | // Codex ids name slots, so pool by kind; other drivers' ids identify distinct allowances. |
| 569 | function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string { |
| 570 | return driver === "codex" ? window.kind : `${window.kind}:${window.id}`; |
| 571 | } |
| 572 | |
| 573 | function poolMember(account: LimitAccount, reported: ServerProviderUsageWindow, now: number) { |
| 574 | const spentWeekly = |
| 575 | reported.kind === "session" |
| 576 | ? account.limits.windows.find( |
| 577 | (window) => |
| 578 | window.usedPercent >= 100 && |
| 579 | (account.driver === "claudeAgent" |
| 580 | ? window.id === "seven_day" |
| 581 | : account.driver === "codex" && window.kind === "weekly"), |
| 582 | ) |
| 583 | : undefined; |
| 584 | if (!spentWeekly) return { account, window: reported, refillPercent: reported.usedPercent }; |
| 585 | |
| 586 | const weeklyReset = resetMillis(spentWeekly); |
| 587 | const sessionReset = resetMillis(reported); |
| 588 | const cutoff = Math.max(now, Date.parse(account.limits.checkedAt)); |
| 589 | let resetsAt: string | undefined; |
| 590 | let refillPercent = 0; |
| 591 | // A stale or missing clock cannot tell us when blocked quota becomes usable. |
| 592 | if ( |
| 593 | weeklyReset !== null && |
| 594 | sessionReset !== null && |
| 595 | weeklyReset > cutoff && |
| 596 | sessionReset > cutoff |
| 597 | ) { |
| 598 | if (sessionReset <= weeklyReset) { |
| 599 | resetsAt = spentWeekly.resetsAt; |
| 600 | refillPercent = 100; |
| 601 | } else if (reported.usedPercent >= 100) { |
| 602 | resetsAt = reported.resetsAt; |
| 603 | refillPercent = 100; |
| 604 | } else { |
| 605 | resetsAt = spentWeekly.resetsAt; |
| 606 | refillPercent = 100 - Math.max(0, Math.min(100, reported.usedPercent)); |
| 607 | } |
| 608 | } |
| 609 | return { |
| 610 | account, |
| 611 | // Suppression is not session spending, so it has no session pace clock. |
| 612 | window: { ...reported, usedPercent: 100, resetsAt, windowDurationMins: undefined }, |
| 613 | refillPercent, |
| 614 | }; |
| 615 | } |
| 616 | |
| 617 | function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] { |
| 618 | const byKey = new Map<string, LimitPoolMember[]>(); |
| 619 | for (const account of accounts) { |
| 620 | for (const reported of account.limits.windows) { |
| 621 | const member = poolMember(account, reported, now); |
| 622 | const { window } = member; |
| 623 | const pooled = poolKey(account.driver, window); |
| 624 | const key = byKey.get(pooled)?.some((member) => member.account === account) |
| 625 | ? `${window.kind}:${window.id}` |
| 626 | : pooled; |
| 627 | const list = byKey.get(key); |
| 628 | if (list) list.push(member); |
| 629 | else byKey.set(key, [member]); |
| 630 | } |
| 631 | } |
| 632 | const pools = [...byKey].map(([key, members]): LimitPoolWindow => { |
| 633 | const memberByAccount = new Map(members.map((member) => [member.account.key, member])); |
| 634 | const first = members[0]!.window; |
| 635 | const id = members[0]!.account.driver === "codex" ? key : first.id; |
| 636 | // One unknown plan makes the pool incomparable by plan, so every member then counts once. |
| 637 | const capacities = members.map((m) => planCapacity(m.account, first.kind)); |
| 638 | const weights = capacities.every((capacity) => capacity !== undefined) |
| 639 | ? capacities |
| 640 | : members.map(() => 1); |
| 641 | const weightOf = new Map(members.map((m, index) => [m, weights[index]!])); |
| 642 | const totalWeight = weights.reduce((sum, weight) => sum + weight, 0); |
| 643 | const usedPercent = |
| 644 | members.reduce((sum, m) => sum + m.window.usedPercent * weightOf.get(m)!, 0) / totalWeight; |
| 645 | // Judge pace only for windows with reset clocks; others add spend without elapsed time. |
| 646 | const timed = members.flatMap((m) => { |
| 647 | const share = elapsedShare(m.window, now); |
| 648 | return share === null |
| 649 | ? [] |
| 650 | : [{ used: m.window.usedPercent, elapsed: share, weight: weightOf.get(m)! }]; |
| 651 | }); |
| 652 | const timedWeight = timed.reduce((sum, t) => sum + t.weight, 0); |
| 653 | const timedUsed = timed.reduce((sum, t) => sum + t.used * t.weight, 0) / timedWeight; |
| 654 | const meanElapsed = |
| 655 | timed.length > 0 |
| 656 | ? timed.reduce((sum, t) => sum + t.elapsed * t.weight, 0) / timedWeight |
| 657 | : null; |
| 658 | const resets = members |
| 659 | .flatMap((member) => { |
| 660 | const at = resetMillis(member.window); |
| 661 | return at === null |
| 662 | ? [] |
| 663 | : [ |
| 664 | { |
| 665 | member, |
| 666 | at, |
| 667 | restoresPercent: Math.round( |
| 668 | (member.refillPercent * weightOf.get(member)!) / totalWeight, |
| 669 | ), |
| 670 | }, |
| 671 | ]; |
| 672 | }) |
| 673 | .sort((left, right) => left.at - right.at); |
| 674 | return { |
| 675 | id, |
| 676 | kind: first.kind, |
| 677 | label: first.label, |
| 678 | members, |
| 679 | columns: accounts.map( |
| 680 | (account) => memberByAccount.get(account.key) ?? { account, window: null }, |
| 681 | ), |
| 682 | usedPercent: Math.round(usedPercent), |
| 683 | remainingPercent: Math.round(100 - usedPercent), |
| 684 | pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed), |
| 685 | resets, |
| 686 | }; |
| 687 | }); |
| 688 | return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]); |
| 689 | } |
| 690 | |
| 691 | function limitsNotice(limits: ServerProviderUsageLimits): string | null { |
| 692 | if (limits.unavailable?.reason === "unsupported") { |
| 693 | return limits.unavailable.message ?? "This account has no subscription limits."; |
| 694 | } |
| 695 | if (limits.unavailable?.reason === "probeFailed") { |
| 696 | return limits.unavailable.message ?? "Could not read limits."; |
| 697 | } |
| 698 | return limits.windows.length === 0 ? "No limits reported." : null; |
| 699 | } |
| 700 | |
| 701 | export function remainingPercent(window: ServerProviderUsageWindow): number { |
| 702 | return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent))); |
| 703 | } |
| 704 | |
| 705 | function resetMillis(window: ServerProviderUsageWindow): number | null { |
| 706 | if (window.resetsAt === undefined) return null; |
| 707 | const at = Date.parse(window.resetsAt); |
| 708 | return Number.isFinite(at) ? at : null; |
| 709 | } |
| 710 | |
| 711 | export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null { |
| 712 | const resetsAt = resetMillis(window); |
| 713 | if (resetsAt === null || window.windowDurationMins === undefined) return null; |
| 714 | const length = window.windowDurationMins * MINUTE; |
| 715 | if (length <= 0) return null; |
| 716 | return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length)); |
| 717 | } |
| 718 | |
| 719 | // Bars show quota remaining, so even pace tracks time remaining. |
| 720 | export function paceRemainingPercent( |
| 721 | window: ServerProviderUsageWindow, |
| 722 | now: number, |
| 723 | ): number | null { |
| 724 | const elapsed = elapsedShare(window, now); |
| 725 | return elapsed === null ? null : Math.round((1 - elapsed) * 100); |
| 726 | } |
| 727 | |
| 728 | export type LimitPace = "ahead" | "on" | "under"; |
| 729 | |
| 730 | export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null { |
| 731 | const elapsed = elapsedShare(window, now); |
| 732 | return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed); |
| 733 | } |
| 734 | |
| 735 | function paceOfShares(usedPercent: number, elapsed: number): LimitPace { |
| 736 | const gap = usedPercent - elapsed * 100; |
| 737 | if (gap > 5) return "ahead"; |
| 738 | if (gap < -5) return "under"; |
| 739 | return "on"; |
| 740 | } |
| 741 | |
| 742 | /** One redeemable reset as clients offer it; `input` already names the chosen credit. */ |
| 743 | export interface ResetCreditChoice { |
| 744 | readonly key: string; |
| 745 | readonly summary: string; |
| 746 | readonly actionLabel: string; |
| 747 | readonly confirmDescription: string; |
| 748 | readonly availableCount: number; |
| 749 | readonly input: ProviderConsumeResetCreditInput; |
| 750 | } |
| 751 | |
| 752 | export type ResetCountdown = |
| 753 | | { readonly kind: "now" } |
| 754 | | { readonly kind: "momentarily" } |
| 755 | | { readonly kind: "in"; readonly ms: number }; |
| 756 | |
| 757 | export function resetCountdown( |
| 758 | window: ServerProviderUsageWindow, |
| 759 | now: number, |
| 760 | ): ResetCountdown | null { |
| 761 | const resetsAt = resetMillis(window); |
| 762 | if (resetsAt === null) return null; |
| 763 | if (resetsAt <= now) return { kind: "now" }; |
| 764 | if (resetsAt - now < MINUTE) return { kind: "momentarily" }; |
| 765 | return { kind: "in", ms: resetsAt - now }; |
| 766 | } |
| 767 | |
| 768 | export const USAGE_LIMITS_COMMAND = { |
| 769 | name: "usage-limits", |
| 770 | description: "Show this provider's usage limits", |
| 771 | } satisfies ServerProviderSlashCommand; |
| 772 | |
| 773 | export function isUsageLimitsCommand(prompt: string): boolean { |
| 774 | return prompt.trim().toLowerCase() === "/usage-limits"; |
| 775 | } |
| 776 | |
| 777 | export function hasProviderUsageLimits( |
| 778 | driver: ServerProvider["driver"], |
| 779 | providers: readonly ServerProvider[], |
| 780 | sources: UsageLimitSourceSnapshots, |
| 781 | ): boolean { |
| 782 | return ( |
| 783 | providersWithLimits(providers).some((provider) => provider.driver === driver) || |
| 784 | sources.some( |
| 785 | (source) => |
| 786 | source.accounts.some((account) => account.driver === driver) || |
| 787 | (source.error !== undefined && source.accounts.length === 0), |
| 788 | ) |
| 789 | ); |
| 790 | } |
| 791 | |
| 792 | export function sameUsageLimitCommandCoverage( |
| 793 | previous: UsageLimitSourceSnapshots, |
| 794 | next: UsageLimitSourceSnapshots, |
| 795 | ): boolean { |
| 796 | const coverage = (sources: UsageLimitSourceSnapshots) => |
| 797 | new Set( |
| 798 | sources.flatMap((source) => |
| 799 | source.error !== undefined && source.accounts.length === 0 |
| 800 | ? ["*"] |
| 801 | : source.accounts.map((account) => String(account.driver)), |
| 802 | ), |
| 803 | ); |
| 804 | const before = coverage(previous); |
| 805 | const after = coverage(next); |
| 806 | return before.size === after.size && [...before].every((driver) => after.has(driver)); |
| 807 | } |
| 808 | |
| 809 | /** Advertise on workspace catalogs too, which replace the global command list. */ |
| 810 | export function withUsageLimitsCommands( |
| 811 | providers: readonly ServerProvider[], |
| 812 | sources: UsageLimitSourceSnapshots, |
| 813 | ): ServerProvider[] { |
| 814 | const supportedDrivers = new Set([ |
| 815 | ...providersWithLimits(providers).map((provider) => provider.driver), |
| 816 | ...sources.flatMap((source) => source.accounts.map((account) => account.driver)), |
| 817 | ]); |
| 818 | const unreadableSource = sources.some( |
| 819 | (source) => source.error !== undefined && source.accounts.length === 0, |
| 820 | ); |
| 821 | return providers.map((provider) => { |
| 822 | if (!unreadableSource && !supportedDrivers.has(provider.driver)) return provider; |
| 823 | const commands = (items: readonly ServerProviderSlashCommand[]) => [ |
| 824 | ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name), |
| 825 | USAGE_LIMITS_COMMAND, |
| 826 | ]; |
| 827 | return { |
| 828 | ...provider, |
| 829 | slashCommands: commands(provider.slashCommands), |
| 830 | ...(provider.workspaceSnapshots |
| 831 | ? { |
| 832 | workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({ |
| 833 | ...snapshot, |
| 834 | slashCommands: commands(snapshot.slashCommands), |
| 835 | })), |
| 836 | } |
| 837 | : {}), |
| 838 | }; |
| 839 | }); |
| 840 | } |
| 841 | |
| 842 | /** The hubs an instance sends its requests through: those whose address is its endpoint. */ |
| 843 | export function instanceHubs( |
| 844 | provider: ServerProvider, |
| 845 | sources: UsageLimitSourceSnapshots, |
| 846 | ): UsageLimitSourceSnapshots { |
| 847 | const endpoint = provider.auth.endpoint; |
| 848 | return endpoint === undefined ? [] : sources.filter((source) => source.origin === endpoint); |
| 849 | } |
| 850 | |
| 851 | // Antigravity meters Gemini Argon, Gemini Carbon, other Gemini, and Claude/GPT models apart. |
| 852 | function antigravityQuotaFamily(id: string) { |
| 853 | if (!id.startsWith("gemini")) return "shared"; |
| 854 | return id.includes("argon") ? "argon" : id.includes("carbon") ? "carbon" : "gemini"; |
| 855 | } |
| 856 | |
| 857 | /** Each Antigravity quota blocks only the models it meters. */ |
| 858 | export function antigravityWindowLimitsModel( |
| 859 | window: Pick<ServerProviderUsageWindow, "id">, |
| 860 | model: string | null, |
| 861 | ): boolean { |
| 862 | // A hub can prefix model ids, such as "ag/gemini-3.1-pro". |
| 863 | const base = model?.slice(model.lastIndexOf("/") + 1); |
| 864 | // An alias such as "fast" may route to either quota, so both hold it back. |
| 865 | if (base === undefined || !/^(gemini|claude|gpt)/.test(base)) return true; |
| 866 | return antigravityQuotaFamily(window.id) === antigravityQuotaFamily(base); |
| 867 | } |
| 868 | |
| 869 | /** The hub accounts that serve a model: those that list it, else every account of the driver. */ |
| 870 | export function hubRoutes( |
| 871 | sources: UsageLimitSourceSnapshots, |
| 872 | driver: ServerProvider["driver"], |
| 873 | model: string | null, |
| 874 | ): (account: UsageLimitSourceAccount) => boolean { |
| 875 | // Claude Code's 1M-context suffix is not part of the model id a hub routes. |
| 876 | const full = model?.replace(/\[1m\]$/i, ""); |
| 877 | // The hub routes a thinking suffix such as "gpt-5.2(high)" by its base model when one lists it. |
| 878 | const base = full?.replace(/\([^)]*\)$/, ""); |
| 879 | const lists = (id: string | undefined) => |
| 880 | sources.some((source) => source.accounts.some((account) => account.models?.includes(id ?? ""))); |
| 881 | const slug = lists(base) ? base : full; |
| 882 | const listed = (account: UsageLimitSourceAccount) => |
| 883 | slug !== undefined && account.models?.includes(slug) === true; |
| 884 | const serving = new Set( |
| 885 | sources.flatMap((source) => source.accounts.filter(listed).map((account) => account.driver)), |
| 886 | ); |
| 887 | // Model ids such as "opus" are aliases no hub lists, so no listing falls back to the driver. |
| 888 | if (serving.size === 0) |
| 889 | return (account) => account.driver === driver && account.models?.length !== 0; |
| 890 | // An account whose model list was unreadable may serve the model too. |
| 891 | return (account) => |
| 892 | account.models ? listed(account) : serving.has(account.driver) || account.driver === driver; |
| 893 | } |
| 894 | |
| 895 | export function collectProviderUsageLimits( |
| 896 | instanceId: ProviderInstanceId, |
| 897 | providers: readonly ServerProvider[], |
| 898 | sources: UsageLimitSourceSnapshots, |
| 899 | now: number, |
| 900 | model: string | null = null, |
| 901 | ): UsageLimitsReport | null { |
| 902 | const selected = providers.find((provider) => provider.instanceId === instanceId); |
| 903 | if (!selected) return null; |
| 904 | // Only an instance sent to a hub is known to reach the accounts that hub routes its model to. |
| 905 | const hubs = instanceHubs(selected, sources); |
| 906 | const routes = |
| 907 | hubs.length > 0 |
| 908 | ? hubRoutes(hubs, selected.driver, model) |
| 909 | : (account: UsageLimitSourceAccount) => account.driver === selected.driver; |
| 910 | const shownHubs = hubs.length > 0 ? hubs : sources; |
| 911 | const drivers = new Set( |
| 912 | shownHubs.flatMap((source) => source.accounts.filter(routes).map((account) => account.driver)), |
| 913 | ); |
| 914 | if (drivers.size === 0) drivers.add(selected.driver); |
| 915 | if (![...drivers].some((driver) => hasProviderUsageLimits(driver, providers, sources))) { |
| 916 | return null; |
| 917 | } |
| 918 | const resolveKey = accountKeyResolver([ |
| 919 | ...providers.filter((provider) => provider.enabled).map(nativeReport), |
| 920 | ...sources.flatMap((source) => source.accounts), |
| 921 | ]); |
| 922 | // Behind a hub, a local login counts only when it is one of the accounts the hub routes to. |
| 923 | const routedKeys = |
| 924 | hubs.length > 0 |
| 925 | ? new Set(hubs.flatMap((source) => source.accounts.filter(routes).map(resolveKey))) |
| 926 | : null; |
| 927 | type NativeSnapshot = { provider: ServerProvider; limits: ServerProviderUsageLimits }; |
| 928 | const nativeByAccount = new Map< |
| 929 | string, |
| 930 | { usage: NativeSnapshot; credits: NativeSnapshot | null } |
| 931 | >(); |
| 932 | for (const provider of providersWithLimits(providers)) { |
| 933 | if (!drivers.has(provider.driver) || !provider.usageLimits) continue; |
| 934 | const accountKey = resolveKey(nativeReport(provider)); |
| 935 | if (routedKeys && (accountKey === null || !routedKeys.has(accountKey))) continue; |
| 936 | const snapshot = { provider, limits: provider.usageLimits }; |
| 937 | const key = accountKey ?? `instance:${provider.instanceId}`; |
| 938 | const previous = nativeByAccount.get(key); |
| 939 | const previousUsable = previous ? limitsNotice(previous.usage.limits) === null : false; |
| 940 | const usable = limitsNotice(snapshot.limits) === null; |
| 941 | const providerWins = |
| 942 | !previous || |
| 943 | (usable && !previousUsable) || |
| 944 | (usable === previousUsable && |
| 945 | Date.parse(snapshot.limits.checkedAt) > Date.parse(previous.usage.limits.checkedAt)); |
| 946 | const previousCredit = previous?.credits; |
| 947 | const credits = |
| 948 | snapshot.limits.resetCredits && |
| 949 | (!previousCredit || |
| 950 | Date.parse(snapshot.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt)) |
| 951 | ? snapshot |
| 952 | : (previousCredit ?? null); |
| 953 | nativeByAccount.set(key, { |
| 954 | usage: providerWins ? snapshot : previous.usage, |
| 955 | credits, |
| 956 | }); |
| 957 | } |
| 958 | const native = [...nativeByAccount.values()]; |
| 959 | const nativeAccountKeys = new Set( |
| 960 | native.flatMap(({ usage: { provider, limits } }) => { |
| 961 | const key = resolveKey(nativeReport(provider)); |
| 962 | return key && limits.windows.length && !limits.unavailable ? [key] : []; |
| 963 | }), |
| 964 | ); |
| 965 | const accounts: Array<UsageLimitsReport["accounts"][number]> = []; |
| 966 | const notices: string[] = []; |
| 967 | for (const { |
| 968 | usage: { provider, limits }, |
| 969 | credits, |
| 970 | } of native) { |
| 971 | const key = resolveKey(nativeReport(provider)); |
| 972 | // Only a hub this instance reaches may redeem a credit for its thread. |
| 973 | const hubCredits = shownHubs |
| 974 | .flatMap((source) => source.accounts.map((account) => ({ source, account }))) |
| 975 | .filter( |
| 976 | ({ account }) => |
| 977 | key !== null && |
| 978 | resolveKey(account) === key && |
| 979 | account.usageLimits.resetCredits && |
| 980 | !limitsNotice(account.usageLimits), |
| 981 | ) |
| 982 | .sort( |
| 983 | (a, b) => |
| 984 | Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt), |
| 985 | )[0]; |
| 986 | const hubCreditId = hubCredits?.account.usageLimits.resetCredits?.nextCreditId; |
| 987 | const showHubCredits = |
| 988 | hubCredits && |
| 989 | (!credits || |
| 990 | Date.parse(hubCredits.account.usageLimits.checkedAt) > |
| 991 | Date.parse(credits.limits.checkedAt)); |
| 992 | const shownCredits = showHubCredits |
| 993 | ? hubCredits.account.usageLimits.resetCredits |
| 994 | : credits?.limits.resetCredits; |
| 995 | accounts.push({ |
| 996 | id: provider.instanceId, |
| 997 | driver: provider.driver, |
| 998 | label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`, |
| 999 | ...(provider.auth.label ? { plan: provider.auth.label } : {}), |
| 1000 | instanceId: provider.instanceId, |
| 1001 | resetCreditInput: |
| 1002 | hubCreditId && hubCredits |
| 1003 | ? { |
| 1004 | sourceId: hubCredits.source.id, |
| 1005 | accountId: hubCredits.account.id, |
| 1006 | creditId: hubCreditId, |
| 1007 | } |
| 1008 | : { instanceId: credits?.provider.instanceId ?? provider.instanceId }, |
| 1009 | ...(provider.displayName ? { displayName: provider.displayName } : {}), |
| 1010 | ...(provider.accentColor ? { accentColor: provider.accentColor } : {}), |
| 1011 | ...(provider.auth.email ? { email: provider.auth.email } : {}), |
| 1012 | limits: shownCredits ? { ...limits, resetCredits: shownCredits } : limits, |
| 1013 | }); |
| 1014 | } |
| 1015 | for (const source of shownHubs) { |
| 1016 | const matching = source.accounts.filter(routes); |
| 1017 | for (const account of matching) { |
| 1018 | const key = resolveKey(account); |
| 1019 | if (key && nativeAccountKeys.has(key)) continue; |
| 1020 | accounts.push({ |
| 1021 | id: `${source.id}:${account.id}`, |
| 1022 | driver: account.driver, |
| 1023 | label: `${source.label} · ${hubAccountName(account)}`, |
| 1024 | sourceLabel: "CLI Proxy", |
| 1025 | ...(account.usageLimits.resetCredits?.nextCreditId |
| 1026 | ? { |
| 1027 | resetCreditInput: { |
| 1028 | sourceId: source.id, |
| 1029 | accountId: account.id, |
| 1030 | creditId: account.usageLimits.resetCredits.nextCreditId, |
| 1031 | }, |
| 1032 | } |
| 1033 | : {}), |
| 1034 | ...(account.plan ? { plan: account.plan } : {}), |
| 1035 | ...(account.email ? { email: account.email } : {}), |
| 1036 | limits: account.usageLimits, |
| 1037 | }); |
| 1038 | } |
| 1039 | if (source.error && (matching.length > 0 || source.accounts.length === 0)) { |
| 1040 | notices.push(`${source.label}: ${source.error}`); |
| 1041 | } |
| 1042 | } |
| 1043 | return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices }; |
| 1044 | } |