| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // Claude Code 2.1.312, SHA256 claude.ExecutableSHA256, bundled source: |
| 18 | // The /usage loader U calls JO at byte 263017232; JO selects the plain read. |
| 19 | // ce at byte 246565477 selects /api/oauth/usage for the plain read; |
| 20 | // fe at 246565833 calls Gt.get with a 5000 ms timeout and JSON content type. |
| 21 | // Gt at 242750820 calls Hr (242743373); Xm (242741767) selects BASE_API_URL, |
| 22 | // https://api.anthropic.com. DX (242537317) supplies Bearer and anthropic-beta |
| 23 | // oauth-2025-04-20 (_u at 239047067). The schema at 246583562 has nullable utilization (percent) |
| 24 | // and resets_at (ISO time) for five_hour and seven_day windows. |
| 25 | // auth status at 269608610 reports subscriptionType for claude.ai logins. |
| 26 | // The runner uses the profile reader's SafeClient and its own User-Agent. |
| 27 | // No turn, refresh request, redirect, proxy or additional host is involved. |
| 28 | const usagePath = "/api/oauth/usage" |
| 29 | |
| 30 | const usageSchema = ` |
| 31 | CREATE TABLE IF NOT EXISTS conn_usage (id TEXT PRIMARY KEY, mark TEXT NOT NULL, read_at TEXT NOT NULL); |
| 32 | ` |
| 33 | |
| 34 | func (p *ProfileReader) readUsage(ctx context.Context, token []byte) (int, *connect.Limit) { |
| 35 | // A release reader cannot send credentials to a configurable origin. |
| 36 | if p.HTTP == nil && p.Origin != ProfileOrigin { |
| 37 | return 0, nil |
| 38 | } |
| 39 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 40 | defer cancel() |
| 41 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(p.Origin, "/")+usagePath, nil) |
| 42 | if err != nil { |
| 43 | return 0, nil |
| 44 | } |
| 45 | req.Header.Set("User-Agent", p.userAgent()) |
| 46 | req.Header.Set("Authorization", "Bearer "+string(token)) |
| 47 | req.Header.Set("anthropic-beta", "oauth-2025-04-20") |
| 48 | req.Header.Set("Content-Type", "application/json") |
| 49 | req.Header.Set("Cache-Control", "no-cache") |
| 50 | res, err := p.client().Do(req) |
| 51 | if err != nil { |
| 52 | return 0, nil |
| 53 | } |
| 54 | defer res.Body.Close() |
| 55 | if res.StatusCode != http.StatusOK { |
| 56 | return res.StatusCode, nil |
| 57 | } |
| 58 | raw, err := io.ReadAll(io.LimitReader(res.Body, maxProfileBytes+1)) |
| 59 | if err != nil || len(raw) > maxProfileBytes { |
| 60 | return res.StatusCode, nil |
| 61 | } |
| 62 | return res.StatusCode, claudeUsage(raw) |
| 63 | } |
| 64 | |
| 65 | func claudeUsage(raw []byte) *connect.Limit { |
| 66 | // Read known windows only; unrelated provider fields have other shapes. |
| 67 | var body map[string]json.RawMessage |
| 68 | if json.Unmarshal(raw, &body) != nil { |
| 69 | return nil |
| 70 | } |
| 71 | h := &wire.Headroom{Fetched: true, Windows: []wire.Window{}} |
| 72 | var used float64 |
| 73 | for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} { |
| 74 | raw, ok := body[name] |
| 75 | if !ok { |
| 76 | continue |
| 77 | } |
| 78 | var w struct { |
| 79 | Utilization *float64 `json:"utilization"` |
| 80 | ResetsAt *time.Time `json:"resets_at"` |
| 81 | } |
| 82 | if json.Unmarshal(raw, &w) != nil { |
| 83 | return nil |
| 84 | } |
| 85 | if w.Utilization == nil { |
| 86 | continue |
| 87 | } |
| 88 | if *w.Utilization < 0 { |
| 89 | return nil |
| 90 | } |
| 91 | minutes := int64(10080) |
| 92 | if name == "five_hour" { |
| 93 | minutes = 300 |
| 94 | } |
| 95 | h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: *w.Utilization, Minutes: minutes, ResetsAt: w.ResetsAt}) |
| 96 | used = max(used, *w.Utilization/100) |
| 97 | } |
| 98 | if len(h.Windows) == 0 { |
| 99 | return nil |
| 100 | } |
| 101 | h.Utilization = &used |
| 102 | return &connect.Limit{Headroom: h} |
| 103 | } |
| 104 | |
| 105 | // readClaudeUsage remembers 403/404 refusals for one token for a week; a 401 |
| 106 | // (a stale or revoked token) is retried like a transient error. |
| 107 | func (c *Conns) readClaudeUsage(ctx context.Context, id string, token []byte) { |
| 108 | c.usageMu.Lock() |
| 109 | defer c.usageMu.Unlock() |
| 110 | var mark, at string |
| 111 | err := c.State.db.QueryRowContext(ctx, "SELECT mark, read_at FROM conn_usage WHERE id=?", id).Scan(&mark, &at) |
| 112 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 113 | return |
| 114 | } |
| 115 | tokenMark := profileMark(token) |
| 116 | read, perr := time.Parse(time.RFC3339Nano, at) |
| 117 | if err == nil && mark == tokenMark && perr == nil && c.clock().Before(read.Add(ProfileRetry)) { |
| 118 | return |
| 119 | } |
| 120 | status, l := c.ClaudeUsage.readUsage(ctx, token) |
| 121 | if c.Logger != nil { |
| 122 | c.Logger.Info("claude usage", "status", status) |
| 123 | } |
| 124 | if ctx.Err() != nil { |
| 125 | return |
| 126 | } |
| 127 | if l != nil { |
| 128 | if _, err = c.State.db.ExecContext(ctx, "DELETE FROM conn_usage WHERE id=?", id); err != nil { |
| 129 | return |
| 130 | } |
| 131 | c.Observe(id, *l, "") |
| 132 | c.changed() |
| 133 | return |
| 134 | } |
| 135 | if status != 403 && status != 404 { |
| 136 | return |
| 137 | } |
| 138 | if _, err = c.State.db.ExecContext(ctx, "INSERT INTO conn_usage(id,mark,read_at) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET mark=excluded.mark, read_at=excluded.read_at", id, tokenMark, c.clock().UTC().Format(time.RFC3339Nano)); err != nil { |
| 139 | return |
| 140 | } |
| 141 | c.mu.Lock() |
| 142 | cs := c.live[id] |
| 143 | h := wire.Headroom{} |
| 144 | if cs.Headroom != nil { |
| 145 | h = *cs.Headroom |
| 146 | } |
| 147 | h.Unavailable = true |
| 148 | cs.Headroom = &h |
| 149 | c.save(id, cs) |
| 150 | c.mu.Unlock() |
| 151 | c.changed() |
| 152 | } |
| 153 | |