Gate 1a: usage rows per attempt and model, Codex totals from baselines
Usage is a row per attempt and model (rev 2b §6): outcome, complete, nullable figures (null when the harness did not report one). Claude's rows come from the result's modelUsage; Codex's from a tally of the thread's notices: the attempt's last total less the total seen before it began (the first total after a resume), so several notices and a resent one count once. Rows travel on reply, step and answer frames, and a usage frame carries attempts that did not reply (failed, cancelled, refused before a failover). The instance keys rows by turn, step, attempt, connection and model, so a resent frame is a no-op. The fake Codex sends running totals, several notices per turn and the resume replay. Unit tests over the recorded probe and the resume case; headless U1 and U2. The turn between attempts is waiting (limited or sign_in_again) and only then running on the next attempt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
32 files changed,
+630
−134
internal/equipo/chat/connections.go+64 −20internal/equipo/chat/questions.go+1 −1internal/equipo/chat/runner.go+12 −3internal/equipo/chat/stream.go+1 −1internal/equipo/chat/tasks.go+1 −1internal/equipo/chat_page.go+1 −1internal/equipo/migrations/0048_thin_connections.sql+2 −1internal/equipo/migrations/schema.sql+2 −1internal/equipo/static/chat-stream.js+1 −1internal/fakecodex/fake.go+62 −2internal/headless/connections_test.go+64 −0internal/runner/connect/usage.go+155 −0internal/runner/connect/usage_test.go+112 −0internal/runner/provider/claude/events.go+0 −6internal/runner/thin/claude.go+4 −3internal/runner/thin/codex.go+15 −22internal/runner/thin/contract_test.go+4 −2internal/runner/thin/engine.go+13 −6internal/runner/thin/engineer.go+17 −16internal/runner/thin/failover.go+38 −21internal/runner/thin/judge.go+2 −1internal/runner/thin/state.go+7 −1internal/thintest/connections_contract_test.go+3 −1internal/thintest/instance_contract_test.go+1 −1internal/wire/connections_test.go+2 −2internal/wire/frames.go+40 −15internal/wire/questions.go+1 −1internal/wire/tasks.go+1 −1internal/wire/wire_test.go+1 −1internal/wire/wiretest/testdata/frames/reply-usage.json+1 −1internal/wire/wiretest/testdata/frames/reply.json+1 −1internal/wire/wiretest/testdata/frames/usage.json+1 −0
CI failed — run details
Intent
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index cb529649..84d9268e 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -9,6 +9,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/wire" |
| "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| ) |
| // Connections (Equipo Connections spec §§2, 7, slice 1): the instance |
| @@ -49,21 +50,25 @@ func (connectionRecord) TableName() string { return "chat_connections" } |
| // usageRecord is one turn's, step attempt's or answer's token use, as the |
| // runner reported it from the harness (spec §6, recorded from day one). |
| type usageRecord struct { |
| - ID int64 `gorm:"primaryKey"` |
| - Person string `gorm:"index:chat_usage_person,priority:1"` |
| - Connection string |
| - Provider string |
| - Model string |
| - Role string |
| - TaskID string |
| - StepID string |
| - TurnID string |
| - Attempt int64 |
| - InputTokens int64 |
| - CachedInputTokens int64 |
| - CacheWriteTokens int64 |
| - OutputTokens int64 |
| - ReasoningOutputTokens int64 |
| + ID int64 `gorm:"primaryKey"` |
| + Person string `gorm:"index:chat_usage_person,priority:1"` |
| + Connection string `gorm:"uniqueIndex:chat_usage_key,priority:4"` |
| + Provider string |
| + Model string `gorm:"uniqueIndex:chat_usage_key,priority:5"` |
| + Role string |
| + TaskID string |
| + // StepID is a step's, or a question's; TurnID a coordinator turn's. |
| + StepID string `gorm:"uniqueIndex:chat_usage_key,priority:2"` |
| + TurnID string `gorm:"uniqueIndex:chat_usage_key,priority:1"` |
| + Attempt int64 `gorm:"uniqueIndex:chat_usage_key,priority:3"` |
| + Outcome string |
| + Complete bool |
| + // Figures the harness did not report stay null, never zero. |
| + InputTokens *int64 |
| + CachedInputTokens *int64 |
| + CacheWriteTokens *int64 |
| + OutputTokens *int64 |
| + ReasoningOutputTokens *int64 |
| RecordedAt time.Time `gorm:"index:chat_usage_person,priority:2"` |
| } |
| @@ -352,12 +357,51 @@ func (t *txn) expireAttempts() error { |
| return nil |
| } |
| -// recordUsage keeps one usage row; a usage with no tokens is not one. |
| -func (t *txn) recordUsage(person, role, task, step, turn string, attempt int64, u *wire.Usage) error { |
| - if u == nil || u.InputTokens+u.OutputTokens+u.CachedInputTokens+u.CacheWriteTokens+u.ReasoningOutputTokens == 0 { |
| - return nil |
| +// usageOutcomes are the endings a usage row may name. |
| +var usageOutcomes = map[string]bool{wire.OutcomeReplied: true, wire.OutcomeFailed: true, wire.OutcomeCancelled: true, wire.OutcomeSuperseded: true} |
| + |
| +// recordUsage keeps one row per attempt and model, keyed so a resent |
| +// frame changes nothing. turn is a coordinator turn, step a step or a |
| +// question. |
| +func (t *txn) recordUsage(person, role, task, step, turn string, rows []wire.Usage) error { |
| + for _, u := range rows { |
| + if !usageOutcomes[u.Outcome] || u.Attempt < 1 || len(u.Model) > 200 || len(u.Connection) > 200 { |
| + return ErrInvalid |
| + } |
| + r := usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, RecordedAt: t.now()} |
| + if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// usageReport records the rows of attempts that produced no reply, for |
| +// one of the person's own turns, steps or questions. |
| +func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| + person := l.Runner.Person |
| + switch { |
| + case v.TurnID != "" && v.StepID == "" && v.QuestionID == "": |
| + if _, err := t.ownTurn(l, v.TurnID); err != nil { |
| + return err |
| + } |
| + return t.recordUsage(person, "coordinator", "", "", v.TurnID, v.Rows) |
| + case v.StepID != "" && v.TurnID == "" && v.QuestionID == "": |
| + var s stepRecord |
| + if err := t.db.Where("id = ? AND person = ?", v.StepID, person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + return t.recordUsage(person, s.Specialist, s.TaskID, s.ID, "", v.Rows) |
| + case v.QuestionID != "" && v.TurnID == "" && v.StepID == "": |
| + q, err := t.ownQuestion(l, v.QuestionID) |
| + if err != nil { |
| + return err |
| + } |
| + return t.recordUsage(person, "ask", q.TaskID, q.ID, "", v.Rows) |
| } |
| - return t.db.Create(&usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: attempt, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, RecordedAt: t.now()}).Error |
| + return ErrInvalid |
| } |
| // NoConnectionLine is what the person's connections say about why |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index 52802b2b..e45bef49 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -422,7 +422,7 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| break |
| } |
| q.State, q.Reason, q.Answer = wire.QuestionAnswered, "", clipText(answer, wire.MaxAnswerText) |
| - if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.StepID, q.ID, q.Attempt, v.Usage); err != nil { |
| + if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.ID, "", v.Usage); err != nil { |
| return err |
| } |
| if v.Timing != nil { |
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go| index d875086b..5f6c0451 100644 |
| --- a/internal/equipo/chat/runner.go |
| +++ b/internal/equipo/chat/runner.go |
| @@ -232,6 +232,8 @@ func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) erro |
| return t.branchMoved(l, v) |
| case *wire.ConnectionReport: |
| return t.connectionReport(l, v) |
| + case *wire.UsageReport: |
| + return t.usageReport(l, v) |
| } |
| return ErrInvalid |
| }) |
| @@ -321,8 +323,11 @@ func (t *txn) reply(l Lease, v *wire.Reply) error { |
| if len(v.Text) > 4*wire.MaxMessageBytes { |
| v.Text = v.Text[:4*wire.MaxMessageBytes] |
| } |
| - r.State, r.Reason, r.Attempt, r.Connection = wire.TurnReplied, "", v.Attempt, v.Usage.Connection |
| - if err := t.recordUsage(r.Person, "coordinator", "", "", r.ID, v.Attempt, &v.Usage); err != nil { |
| + r.State, r.Reason, r.Attempt = wire.TurnReplied, "", v.Attempt |
| + for _, u := range v.Usage { |
| + r.Connection = u.Connection |
| + } |
| + if err := t.recordUsage(r.Person, "coordinator", "", "", r.ID, v.Usage); err != nil { |
| return err |
| } |
| // A move-in or explore turn with nothing to say posts nothing. |
| @@ -353,6 +358,10 @@ func (t *txn) reply(l Lease, v *wire.Reply) error { |
| return t.dispatchNext(r.Person) |
| } |
| +// waitReasons say why a turn waits: its connection was limited or |
| +// refused its credential (between attempts), or nothing can answer. |
| +var waitReasons = map[string]bool{"limited": true, "sign_in_again": true, wire.ReasonNoConnection: true} |
| + |
| func (t *txn) report(l Lease, v *wire.TurnReport) error { |
| if !wire.Reasons[v.Reason] { |
| return ErrInvalid |
| @@ -368,7 +377,7 @@ func (t *txn) report(l Lease, v *wire.TurnReport) error { |
| case wire.TurnRunning, wire.TurnWaiting: |
| // Running again on a new attempt (recovery, a failover), held for a |
| // connection (waiting, no_connection), or going again (running). |
| - if v.State == wire.TurnRunning && v.Reason != "" || v.State == wire.TurnWaiting && v.Reason != wire.ReasonNoConnection { |
| + if v.State == wire.TurnRunning && v.Reason != "" || v.State == wire.TurnWaiting && !waitReasons[v.Reason] { |
| return ErrInvalid |
| } |
| if v.Attempt == r.Attempt && r.State == v.State { |
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go| index 320fc347..bf38e240 100644 |
| --- a/internal/equipo/chat/stream.go |
| +++ b/internal/equipo/chat/stream.go |
| @@ -153,7 +153,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode { |
| switch v := body.(type) { |
| case *wire.Hello: |
| err = store.Heartbeat(ctx, rc.lease, *v) |
| - case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport: |
| + case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport: |
| err = store.Apply(ctx, rc.lease, f, body) |
| case *wire.LeaseCheck: |
| // Answered only while this connection holds the lease. |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index 30422e2d..2fdc8c7a 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -767,7 +767,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| } |
| } else { |
| if wire.StepTerminal(v.State) { |
| - if err := t.recordUsage(s.Person, s.Specialist, s.TaskID, s.ID, "", s.Attempt, v.Usage); err != nil { |
| + if err := t.recordUsage(s.Person, s.Specialist, s.TaskID, s.ID, "", v.Usage); err != nil { |
| return err |
| } |
| } |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go| index a79af57b..f5559b1f 100644 |
| --- a/internal/equipo/chat_page.go |
| +++ b/internal/equipo/chat_page.go |
| @@ -205,7 +205,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) { |
| for i, t := range snap.Turns { |
| if !wire.Terminal(t.State) { |
| view.Waiting = append(view.Waiting, t) |
| - if t.State == wire.TurnWaiting && view.NoConnection == nil { |
| + if t.State == wire.TurnWaiting && t.Reason == wire.ReasonNoConnection && view.NoConnection == nil { |
| lines, err := a.store.Chat().NoConnection(ctx, address) |
| if err != nil { |
| a.failure(w, r, chatError(err)) |
diff --git a/internal/equipo/migrations/0048_thin_connections.sql b/internal/equipo/migrations/0048_thin_connections.sql| index 95cd666b..dccace2f 100644 |
| --- a/internal/equipo/migrations/0048_thin_connections.sql |
| +++ b/internal/equipo/migrations/0048_thin_connections.sql |
| @@ -1,7 +1,8 @@ |
| CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime); |
| CREATE INDEX chat_connection_person ON chat_connections(person); |
| -CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| +CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at); |
| +CREATE UNIQUE INDEX chat_usage_key ON chat_usage(turn_id, step_id, attempt, connection, model); |
| ALTER TABLE chat_messages ADD COLUMN switched text; |
| ALTER TABLE chat_turns ADD COLUMN connection text; |
| ALTER TABLE chat_steps ADD COLUMN switched text; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 1b33fba6..0766edf9 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -604,5 +604,6 @@ CREATE INDEX chat_question_task ON chat_questions(task_id); |
| CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key); |
| CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime); |
| CREATE INDEX chat_connection_person ON chat_connections(person); |
| -CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| +CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at); |
| +CREATE UNIQUE INDEX chat_usage_key ON chat_usage(turn_id, step_id, attempt, connection, model); |
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js| index a59e5a73..0bffac3b 100644 |
| --- a/internal/equipo/static/chat-stream.js |
| +++ b/internal/equipo/static/chat-stream.js |
| @@ -444,7 +444,7 @@ |
| } |
| // Held for a connection, or going again: the card is the server's. |
| var held = !!feed.querySelector('[data-no-connection="' + CSS.escape(v.id) + '"]'); |
| - if ((v.state === "waiting") !== held) refresh().catch(function () { location.reload(); }); |
| + if ((v.state === "waiting" && v.reason === "no_connection") !== held) refresh().catch(function () { location.reload(); }); |
| } else if (v.state === "replied" && !v.reply_id) { |
| // A turn that ended with nothing to say (an empty explore). |
| delete drafts[v.id]; |
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go| index 114786f0..51810403 100644 |
| --- a/internal/fakecodex/fake.go |
| +++ b/internal/fakecodex/fake.go |
| @@ -88,6 +88,8 @@ type server struct { |
| answers map[string]chan json.RawMessage |
| reqID int |
| + total tokens |
| + |
| mcpIn io.Writer |
| mcpOut *bufio.Reader |
| callID int |
| @@ -251,6 +253,14 @@ func (s *server) handle(id json.RawMessage, method string, params json.RawMessag |
| s.mu.Unlock() |
| model, _ := s.settings["model"].(string) |
| s.reply(id, map[string]any{"thread": map[string]any{"id": thread}, "model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "activePermissionProfile": map[string]any{"id": "equipo", "extends": nil}, "runtimeWorkspaceRoots": []string{"/workspace"}}) |
| + s.total = tokens{} |
| + if method == "thread/resume" { |
| + // The resumed thread's last turn's usage, sent again. |
| + if last, turn, ok := s.loadTotal(thread); ok { |
| + s.total = last |
| + s.usage(thread, turn, last, last) |
| + } |
| + } |
| case "turn/start": |
| var p struct { |
| ThreadID string `json:"threadId"` |
| @@ -453,12 +463,62 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { |
| } |
| s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": text}}) |
| s.record(thread, prompt, text) |
| - usage := map[string]any{"inputTokens": len(prompt) / 4, "cachedInputTokens": len(prompt) / 8, "cacheWriteInputTokens": 0, "outputTokens": len(text) / 4, "reasoningOutputTokens": 7, "totalTokens": len(prompt)/4 + len(text)/4 + 7} |
| - s.notify("thread/tokenUsage/updated", map[string]any{"threadId": thread, "turnId": turn, "tokenUsage": map[string]any{"last": usage, "total": usage, "modelContextWindow": 272000}}) |
| + // Two notices for the turn, each with the thread's running total (as |
| + // the pinned app-server sends them), the second resent once. |
| + half := tokens{Input: len(prompt) / 8, Cached: len(prompt) / 16, Output: len(text) / 8, Reasoning: 3} |
| + full := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(text) / 4, Reasoning: 7} |
| + s.usage(thread, turn, s.total.plus(half), half) |
| + s.usage(thread, turn, s.total.plus(full), full) |
| + s.usage(thread, turn, s.total.plus(full), full) |
| + s.total = s.total.plus(full) |
| + s.saveTotal(thread, turn) |
| s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) |
| done("completed", nil) |
| } |
| +type tokens struct{ Input, Cached, Output, Reasoning int } |
| + |
| +func (a tokens) plus(b tokens) tokens { |
| + return tokens{a.Input + b.Input, a.Cached + b.Cached, a.Output + b.Output, a.Reasoning + b.Reasoning} |
| +} |
| + |
| +func (a tokens) breakdown() map[string]any { |
| + return map[string]any{"inputTokens": a.Input, "cachedInputTokens": a.Cached, "cacheWriteInputTokens": 0, "outputTokens": a.Output, "reasoningOutputTokens": a.Reasoning, "totalTokens": a.Input + a.Output + a.Reasoning} |
| +} |
| + |
| +func (s *server) usage(thread, turn string, total, last tokens) { |
| + s.notify("thread/tokenUsage/updated", map[string]any{"threadId": thread, "turnId": turn, "tokenUsage": map[string]any{"last": last.breakdown(), "total": total.breakdown(), "modelContextWindow": 272000}}) |
| +} |
| + |
| +func (s *server) saveTotal(thread, turn string) { |
| + if path := s.rollout(thread); path != "" { |
| + if f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600); err == nil { |
| + raw, _ := json.Marshal(map[string]any{"type": "usage", "turn": turn, "total": s.total}) |
| + f.Write(append(raw, '\n')) |
| + f.Close() |
| + } |
| + } |
| +} |
| + |
| +func (s *server) loadTotal(thread string) (tokens, string, bool) { |
| + raw, err := os.ReadFile(s.rollout(thread)) |
| + if err != nil { |
| + return tokens{}, "", false |
| + } |
| + var out tokens |
| + turn, ok := "", false |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + var v struct { |
| + Type, Turn string |
| + Total tokens |
| + } |
| + if json.Unmarshal([]byte(line), &v) == nil && v.Type == "usage" { |
| + out, turn, ok = v.Total, v.Turn, true |
| + } |
| + } |
| + return out, turn, ok |
| +} |
| + |
| // callTool calls an Equipo tool through the configured MCP server, |
| // starting it on first use. |
| func (s *server) callTool(name string, input map[string]any) (string, bool) { |
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go| index 5791a336..ce93599d 100644 |
| --- a/internal/headless/connections_test.go |
| +++ b/internal/headless/connections_test.go |
| @@ -100,6 +100,7 @@ func TestHeadlessConnections(t *testing.T) { |
| name string |
| run func(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) |
| }{ |
| + {"U_usage_rows", connUsageRows}, |
| {"C1_claude_failover", connClaudeFailover}, |
| {"C2_codex_coordinator", connCodexCoordinator}, |
| {"C3_codex_device_code", connCodexDeviceCode}, |
| @@ -409,3 +410,66 @@ func connReviewFailover(t *testing.T, env *Env, inst *thintest.Instance, r *loca |
| t.Fatalf("review switched %+v", review.Switched) |
| } |
| } |
| + |
| +// usageRow is one recorded usage row. |
| +type usageRow struct { |
| + Attempt int64 |
| + Outcome, Model, Conn string |
| + Complete bool |
| + Input, Output, Reasoning *int64 |
| +} |
| + |
| +func usageRows(t *testing.T, inst *thintest.Instance, turn string) []usageRow { |
| + t.Helper() |
| + rows, err := inst.DB.Writer().Query("SELECT attempt, outcome, model, connection, complete, input_tokens, output_tokens, reasoning_output_tokens FROM chat_usage WHERE turn_id = ? ORDER BY attempt, model", turn) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []usageRow |
| + for rows.Next() { |
| + var r usageRow |
| + if err := rows.Scan(&r.Attempt, &r.Outcome, &r.Model, &r.Conn, &r.Complete, &r.Input, &r.Output, &r.Reasoning); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, r) |
| + } |
| + return out |
| +} |
| + |
| +// U1 and U2: a Claude turn and a Codex turn each record one complete |
| +// row (Claude's reasoning null, Codex's aggregated from several notices |
| +// and a resent one); a cancelled turn records its attempt as cancelled. |
| +func connUsageRows(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| + r.addAccount(t, "codex", "codex-1", second) |
| + r.start(t) |
| + s := open(t, env) |
| + first := s.send(t, "Hello.") |
| + replyOf(t, s, first.Turn.ID) |
| + rows := usageRows(t, inst, first.Turn.ID) |
| + if len(rows) != 1 || rows[0].Outcome != wire.OutcomeReplied || !rows[0].Complete || rows[0].Conn != "claude-1" || rows[0].Input == nil || rows[0].Reasoning != nil { |
| + t.Fatalf("claude rows %+v", rows) |
| + } |
| + // Claude limited: the turn moves to Codex; the refused attempt is |
| + // recorded as failed, the reply's as replied. |
| + moved := s.send(t, "Again. limit:"+thintest.Owner) |
| + replyOf(t, s, moved.Turn.ID) |
| + rows = usageRows(t, inst, moved.Turn.ID) |
| + if len(rows) != 2 || rows[0].Attempt != 1 || rows[0].Outcome != wire.OutcomeFailed || rows[0].Conn != "claude-1" || rows[1].Attempt != 2 || rows[1].Outcome != wire.OutcomeReplied || rows[1].Conn != "codex-1" || !rows[1].Complete || rows[1].Reasoning == nil || *rows[1].Reasoning != 7 { |
| + t.Fatalf("failover rows %+v", rows) |
| + } |
| + cancelled := s.send(t, "Take your time. sleep:4000") |
| + s.wait(t, "draft", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[cancelled.Turn.ID] != "" }) |
| + if _, err := env.Client.Cancel(s.ctx, cancelled.Turn.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.waitTurn(t, cancelled.Turn.ID, wire.TurnCancelled) |
| + var got []usageRow |
| + s.wait(t, "cancelled row", time.Minute, func(*thintest.Conversation) bool { |
| + got = usageRows(t, inst, cancelled.Turn.ID) |
| + return len(got) > 0 |
| + }) |
| + if len(got) != 1 || got[0].Outcome != wire.OutcomeCancelled || got[0].Complete { |
| + t.Fatalf("cancelled rows %+v", got) |
| + } |
| +} |
diff --git a/internal/runner/connect/usage.go b/internal/runner/connect/usage.go| new file mode 100644 |
| index 00000000..405d4064 |
| --- /dev/null |
| +++ b/internal/runner/connect/usage.go |
| @@ -0,0 +1,155 @@ |
| +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 |
| +} |
| + |
| +// CodexTally aggregates thread/tokenUsage/updated notices for one Codex |
| +// thread. Codex sends several per turn and repeats the last turn's after |
| +// thread/resume; the attempt's figure is its last total minus the total |
| +// seen before it began (the first total after a resume is the baseline), |
| +// so a resent notice changes nothing. A notice for another thread is |
| +// dropped. |
| +type CodexTally struct { |
| + Thread string |
| + turn string |
| + base Breakdown |
| + cur Breakdown |
| + seen bool |
| +} |
| + |
| +// CodexNotice decodes a thread/tokenUsage/updated notice. |
| +func CodexNotice(params json.RawMessage) (thread, turn string, total Breakdown, ok bool) { |
| + var v struct { |
| + ThreadID string `json:"threadId"` |
| + TurnID string `json:"turnId"` |
| + TokenUsage struct { |
| + Total *Breakdown `json:"total"` |
| + } `json:"tokenUsage"` |
| + } |
| + if json.Unmarshal(params, &v) != nil || v.TokenUsage.Total == nil { |
| + return "", "", Breakdown{}, false |
| + } |
| + return v.ThreadID, v.TurnID, *v.TokenUsage.Total, true |
| +} |
| + |
| +// Notice takes one notice. |
| +func (t *CodexTally) Notice(thread, turn string, total Breakdown) { |
| + if thread != t.Thread { |
| + return |
| + } |
| + if t.turn != "" && turn == t.turn { |
| + t.cur, t.seen = total, true |
| + return |
| + } |
| + if !t.seen { |
| + // Before this attempt's own notices: the thread's running total. |
| + t.base = total |
| + } |
| +} |
| + |
| +// Begin starts an attempt on the thread's provider turn: its baseline is |
| +// the total seen so far. |
| +func (t *CodexTally) Begin(turn string) { |
| + if t.seen { |
| + t.base = t.cur |
| + } |
| + t.turn, t.seen, t.cur = turn, false, Breakdown{} |
| +} |
| + |
| +// 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, ok := t.cur.minus(t.base) |
| + if !ok { |
| + // The thread's total went back (a new thread): the notice is the |
| + // attempt's own. |
| + d = t.cur |
| + } |
| + return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: true} |
| +} |
| + |
| +// ClaudeRows reads a stream-json result: one row per model in |
| +// modelUsage (or one row from usage when the CLI reported no models), |
| +// complete because the result is the CLI's final usage message. Claude |
| +// reports no reasoning figure: null. |
| +func ClaudeRows(result []byte) []wire.Usage { |
| + var v struct { |
| + 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:"modelUsage"` |
| + } |
| + 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) |
| + 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] |
| + } |
| + } |
| +} |
diff --git a/internal/runner/connect/usage_test.go b/internal/runner/connect/usage_test.go| new file mode 100644 |
| index 00000000..9c327911 |
| --- /dev/null |
| +++ b/internal/runner/connect/usage_test.go |
| @@ -0,0 +1,112 @@ |
| +package connect |
| + |
| +import ( |
| + "bufio" |
| + "encoding/json" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func notice(thread, turn, total string) json.RawMessage { |
| + return json.RawMessage(`{"threadId":"` + thread + `","turnId":"` + turn + `","tokenUsage":{"total":` + total + `,"last":{"inputTokens":1,"outputTokens":1}}}`) |
| +} |
| + |
| +func feed(t *testing.T, tally *CodexTally, params ...json.RawMessage) { |
| + t.Helper() |
| + for _, p := range params { |
| + thread, turn, total, ok := CodexNotice(p) |
| + if !ok { |
| + t.Fatalf("notice %s", p) |
| + } |
| + tally.Notice(thread, turn, total) |
| + } |
| +} |
| + |
| +func get(p *int64) int64 { |
| + if p == nil { |
| + return -1 |
| + } |
| + return *p |
| +} |
| + |
| +// The recorded probe: two notices in one turn; the turn's figure is the |
| +// last total, not the sum and not the last notice's "last". Figures the |
| +// notice did not carry stay null. |
| +func TestCodexTallyRecorded(t *testing.T) { |
| + f, err := os.Open("../provider/codex/testdata/probe.jsonl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.Close() |
| + tally := &CodexTally{Thread: "thread-1"} |
| + tally.Begin("turn-1") |
| + scan := bufio.NewScanner(f) |
| + scan.Buffer(make([]byte, 0, 1<<20), 1<<20) |
| + seen := 0 |
| + for scan.Scan() { |
| + var m struct { |
| + Method string `json:"method"` |
| + Params json.RawMessage `json:"params"` |
| + } |
| + if json.Unmarshal(scan.Bytes(), &m) != nil || m.Method != "thread/tokenUsage/updated" { |
| + continue |
| + } |
| + seen++ |
| + feed(t, tally, m.Params) |
| + } |
| + row := tally.Row() |
| + if seen != 2 || !row.Complete || get(row.InputTokens) != 28254 || get(row.OutputTokens) != 142 || row.CachedInputTokens != nil || row.ReasoningOutputTokens != nil { |
| + t.Fatalf("%d notices, row %+v", seen, row) |
| + } |
| +} |
| + |
| +func TestCodexTally(t *testing.T) { |
| + // A fresh process resumes a thread: the first total after |
| + // thread/resume (the previous turn's) is the baseline. |
| + tally := &CodexTally{Thread: "th"} |
| + feed(t, tally, notice("th", "old", `{"inputTokens":1000,"outputTokens":100,"cachedInputTokens":800}`)) |
| + tally.Begin("t2") |
| + feed(t, tally, |
| + notice("th", "t2", `{"inputTokens":1500,"outputTokens":130,"cachedInputTokens":1100}`), |
| + notice("other", "t2", `{"inputTokens":99999,"outputTokens":99999}`), |
| + notice("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`), |
| + // A resent frame changes nothing. |
| + notice("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`)) |
| + row := tally.Row() |
| + if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || get(row.CachedInputTokens) != 400 || !row.Complete || row.CacheWriteTokens != nil { |
| + t.Fatalf("resumed turn %+v", row) |
| + } |
| + // The next turn in the same process starts from that total. |
| + tally.Begin("t3") |
| + if r := tally.Row(); r.Complete || r.InputTokens != nil { |
| + t.Fatalf("no notice yet: %+v", r) |
| + } |
| + feed(t, tally, notice("th", "t3", `{"inputTokens":1800,"outputTokens":160,"cachedInputTokens":1250}`)) |
| + if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 { |
| + t.Fatalf("next turn %+v", r) |
| + } |
| + // A total that went back is the attempt's own. |
| + fresh := &CodexTally{Thread: "new"} |
| + feed(t, fresh, notice("new", "x", `{"inputTokens":5000,"outputTokens":5}`)) |
| + fresh.Begin("y") |
| + feed(t, fresh, notice("new", "y", `{"inputTokens":40,"outputTokens":4}`)) |
| + if r := fresh.Row(); get(r.InputTokens) != 40 { |
| + t.Fatalf("went back %+v", r) |
| + } |
| +} |
| + |
| +func TestClaudeRows(t *testing.T) { |
| + rows := ClaudeRows([]byte(`{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":3},"modelUsage":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":4,"cacheReadInputTokens":3,"cacheCreationInputTokens":0},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`)) |
| + if len(rows) != 2 || rows[0].Model != "claude-haiku-5" || get(rows[1].InputTokens) != 8 || rows[0].CachedInputTokens != nil || rows[1].ReasoningOutputTokens != nil || !rows[0].Complete { |
| + t.Fatalf("rows %+v", rows) |
| + } |
| + rows = ClaudeRows([]byte(`{"type":"result","usage":{"input_tokens":10,"output_tokens":5}}`)) |
| + if len(rows) != 1 || rows[0].Model != "" || get(rows[0].OutputTokens) != 5 || rows[0].CacheWriteTokens != nil { |
| + t.Fatalf("no models %+v", rows) |
| + } |
| + var _ = strings.Contains |
| + var _ wire.Usage |
| +} |
diff --git a/internal/runner/provider/claude/events.go b/internal/runner/provider/claude/events.go| index dea89950..8cb362b6 100644 |
| --- a/internal/runner/provider/claude/events.go |
| +++ b/internal/runner/provider/claude/events.go |
| @@ -6,7 +6,6 @@ import ( |
| "io" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| - "amadan.net/oficina/equipo/internal/wire" |
| ) |
| const MaxFrameBytes = 1024 * 1024 |
| @@ -151,11 +150,6 @@ type Result struct { |
| Failed bool |
| } |
| -// Usage is the result's token use for Equipo's usage record. |
| -func (r Result) Usage() wire.Usage { |
| - return wire.Usage{InputTokens: r.InputTokens, OutputTokens: r.OutputTokens, CachedInputTokens: r.CacheRead, CacheWriteTokens: r.CacheCreation, Model: r.Model} |
| -} |
| - |
| // ParseResult reads a result frame. Provider error text is never surfaced. |
| func ParseResult(raw []byte) (Result, bool) { |
| var v struct { |
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go| index 62f4f559..195fe0dd 100644 |
| --- a/internal/runner/thin/claude.go |
| +++ b/internal/runner/thin/claude.go |
| @@ -420,6 +420,7 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st |
| } |
| case "turn.completed", "turn.failed": |
| res, ok := claude.ParseResult(ev.Payload) |
| + rows := connect.ClaudeRows(ev.Payload) |
| if !ok || res.Failed { |
| proven := c.stop(false) |
| // Refused on quota: the provider said so with a |
| @@ -427,9 +428,9 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st |
| // connection may take the turn over only once this |
| // attempt's exit is proven. |
| if seen != nil && seen.Limited { |
| - return TurnResult{Reason: "limited", Limit: seen, Proven: proven} |
| + return TurnResult{Reason: "limited", Limit: seen, Proven: proven, Usage: rows} |
| } |
| - return TurnResult{Reason: "provider_failed", Seen: seen} |
| + return TurnResult{Reason: "provider_failed", Seen: seen, Usage: rows} |
| } |
| p.turns++ |
| // A move-in or explore turn is done only once the desk |
| @@ -454,7 +455,7 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st |
| c.idle, c.idleAt = time.AfterFunc(c.o.Idle, c.idleExit), time.Now().Add(c.o.Idle) |
| c.scheduleWarm() |
| timing.ResultMs = max(time.Since(stdin).Milliseconds(), 1) |
| - return TurnResult{Text: res.Text, Usage: res.Usage(), Timing: timing, Seen: seen} |
| + return TurnResult{Text: res.Text, Usage: rows, Timing: timing, Seen: seen} |
| } |
| } |
| } |
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go| index 30ffee86..c4e89ab7 100644 |
| --- a/internal/runner/thin/codex.go |
| +++ b/internal/runner/thin/codex.go |
| @@ -81,6 +81,8 @@ type codexProcess struct { |
| tool *toolSocket |
| scratch string |
| exitErr error |
| + // tally aggregates the thread's usage notices into attempt rows. |
| + tally *connect.CodexTally |
| } |
| func (c *codexCoordinator) Close() { |
| @@ -181,9 +183,14 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| return TurnResult{Reason: "provider_failed"} |
| } |
| turnID := started.Turn.ID |
| + p.tally.Begin(turnID) |
| + usage := func() []wire.Usage { |
| + row := p.tally.Row() |
| + row.Model = c.account.Model |
| + return []wire.Usage{row} |
| + } |
| var seen *connect.Limit |
| plan := "" |
| - usage := wire.Usage{} |
| final := "" |
| items := map[string]codexItem{} |
| lastActivity := "" |
| @@ -216,15 +223,6 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| Item codexItem `json:"item"` |
| Turn json.RawMessage `json:"turn"` |
| RateLimits json.RawMessage `json:"rateLimits"` |
| - TokenUsage struct { |
| - Last struct { |
| - Input int64 `json:"inputTokens"` |
| - Cached int64 `json:"cachedInputTokens"` |
| - CacheWrite int64 `json:"cacheWriteInputTokens"` |
| - Output int64 `json:"outputTokens"` |
| - ReasoningOutput int64 `json:"reasoningOutputTokens"` |
| - } `json:"last"` |
| - } `json:"tokenUsage"` |
| } |
| if json.Unmarshal(m.Params, &n) != nil { |
| continue |
| @@ -271,13 +269,8 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| } |
| } |
| case "thread/tokenUsage/updated": |
| - if n.TurnID == turnID { |
| - u := n.TokenUsage.Last |
| - usage.InputTokens += u.Input |
| - usage.CachedInputTokens += u.Cached |
| - usage.CacheWriteTokens += u.CacheWrite |
| - usage.OutputTokens += u.Output |
| - usage.ReasoningOutputTokens += u.ReasoningOutput |
| + if thread, turn, total, ok := connect.CodexNotice(m.Params); ok { |
| + p.tally.Notice(thread, turn, total) |
| } |
| case "turn/completed": |
| var t struct { |
| @@ -288,7 +281,6 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| if json.Unmarshal(n.Turn, &t) != nil || t.ID != turnID { |
| continue |
| } |
| - usage.Model = c.account.Model |
| if t.Status != "completed" { |
| proven := c.stop(false) |
| switch { |
| @@ -300,11 +292,11 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| l = *seen |
| l.Limited = true |
| } |
| - return TurnResult{Reason: "limited", Limit: &l, Plan: plan, Proven: proven} |
| + return TurnResult{Reason: "limited", Limit: &l, Plan: plan, Proven: proven, Usage: usage()} |
| case connect.CodexFailure(t.Error) == connect.FailAuth: |
| - return TurnResult{Reason: "sign_in_again", SignIn: true, Proven: proven} |
| + return TurnResult{Reason: "sign_in_again", SignIn: true, Proven: proven, Usage: usage()} |
| } |
| - return TurnResult{Reason: "provider_failed", Seen: seen, Plan: plan} |
| + return TurnResult{Reason: "provider_failed", Seen: seen, Plan: plan, Usage: usage()} |
| } |
| p.turns++ |
| if in.Kind != wire.TurnPerson { |
| @@ -321,7 +313,7 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| } |
| c.idle, c.idleAt = time.AfterFunc(c.o.Idle, c.idleExit), time.Now().Add(c.o.Idle) |
| timing.ResultMs = max(time.Since(start).Milliseconds(), 1) |
| - return TurnResult{Text: final, Usage: usage, Timing: timing, Seen: seen, Plan: plan} |
| + return TurnResult{Text: final, Usage: usage(), Timing: timing, Seen: seen, Plan: plan} |
| } |
| } |
| } |
| @@ -478,6 +470,7 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) { |
| return errors.Join(provider.ErrPolicy, err) |
| } |
| } |
| + p.tally = &connect.CodexTally{Thread: p.thread} |
| c.proc = p |
| return nil |
| } |
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go| index b8242385..f804685b 100644 |
| --- a/internal/runner/thin/contract_test.go |
| +++ b/internal/runner/thin/contract_test.go |
| @@ -45,10 +45,12 @@ func (s *stubCoordinator) Turn(ctx context.Context, in TurnInput, emit func(stri |
| } |
| emit("Hel") |
| emit("lo.") |
| - return TurnResult{Text: "Hello.", Usage: wire.Usage{InputTokens: 1, OutputTokens: 2}} |
| + return TurnResult{Text: "Hello.", Usage: []wire.Usage{{InputTokens: i64(1), OutputTokens: i64(2), Complete: true}}} |
| } |
| func (s *stubCoordinator) Close() {} |
| +func i64(v int64) *int64 { return &v } |
| + |
| // fakeInstance is the instance end of the stream, driven from fixtures. |
| type fakeInstance struct { |
| t *testing.T |
| @@ -398,7 +400,7 @@ func TestRunnerRecoveryAcksAndCancels(t *testing.T) { |
| announcement := frames[len(frames)-1].ID |
| // The retried attempt replies before the announcement's ack arrives. |
| held, _, _ := s.next(ctx, "p") |
| - if err = s.Report(ctx, held, &wire.Reply{TurnID: "t1", Attempt: held.Attempt, Text: "done"}, nil); err != nil { |
| + if err = s.Report(ctx, held, &wire.Reply{TurnID: "t1", Attempt: held.Attempt, Text: "done"}, nil, nil); err != nil { |
| t.Fatal(err) |
| } |
| if err = s.Acked(ctx, announcement); err != nil { |
diff --git a/internal/runner/thin/engine.go b/internal/runner/thin/engine.go| index c93a7793..1334a866 100644 |
| --- a/internal/runner/thin/engine.go |
| +++ b/internal/runner/thin/engine.go |
| @@ -39,8 +39,11 @@ type TurnInput struct { |
| // the engine moves the turn to another connection. Seen is headroom the |
| // provider reported on a turn that went on. |
| type TurnResult struct { |
| - Text string |
| - Usage wire.Usage |
| + Text string |
| + // Usage are the attempt's rows as the harness reported them (per |
| + // model; empty when it reported nothing). The engine adds the |
| + // attempt, outcome and connection. |
| + Usage []wire.Usage |
| Reason string |
| Timing *wire.TurnTiming |
| Limit *connect.Limit |
| @@ -55,8 +58,8 @@ type TurnResult struct { |
| Proven bool |
| // Switched is set by the engine when the turn moved connection. |
| Switched *wire.Switched |
| - // Failed is the usage of an attempt that ended without a reply. |
| - Failed *wire.Usage |
| + // rows are the usage rows the engine filled in for the report. |
| + rows []wire.Usage |
| } |
| // ConnChooser is what the engine asks about connections (Conns). |
| @@ -256,13 +259,17 @@ func (e *Engine) runOne(person string, w *worker, r run) { |
| report := func(res TurnResult) { |
| var err error |
| if res.Reason == "" { |
| - err = e.State.Report(e.ctx, r, &wire.Reply{TurnID: r.TurnID, Attempt: r.Attempt, Text: res.Text, Usage: res.Usage, Timing: res.Timing, Switched: res.Switched}, nil) |
| + err = e.State.Report(e.ctx, r, &wire.Reply{TurnID: r.TurnID, Attempt: r.Attempt, Text: res.Text, Usage: res.rows, Timing: res.Timing, Switched: res.Switched}, nil, nil) |
| } else { |
| state := wire.TurnFailed |
| if res.Reason == "cancelled" { |
| state = wire.TurnCancelled |
| } |
| - err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason, Usage: res.Failed}) |
| + rows := res.rows |
| + for i := range rows { |
| + rows[i].Outcome = state |
| + } |
| + err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason}, rows) |
| } |
| e.log("runner report", err) |
| e.Notify() |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index e36d1a6d..afe37bac 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -202,6 +202,7 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| if rep.Switched == nil { |
| rep.Switched = e.Conns.LimitedFrom(b.ID) |
| } |
| + rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| avoid = append(avoid, b.ID) |
| if prompt, reason = prepare(); reason != "" { |
| return fail(reason, true) |
| @@ -211,7 +212,7 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| if rep.Switched != nil && res.reason == "" { |
| rep.Switched.To = b.Provider |
| } |
| - rep.Usage = res.usage(b) |
| + rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| rep.Summary, rep.LogTail = clip(res.summary, wire.MaxStepSummary), res.tail |
| kept := e.recordKept(ctx, r, b.LocalID, res, "") |
| if !res.terminated { |
| @@ -457,20 +458,20 @@ type stepResult struct { |
| // limit is set when the provider refused on quota (reason limited); |
| // seen is headroom it reported otherwise; tokens what the run used. |
| limit, seen *connect.Limit |
| - tokens *wire.Usage |
| + tokens []wire.Usage |
| } |
| -// usage is the run's token use as recorded, or nil when none was reported. |
| -func (res stepResult) usage(b runner.AccountBinding) *wire.Usage { |
| - if res.tokens == nil { |
| - return nil |
| - } |
| - u := *res.tokens |
| - u.Provider, u.Connection = b.Provider, b.ID |
| - if u.Model == "" { |
| - u.Model = b.Model |
| +// usage is the run's usage rows for the step attempt. |
| +func (res stepResult) usage(b runner.AccountBinding, attempt int64) []wire.Usage { |
| + outcome := wire.OutcomeReplied |
| + switch res.reason { |
| + case "": |
| + case "cancelled": |
| + outcome = wire.OutcomeCancelled |
| + default: |
| + outcome = wire.OutcomeFailed |
| } |
| - return &u |
| + return usageRows(res.tokens, b, attempt, outcome) |
| } |
| // engineerOn is the connection an Engineering attempt runs on. |
| @@ -698,17 +699,17 @@ func (e *Engineer) converse(ctx context.Context, proc provider.Process, session |
| } |
| case "turn.completed", "turn.failed": |
| res, ok := claude.ParseResult(ev.Payload) |
| + rows := connect.ClaudeRows(ev.Payload) |
| if !ok || res.Failed { |
| if seen != nil && seen.Limited { |
| - return stepResult{reason: "limited", limit: seen, tail: tail.String()} |
| + return stepResult{reason: "limited", limit: seen, tail: tail.String(), tokens: rows} |
| } |
| - return stepResult{reason: "provider_failed", summary: res.Text, tail: tail.String(), seen: seen} |
| + return stepResult{reason: "provider_failed", summary: res.Text, tail: tail.String(), seen: seen, tokens: rows} |
| } |
| if stream != nil { |
| stream.timing.ResultMs = max(time.Since(stream.stdin).Milliseconds(), 1) |
| } |
| - u := res.Usage() |
| - return stepResult{summary: res.Text, tail: tail.String(), seen: seen, tokens: &u} |
| + return stepResult{summary: res.Text, tail: tail.String(), seen: seen, tokens: rows} |
| } |
| } |
| } |
diff --git a/internal/runner/thin/failover.go b/internal/runner/thin/failover.go| index 37365085..1cd7ead5 100644 |
| --- a/internal/runner/thin/failover.go |
| +++ b/internal/runner/thin/failover.go |
| @@ -86,17 +86,12 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| if res.SignIn && e.Conns != nil { |
| e.Conns.SignInAgain(b.ID) |
| } |
| - if res.Reason != "" { |
| - res.Failed = attemptUsage(res, b) |
| - } |
| + res.rows = usageRows(res.Usage, b, r.Attempt, wire.OutcomeReplied) |
| if res.Limit == nil && !res.SignIn || !res.Proven || ctx.Err() != nil || e.Conns == nil { |
| if res.Reason == "" && e.Conns != nil { |
| e.log("runner session", e.State.setMeta(context.WithoutCancel(ctx), "conn:"+person, b.ID)) |
| } |
| - res.Usage.Provider, res.Usage.Connection = b.Provider, b.ID |
| - if res.Usage.Model == "" { |
| - res.Usage.Model = b.Model |
| - } |
| + |
| if switched != nil && res.Reason == "" { |
| switched.To = b.Provider |
| res.Switched = switched |
| @@ -113,7 +108,7 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| } |
| w.coord.Close() |
| w.coord = nil |
| - if err := e.State.Retry(e.ctx, r, attemptUsage(res, b)); err != nil { |
| + if err := e.State.Retry(e.ctx, r, waitReason(res), usageRows(res.Usage, b, r.Attempt, wire.OutcomeFailed)); err != nil { |
| e.log("runner retry", err) |
| return TurnResult{Reason: "limited"} |
| } |
| @@ -124,18 +119,35 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| } |
| } |
| -// attemptUsage is an attempt's token use with what ran it, or nil when |
| -// the harness reported none. |
| -func attemptUsage(res TurnResult, b runner.AccountBinding) *wire.Usage { |
| - u := res.Usage |
| - if u.InputTokens+u.OutputTokens+u.CachedInputTokens+u.CacheWriteTokens+u.ReasoningOutputTokens == 0 { |
| - return nil |
| +// usageRows fills an attempt's rows with what ran it: one row with no |
| +// figures (complete false) when the harness reported nothing, so the |
| +// attempt is recorded all the same. |
| +func usageRows(rows []wire.Usage, b runner.AccountBinding, attempt int64, outcome string) []wire.Usage { |
| + if b.ID == "" { |
| + // No connection (an engine test without one): nothing to key a row by. |
| + return []wire.Usage{} |
| + } |
| + if len(rows) == 0 { |
| + rows = []wire.Usage{{}} |
| + } |
| + out := make([]wire.Usage, len(rows)) |
| + for i, u := range rows { |
| + u.Provider, u.Connection, u.Attempt, u.Outcome = b.Provider, b.ID, attempt, outcome |
| + if u.Model == "" { |
| + u.Model = b.Model |
| + } |
| + out[i] = u |
| } |
| - u.Provider, u.Connection = b.Provider, b.ID |
| - if u.Model == "" { |
| - u.Model = b.Model |
| + return out |
| +} |
| + |
| +// waitReason is why a turn waits between attempts: its connection was |
| +// limited, or refused the credential. |
| +func waitReason(res TurnResult) string { |
| + if res.SignIn { |
| + return "sign_in_again" |
| } |
| - return &u |
| + return "limited" |
| } |
| // choose asks Conns for the person's coordinator connection; without |
| @@ -181,7 +193,7 @@ func (s *State) Hold(ctx context.Context, r run, reason string) error { |
| // refused: the instance learns of it (state running, the new attempt) |
| // in the same transaction, so a draft of the old attempt is dropped and |
| // a cancel names the new one. |
| -func (s *State) Retry(ctx context.Context, r *run, used *wire.Usage) error { |
| +func (s *State) Retry(ctx context.Context, r *run, reason string, used []wire.Usage) error { |
| err := s.tx(ctx, func(t *sql.Tx) error { |
| res, err := t.Exec("UPDATE runs SET attempt=attempt+1 WHERE turn_id=? AND attempt=? AND state=?", r.TurnID, r.Attempt, runRunning) |
| if err != nil { |
| @@ -190,12 +202,17 @@ func (s *State) Retry(ctx context.Context, r *run, used *wire.Usage) error { |
| if n, _ := res.RowsAffected(); n != 1 { |
| return errors.New("run not held") |
| } |
| - if used != nil { |
| + if len(used) > 0 { |
| // What the refused attempt used, recorded against it. |
| - if err = s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnRunning, Usage: used}); err != nil { |
| + if err = s.enqueue(t, wire.FrameUsage, r.TurnID, wire.UsageReport{TurnID: r.TurnID, Rows: used}); err != nil { |
| return err |
| } |
| } |
| + // The turn waits between attempts (spec §3 step 2): the draft goes, |
| + // and the instance takes the new attempt only after it. |
| + if err = s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnWaiting, Reason: reason}); err != nil { |
| + return err |
| + } |
| return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt + 1, State: wire.TurnRunning}) |
| }) |
| if err == nil { |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index 66aa0f46..a7afc959 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -714,6 +714,7 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| if rep.Switched == nil { |
| rep.Switched = e.Conns.LimitedFrom(b.ID) |
| } |
| + rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| next, nextLabel, err := e.reviewer(ctx, r.Person, r.AvoidAccount) |
| if err != nil { |
| break |
| @@ -725,7 +726,7 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| res = e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r)}) |
| e.observe(b.ID, res) |
| } |
| - rep.Usage = res.usage(b) |
| + rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| rep.LogTail = res.tail |
| kept := e.recordKept(ctx, r, b.LocalID, res, r.CandidateSHA) |
| mu.Lock() |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index c6a867d1..4a773a1d 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -421,7 +421,7 @@ func (s *State) persons(ctx context.Context) ([]string, error) { |
| // Report ends a run: its reply or failure goes into the outbox in the same |
| // transaction as the state change. |
| -func (s *State) Report(ctx context.Context, r run, reply *wire.Reply, report *wire.TurnReport) error { |
| +func (s *State) Report(ctx context.Context, r run, reply *wire.Reply, report *wire.TurnReport, usage []wire.Usage) error { |
| return s.tx(ctx, func(t *sql.Tx) error { |
| res, err := t.Exec("UPDATE runs SET state=? WHERE turn_id=? AND attempt=? AND state=?", runReported, r.TurnID, r.Attempt, runRunning) |
| if err != nil { |
| @@ -433,6 +433,12 @@ func (s *State) Report(ctx context.Context, r run, reply *wire.Reply, report *wi |
| if reply != nil { |
| return s.enqueue(t, wire.FrameReply, r.TurnID, reply) |
| } |
| + if len(usage) > 0 { |
| + // What the attempt used, though it did not reply. |
| + if err := s.enqueue(t, wire.FrameUsage, r.TurnID, wire.UsageReport{TurnID: r.TurnID, Rows: usage}); err != nil { |
| + return err |
| + } |
| + } |
| return s.enqueue(t, wire.FrameTurn, r.TurnID, report) |
| }) |
| } |
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go| index 0317c60a..f327af98 100644 |
| --- a/internal/thintest/connections_contract_test.go |
| +++ b/internal/thintest/connections_contract_test.go |
| @@ -9,6 +9,8 @@ import ( |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| +func i64(v int64) *int64 { return &v } |
| + |
| func held(conns ...wire.HeldConnection) wire.Hello { |
| return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: conns, Versions: map[string]string{"runner": "test"}} |
| } |
| @@ -185,7 +187,7 @@ func TestContractHeldTurnAndSwitch(t *testing.T) { |
| runner.Send(r.ctx, "r-d2", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 2, Offset: 0, Text: "Done."}) |
| r.wait("new draft", func(c *Conversation) bool { return c.Drafts[turn] == "Done." }) |
| reset := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC) |
| - reply := wire.Reply{TurnID: turn, Attempt: 2, Text: "Done.", Usage: wire.Usage{InputTokens: 5120, OutputTokens: 88, CachedInputTokens: 4096, ReasoningOutputTokens: 40, Provider: "codex", Model: "gpt-6-astra", Connection: "codex-1"}, Switched: &wire.Switched{From: "claude", To: "codex", Window: "seven_day", ResetsAt: &reset}} |
| + reply := wire.Reply{TurnID: turn, Attempt: 2, Text: "Done.", Usage: []wire.Usage{{Provider: "codex", Connection: "codex-1", Model: "gpt-6-astra", Attempt: 2, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(5120), CachedInputTokens: i64(4096), CacheWriteTokens: i64(0), OutputTokens: i64(88), ReasoningOutputTokens: i64(40)}}, Switched: &wire.Switched{From: "claude", To: "codex", ResetsAt: &reset}} |
| runner.Send(r.ctx, "r-reply", wire.FrameReply, reply) |
| r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied && len(c.Replies()) == 1 }) |
| m := r.conv.Replies()[0] |
diff --git a/internal/thintest/instance_contract_test.go b/internal/thintest/instance_contract_test.go| index 3f32e524..330e09ef 100644 |
| --- a/internal/thintest/instance_contract_test.go |
| +++ b/internal/thintest/instance_contract_test.go |
| @@ -128,7 +128,7 @@ func TestContractConversation(t *testing.T) { |
| shape(t, "frames/delta.json", runner.Sent[len(runner.Sent)-1]) |
| r.wait("draft", func(c *Conversation) bool { return c.Drafts[cmd.TurnID] == "Hello." }) |
| - if err = runner.Send(r.ctx, "r-reply-1", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hello. What shall we work on?", Usage: wire.Usage{InputTokens: 3, OutputTokens: 4}}); err != nil { |
| + if err = runner.Send(r.ctx, "r-reply-1", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hello. What shall we work on?", Usage: []wire.Usage{{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(12), CachedInputTokens: i64(0), CacheWriteTokens: i64(0), OutputTokens: i64(9)}}}); err != nil { |
| t.Fatal(err) |
| } |
| shape(t, "frames/reply.json", runner.Sent[len(runner.Sent)-1]) |
diff --git a/internal/wire/connections_test.go b/internal/wire/connections_test.go| index 656ff698..592d7559 100644 |
| --- a/internal/wire/connections_test.go |
| +++ b/internal/wire/connections_test.go |
| @@ -38,7 +38,7 @@ func fieldNames(t reflect.Type, seen map[reflect.Type]bool, out *[]string) { |
| func TestConnectionTypesCarryNoSecrets(t *testing.T) { |
| var names []string |
| seen := map[reflect.Type]bool{} |
| - for _, v := range []any{wire.Connection{}, wire.ConnectionList{}, wire.Connect{}, wire.ConnectCommand{}, wire.CancelConnectCommand{}, wire.ConnectionReport{}, wire.Hello{}, wire.Reply{}, wire.TurnReport{}, wire.Snapshot{}, wire.StepReport{}, wire.AnswerReport{}} { |
| + for _, v := range []any{wire.Connection{}, wire.ConnectionList{}, wire.Connect{}, wire.ConnectCommand{}, wire.CancelConnectCommand{}, wire.ConnectionReport{}, wire.Hello{}, wire.Reply{}, wire.TurnReport{}, wire.Snapshot{}, wire.StepReport{}, wire.AnswerReport{}, wire.UsageReport{}} { |
| fieldNames(reflect.TypeOf(v), seen, &names) |
| } |
| allowed := map[string]bool{"Usage.input_tokens": true, "Usage.output_tokens": true, "Usage.cached_input_tokens": true, "Usage.cache_write_tokens": true, "Usage.reasoning_output_tokens": true} |
| @@ -63,7 +63,7 @@ func TestConnectionTypesCarryNoSecrets(t *testing.T) { |
| // TestConnectionFixturesCarryNoSecrets: the recorded documents a native |
| // app replays hold no secret-shaped key either. |
| func TestConnectionFixturesCarryNoSecrets(t *testing.T) { |
| - for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json"} { |
| + for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json"} { |
| raw := strings.ToLower(string(wiretest.Fixture(name))) |
| for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key", "api_key", "access_token", "refresh"} { |
| if strings.Contains(raw, bad) { |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index 55ffe048..a390297c 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -59,7 +59,7 @@ type Frame struct { |
| // Durable reports whether a frame must be acked and resent until acked. |
| func (f Frame) Durable() bool { |
| switch f.Type { |
| - case FrameMessage, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameConnect, FrameCancelConnect, FrameConnection: |
| + case FrameMessage, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage: |
| return true |
| } |
| return false |
| @@ -140,6 +140,8 @@ func (f Frame) Decode() (any, error) { |
| v = &CancelConnectCommand{} |
| case FrameConnection: |
| v = &ConnectionReport{} |
| + case FrameUsage: |
| + v = &UsageReport{} |
| default: |
| return nil, fmt.Errorf("%w: frame type %q", ErrStrict, f.Type) |
| } |
| @@ -289,19 +291,45 @@ type DeltaReport struct { |
| Text string `json:"text"` |
| } |
| -// Usage is the provider's token count for one turn or step attempt, as |
| -// the harness reported it (Claude's result usage, Codex's last token |
| -// usage), and what produced it. No cost: subscriptions have none, and |
| -// metered estimates come with the endpoints of a later slice. |
| +// Usage is one usage row (Connections spec §6): what one attempt of a |
| +// turn, step or question used on one model, as its harness reported it. |
| +// A figure the harness did not report is null, never zero; Complete is |
| +// true only when the harness's final usage message for the attempt was |
| +// seen. No cost: subscriptions within plan have none, and metered |
| +// estimates come with the endpoints of a later slice. |
| type Usage struct { |
| - InputTokens int64 `json:"input_tokens"` |
| - OutputTokens int64 `json:"output_tokens"` |
| - CachedInputTokens int64 `json:"cached_input_tokens"` |
| - CacheWriteTokens int64 `json:"cache_write_tokens"` |
| - ReasoningOutputTokens int64 `json:"reasoning_output_tokens"` |
| Provider string `json:"provider"` |
| - Model string `json:"model"` |
| Connection string `json:"connection"` |
| + Model string `json:"model"` |
| + Attempt int64 `json:"attempt"` |
| + Outcome string `json:"outcome"` |
| + Complete bool `json:"complete"` |
| + InputTokens *int64 `json:"input_tokens"` |
| + CachedInputTokens *int64 `json:"cached_input_tokens"` |
| + CacheWriteTokens *int64 `json:"cache_write_tokens"` |
| + OutputTokens *int64 `json:"output_tokens"` |
| + ReasoningOutputTokens *int64 `json:"reasoning_output_tokens"` |
| +} |
| + |
| +// Usage outcomes: how the attempt the row belongs to ended. |
| +const ( |
| + OutcomeReplied = "replied" |
| + OutcomeFailed = "failed" |
| + OutcomeCancelled = "cancelled" |
| + OutcomeSuperseded = "superseded" |
| +) |
| + |
| +// FrameUsage (runner to instance, durable) carries the usage rows of |
| +// attempts that produced no reply (failed, cancelled, refused before a |
| +// failover). Exactly one of TurnID, StepID or QuestionID is set. |
| +const FrameUsage = "usage" |
| + |
| +// UsageReport is a usage frame. |
| +type UsageReport struct { |
| + TurnID string `json:"turn_id"` |
| + StepID string `json:"step_id"` |
| + QuestionID string `json:"question_id"` |
| + Rows []Usage `json:"rows"` |
| } |
| // Reply is the committed coordinator answer for a turn. |
| @@ -309,7 +337,7 @@ type Reply struct { |
| TurnID string `json:"turn_id"` |
| Attempt int64 `json:"attempt"` |
| Text string `json:"text"` |
| - Usage Usage `json:"usage"` |
| + Usage []Usage `json:"usage"` |
| Timing *TurnTiming `json:"timing"` |
| // Switched is set when this turn moved to another connection. |
| Switched *Switched `json:"switched"` |
| @@ -441,9 +469,6 @@ type TurnReport struct { |
| Attempt int64 `json:"attempt"` |
| State string `json:"state"` |
| Reason string `json:"reason"` |
| - // Usage is what this attempt used when it ended without a reply |
| - // (failed, cancelled, or refused on quota before a failover), or null. |
| - Usage *Usage `json:"usage"` |
| } |
| // Failure reasons a runner may report. Anything else is refused. |
diff --git a/internal/wire/questions.go b/internal/wire/questions.go| index 43ced6a5..e3e18b85 100644 |
| --- a/internal/wire/questions.go |
| +++ b/internal/wire/questions.go |
| @@ -128,7 +128,7 @@ type AnswerReport struct { |
| Reason string `json:"reason"` |
| Text string `json:"text"` |
| Timing *TurnTiming `json:"timing"` |
| - Usage *Usage `json:"usage"` |
| + Usage []Usage `json:"usage"` |
| } |
| // ForgetTaskCommand: the task is done or cancelled. |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index 9148d0ab..c6b19ded 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -498,7 +498,7 @@ type StepReport struct { |
| // Usage is the attempt's token use (null for checks and merges); |
| // Switched is set when the attempt moved to another connection after |
| // the first was limited (its partial work was discarded). |
| - Usage *Usage `json:"usage"` |
| + Usage []Usage `json:"usage"` |
| Switched *Switched `json:"switched"` |
| } |
diff --git a/internal/wire/wire_test.go b/internal/wire/wire_test.go| index dea62f85..26be3955 100644 |
| --- a/internal/wire/wire_test.go |
| +++ b/internal/wire/wire_test.go |
| @@ -33,7 +33,7 @@ func TestFrameFixturesRoundTrip(t *testing.T) { |
| t.Fatalf("%s: round trip\n got %s\nwant %s", name, out, raw) |
| } |
| } |
| - for _, kind := range []string{wire.FrameWelcome, wire.FrameMessage, wire.FrameCancel, wire.FrameDrain, wire.FrameAck, wire.FrameHello, wire.FrameSync, wire.FrameDelta, wire.FrameReply, wire.FrameTurn, wire.FrameLease, wire.FrameToolCall, wire.FrameToolResult, wire.FrameActivity, wire.FrameMoveIn, wire.FrameNotebook, wire.FrameReset, wire.FrameDispatch, wire.FrameCancelStep, wire.FrameStep, wire.FrameRecheck, wire.FrameWatchMerge, wire.FrameMerged, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameAnswer, wire.FrameForgetTask, wire.FrameBranch, wire.FrameConnect, wire.FrameCancelConnect, wire.FrameConnection} { |
| + for _, kind := range []string{wire.FrameWelcome, wire.FrameMessage, wire.FrameCancel, wire.FrameDrain, wire.FrameAck, wire.FrameHello, wire.FrameSync, wire.FrameDelta, wire.FrameReply, wire.FrameTurn, wire.FrameLease, wire.FrameToolCall, wire.FrameToolResult, wire.FrameActivity, wire.FrameMoveIn, wire.FrameNotebook, wire.FrameReset, wire.FrameDispatch, wire.FrameCancelStep, wire.FrameStep, wire.FrameRecheck, wire.FrameWatchMerge, wire.FrameMerged, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameAnswer, wire.FrameForgetTask, wire.FrameBranch, wire.FrameConnect, wire.FrameCancelConnect, wire.FrameConnection, wire.FrameUsage} { |
| if !seen[kind] { |
| t.Fatalf("no fixture for frame %s", kind) |
| } |
diff --git a/internal/wire/wiretest/testdata/frames/reply-usage.json b/internal/wire/wiretest/testdata/frames/reply-usage.json| index 6bbc2452..4901c849 100644 |
| --- a/internal/wire/wiretest/testdata/frames/reply-usage.json |
| +++ b/internal/wire/wiretest/testdata/frames/reply-usage.json |
| @@ -1 +1 @@ |
| -{"id":"r-9","type":"reply","data":{"turn_id":"t_0002","attempt":2,"text":"Done. The README now reads as you asked.","usage":{"input_tokens":5120,"output_tokens":88,"cached_input_tokens":4096,"cache_write_tokens":0,"reasoning_output_tokens":40,"provider":"codex","model":"gpt-6-astra","connection":"codex-1"},"timing":null,"switched":{"from":"claude","to":"codex","window":"seven_day","resets_at":"2026-11-10T10:00:00Z"}}} |
| +{"id":"r-9","type":"reply","data":{"turn_id":"t_0002","attempt":2,"text":"Done. The README now reads as you asked.","usage":[{"provider":"codex","connection":"codex-1","model":"gpt-6-astra","attempt":2,"outcome":"replied","complete":true,"input_tokens":5120,"cached_input_tokens":4096,"cache_write_tokens":0,"output_tokens":88,"reasoning_output_tokens":40}],"timing":null,"switched":{"from":"claude","to":"codex","window":"","resets_at":"2026-11-10T10:00:00Z"}}} |
diff --git a/internal/wire/wiretest/testdata/frames/reply.json b/internal/wire/wiretest/testdata/frames/reply.json| index 0abc2378..1b7543bf 100644 |
| --- a/internal/wire/wiretest/testdata/frames/reply.json |
| +++ b/internal/wire/wiretest/testdata/frames/reply.json |
| @@ -1 +1 @@ |
| -{"id":"r-4","type":"reply","data":{"turn_id":"t_0001","attempt":1,"text":"Hello. What shall we work on?","usage":{"input_tokens":12,"output_tokens":9,"cached_input_tokens":0,"cache_write_tokens":0,"reasoning_output_tokens":0,"provider":"","model":"","connection":""},"timing":null,"switched":null}} |
| +{"id":"r-4","type":"reply","data":{"turn_id":"t_0001","attempt":1,"text":"Hello. What shall we work on?","usage":[{"provider":"claude","connection":"claude-a","model":"claude-opus-5-5","attempt":1,"outcome":"replied","complete":true,"input_tokens":12,"cached_input_tokens":0,"cache_write_tokens":0,"output_tokens":9,"reasoning_output_tokens":null}],"timing":null,"switched":null}} |
diff --git a/internal/wire/wiretest/testdata/frames/usage.json b/internal/wire/wiretest/testdata/frames/usage.json| new file mode 100644 |
| index 00000000..88f317c4 |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/frames/usage.json |
| @@ -0,0 +1 @@ |
| +{"id":"r-8","type":"usage","data":{"turn_id":"t_0002","step_id":"","question_id":"","rows":[{"provider":"claude","connection":"claude-a","model":"claude-opus-5-5","attempt":1,"outcome":"failed","complete":true,"input_tokens":0,"cached_input_tokens":0,"cache_write_tokens":0,"output_tokens":0,"reasoning_output_tokens":null}]}} |