Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-3273: fix(agent): parse Cursor token usage fields

Willow Lopeza4fb84d5ac70
diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.go
index b550874ec2..e9f5cffa68 100644
--- a/server/pkg/agent/cursor.go
+++ b/server/pkg/agent/cursor.go
@@ -150,7 +150,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
output.WriteString(evt.ResultText)
}
b.accumulateResultUsage(resultUsage, &evt)
- if evt.Usage != nil {
+ if evt.hasResultUsage() {
hasResultUsage = true
}
// Current Cursor Agent versions can emit the terminal result
@@ -268,17 +268,30 @@ func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<-
}
func (b *cursorBackend) accumulateResultUsage(usage map[string]TokenUsage, evt *cursorStreamEvent) {
- if evt.Usage == nil {
- return
- }
model := evt.Model
if model == "" {
model = "cursor"
}
u := usage[model]
- u.InputTokens += evt.Usage.InputTokens
- u.OutputTokens += evt.Usage.OutputTokens
- u.CacheReadTokens += evt.Usage.CacheReadInputTokens
+
+ // Cursor agent has emitted token usage in multiple shapes: top-level
+ // camelCase fields, nested camelCase usage, and nested legacy snake_case
+ // usage. Prefer top-level result totals when present, otherwise use the
+ // nested usage object.
+ if evt.InputTokens != 0 || evt.OutputTokens != 0 || evt.CacheReadTokens != 0 || evt.CacheWriteTokens != 0 {
+ u.InputTokens += evt.InputTokens
+ u.OutputTokens += evt.OutputTokens
+ u.CacheReadTokens += evt.CacheReadTokens
+ u.CacheWriteTokens += evt.CacheWriteTokens
+ } else if evt.Usage != nil {
+ u.InputTokens += evt.Usage.InputTokens
+ u.OutputTokens += evt.Usage.OutputTokens
+ u.CacheReadTokens += evt.Usage.CacheReadInputTokens
+ u.CacheWriteTokens += evt.Usage.CacheWriteInputTokens
+ } else {
+ return
+ }
+
usage[model] = u
}
@@ -302,10 +315,14 @@ type cursorStreamEvent struct {
Output string `json:"output,omitempty"`
// result fields
- ResultText string `json:"result,omitempty"`
- IsError bool `json:"is_error,omitempty"`
- Usage *cursorUsage `json:"usage,omitempty"`
- TotalCost float64 `json:"total_cost_usd,omitempty"`
+ ResultText string `json:"result,omitempty"`
+ IsError bool `json:"is_error,omitempty"`
+ InputTokens int64 `json:"inputTokens,omitempty"`
+ OutputTokens int64 `json:"outputTokens,omitempty"`
+ CacheReadTokens int64 `json:"cacheReadTokens,omitempty"`
+ CacheWriteTokens int64 `json:"cacheWriteTokens,omitempty"`
+ Usage *cursorUsage `json:"usage,omitempty"`
+ TotalCost float64 `json:"total_cost_usd,omitempty"`
// error fields
ErrorMsg string `json:"error,omitempty"`
@@ -322,10 +339,59 @@ func (evt *cursorStreamEvent) readSessionID() string {
return ""
}
+func (evt *cursorStreamEvent) hasResultUsage() bool {
+ return evt.Usage != nil || evt.InputTokens != 0 || evt.OutputTokens != 0 || evt.CacheReadTokens != 0 || evt.CacheWriteTokens != 0
+}
+
type cursorUsage struct {
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadInputTokens int64 `json:"cached_input_tokens"`
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheReadInputTokens int64 `json:"cached_input_tokens"`
+ CacheWriteInputTokens int64
+}
+
+func (u *cursorUsage) UnmarshalJSON(data []byte) error {
+ var raw struct {
+ InputTokensSnake int64 `json:"input_tokens"`
+ InputTokensCamel int64 `json:"inputTokens"`
+ OutputTokensSnake int64 `json:"output_tokens"`
+ OutputTokensCamel int64 `json:"outputTokens"`
+ CachedInputTokensSnake int64 `json:"cached_input_tokens"`
+ CachedInputTokensCamel int64 `json:"cachedInputTokens"`
+ CacheReadTokensCamel int64 `json:"cacheReadTokens"`
+ CacheReadInputTokensSnake int64 `json:"cache_read_input_tokens"`
+ CacheReadInputTokensCamel int64 `json:"cacheReadInputTokens"`
+ CacheWriteTokensCamel int64 `json:"cacheWriteTokens"`
+ CacheCreationInputTokensSnake int64 `json:"cache_creation_input_tokens"`
+ CacheCreationInputTokensCamel int64 `json:"cacheCreationInputTokens"`
+ }
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return err
+ }
+ u.InputTokens = firstNonZeroInt64(raw.InputTokensSnake, raw.InputTokensCamel)
+ u.OutputTokens = firstNonZeroInt64(raw.OutputTokensSnake, raw.OutputTokensCamel)
+ u.CacheReadInputTokens = firstNonZeroInt64(
+ raw.CachedInputTokensSnake,
+ raw.CachedInputTokensCamel,
+ raw.CacheReadTokensCamel,
+ raw.CacheReadInputTokensSnake,
+ raw.CacheReadInputTokensCamel,
+ )
+ u.CacheWriteInputTokens = firstNonZeroInt64(
+ raw.CacheWriteTokensCamel,
+ raw.CacheCreationInputTokensSnake,
+ raw.CacheCreationInputTokensCamel,
+ )
+ return nil
+}
+
+func firstNonZeroInt64(values ...int64) int64 {
+ for _, v := range values {
+ if v != 0 {
+ return v
+ }
+ }
+ return 0
}
type cursorAssistantMessage struct {
diff --git a/server/pkg/agent/cursor_test.go b/server/pkg/agent/cursor_test.go
index e63af50ec7..4bca817844 100644
--- a/server/pkg/agent/cursor_test.go
+++ b/server/pkg/agent/cursor_test.go
@@ -255,23 +255,92 @@ func TestCursorAccumulateResultUsage(t *testing.T) {
t.Parallel()
b := &cursorBackend{cfg: Config{Logger: slog.Default()}}
- usage := make(map[string]TokenUsage)
-
- evt := &cursorStreamEvent{
- Model: "gpt-5.3",
- Usage: &cursorUsage{
- InputTokens: 200,
- OutputTokens: 100,
- CacheReadInputTokens: 50,
- },
- }
- b.accumulateResultUsage(usage, evt)
+ // Nested usage object (snake_case keys) — compatible with
+ // cursor-agent versions that wrap usage in a sub-object.
+ t.Run("nested_usage_object", func(t *testing.T) {
+ usage := make(map[string]TokenUsage)
+ evt := &cursorStreamEvent{
+ Model: "gpt-5.3",
+ Usage: &cursorUsage{
+ InputTokens: 200,
+ OutputTokens: 100,
+ CacheReadInputTokens: 50,
+ CacheWriteInputTokens: 25,
+ },
+ }
+ b.accumulateResultUsage(usage, evt)
+ u := usage["gpt-5.3"]
+ if u.InputTokens != 200 || u.OutputTokens != 100 || u.CacheReadTokens != 50 || u.CacheWriteTokens != 25 {
+ t.Fatalf("unexpected usage: %+v", u)
+ }
+ })
+
+ // Top-level camelCase fields (cursor-agent v0.46+) — the current
+ // default shape from the Cursor CLI. When present, they take
+ // precedence over any nested usage object.
+ t.Run("top_level_camelcase", func(t *testing.T) {
+ usage := make(map[string]TokenUsage)
+ evt := &cursorStreamEvent{
+ Model: "gpt-5.3",
+ InputTokens: 300,
+ OutputTokens: 150,
+ CacheReadTokens: 75,
+ CacheWriteTokens: 25,
+ }
+ b.accumulateResultUsage(usage, evt)
+ u := usage["gpt-5.3"]
+ if u.InputTokens != 300 || u.OutputTokens != 150 || u.CacheReadTokens != 75 || u.CacheWriteTokens != 25 {
+ t.Fatalf("unexpected usage: %+v (want input=300 output=150 cache_read=75 cache_write=25)", u)
+ }
+ })
+
+ // Top-level fields win when both shapes are present — this
+ // prevents double-counting from the nested fallback.
+ t.Run("top_level_wins_over_nested", func(t *testing.T) {
+ usage := make(map[string]TokenUsage)
+ evt := &cursorStreamEvent{
+ Model: "gpt-5.3",
+ InputTokens: 300,
+ OutputTokens: 150,
+ Usage: &cursorUsage{
+ InputTokens: 999,
+ OutputTokens: 888,
+ CacheReadInputTokens: 777,
+ },
+ }
+ b.accumulateResultUsage(usage, evt)
+ u := usage["gpt-5.3"]
+ if u.InputTokens != 300 || u.OutputTokens != 150 || u.CacheReadTokens != 0 {
+ t.Fatalf("unexpected usage: %+v (want input=300 output=150 cache=0)", u)
+ }
+ })
- u := usage["gpt-5.3"]
- if u.InputTokens != 200 || u.OutputTokens != 100 || u.CacheReadTokens != 50 {
- t.Fatalf("unexpected usage: %+v", u)
- }
+ // No usage at all — early return, map unchanged.
+ t.Run("no_usage", func(t *testing.T) {
+ usage := make(map[string]TokenUsage)
+ evt := &cursorStreamEvent{
+ Model: "gpt-5.3",
+ }
+ b.accumulateResultUsage(usage, evt)
+ if _, ok := usage["gpt-5.3"]; ok {
+ t.Fatalf("expected no entry, got %+v", usage["gpt-5.3"])
+ }
+ })
+
+ // Empty model defaults to "cursor".
+ t.Run("default_model", func(t *testing.T) {
+ usage := make(map[string]TokenUsage)
+ evt := &cursorStreamEvent{
+ InputTokens: 50,
+ OutputTokens: 25,
+ }
+ b.accumulateResultUsage(usage, evt)
+ u := usage["cursor"]
+ if u.InputTokens != 50 || u.OutputTokens != 25 {
+ t.Fatalf("unexpected usage: %+v (want input=50 output=25)", u)
+ }
+ })
}
func TestCursorUsageOnlyFromResult(t *testing.T) {
@@ -377,6 +446,44 @@ func TestCursorUsageNoDoubleCount(t *testing.T) {
"gpt-5": {InputTokens: 100, OutputTokens: 50, CacheReadTokens: 10},
},
},
+ {
+ name: "camelcase_result — top-level inputTokens/outputTokens (v0.46+)",
+ lines: []string{
+ `{"type":"result","model":"gpt-5","inputTokens":1000,"outputTokens":500,"cacheReadTokens":250,"cacheWriteTokens":50}`,
+ },
+ want: map[string]TokenUsage{
+ "gpt-5": {InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 250, CacheWriteTokens: 50},
+ },
+ },
+ {
+ name: "nested_camelcase_result — actual cursor-agent stream-json shape",
+ lines: []string{
+ `{"type":"result","subtype":"success","duration_ms":10606,"duration_api_ms":10606,"is_error":false,"result":"pong","session_id":"b729a81b-9825-471d-812d-377c547b91e4","request_id":"4126abbe-dbc7-4ea4-a83e-7fab284c559c","usage":{"inputTokens":26640,"outputTokens":40,"cacheReadTokens":467,"cacheWriteTokens":12}}`,
+ },
+ want: map[string]TokenUsage{
+ "cursor": {InputTokens: 26640, OutputTokens: 40, CacheReadTokens: 467, CacheWriteTokens: 12},
+ },
+ },
+ {
+ name: "camelcase_result_wins_over_step_finish — no double count",
+ lines: []string{
+ `{"type":"step_finish","model":"gpt-5","part":{"tokens":{"input":300,"output":100,"cache":{"read":50}}}}`,
+ `{"type":"step_finish","model":"gpt-5","part":{"tokens":{"input":200,"output":80,"cache":{"read":30}}}}`,
+ `{"type":"result","model":"gpt-5","inputTokens":500,"outputTokens":180}`,
+ },
+ want: map[string]TokenUsage{
+ "gpt-5": {InputTokens: 500, OutputTokens: 180},
+ },
+ },
+ {
+ name: "camelcase_default_model — no model field defaults to cursor",
+ lines: []string{
+ `{"type":"result","inputTokens":400,"outputTokens":200}`,
+ },
+ want: map[string]TokenUsage{
+ "cursor": {InputTokens: 400, OutputTokens: 200},
+ },
+ },
}
for _, tc := range tests {
@@ -396,7 +503,7 @@ func TestCursorUsageNoDoubleCount(t *testing.T) {
switch evt.Type {
case "result":
b.accumulateResultUsage(resultUsage, &evt)
- if evt.Usage != nil {
+ if evt.hasResultUsage() {
hasResultUsage = true
}
case "step_finish":
@@ -432,3 +539,107 @@ func TestCursorUsageNoDoubleCount(t *testing.T) {
})
}
}
+
+// TestCursorStreamEventUnmarshalTopLevelCamelCase verifies that the
+// cursorStreamEvent struct correctly deserializes result events where token
+// usage fields are top-level camelCase keys.
+func TestCursorStreamEventUnmarshalTopLevelCamelCase(t *testing.T) {
+ t.Parallel()
+
+ raw := `{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"abc-123","model":"gpt-5.3","inputTokens":1500,"outputTokens":300,"cacheReadTokens":75,"cacheWriteTokens":25,"duration_ms":5234,"duration_api_ms":5100}`
+
+ var evt cursorStreamEvent
+ if err := json.Unmarshal([]byte(raw), &evt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if evt.Type != "result" {
+ t.Errorf("type = %q, want result", evt.Type)
+ }
+ if evt.SessionID != "abc-123" {
+ t.Errorf("session_id = %q, want abc-123", evt.SessionID)
+ }
+ if evt.Model != "gpt-5.3" {
+ t.Errorf("model = %q, want gpt-5.3", evt.Model)
+ }
+ if evt.InputTokens != 1500 {
+ t.Errorf("inputTokens = %d, want 1500", evt.InputTokens)
+ }
+ if evt.OutputTokens != 300 {
+ t.Errorf("outputTokens = %d, want 300", evt.OutputTokens)
+ }
+ if evt.CacheReadTokens != 75 {
+ t.Errorf("cacheReadTokens = %d, want 75", evt.CacheReadTokens)
+ }
+ if evt.CacheWriteTokens != 25 {
+ t.Errorf("cacheWriteTokens = %d, want 25", evt.CacheWriteTokens)
+ }
+ if evt.Usage != nil {
+ t.Errorf("usage = %+v, want nil", evt.Usage)
+ }
+
+ // Verify accumulateResultUsage processes the new shape.
+ b := &cursorBackend{cfg: Config{Logger: slog.Default()}}
+ usage := make(map[string]TokenUsage)
+ b.accumulateResultUsage(usage, &evt)
+ u := usage["gpt-5.3"]
+ if u.InputTokens != 1500 || u.OutputTokens != 300 || u.CacheReadTokens != 75 || u.CacheWriteTokens != 25 {
+ t.Fatalf("accumulated usage = %+v, want input=1500 output=300 cache_read=75 cache_write=25", u)
+ }
+}
+
+// TestCursorStreamEventUnmarshalNestedCamelCase verifies the stream-json shape
+// emitted by the locally installed cursor-agent version.
+func TestCursorStreamEventUnmarshalNestedCamelCase(t *testing.T) {
+ t.Parallel()
+
+ raw := `{"type":"result","subtype":"success","duration_ms":10606,"duration_api_ms":10606,"is_error":false,"result":"pong","session_id":"b729a81b-9825-471d-812d-377c547b91e4","request_id":"4126abbe-dbc7-4ea4-a83e-7fab284c559c","usage":{"inputTokens":26640,"outputTokens":40,"cacheReadTokens":467,"cacheWriteTokens":12}}`
+
+ var evt cursorStreamEvent
+ if err := json.Unmarshal([]byte(raw), &evt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if evt.Usage == nil {
+ t.Fatal("usage should be non-nil")
+ }
+ if evt.Usage.InputTokens != 26640 || evt.Usage.OutputTokens != 40 || evt.Usage.CacheReadInputTokens != 467 || evt.Usage.CacheWriteInputTokens != 12 {
+ t.Fatalf("usage = %+v, want input=26640 output=40 cache_read=467 cache_write=12", evt.Usage)
+ }
+
+ b := &cursorBackend{cfg: Config{Logger: slog.Default()}}
+ usage := make(map[string]TokenUsage)
+ b.accumulateResultUsage(usage, &evt)
+ u := usage["cursor"]
+ if u.InputTokens != 26640 || u.OutputTokens != 40 || u.CacheReadTokens != 467 || u.CacheWriteTokens != 12 {
+ t.Fatalf("accumulated usage = %+v, want input=26640 output=40 cache_read=467 cache_write=12", u)
+ }
+}
+
+// TestCursorStreamEventUnmarshalLegacyUsage verifies backwards compatibility
+// with cursor-agent versions that wrap usage in a nested object.
+func TestCursorStreamEventUnmarshalLegacyUsage(t *testing.T) {
+ t.Parallel()
+
+ raw := `{"type":"result","model":"gpt-5","usage":{"input_tokens":800,"output_tokens":400,"cached_input_tokens":200,"cache_creation_input_tokens":100}}`
+
+ var evt cursorStreamEvent
+ if err := json.Unmarshal([]byte(raw), &evt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if evt.InputTokens != 0 || evt.OutputTokens != 0 {
+ t.Errorf("top-level tokens should be 0 for nested-usage shape, got input=%d output=%d", evt.InputTokens, evt.OutputTokens)
+ }
+ if evt.Usage == nil {
+ t.Fatal("usage should be non-nil for nested-usage shape")
+ }
+ if evt.Usage.InputTokens != 800 || evt.Usage.OutputTokens != 400 || evt.Usage.CacheReadInputTokens != 200 || evt.Usage.CacheWriteInputTokens != 100 {
+ t.Fatalf("nested usage = %+v, want input=800 output=400 cache_read=200 cache_write=100", evt.Usage)
+ }
+
+ b := &cursorBackend{cfg: Config{Logger: slog.Default()}}
+ usage := make(map[string]TokenUsage)
+ b.accumulateResultUsage(usage, &evt)
+ u := usage["gpt-5"]
+ if u.InputTokens != 800 || u.OutputTokens != 400 || u.CacheReadTokens != 200 || u.CacheWriteTokens != 100 {
+ t.Fatalf("accumulated usage = %+v, want input=800 output=400 cache_read=200 cache_write=100", u)
+ }
+}