package connect import ( "encoding/json" "time" "amadan.net/oficina/equipo/internal/wire" ) // Limit is a provider's word that a connection may not run now (Limited) // or how much of it is used (Headroom). Only what the provider reported: // no reset time is invented, no percentage guessed. type Limit struct { Limited bool ResetsAt time.Time // Window names the limit that was hit, as the provider named it // (Claude's seven_day or five_hour, Codex's primary or secondary). Window string Headroom *wire.Headroom } func fromUnix(sec int64) *time.Time { if sec <= 0 { return nil } t := time.Unix(sec, 0).UTC() return &t } // ClaudeRateLimit reads a stream-json rate_limit_event (the CLI's // SDKRateLimitEvent): status allowed, allowed_warning or rejected, one // utilization figure, the reset time and, when present, the per-window // figures. ok is false for any other frame. func ClaudeRateLimit(raw []byte) (Limit, bool) { var v struct { Type string `json:"type"` Info *struct { Status string `json:"status"` ResetsAt int64 `json:"resetsAt"` Type string `json:"rateLimitType"` Utilization *float64 `json:"utilization"` Windows map[string]struct { Utilization float64 `json:"utilization"` ResetsAt int64 `json:"resetsAt"` } `json:"unifiedWindows"` } `json:"rate_limit_info"` } if json.Unmarshal(raw, &v) != nil || v.Type != "rate_limit_event" || v.Info == nil { return Limit{}, false } h := &wire.Headroom{Utilization: v.Info.Utilization, ResetsAt: fromUnix(v.Info.ResetsAt), Windows: []wire.Window{}} for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} { if w, ok := v.Info.Windows[name]; ok { minutes := int64(300) if name != "five_hour" { minutes = 10080 } h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: w.Utilization * 100, Minutes: minutes, ResetsAt: fromUnix(w.ResetsAt)}) } } l := Limit{Limited: v.Info.Status == "rejected", Window: v.Info.Type, Headroom: h} if h.ResetsAt != nil { l.ResetsAt = *h.ResetsAt } return l, true } type codexWindow struct { UsedPercent float64 `json:"usedPercent"` Minutes *int64 `json:"windowDurationMins"` ResetsAt *int64 `json:"resetsAt"` } // CodexSnapshot is the app-server's rateLimits object, as carried by // account/rateLimits/updated and account/rateLimits/read. type CodexSnapshot struct { Primary *codexWindow `json:"primary"` Secondary *codexWindow `json:"secondary"` PlanType *string `json:"planType"` Reached *string `json:"rateLimitReachedType"` } // CodexRateLimits reads a rateLimits object: both windows with their // reset times, the plan, and whether a limit was reached (a window at // 100% or rateLimitReachedType set). Utilization is the fuller window. func CodexRateLimits(raw json.RawMessage) (Limit, string, bool) { var s CodexSnapshot if len(raw) == 0 || json.Unmarshal(raw, &s) != nil { return Limit{}, "", false } h := &wire.Headroom{Windows: []wire.Window{}} l := Limit{Headroom: h, Limited: s.Reached != nil && *s.Reached != ""} var used float64 for _, w := range []struct { name string w *codexWindow }{{"primary", s.Primary}, {"secondary", s.Secondary}} { if w.w == nil { continue } win := wire.Window{Name: w.name, UsedPercent: w.w.UsedPercent} if w.w.Minutes != nil { win.Minutes = *w.w.Minutes } if w.w.ResetsAt != nil { win.ResetsAt = fromUnix(*w.w.ResetsAt) } h.Windows = append(h.Windows, win) if w.w.UsedPercent >= used { used = w.w.UsedPercent } if w.w.UsedPercent >= 100 { l.Limited = true // The later reset of the spent windows is when it can answer. if win.ResetsAt != nil && win.ResetsAt.After(l.ResetsAt) { l.ResetsAt, l.Window = *win.ResetsAt, w.name } } } if len(h.Windows) > 0 { u := min(used/100, 1) h.Utilization = &u } if !l.ResetsAt.IsZero() { at := l.ResetsAt h.ResetsAt = &at } plan := "" if s.PlanType != nil { plan = *s.PlanType } return l, plan, true } // Failure classes of a turn that did not complete (spec ยง2.7): quota // (the account's usage limit: move to another connection, limited until // the reset), auth (the provider refused the credential: move, and the // connection needs signing in again) and transient (a rate limit, an // overloaded server, a dropped stream: no move, the turn fails). const ( FailQuota = "quota" FailAuth = "auth" FailTransient = "transient" ) // claudeAuth are the assistant message errors that mean the provider // refused the credential or the account. var claudeAuth = map[string]bool{"authentication_failed": true, "oauth_org_not_allowed": true, "account_on_hold": true, "billing_error": true} // ClaudeSignal reads what a stream-json frame says about the turn's // failure class: an assistant message whose error is an auth error, or a // system/api_retry for a rate limit (quota once the retries run out). func ClaudeSignal(raw []byte) string { var v struct { Type string `json:"type"` Subtype string `json:"subtype"` Error string `json:"error"` } if json.Unmarshal(raw, &v) != nil { return "" } switch { case v.Type == "assistant" && claudeAuth[v.Error]: return FailAuth case v.Type == "system" && v.Subtype == "api_retry" && v.Error == "rate_limit": return FailQuota } return "" } // CodexFailure classifies a failed turn's error (codexErrorInfo). func CodexFailure(turnError json.RawMessage) string { var e struct { Info json.RawMessage `json:"codexErrorInfo"` } var s string if json.Unmarshal(turnError, &e) != nil || json.Unmarshal(e.Info, &s) != nil { return FailTransient } switch s { case "usageLimitExceeded": return FailQuota case "unauthorized": return FailAuth } return FailTransient } // CodexQuotaError reports whether a failed turn's error is the account's // usage limit (codexErrorInfo usageLimitExceeded). func CodexQuotaError(turnError json.RawMessage) bool { return CodexFailure(turnError) == FailQuota }