| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | |
| 6 | "amadan.net/oficina/equipo/internal/wire" |
| 7 | ) |
| 8 | |
| 9 | // Usage recording (spec §6, gate 1a): one row per attempt and model, |
| 10 | // each figure nullable (a harness that did not report it leaves null, |
| 11 | // never zero), and complete only when the harness's final usage message |
| 12 | // for the attempt was seen. |
| 13 | |
| 14 | // Breakdown is a Codex TokenUsageBreakdown; a figure absent from the |
| 15 | // notice is nil. |
| 16 | type Breakdown struct { |
| 17 | Input *int64 `json:"inputTokens"` |
| 18 | Cached *int64 `json:"cachedInputTokens"` |
| 19 | CacheWrite *int64 `json:"cacheWriteInputTokens"` |
| 20 | Output *int64 `json:"outputTokens"` |
| 21 | Reasoning *int64 `json:"reasoningOutputTokens"` |
| 22 | } |
| 23 | |
| 24 | func (b Breakdown) fields() []*int64 { |
| 25 | return []*int64{b.Input, b.Cached, b.CacheWrite, b.Output, b.Reasoning} |
| 26 | } |
| 27 | |
| 28 | // minus is b less a baseline, figure by figure; a figure the notice did |
| 29 | // not carry stays nil, and a baseline without it counts as zero. ok is |
| 30 | // false when a figure went back (a new thread). |
| 31 | func (b Breakdown) minus(o Breakdown) (Breakdown, bool) { |
| 32 | var out [5]*int64 |
| 33 | ok := true |
| 34 | base := o.fields() |
| 35 | for i, v := range b.fields() { |
| 36 | if v == nil { |
| 37 | continue |
| 38 | } |
| 39 | d := *v |
| 40 | if base[i] != nil { |
| 41 | d -= *base[i] |
| 42 | } |
| 43 | ok = ok && d >= 0 |
| 44 | out[i] = &d |
| 45 | } |
| 46 | return Breakdown{out[0], out[1], out[2], out[3], out[4]}, ok |
| 47 | } |
| 48 | |
| 49 | // plus is b with o's figures added, figure by figure; a figure neither |
| 50 | // carried stays nil. |
| 51 | func (b Breakdown) plus(o Breakdown) Breakdown { |
| 52 | var out [5]*int64 |
| 53 | add := o.fields() |
| 54 | for i, v := range b.fields() { |
| 55 | switch { |
| 56 | case v == nil && add[i] == nil: |
| 57 | continue |
| 58 | case v == nil: |
| 59 | n := *add[i] |
| 60 | out[i] = &n |
| 61 | case add[i] == nil: |
| 62 | n := *v |
| 63 | out[i] = &n |
| 64 | default: |
| 65 | n := *v + *add[i] |
| 66 | out[i] = &n |
| 67 | } |
| 68 | } |
| 69 | return Breakdown{out[0], out[1], out[2], out[3], out[4]} |
| 70 | } |
| 71 | |
| 72 | // same reports whether two breakdowns carry the same figures. |
| 73 | func same(a, b Breakdown) bool { |
| 74 | x, y := a.fields(), b.fields() |
| 75 | for i := range x { |
| 76 | if (x[i] == nil) != (y[i] == nil) || x[i] != nil && *x[i] != *y[i] { |
| 77 | return false |
| 78 | } |
| 79 | } |
| 80 | return true |
| 81 | } |
| 82 | |
| 83 | // CodexTally aggregates thread/tokenUsage/updated notices for one Codex |
| 84 | // thread (spec §6). Codex sends several per turn, each with the thread's |
| 85 | // running total and the last request's figures, and the first notice |
| 86 | // after a resume can already include new use, so a post-resume notice is |
| 87 | // never subtracted. An attempt's figure is its last total minus a |
| 88 | // verified pre-turn baseline: zero for a thread started here, or the |
| 89 | // last total this process saw on the thread before the attempt began |
| 90 | // (the previous turn's, including its late notices). Without one (a |
| 91 | // resumed thread, whose total so far the pinned app-server cannot read) |
| 92 | // the row is the sum of the attempt's own "last" figures, complete: |
| 93 | // false. A row is complete only when the baseline was verified and the |
| 94 | // turn's completion was observed after its notices. A notice for another |
| 95 | // thread, or for a turn that is neither this attempt's nor the one |
| 96 | // before it, is dropped, so a resent notice changes nothing. |
| 97 | type CodexTally struct { |
| 98 | Thread string |
| 99 | turn, previous string |
| 100 | base, cur Breakdown |
| 101 | lasts Breakdown |
| 102 | verified bool |
| 103 | seen, ended bool |
| 104 | // requests counts the attempt's own distinct notices: one per model |
| 105 | // request. |
| 106 | requests int64 |
| 107 | } |
| 108 | |
| 109 | // NewCodexTally starts a tally for a thread: fresh (started here, zero |
| 110 | // so far) or resumed (its total so far unknown). |
| 111 | func NewCodexTally(thread string, fresh bool) *CodexTally { |
| 112 | return &CodexTally{Thread: thread, verified: fresh} |
| 113 | } |
| 114 | |
| 115 | // CodexNotice decodes a thread/tokenUsage/updated notice: the thread's |
| 116 | // running total and the last request's figures. |
| 117 | func CodexNotice(params json.RawMessage) (thread, turn string, total, last Breakdown, ok bool) { |
| 118 | var v struct { |
| 119 | ThreadID string `json:"threadId"` |
| 120 | TurnID string `json:"turnId"` |
| 121 | TokenUsage struct { |
| 122 | Total *Breakdown `json:"total"` |
| 123 | Last *Breakdown `json:"last"` |
| 124 | } `json:"tokenUsage"` |
| 125 | } |
| 126 | if json.Unmarshal(params, &v) != nil || v.TokenUsage.Total == nil { |
| 127 | return "", "", Breakdown{}, Breakdown{}, false |
| 128 | } |
| 129 | if v.TokenUsage.Last != nil { |
| 130 | last = *v.TokenUsage.Last |
| 131 | } |
| 132 | return v.ThreadID, v.TurnID, *v.TokenUsage.Total, last, true |
| 133 | } |
| 134 | |
| 135 | // Notice takes one notice. |
| 136 | func (t *CodexTally) Notice(thread, turn string, total, last Breakdown) { |
| 137 | if thread != t.Thread || turn == "" { |
| 138 | return |
| 139 | } |
| 140 | switch turn { |
| 141 | case t.turn: |
| 142 | if t.ended || t.seen && same(total, t.cur) { |
| 143 | // After the completion, or the same notice again. |
| 144 | return |
| 145 | } |
| 146 | t.cur, t.seen = total, true |
| 147 | t.lasts = t.lasts.plus(last) |
| 148 | t.requests++ |
| 149 | case t.previous: |
| 150 | // The turn before, late: its total is still this attempt's base. |
| 151 | t.base = total |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // Begin starts an attempt on the thread's provider turn. The last total |
| 156 | // seen on the thread so far is its verified base; with none seen, a |
| 157 | // thread started here stays at zero and a resumed one has no base. |
| 158 | func (t *CodexTally) Begin(turn string) { |
| 159 | if t.seen { |
| 160 | t.base, t.verified = t.cur, true |
| 161 | } |
| 162 | if t.turn != "" { |
| 163 | t.previous = t.turn |
| 164 | } |
| 165 | t.turn, t.seen, t.ended, t.cur, t.lasts, t.requests = turn, false, false, Breakdown{}, Breakdown{}, 0 |
| 166 | } |
| 167 | |
| 168 | // End records that the attempt's turn completed: its notices are final. |
| 169 | func (t *CodexTally) End() { t.ended = true } |
| 170 | |
| 171 | // Row is the attempt's usage row (figures null when no notice was seen). |
| 172 | func (t *CodexTally) Row() wire.Usage { |
| 173 | if !t.seen { |
| 174 | return wire.Usage{} |
| 175 | } |
| 176 | d, complete := t.lasts, false |
| 177 | if t.verified { |
| 178 | if since, ok := t.cur.minus(t.base); ok { |
| 179 | d, complete = since, t.ended |
| 180 | } |
| 181 | } |
| 182 | turns := t.requests |
| 183 | return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: complete, Turns: &turns} |
| 184 | } |
| 185 | |
| 186 | // ClaudeRows reads a stream-json result: one row per model in |
| 187 | // model_usage_since_last_result (or one row from usage, this result's |
| 188 | // own, when the CLI reported no models), complete because the result is |
| 189 | // the CLI's final usage message. modelUsage is never read: it is the |
| 190 | // session's running total, so a later turn of a process or a resumed |
| 191 | // session would count the earlier ones again. Claude reports no |
| 192 | // reasoning figure: null. The result's num_turns goes on the row of the |
| 193 | // model that wrote most, so each request counts once. |
| 194 | func ClaudeRows(result []byte) []wire.Usage { |
| 195 | var v struct { |
| 196 | Turns *int64 `json:"num_turns"` |
| 197 | Usage *struct { |
| 198 | Input *int64 `json:"input_tokens"` |
| 199 | Output *int64 `json:"output_tokens"` |
| 200 | CacheRead *int64 `json:"cache_read_input_tokens"` |
| 201 | CacheCreation *int64 `json:"cache_creation_input_tokens"` |
| 202 | } `json:"usage"` |
| 203 | Models map[string]struct { |
| 204 | Input *int64 `json:"inputTokens"` |
| 205 | Output *int64 `json:"outputTokens"` |
| 206 | CacheRead *int64 `json:"cacheReadInputTokens"` |
| 207 | CacheCreation *int64 `json:"cacheCreationInputTokens"` |
| 208 | } `json:"model_usage_since_last_result"` |
| 209 | } |
| 210 | if json.Unmarshal(result, &v) != nil { |
| 211 | return nil |
| 212 | } |
| 213 | var out []wire.Usage |
| 214 | for model, m := range v.Models { |
| 215 | out = append(out, wire.Usage{Model: model, InputTokens: m.Input, OutputTokens: m.Output, CachedInputTokens: m.CacheRead, CacheWriteTokens: m.CacheCreation, Complete: true}) |
| 216 | } |
| 217 | if len(out) == 0 && v.Usage != nil { |
| 218 | out = append(out, wire.Usage{InputTokens: v.Usage.Input, OutputTokens: v.Usage.Output, CachedInputTokens: v.Usage.CacheRead, CacheWriteTokens: v.Usage.CacheCreation, Complete: true}) |
| 219 | } |
| 220 | sortRows(out) |
| 221 | if v.Turns != nil && len(out) > 0 { |
| 222 | main := 0 |
| 223 | for i, r := range out { |
| 224 | if r.OutputTokens != nil && (out[main].OutputTokens == nil || *r.OutputTokens > *out[main].OutputTokens) { |
| 225 | main = i |
| 226 | } |
| 227 | } |
| 228 | n := *v.Turns |
| 229 | out[main].Turns = &n |
| 230 | } |
| 231 | return out |
| 232 | } |
| 233 | |
| 234 | func sortRows(rows []wire.Usage) { |
| 235 | for i := 1; i < len(rows); i++ { |
| 236 | for j := i; j > 0 && rows[j].Model < rows[j-1].Model; j-- { |
| 237 | rows[j], rows[j-1] = rows[j-1], rows[j] |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |