Expose native OpenCode chat usage snapshots and replay session metrics

Read V2 session accounting, latest assistant prompt/cache components and native request-to-stream boundary. Resolve capacity by location/provider/catalog id with bounded metadata caching. Coalesce active/final readbacks; retain message-less session snapshots without changing admission or compaction state.

Provenance: https://opencode.ai/v2/openapi.json and anomalyco/opencode V2 4617210822bdbb31e5749751afbfb4584ccedac8: packages/schema/src/token-usage.ts, session-event.ts; packages/core/src/session/usage.ts, projector.ts, message-updater.ts, runner/step.ts. Native output is visible output, reasoning separate. Session totals include all five non-overlapping components. Generation rate uses created-to-streamed, not tool-inclusive completion.

Limitations: metrics remain unknown for missing components, absent timing/model metadata, reads beyond bounded latest-message/catalog budgets, or context preceding compaction. No local pricing, token estimation or default capacity. V1 gets no invented cumulative metrics; older V2 events remain available when readback is unavailable. No deployment or protocol/web/docs changes.

Checks: go test ./...; focused usage/stream race tests; go vet ./internal/opencode ./internal/server; go build ./...; git diff --check.
This commit is contained in:
2026-10-21 00:12:25 +01:00
parent 83b60990d2
commit ce3482b057
10 changed files with 733 additions and 15 deletions
+47 -1
View File
@@ -162,7 +162,7 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
turn.step = frame.Step
return
case protocol.ChatEventUsage:
turn.usage = frame.Usage
turn.usage = cloneChatUsage(frame.Usage)
return
case protocol.ChatEventShell:
// A shell frame carries no message id (it outlives the tool call that
@@ -276,6 +276,52 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
}
}
func cloneChatUsage(usage *protocol.ChatUsage) *protocol.ChatUsage {
if usage == nil {
return nil
}
copy := *usage
if usage.TotalTokens != nil {
value := *usage.TotalTokens
copy.TotalTokens = &value
}
if usage.ContextTokens != nil {
value := *usage.ContextTokens
copy.ContextTokens = &value
}
if usage.ContextWindow != nil {
value := *usage.ContextWindow
copy.ContextWindow = &value
}
if usage.CostUSD != nil {
value := *usage.CostUSD
copy.CostUSD = &value
}
if usage.OutputTokensPerSecond != nil {
value := *usage.OutputTokensPerSecond
copy.OutputTokensPerSecond = &value
}
return &copy
}
// Usage is session state, not an actor step. Replace even on native counter
// resets; never sum snapshots or derive admission/running state from counters.
// Enqueue replay under the fold lock, ordered with live usage (no I/O here).
func (h *chatHub) replayUsage(sub *chatSub) {
h.mu.Lock()
slow := false
if h.rooms[sub.room.sessionID] == sub.room && sub.room.subs[sub.clientID] == sub {
if turn := h.turns[sub.room.sessionID]; turn != nil && turn.usage != nil {
frame := protocol.ChatEventFrame{SessionID: sub.room.sessionID, Kind: protocol.ChatEventUsage, Usage: cloneChatUsage(turn.usage)}
slow = !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame})
}
}
h.mu.Unlock()
if slow {
sub.close()
}
}
// applyShell folds one shell frame into the session's retained shells. A running
// shell is upserted (keyed by its id) so a client that reattaches can be
// re-synced the processes still running; an exited shell is dropped, which is
+1 -1
View File
@@ -425,7 +425,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
}
// Shell replay and live lifecycle delivery must enqueue in the same order
// as folding. Otherwise an exit can overtake an older running replay.
if (frame.Kind == protocol.ChatEventShell || frame.Kind == protocol.ChatEventCompaction) && !buffered {
if (frame.Kind == protocol.ChatEventShell || frame.Kind == protocol.ChatEventCompaction || frame.Kind == protocol.ChatEventUsage) && !buffered {
msg := protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}
var slow []*chatSub
for _, sub := range targets {
+1
View File
@@ -244,4 +244,5 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
// shell half of the resume.
hub.replayShells(sub)
hub.replayCompaction(sub)
hub.replayUsage(sub)
}
+4
View File
@@ -886,6 +886,8 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) {
case r.Method == http.MethodGet && r.URL.Path == "/api/session/ses_1/message":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[]}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/session/ses_1":
w.WriteHeader(http.StatusNotFound) // metrics unavailable on this source flavor
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
@@ -1390,6 +1392,8 @@ func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame {
case r.Method == http.MethodGet && (r.URL.Path == "/api/session/ses_1/permission" || r.URL.Path == "/api/session/ses_1/form" || r.URL.Path == "/api/session/ses_1/message"):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/session/ses_1":
w.WriteHeader(http.StatusNotFound) // events-only source flavor
case r.Method == http.MethodGet && r.URL.Path == "/api/shell":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[]}`))
+64
View File
@@ -0,0 +1,64 @@
package server
import (
"context"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing.T) {
h := newChatHub()
room := newChatRoom(context.Background(), "ses_usage")
defer room.cancel()
room.running = true
room.nativeTurnID = "turn_keep"
room.turnDone = make(chan struct{})
h.rooms[room.sessionID] = room
sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})}
room.subs[sub.clientID] = sub
h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}})
for _, n := range []int64{123, 123, 0, 5} {
total := n
u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total}
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u})
live := (<-sub.ch).ChatEvent
if live.MessageID != "" || *live.Usage.TotalTokens != n {
t.Fatalf("live=%+v", live)
}
total = 999 // producer-owned data must not mutate retained state
h.replayUsage(sub)
frame := (<-sub.ch).ChatEvent
if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n {
t.Fatalf("replay=%+v", frame)
}
*frame.Usage.TotalTokens = 888 // neither may a consumer
if !room.running || room.nativeTurnID != "turn_keep" || h.turns[room.sessionID].step != nil || h.turns[room.sessionID].compaction == nil {
t.Fatal("usage changed turn/admission/compaction")
}
select {
case <-room.turnDone:
t.Fatal("usage settled turn")
default:
}
}
if got := h.snapshot(room.sessionID); len(got) != 0 {
t.Fatalf("usage created transcript messages %+v", got)
}
// A full snapshot may legitimately reset every unknown field to nil.
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}})
<-sub.ch
h.replayUsage(sub)
if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil {
t.Fatal("unknown snapshot accumulated old counter")
}
other := newChatRoom(context.Background(), "ses_other")
defer other.cancel()
h.rooms[other.sessionID] = other
otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})}
other.subs[otherSub.clientID] = otherSub
h.replayUsage(otherSub)
if len(otherSub.ch) != 0 {
t.Fatal("foreign usage replayed")
}
}