package runner import ( "context" "encoding/json" "math" "sync" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type TokenUsage struct { UncachedInput, CachedInput, Output int64 UncachedKnown, CachedKnown, OutputKnown bool } type ProviderTokens struct { Input, Cached, CacheWrite, Output int64 InputKnown, CachedKnown, CacheWriteKnown, OutputKnown bool } func NormalizeTokens(v ProviderTokens, inputSemantics string, writeIncluded bool) (TokenUsage, error) { u := TokenUsage{UncachedInput: v.Input, CachedInput: v.Cached, Output: v.Output, UncachedKnown: v.InputKnown, CachedKnown: v.CachedKnown, OutputKnown: v.OutputKnown} if v.Input < 0 || v.Cached < 0 || v.CacheWrite < 0 || v.Output < 0 { return TokenUsage{}, runnerproto.ErrInvalid } switch inputSemantics { case "inclusive": if !v.CachedKnown { u.UncachedKnown = false } else if v.InputKnown { if v.Cached > v.Input { return TokenUsage{}, runnerproto.ErrInvalid } u.UncachedInput -= v.Cached } case "exclusive": default: return TokenUsage{}, runnerproto.ErrInvalid } if !writeIncluded { if !v.CacheWriteKnown { u.UncachedKnown = false } else if v.CacheWrite > math.MaxInt64-u.UncachedInput { return TokenUsage{}, runnerproto.ErrInvalid } else { u.UncachedInput += v.CacheWrite } } if u.UncachedKnown && u.CachedKnown && u.UncachedInput > math.MaxInt64-u.CachedInput { return TokenUsage{}, runnerproto.ErrInvalid } return u, nil } type UsageProfile struct { Version int Provider, ProviderVersion, PaseoVersion, TokenSemantics, InputSemantics, CostSemantics string Subscription bool // Paseo exposes cache writes only when its adapter includes them in input. CacheWriteSeparate bool } type UsageAccumulator struct { mu sync.Mutex profile UsageProfile settled map[string]team.Usage cost map[string]float64 estimated float64 direct directUsageState } func NewUsageAccumulator(profile UsageProfile) *UsageAccumulator { return &UsageAccumulator{profile: profile, settled: map[string]team.Usage{}, cost: map[string]float64{}} } type observedUsage struct { Input *int64 `json:"inputTokens"` Cached *int64 `json:"cachedInputTokens"` CacheWrite *int64 `json:"cacheWriteInputTokens"` Output *int64 `json:"outputTokens"` Cost *float64 `json:"totalCostUsd"` } func (a *UsageAccumulator) ObservePaseo(e provider.RecordedEvent) *team.Usage { a.mu.Lock() defer a.mu.Unlock() p := a.profile if p.Version != 1 || p.PaseoVersion != "0.14.0" || p.TokenSemantics != "turn" || e.Kind != "turn_completed" || e.TurnID == "" || e.ServerID == "" || e.AgentID == "" || e.ProviderSessionID == "" { return nil } var envelope struct { Event struct { Type string `json:"type"` Provider string `json:"provider"` TurnID string `json:"turnId"` Usage *observedUsage `json:"usage"` } `json:"event"` } if json.Unmarshal(e.Payload, &envelope) != nil || envelope.Event.Type != "turn_completed" || envelope.Event.Provider != p.Provider || envelope.Event.TurnID != e.TurnID { return nil } key := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID, e.TurnID}) if old, ok := a.settled[key]; ok { return &old } v := envelope.Event.Usage if v == nil { return nil } tokens := ProviderTokens{InputKnown: v.Input != nil, CachedKnown: v.Cached != nil, OutputKnown: v.Output != nil, CacheWriteKnown: v.CacheWrite != nil} if v.Input != nil { tokens.Input = *v.Input } if v.Cached != nil { tokens.Cached = *v.Cached } if v.Output != nil { tokens.Output = *v.Output } if v.CacheWrite != nil { tokens.CacheWrite = *v.CacheWrite } t, err := NormalizeTokens(tokens, p.InputSemantics, !p.CacheWriteSeparate) if err != nil || !t.UncachedKnown || !t.CachedKnown || !t.OutputKnown { return nil } u := team.Usage{Calls: 1, InputTokens: t.UncachedInput + t.CachedInput, CachedInputTokens: t.CachedInput, OutputTokens: t.Output, CostUnavailable: p.Subscription} if v.Cost != nil && (*v.Cost < 0 || math.IsNaN(*v.Cost) || math.IsInf(*v.Cost, 0)) { return nil } if !p.Subscription { // Cumulative currency is not a per-turn receipt without a verified baseline. if p.CostSemantics != "turn" || v.Cost == nil || *v.Cost >= float64(math.MaxInt64)/1e6 { return nil } u.CostMicros = int64(math.Ceil(*v.Cost * 1e6)) } if v.Cost != nil { stream := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID}) switch p.CostSemantics { case "cumulative": if *v.Cost > a.cost[stream] { a.estimated += *v.Cost - a.cost[stream] a.cost[stream] = *v.Cost } case "turn": a.estimated += *v.Cost } } a.settled[key] = u return &u } func (a *UsageAccumulator) EstimatedCostUSD() float64 { a.mu.Lock() defer a.mu.Unlock() return a.estimated + a.direct.Estimated } func (j *Journal) Usage(ctx context.Context, a provider.Agent, profile UsageProfile) (*UsageAccumulator, error) { accumulator := NewUsageAccumulator(profile) rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events ORDER BY ordinal") if err != nil { return nil, err } defer rows.Close() for rows.Next() { var b []byte var e Event if rows.Scan(&b) != nil || json.Unmarshal(b, &e) != nil { return nil, ErrJournal } if e.ServerID == a.ServerID && e.AgentID == a.AgentID && e.SessionID == a.ProviderSessionID { 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}) } } return accumulator, rows.Err() }