| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "time" |
| 6 | |
| 7 | "amadan.net/oficina/equipo/internal/wire" |
| 8 | ) |
| 9 | |
| 10 | // Limit is a provider's word that a connection may not run now (Limited) |
| 11 | // or how much of it is used (Headroom). Only what the provider reported: |
| 12 | // no reset time is invented, no percentage guessed. |
| 13 | type Limit struct { |
| 14 | Limited bool |
| 15 | ResetsAt time.Time |
| 16 | // Window names the limit that was hit, as the provider named it |
| 17 | // (Claude's seven_day or five_hour, Codex's primary or secondary). |
| 18 | Window string |
| 19 | Headroom *wire.Headroom |
| 20 | } |
| 21 | |
| 22 | func fromUnix(sec int64) *time.Time { |
| 23 | if sec <= 0 { |
| 24 | return nil |
| 25 | } |
| 26 | t := time.Unix(sec, 0).UTC() |
| 27 | return &t |
| 28 | } |
| 29 | |
| 30 | // ClaudeRateLimit reads a stream-json rate_limit_event (the CLI's |
| 31 | // SDKRateLimitEvent): status allowed, allowed_warning or rejected, one |
| 32 | // utilization figure, the reset time and, when present, the per-window |
| 33 | // figures. ok is false for any other frame. |
| 34 | func ClaudeRateLimit(raw []byte) (Limit, bool) { |
| 35 | var v struct { |
| 36 | Type string `json:"type"` |
| 37 | Info *struct { |
| 38 | Status string `json:"status"` |
| 39 | ResetsAt int64 `json:"resetsAt"` |
| 40 | Type string `json:"rateLimitType"` |
| 41 | Utilization *float64 `json:"utilization"` |
| 42 | Windows map[string]struct { |
| 43 | Utilization float64 `json:"utilization"` |
| 44 | ResetsAt int64 `json:"resetsAt"` |
| 45 | } `json:"unifiedWindows"` |
| 46 | } `json:"rate_limit_info"` |
| 47 | } |
| 48 | if json.Unmarshal(raw, &v) != nil || v.Type != "rate_limit_event" || v.Info == nil { |
| 49 | return Limit{}, false |
| 50 | } |
| 51 | h := &wire.Headroom{Utilization: v.Info.Utilization, ResetsAt: fromUnix(v.Info.ResetsAt), Windows: []wire.Window{}} |
| 52 | for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} { |
| 53 | if w, ok := v.Info.Windows[name]; ok { |
| 54 | minutes := int64(300) |
| 55 | if name != "five_hour" { |
| 56 | minutes = 10080 |
| 57 | } |
| 58 | h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: w.Utilization * 100, Minutes: minutes, ResetsAt: fromUnix(w.ResetsAt)}) |
| 59 | } |
| 60 | } |
| 61 | l := Limit{Limited: v.Info.Status == "rejected", Window: v.Info.Type, Headroom: h} |
| 62 | if h.ResetsAt != nil { |
| 63 | l.ResetsAt = *h.ResetsAt |
| 64 | } |
| 65 | return l, true |
| 66 | } |
| 67 | |
| 68 | type codexWindow struct { |
| 69 | UsedPercent float64 `json:"usedPercent"` |
| 70 | Minutes *int64 `json:"windowDurationMins"` |
| 71 | ResetsAt *int64 `json:"resetsAt"` |
| 72 | } |
| 73 | |
| 74 | // CodexSnapshot is the app-server's rateLimits object, as carried by |
| 75 | // account/rateLimits/updated and account/rateLimits/read. |
| 76 | type CodexSnapshot struct { |
| 77 | Primary *codexWindow `json:"primary"` |
| 78 | Secondary *codexWindow `json:"secondary"` |
| 79 | PlanType *string `json:"planType"` |
| 80 | Reached *string `json:"rateLimitReachedType"` |
| 81 | } |
| 82 | |
| 83 | // CodexRateLimits reads a rateLimits object: both windows with their |
| 84 | // reset times, the plan, and whether a limit was reached (a window at |
| 85 | // 100% or rateLimitReachedType set). Utilization is the fuller window. |
| 86 | func CodexRateLimits(raw json.RawMessage) (Limit, string, bool) { |
| 87 | var s CodexSnapshot |
| 88 | if len(raw) == 0 || json.Unmarshal(raw, &s) != nil { |
| 89 | return Limit{}, "", false |
| 90 | } |
| 91 | h := &wire.Headroom{Windows: []wire.Window{}} |
| 92 | l := Limit{Headroom: h, Limited: s.Reached != nil && *s.Reached != ""} |
| 93 | var used float64 |
| 94 | for _, w := range []struct { |
| 95 | name string |
| 96 | w *codexWindow |
| 97 | }{{"primary", s.Primary}, {"secondary", s.Secondary}} { |
| 98 | if w.w == nil { |
| 99 | continue |
| 100 | } |
| 101 | win := wire.Window{Name: w.name, UsedPercent: w.w.UsedPercent} |
| 102 | if w.w.Minutes != nil { |
| 103 | win.Minutes = *w.w.Minutes |
| 104 | } |
| 105 | if w.w.ResetsAt != nil { |
| 106 | win.ResetsAt = fromUnix(*w.w.ResetsAt) |
| 107 | } |
| 108 | h.Windows = append(h.Windows, win) |
| 109 | if w.w.UsedPercent >= used { |
| 110 | used = w.w.UsedPercent |
| 111 | } |
| 112 | if w.w.UsedPercent >= 100 { |
| 113 | l.Limited = true |
| 114 | // The later reset of the spent windows is when it can answer. |
| 115 | if win.ResetsAt != nil && win.ResetsAt.After(l.ResetsAt) { |
| 116 | l.ResetsAt, l.Window = *win.ResetsAt, w.name |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | if len(h.Windows) > 0 { |
| 121 | u := min(used/100, 1) |
| 122 | h.Utilization = &u |
| 123 | } |
| 124 | if !l.ResetsAt.IsZero() { |
| 125 | at := l.ResetsAt |
| 126 | h.ResetsAt = &at |
| 127 | } |
| 128 | plan := "" |
| 129 | if s.PlanType != nil { |
| 130 | plan = *s.PlanType |
| 131 | } |
| 132 | return l, plan, true |
| 133 | } |
| 134 | |
| 135 | // Failure classes of a turn that did not complete (spec §2.7): quota |
| 136 | // (the account's usage limit: move to another connection, limited until |
| 137 | // the reset), auth (the provider refused the credential: move, and the |
| 138 | // connection needs signing in again) and transient (a rate limit, an |
| 139 | // overloaded server, a dropped stream: no move, the turn fails). |
| 140 | const ( |
| 141 | FailQuota = "quota" |
| 142 | FailAuth = "auth" |
| 143 | FailTransient = "transient" |
| 144 | ) |
| 145 | |
| 146 | // claudeAuth are the assistant message errors that mean the provider |
| 147 | // refused the credential or the account. |
| 148 | var claudeAuth = map[string]bool{"authentication_failed": true, "oauth_org_not_allowed": true, "account_on_hold": true, "billing_error": true} |
| 149 | |
| 150 | // ClaudeSignal reads what a stream-json frame says about the turn's |
| 151 | // failure class: an assistant message whose error is an auth error, or a |
| 152 | // system/api_retry for a rate limit (quota once the retries run out). |
| 153 | func ClaudeSignal(raw []byte) string { |
| 154 | var v struct { |
| 155 | Type string `json:"type"` |
| 156 | Subtype string `json:"subtype"` |
| 157 | Error string `json:"error"` |
| 158 | } |
| 159 | if json.Unmarshal(raw, &v) != nil { |
| 160 | return "" |
| 161 | } |
| 162 | switch { |
| 163 | case v.Type == "assistant" && claudeAuth[v.Error]: |
| 164 | return FailAuth |
| 165 | case v.Type == "system" && v.Subtype == "api_retry" && v.Error == "rate_limit": |
| 166 | return FailQuota |
| 167 | } |
| 168 | return "" |
| 169 | } |
| 170 | |
| 171 | // CodexFailure classifies a failed turn's error (codexErrorInfo). |
| 172 | func CodexFailure(turnError json.RawMessage) string { |
| 173 | var e struct { |
| 174 | Info json.RawMessage `json:"codexErrorInfo"` |
| 175 | } |
| 176 | var s string |
| 177 | if json.Unmarshal(turnError, &e) != nil || json.Unmarshal(e.Info, &s) != nil { |
| 178 | return FailTransient |
| 179 | } |
| 180 | switch s { |
| 181 | case "usageLimitExceeded": |
| 182 | return FailQuota |
| 183 | case "unauthorized": |
| 184 | return FailAuth |
| 185 | } |
| 186 | return FailTransient |
| 187 | } |
| 188 | |
| 189 | // CodexQuotaError reports whether a failed turn's error is the account's |
| 190 | // usage limit (codexErrorInfo usageLimitExceeded). |
| 191 | func CodexQuotaError(turnError json.RawMessage) bool { return CodexFailure(turnError) == FailQuota } |
| 192 | |