| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "math" |
| 7 | "sync" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 10 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | ) |
| 13 | |
| 14 | type TokenUsage struct { |
| 15 | UncachedInput, CachedInput, Output int64 |
| 16 | UncachedKnown, CachedKnown, OutputKnown bool |
| 17 | } |
| 18 | type ProviderTokens struct { |
| 19 | Input, Cached, CacheWrite, Output int64 |
| 20 | InputKnown, CachedKnown, CacheWriteKnown, OutputKnown bool |
| 21 | } |
| 22 | |
| 23 | func NormalizeTokens(v ProviderTokens, inputSemantics string, writeIncluded bool) (TokenUsage, error) { |
| 24 | u := TokenUsage{UncachedInput: v.Input, CachedInput: v.Cached, Output: v.Output, UncachedKnown: v.InputKnown, CachedKnown: v.CachedKnown, OutputKnown: v.OutputKnown} |
| 25 | if v.Input < 0 || v.Cached < 0 || v.CacheWrite < 0 || v.Output < 0 { |
| 26 | return TokenUsage{}, runnerproto.ErrInvalid |
| 27 | } |
| 28 | switch inputSemantics { |
| 29 | case "inclusive": |
| 30 | if !v.CachedKnown { |
| 31 | u.UncachedKnown = false |
| 32 | } else if v.InputKnown { |
| 33 | if v.Cached > v.Input { |
| 34 | return TokenUsage{}, runnerproto.ErrInvalid |
| 35 | } |
| 36 | u.UncachedInput -= v.Cached |
| 37 | } |
| 38 | case "exclusive": |
| 39 | default: |
| 40 | return TokenUsage{}, runnerproto.ErrInvalid |
| 41 | } |
| 42 | if !writeIncluded { |
| 43 | if !v.CacheWriteKnown { |
| 44 | u.UncachedKnown = false |
| 45 | } else if v.CacheWrite > math.MaxInt64-u.UncachedInput { |
| 46 | return TokenUsage{}, runnerproto.ErrInvalid |
| 47 | } else { |
| 48 | u.UncachedInput += v.CacheWrite |
| 49 | } |
| 50 | } |
| 51 | if u.UncachedKnown && u.CachedKnown && u.UncachedInput > math.MaxInt64-u.CachedInput { |
| 52 | return TokenUsage{}, runnerproto.ErrInvalid |
| 53 | } |
| 54 | return u, nil |
| 55 | } |
| 56 | |
| 57 | type UsageProfile struct { |
| 58 | Version int |
| 59 | Provider, ProviderVersion, PaseoVersion, TokenSemantics, InputSemantics, CostSemantics string |
| 60 | Subscription bool |
| 61 | // Paseo exposes cache writes only when its adapter includes them in input. |
| 62 | CacheWriteSeparate bool |
| 63 | } |
| 64 | type UsageAccumulator struct { |
| 65 | mu sync.Mutex |
| 66 | profile UsageProfile |
| 67 | settled map[string]team.Usage |
| 68 | cost map[string]float64 |
| 69 | estimated float64 |
| 70 | direct directUsageState |
| 71 | } |
| 72 | |
| 73 | func NewUsageAccumulator(profile UsageProfile) *UsageAccumulator { |
| 74 | return &UsageAccumulator{profile: profile, settled: map[string]team.Usage{}, cost: map[string]float64{}} |
| 75 | } |
| 76 | |
| 77 | type observedUsage struct { |
| 78 | Input *int64 `json:"inputTokens"` |
| 79 | Cached *int64 `json:"cachedInputTokens"` |
| 80 | CacheWrite *int64 `json:"cacheWriteInputTokens"` |
| 81 | Output *int64 `json:"outputTokens"` |
| 82 | Cost *float64 `json:"totalCostUsd"` |
| 83 | } |
| 84 | |
| 85 | func (a *UsageAccumulator) ObservePaseo(e provider.RecordedEvent) *team.Usage { |
| 86 | a.mu.Lock() |
| 87 | defer a.mu.Unlock() |
| 88 | p := a.profile |
| 89 | if p.Version != 1 || p.PaseoVersion != "0.14.0" || p.TokenSemantics != "turn" || e.Kind != "turn_completed" || e.TurnID == "" || e.ServerID == "" || e.AgentID == "" || e.ProviderSessionID == "" { |
| 90 | return nil |
| 91 | } |
| 92 | var envelope struct { |
| 93 | Event struct { |
| 94 | Type string `json:"type"` |
| 95 | Provider string `json:"provider"` |
| 96 | TurnID string `json:"turnId"` |
| 97 | Usage *observedUsage `json:"usage"` |
| 98 | } `json:"event"` |
| 99 | } |
| 100 | if json.Unmarshal(e.Payload, &envelope) != nil || envelope.Event.Type != "turn_completed" || envelope.Event.Provider != p.Provider || envelope.Event.TurnID != e.TurnID { |
| 101 | return nil |
| 102 | } |
| 103 | key := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID, e.TurnID}) |
| 104 | if old, ok := a.settled[key]; ok { |
| 105 | return &old |
| 106 | } |
| 107 | v := envelope.Event.Usage |
| 108 | if v == nil { |
| 109 | return nil |
| 110 | } |
| 111 | tokens := ProviderTokens{InputKnown: v.Input != nil, CachedKnown: v.Cached != nil, OutputKnown: v.Output != nil, CacheWriteKnown: v.CacheWrite != nil} |
| 112 | if v.Input != nil { |
| 113 | tokens.Input = *v.Input |
| 114 | } |
| 115 | if v.Cached != nil { |
| 116 | tokens.Cached = *v.Cached |
| 117 | } |
| 118 | if v.Output != nil { |
| 119 | tokens.Output = *v.Output |
| 120 | } |
| 121 | if v.CacheWrite != nil { |
| 122 | tokens.CacheWrite = *v.CacheWrite |
| 123 | } |
| 124 | t, err := NormalizeTokens(tokens, p.InputSemantics, !p.CacheWriteSeparate) |
| 125 | if err != nil || !t.UncachedKnown || !t.CachedKnown || !t.OutputKnown { |
| 126 | return nil |
| 127 | } |
| 128 | u := team.Usage{Calls: 1, InputTokens: t.UncachedInput + t.CachedInput, CachedInputTokens: t.CachedInput, OutputTokens: t.Output, CostUnavailable: p.Subscription} |
| 129 | if v.Cost != nil && (*v.Cost < 0 || math.IsNaN(*v.Cost) || math.IsInf(*v.Cost, 0)) { |
| 130 | return nil |
| 131 | } |
| 132 | if !p.Subscription { |
| 133 | // Cumulative currency is not a per-turn receipt without a verified baseline. |
| 134 | if p.CostSemantics != "turn" || v.Cost == nil || *v.Cost >= float64(math.MaxInt64)/1e6 { |
| 135 | return nil |
| 136 | } |
| 137 | u.CostMicros = int64(math.Ceil(*v.Cost * 1e6)) |
| 138 | } |
| 139 | if v.Cost != nil { |
| 140 | stream := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID}) |
| 141 | switch p.CostSemantics { |
| 142 | case "cumulative": |
| 143 | if *v.Cost > a.cost[stream] { |
| 144 | a.estimated += *v.Cost - a.cost[stream] |
| 145 | a.cost[stream] = *v.Cost |
| 146 | } |
| 147 | case "turn": |
| 148 | a.estimated += *v.Cost |
| 149 | } |
| 150 | } |
| 151 | a.settled[key] = u |
| 152 | return &u |
| 153 | } |
| 154 | func (a *UsageAccumulator) EstimatedCostUSD() float64 { |
| 155 | a.mu.Lock() |
| 156 | defer a.mu.Unlock() |
| 157 | return a.estimated + a.direct.Estimated |
| 158 | } |
| 159 | func (j *Journal) Usage(ctx context.Context, a provider.Agent, profile UsageProfile) (*UsageAccumulator, error) { |
| 160 | accumulator := NewUsageAccumulator(profile) |
| 161 | rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events ORDER BY ordinal") |
| 162 | if err != nil { |
| 163 | return nil, err |
| 164 | } |
| 165 | defer rows.Close() |
| 166 | for rows.Next() { |
| 167 | var b []byte |
| 168 | var e Event |
| 169 | if rows.Scan(&b) != nil || json.Unmarshal(b, &e) != nil { |
| 170 | return nil, ErrJournal |
| 171 | } |
| 172 | if e.ServerID == a.ServerID && e.AgentID == a.AgentID && e.SessionID == a.ProviderSessionID { |
| 173 | accumulator.ObservePaseo(provider.RecordedEvent{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Epoch: e.Epoch, Sequence: e.Sequence, Payload: e.Payload}) |
| 174 | } |
| 175 | } |
| 176 | return accumulator, rows.Err() |
| 177 | } |
| 178 | |