package connect import ( "encoding/json" "amadan.net/oficina/equipo/internal/wire" ) // Usage recording (spec §6, gate 1a): one row per attempt and model, // each figure nullable (a harness that did not report it leaves null, // never zero), and complete only when the harness's final usage message // for the attempt was seen. // Breakdown is a Codex TokenUsageBreakdown; a figure absent from the // notice is nil. type Breakdown struct { Input *int64 `json:"inputTokens"` Cached *int64 `json:"cachedInputTokens"` CacheWrite *int64 `json:"cacheWriteInputTokens"` Output *int64 `json:"outputTokens"` Reasoning *int64 `json:"reasoningOutputTokens"` } func (b Breakdown) fields() []*int64 { return []*int64{b.Input, b.Cached, b.CacheWrite, b.Output, b.Reasoning} } // minus is b less a baseline, figure by figure; a figure the notice did // not carry stays nil, and a baseline without it counts as zero. ok is // false when a figure went back (a new thread). func (b Breakdown) minus(o Breakdown) (Breakdown, bool) { var out [5]*int64 ok := true base := o.fields() for i, v := range b.fields() { if v == nil { continue } d := *v if base[i] != nil { d -= *base[i] } ok = ok && d >= 0 out[i] = &d } return Breakdown{out[0], out[1], out[2], out[3], out[4]}, ok } // plus is b with o's figures added, figure by figure; a figure neither // carried stays nil. func (b Breakdown) plus(o Breakdown) Breakdown { var out [5]*int64 add := o.fields() for i, v := range b.fields() { switch { case v == nil && add[i] == nil: continue case v == nil: n := *add[i] out[i] = &n case add[i] == nil: n := *v out[i] = &n default: n := *v + *add[i] out[i] = &n } } return Breakdown{out[0], out[1], out[2], out[3], out[4]} } // same reports whether two breakdowns carry the same figures. func same(a, b Breakdown) bool { x, y := a.fields(), b.fields() for i := range x { if (x[i] == nil) != (y[i] == nil) || x[i] != nil && *x[i] != *y[i] { return false } } return true } // CodexTally aggregates thread/tokenUsage/updated notices for one Codex // thread (spec §6). Codex sends several per turn, each with the thread's // running total and the last request's figures, and the first notice // after a resume can already include new use, so a post-resume notice is // never subtracted. An attempt's figure is its last total minus a // verified pre-turn baseline: zero for a thread started here, or the // last total this process saw on the thread before the attempt began // (the previous turn's, including its late notices). Without one (a // resumed thread, whose total so far the pinned app-server cannot read) // the row is the sum of the attempt's own "last" figures, complete: // false. A row is complete only when the baseline was verified and the // turn's completion was observed after its notices. A notice for another // thread, or for a turn that is neither this attempt's nor the one // before it, is dropped, so a resent notice changes nothing. type CodexTally struct { Thread string turn, previous string base, cur Breakdown lasts Breakdown verified bool seen, ended bool // requests counts the attempt's own distinct notices: one per model // request. requests int64 } // NewCodexTally starts a tally for a thread: fresh (started here, zero // so far) or resumed (its total so far unknown). func NewCodexTally(thread string, fresh bool) *CodexTally { return &CodexTally{Thread: thread, verified: fresh} } // CodexNotice decodes a thread/tokenUsage/updated notice: the thread's // running total and the last request's figures. func CodexNotice(params json.RawMessage) (thread, turn string, total, last Breakdown, ok bool) { var v struct { ThreadID string `json:"threadId"` TurnID string `json:"turnId"` TokenUsage struct { Total *Breakdown `json:"total"` Last *Breakdown `json:"last"` } `json:"tokenUsage"` } if json.Unmarshal(params, &v) != nil || v.TokenUsage.Total == nil { return "", "", Breakdown{}, Breakdown{}, false } if v.TokenUsage.Last != nil { last = *v.TokenUsage.Last } return v.ThreadID, v.TurnID, *v.TokenUsage.Total, last, true } // Notice takes one notice. func (t *CodexTally) Notice(thread, turn string, total, last Breakdown) { if thread != t.Thread || turn == "" { return } switch turn { case t.turn: if t.ended || t.seen && same(total, t.cur) { // After the completion, or the same notice again. return } t.cur, t.seen = total, true t.lasts = t.lasts.plus(last) t.requests++ case t.previous: // The turn before, late: its total is still this attempt's base. t.base = total } } // Begin starts an attempt on the thread's provider turn. The last total // seen on the thread so far is its verified base; with none seen, a // thread started here stays at zero and a resumed one has no base. func (t *CodexTally) Begin(turn string) { if t.seen { t.base, t.verified = t.cur, true } if t.turn != "" { t.previous = t.turn } t.turn, t.seen, t.ended, t.cur, t.lasts, t.requests = turn, false, false, Breakdown{}, Breakdown{}, 0 } // End records that the attempt's turn completed: its notices are final. func (t *CodexTally) End() { t.ended = true } // Row is the attempt's usage row (figures null when no notice was seen). func (t *CodexTally) Row() wire.Usage { if !t.seen { return wire.Usage{} } d, complete := t.lasts, false if t.verified { if since, ok := t.cur.minus(t.base); ok { d, complete = since, t.ended } } turns := t.requests return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: complete, Turns: &turns} } // ClaudeRows reads a stream-json result: one row per model in // model_usage_since_last_result (or one row from usage, this result's // own, when the CLI reported no models), complete because the result is // the CLI's final usage message. modelUsage is never read: it is the // session's running total, so a later turn of a process or a resumed // session would count the earlier ones again. Claude reports no // reasoning figure: null. The result's num_turns goes on the row of the // model that wrote most, so each request counts once. func ClaudeRows(result []byte) []wire.Usage { var v struct { Turns *int64 `json:"num_turns"` Usage *struct { Input *int64 `json:"input_tokens"` Output *int64 `json:"output_tokens"` CacheRead *int64 `json:"cache_read_input_tokens"` CacheCreation *int64 `json:"cache_creation_input_tokens"` } `json:"usage"` Models map[string]struct { Input *int64 `json:"inputTokens"` Output *int64 `json:"outputTokens"` CacheRead *int64 `json:"cacheReadInputTokens"` CacheCreation *int64 `json:"cacheCreationInputTokens"` } `json:"model_usage_since_last_result"` } if json.Unmarshal(result, &v) != nil { return nil } var out []wire.Usage for model, m := range v.Models { out = append(out, wire.Usage{Model: model, InputTokens: m.Input, OutputTokens: m.Output, CachedInputTokens: m.CacheRead, CacheWriteTokens: m.CacheCreation, Complete: true}) } if len(out) == 0 && v.Usage != nil { out = append(out, wire.Usage{InputTokens: v.Usage.Input, OutputTokens: v.Usage.Output, CachedInputTokens: v.Usage.CacheRead, CacheWriteTokens: v.Usage.CacheCreation, Complete: true}) } sortRows(out) if v.Turns != nil && len(out) > 0 { main := 0 for i, r := range out { if r.OutputTokens != nil && (out[main].OutputTokens == nil || *r.OutputTokens > *out[main].OutputTokens) { main = i } } n := *v.Turns out[main].Turns = &n } return out } func sortRows(rows []wire.Usage) { for i := 1; i < len(rows); i++ { for j := i; j > 0 && rows[j].Model < rows[j-1].Model; j-- { rows[j], rows[j-1] = rows[j-1], rows[j] } } }