Module: CodexLimitless::Limits

Defined in:
lib/codex_limitless/limits.rb

Class Method Summary collapse

Class Method Details

.fetch_rate_limits(codex_bin) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/codex_limitless/limits.rb', line 106

def fetch_rate_limits(codex_bin)
  client = AppServerClient.new(codex_bin)
  client.request(
    "initialize",
    params: {
      "clientInfo" => {
        "name" => "codex-limitless",
        "title" => nil,
        "version" => VERSION
      },
      "capabilities" => {
        "experimentalApi" => true,
        "requestAttestation" => false,
        "optOutNotificationMethods" => []
      }
    }
  )
  client.request("account/rateLimits/read")
ensure
  client&.close
end

.select_limit_snapshot(rate_limits, limit_id) ⇒ Object



128
129
130
131
# File 'lib/codex_limitless/limits.rb', line 128

def select_limit_snapshot(rate_limits, limit_id)
  by_id = rate_limits["rateLimitsByLimitId"] || {}
  by_id[limit_id] || rate_limits["rateLimits"]
end

.select_window(snapshot, duration_mins, fallback_key) ⇒ Object



133
134
135
136
# File 'lib/codex_limitless/limits.rb', line 133

def select_window(snapshot, duration_mins, fallback_key)
  windows = [snapshot["primary"], snapshot["secondary"]].compact
  windows.find { |window| window["windowDurationMins"].to_i == duration_mins } || snapshot[fallback_key]
end

.summary(codex_bin:, limit_id:) ⇒ Object

Raises:



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/codex_limitless/limits.rb', line 91

def summary(codex_bin:, limit_id:)
  rate_limits = fetch_rate_limits(codex_bin)
  snapshot = select_limit_snapshot(rate_limits, limit_id)
  raise Error, "No rate limit snapshot found for limit id `#{limit_id}`" unless snapshot

  {
    "limit_id" => snapshot["limitId"] || limit_id,
    "limit_name" => snapshot["limitName"],
    "plan_type" => snapshot["planType"],
    "five_hour" => window_summary(select_window(snapshot, 300, "primary")),
    "weekly" => window_summary(select_window(snapshot, 10_080, "secondary")),
    "rate_limit_reset_credits" => rate_limits["rateLimitResetCredits"]
  }
end

.window_summary(window) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/codex_limitless/limits.rb', line 138

def window_summary(window)
  used_percent = window&.fetch("usedPercent", nil)
  remaining_percent = used_percent.nil? ? nil : [[100 - used_percent.to_i, 0].max, 100].min
  resets_at = window&.fetch("resetsAt", nil)

  {
    "window_duration_mins" => window&.fetch("windowDurationMins", nil),
    "used_percent" => used_percent,
    "remaining_percent" => remaining_percent,
    "resets_at" => resets_at,
    "resets_at_local" => resets_at ? Time.at(resets_at).strftime("%Y-%m-%d %I:%M:%S %p %Z") : nil,
    "resets_at_iso8601" => resets_at ? Time.at(resets_at).iso8601 : nil
  }
end