package codex import ( "context" "encoding/json" "fmt" "math" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Account quota, verified against the App Server schema generated by the // installed codex-cli 0.164.0 (`codex app-server generate-ts`): // v2/GetAccountRateLimitsResponse.ts, RateLimitSnapshot.ts, RateLimitWindow.ts, // AccountRateLimitsUpdatedNotification.ts and PlanType.ts. // // `account/rateLimits/read` is an account read, not a model call; it runs once // per connection and again only when a chat is opened after the cached copy is // older than accountReadInterval. `account/rateLimits/updated` is a sparse // rolling update that the App Server pushes itself; it is merged into the // latest read, and a null field never clears a known value. const accountReadInterval = 5 * time.Minute const accountReadTimeout = 10 * time.Second type rateLimitWindow struct { UsedPercent *float64 `json:"usedPercent"` WindowDurationMins *int64 `json:"windowDurationMins"` ResetsAt *int64 `json:"resetsAt"` } type rateLimitSnapshot struct { LimitID *string `json:"limitId"` Primary *rateLimitWindow `json:"primary"` Secondary *rateLimitWindow `json:"secondary"` PlanType *string `json:"planType"` } // quotaState is the merged native snapshot behind the published quota. type quotaState struct { limitID string primary *rateLimitWindow secondary *rateLimitWindow plan string asOf time.Time } // windowLabel names a window by its native duration: "5-hour", "Weekly". func windowLabel(minutes *int64, fallback string) string { if minutes == nil || *minutes <= 0 { return fallback } m := *minutes switch { case m == 7*24*60: return "Weekly" case m == 24*60: return "Daily" case m%(24*60) == 0: return fmt.Sprintf("%d-day", m/(24*60)) case m%60 == 0: return fmt.Sprintf("%d-hour", m/60) default: return fmt.Sprintf("%d-minute", m) } } func quotaWindow(id, fallback string, w *rateLimitWindow) (protocol.ChatQuotaWindow, bool) { if w == nil || w.UsedPercent == nil || math.IsNaN(*w.UsedPercent) || math.IsInf(*w.UsedPercent, 0) || *w.UsedPercent < 0 { return protocol.ChatQuotaWindow{}, false } out := protocol.ChatQuotaWindow{ID: id, Label: windowLabel(w.WindowDurationMins, fallback), UsedPercent: *w.UsedPercent} if w.ResetsAt != nil && *w.ResetsAt > 0 { // RateLimitWindow.resetsAt is Unix seconds (codex-rs RateLimitWindow). out.ResetsAt = *w.ResetsAt * 1000 } return out, true } // merge folds a (possibly sparse) snapshot into the state and reports whether // anything usable changed. A snapshot for another metered limit is ignored. func (q *quotaState) merge(s *rateLimitSnapshot, now time.Time) bool { if s == nil { return false } if s.LimitID != nil && *s.LimitID != "" { if q.limitID != "" && q.limitID != *s.LimitID { return false } q.limitID = *s.LimitID } changed := false if s.Primary != nil && s.Primary.UsedPercent != nil { q.primary, changed = s.Primary, true } if s.Secondary != nil && s.Secondary.UsedPercent != nil { q.secondary, changed = s.Secondary, true } if s.PlanType != nil && *s.PlanType != "" && *s.PlanType != "unknown" { changed = changed || q.plan != *s.PlanType q.plan = *s.PlanType } if changed { q.asOf = now } return changed } func (q *quotaState) account() *protocol.ChatAccountUsage { if q == nil { return nil } out := &protocol.ChatAccountUsage{Harness: "Codex", Source: "account/rateLimits", Plan: q.plan, AsOf: q.asOf.UnixMilli()} if w, ok := quotaWindow("primary", "Primary", q.primary); ok { out.Windows = append(out.Windows, w) } if w, ok := quotaWindow("secondary", "Secondary", q.secondary); ok { out.Windows = append(out.Windows, w) } if len(out.Windows) == 0 { return nil } return out } // accountLocked is the published quota. Called under mu. func (c *Chat) accountLocked() *protocol.ChatAccountUsage { return c.quota.account() } // readAccountRateLimits performs the one cheap native read, when due. It never // runs on the reader goroutine (call waits on a response the reader delivers). func (c *Chat) readAccountRateLimits() { c.mu.Lock() due := c.accountReads && !c.closed && !c.accountReading && time.Since(c.accountReadAt) >= accountReadInterval if due { c.accountReading = true c.accountReadAt = time.Now() } c.mu.Unlock() if !due { return } go func() { defer func() { c.mu.Lock() c.accountReading = false c.mu.Unlock() }() ctx, cancel := context.WithTimeout(c.ctx, accountReadTimeout) defer cancel() raw, err := c.call(ctx, "account/rateLimits/read", map[string]any{"excludeResetCreditDetails": true}) if err != nil { return // API-key logins and older servers have no quota; stay unknown } var reply struct { RateLimits *rateLimitSnapshot `json:"rateLimits"` } if json.Unmarshal(raw, &reply) == nil { c.applyRateLimits(reply.RateLimits) } }() } func (c *Chat) receiveRateLimits(raw json.RawMessage) { var p struct { RateLimits *rateLimitSnapshot `json:"rateLimits"` } if json.Unmarshal(raw, &p) == nil { c.applyRateLimits(p.RateLimits) } } // applyRateLimits merges a snapshot and republishes every watched or retained // session's usage with the new quota. Token figures are never invented: a // session without a token snapshot gets an account-only frame. func (c *Chat) applyRateLimits(s *rateLimitSnapshot) { c.mu.Lock() if c.quota == nil { c.quota = "aState{} } if !c.quota.merge(s, time.Now()) { c.mu.Unlock() return } ids := map[string]bool{} for id := range c.subs { ids[id] = true } for id := range c.usage { ids[id] = true } frames := make([]protocol.ChatEventFrame, 0, len(ids)) for id := range ids { usage := &protocol.ChatUsage{} if snapshot, ok := c.usage[id]; ok && snapshot.frame.Usage != nil { copy := *snapshot.frame.Usage usage = © } frames = append(frames, protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventUsage, Usage: usage}) } c.mu.Unlock() for _, frame := range frames { c.emit(frame) } }