package thin import ( "context" "database/sql" "encoding/json" "errors" "io" "net/http" "strings" "time" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/wire" ) // Claude Code 2.1.312, SHA256 claude.ExecutableSHA256, bundled source: // The /usage loader U calls JO at byte 263017232; JO selects the plain read. // ce at byte 246565477 selects /api/oauth/usage for the plain read; // fe at 246565833 calls Gt.get with a 5000 ms timeout and JSON content type. // Gt at 242750820 calls Hr (242743373); Xm (242741767) selects BASE_API_URL, // https://api.anthropic.com. DX (242537317) supplies Bearer and anthropic-beta // oauth-2025-04-20 (_u at 239047067). The schema at 246583562 has nullable utilization (percent) // and resets_at (ISO time) for five_hour and seven_day windows. // auth status at 269608610 reports subscriptionType for claude.ai logins. // The runner uses the profile reader's SafeClient and its own User-Agent. // No turn, refresh request, redirect, proxy or additional host is involved. const usagePath = "/api/oauth/usage" const usageSchema = ` CREATE TABLE IF NOT EXISTS conn_usage (id TEXT PRIMARY KEY, mark TEXT NOT NULL, read_at TEXT NOT NULL); ` func (p *ProfileReader) readUsage(ctx context.Context, token []byte) (int, *connect.Limit) { // A release reader cannot send credentials to a configurable origin. if p.HTTP == nil && p.Origin != ProfileOrigin { return 0, nil } ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(p.Origin, "/")+usagePath, nil) if err != nil { return 0, nil } req.Header.Set("User-Agent", p.userAgent()) req.Header.Set("Authorization", "Bearer "+string(token)) req.Header.Set("anthropic-beta", "oauth-2025-04-20") req.Header.Set("Content-Type", "application/json") req.Header.Set("Cache-Control", "no-cache") res, err := p.client().Do(req) if err != nil { return 0, nil } defer res.Body.Close() if res.StatusCode != http.StatusOK { return res.StatusCode, nil } raw, err := io.ReadAll(io.LimitReader(res.Body, maxProfileBytes+1)) if err != nil || len(raw) > maxProfileBytes { return res.StatusCode, nil } return res.StatusCode, claudeUsage(raw) } func claudeUsage(raw []byte) *connect.Limit { // Read known windows only; unrelated provider fields have other shapes. var body map[string]json.RawMessage if json.Unmarshal(raw, &body) != nil { return nil } h := &wire.Headroom{Fetched: true, Windows: []wire.Window{}} var used float64 for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} { raw, ok := body[name] if !ok { continue } var w struct { Utilization *float64 `json:"utilization"` ResetsAt *time.Time `json:"resets_at"` } if json.Unmarshal(raw, &w) != nil { return nil } if w.Utilization == nil { continue } if *w.Utilization < 0 { return nil } minutes := int64(10080) if name == "five_hour" { minutes = 300 } h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: *w.Utilization, Minutes: minutes, ResetsAt: w.ResetsAt}) used = max(used, *w.Utilization/100) } if len(h.Windows) == 0 { return nil } h.Utilization = &used return &connect.Limit{Headroom: h} } // readClaudeUsage remembers 403/404 refusals for one token for a week; a 401 // (a stale or revoked token) is retried like a transient error. func (c *Conns) readClaudeUsage(ctx context.Context, id string, token []byte) { c.usageMu.Lock() defer c.usageMu.Unlock() var mark, at string err := c.State.db.QueryRowContext(ctx, "SELECT mark, read_at FROM conn_usage WHERE id=?", id).Scan(&mark, &at) if err != nil && !errors.Is(err, sql.ErrNoRows) { return } tokenMark := profileMark(token) read, perr := time.Parse(time.RFC3339Nano, at) if err == nil && mark == tokenMark && perr == nil && c.clock().Before(read.Add(ProfileRetry)) { return } status, l := c.ClaudeUsage.readUsage(ctx, token) if c.Logger != nil { c.Logger.Info("claude usage", "status", status) } if ctx.Err() != nil { return } if l != nil { if _, err = c.State.db.ExecContext(ctx, "DELETE FROM conn_usage WHERE id=?", id); err != nil { return } c.Observe(id, *l, "") c.changed() return } if status != 403 && status != 404 { return } 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 { return } c.mu.Lock() cs := c.live[id] h := wire.Headroom{} if cs.Headroom != nil { h = *cs.Headroom } h.Unavailable = true cs.Headroom = &h c.save(id, cs) c.mu.Unlock() c.changed() }