cursor: a step that calls tools records what it used, the cache included (#676) — Cursor tells a turn's usage (TurnEndedUpdate) only once the client has run the tools and sent their results in the same Run, and the caller runs them after the Run is closed, so every tool step was recorded as an estimated input with no cache (2395 / 0 where Cursor counted 4265, 4224 of them cached), while text turns showed ~99% cache. After the calls Cursor sends only the checkpoint (no token details) and heartbeats; a cancelled Run ends with an error and no usage. Every Run is counted in the dashboard's usage events (DashboardService/GetFilteredUsageEvents) by its conversation_id, input apart from the cache read and written; one shows about 2.5 s after the Run closes. So a tool step with no TurnEnded now closes the Run and looks for its event (after 1.5 s, every 0.5 s, up to 6 s): its conversation's, no older than the Run, not already counted; else the estimate as before. A Run with no conversation id gets one, to be found by. The estimate is also no longer added to a turn read wholly from the cache (input 0, cache read > 0). The mover's min for cursor is 0.1.9, which does the same in the plugin (magpie-community/plugins: cursor 0.1.9). TestCursorToolStepReadsItsUsageEvent fails on the old code (5008 estimated, 0 cached) and passes. Tried with the real Cursor account: the built-in (grok-4.7-medium-fast) reports 6153 in, 6144 cached on a tool call, streamed or not; and through a sandbox magpie's plugin host with plugin 0.1.9, 6186 in, 6144 cached, 121 out, where 0.1.8 recorded 5057 estimated, 0 cached. A tool step now takes about 2.5 s longer to finish. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.

This commit is contained in:
yetone
2026-10-03 21:14:13 +08:00
parent bd45fa452a
commit 730a163f47
3 changed files with 319 additions and 8 deletions
+165 -7
View File
@@ -26,6 +26,7 @@ package gateway
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
@@ -40,6 +41,7 @@ import (
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
@@ -277,6 +279,10 @@ func (s *Server) cursorRun(ctx context.Context, req *Request, model, id, tok, ba
tools := bridgeTools(req)
msgs := cursorMessages(req, tools)
conv, _ := ctx.Value(cursorConvKey{}).(string)
if conv == "" { // a new one: the Run's usage event is found by it
conv = cursorUUID()
}
since := time.Now()
run, blobs := buildCursorRun(msgs, cursorLastUser(req), tools, id, conv, maxMode)
// the Run ends with the turn, or once the calls are made
@@ -314,6 +320,13 @@ func (s *Server) cursorRun(ctx context.Context, req *Request, model, id, tok, ba
return nil, status, "Cursor: " + msg
}
raw := make(chan Event, 16)
st.done = func() {
res.Body.Close()
pw.Close()
}
st.step = func(ctx context.Context) (Usage, bool) {
return s.cursorStepUsage(ctx, tok, conv, since)
}
go func() {
defer res.Body.Close()
defer pw.Close()
@@ -349,7 +362,9 @@ func (s *Server) cursorRun(ctx context.Context, req *Request, model, id, tok, ba
return
}
for ev := range raw {
if ev.Kind == KUsage && ev.Usage.Input == 0 {
// a guess only when Cursor counted nothing: a prompt read whole
// from the cache leaves no uncached rest
if u := ev.Usage; ev.Kind == KUsage && u.Input == 0 && u.CacheRead == 0 && u.CacheWrite == 0 {
ev.Usage.Input = estimate(req)
}
if !send(ev) {
@@ -693,6 +708,130 @@ func cursorUsage(uf []pbField) Usage {
return Usage{Input: max(in-cr-cw, 0), Output: int(pbNum(uf, 2)), CacheRead: cr, CacheWrite: cw, Reasoning: int(pbNum(uf, 5))}
}
// A step that calls the caller's tools has no TurnEndedUpdate: Cursor ends
// the turn, and tells what it used, only once the client has run the tools
// and sent their results in the same Run, and the caller runs them after
// the Run is closed (#676). Before that it sends nothing more than the
// conversation's checkpoint and heartbeats, and a cancelled Run ends with
// an error and no usage either. The dashboard's usage events count every
// Run, by its conversation_id, the uncached input apart from what was read
// from the cache and written to it, as TurnEndedUpdate does; one shows
// about 2.5 s after the Run is closed. cursorStepWait is how long a step's
// is looked for: first after that long, then every so often until the
// end, after which it is guessed as before.
var cursorStepWait = struct{ first, every, until time.Duration }{1500 * time.Millisecond, 500 * time.Millisecond, 6 * time.Second}
// cursorClaimed are the usage events already counted, by conversation and
// time, so that two steps of one conversation never count the same one.
var cursorClaimed = struct {
sync.Mutex
at map[string]time.Time
}{at: map[string]time.Time{}}
// cursorStepUsage is the usage of the Run of conversation conv started at
// since, as the dashboard's usage events count it; false when none shows
// in time.
func (s *Server) cursorStepUsage(ctx context.Context, tok, conv string, since time.Time) (Usage, bool) {
end := time.Now().Add(cursorStepWait.until)
cursorClaimed.Lock()
for k, at := range cursorClaimed.at {
if time.Since(at) > 10*time.Minute {
delete(cursorClaimed.at, k)
}
}
cursorClaimed.Unlock()
wait := func(d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return true
case <-ctx.Done():
return false
}
}
if !wait(cursorStepWait.first) {
return Usage{}, false
}
for {
u, ok, stop := s.cursorUsageEvent(ctx, tok, conv, since)
if ok {
return u, true
}
if stop || time.Now().Add(cursorStepWait.every).After(end) || !wait(cursorStepWait.every) {
return Usage{}, false
}
}
}
// cursorUsageEvent is one look for the Run's usage event: the earliest of
// conv's not counted yet since the Run began; stop when the account can't
// read them.
func (s *Server) cursorUsageEvent(ctx context.Context, tok, conv string, since time.Time) (u Usage, ok, stop bool) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
q, _ := json.Marshal(map[string]any{
"teamId": 0, "page": 1, "pageSize": 50,
"startDate": strconv.FormatInt(since.Add(-time.Minute).UnixMilli(), 10),
"endDate": strconv.FormatInt(time.Now().Add(time.Minute).UnixMilli(), 10),
})
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, cursorAPI+"/aiserver.v1.DashboardService/GetFilteredUsageEvents", bytes.NewReader(q))
if err != nil {
return Usage{}, false, true
}
hr.Header.Set("Content-Type", "application/json")
hr.Header.Set("Connect-Protocol-Version", "1")
hr.Header.Set("Authorization", "Bearer "+tok)
hr.Header.Set("x-cursor-client-version", cursorVersion())
hr.Header.Set("x-cursor-client-type", "cli")
hr.Header.Set("x-ghost-mode", "true")
res, err := s.client.Do(hr)
if err != nil {
return Usage{}, false, false
}
defer res.Body.Close()
if res.StatusCode/100 == 4 && res.StatusCode != http.StatusTooManyRequests {
return Usage{}, false, true // not this account's to read
}
var out struct {
Events []struct {
Timestamp string `json:"timestamp"`
ConversationID string `json:"conversationId"`
TokenUsage *struct {
Input float64 `json:"inputTokens"`
Output float64 `json:"outputTokens"`
CacheRead float64 `json:"cacheReadTokens"`
CacheWrite float64 `json:"cacheWriteTokens"`
} `json:"tokenUsage"`
} `json:"usageEventsDisplay"`
}
if res.StatusCode/100 != 2 || json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&out) != nil {
return Usage{}, false, false
}
cursorClaimed.Lock()
defer cursorClaimed.Unlock()
best, bestAt := -1, int64(0)
for i, e := range out.Events {
at, err := strconv.ParseInt(e.Timestamp, 10, 64)
if err != nil || e.ConversationID != conv || e.TokenUsage == nil || at < since.UnixMilli()-1000 {
continue
}
if _, taken := cursorClaimed.at[conv+"\x00"+e.Timestamp]; taken {
continue
}
if best < 0 || at < bestAt {
best, bestAt = i, at
}
}
if best < 0 {
return Usage{}, false, false
}
e := out.Events[best]
cursorClaimed.at[conv+"\x00"+e.Timestamp] = time.Now()
t := e.TokenUsage
return Usage{Input: int(t.Input), Output: int(t.Output), CacheRead: int(t.CacheRead), CacheWrite: int(t.CacheWrite)}, true, false
}
// cursorToolDef is an McpToolDefinition.
func cursorToolDef(t bridgeTool) pb {
d := pb{}.str(1, t.Name)
@@ -795,6 +934,10 @@ type cursorStream struct {
pw *io.PipeWriter
blobs map[string][]byte
status int // the status an error at the head is answered with
// done closes the Run; step is the usage of a step that called tools,
// which Cursor never tells the Run (cursorStepUsage)
done func()
step func(context.Context) (Usage, bool)
}
func (st *cursorStream) send(msg []byte) {
@@ -840,7 +983,22 @@ func (st *cursorStream) decode(ctx context.Context, br *bufio.Reader, out chan<-
}
var calls, listed, said int
var usage Usage
finish := func() {
ended := false // Cursor said what the turn used
var finish func()
// settle is finish once a step that called tools has its usage: the
// dashboard's count, the Run closed first, when the turn didn't end
settle := func() {
if calls > 0 && !ended && st.step != nil {
if st.done != nil {
st.done()
}
if u, ok := st.step(ctx); ok {
usage = u
}
}
finish()
}
finish = func() {
if usage.Output == 0 {
usage.Output = (said + 3) / 4
}
@@ -856,7 +1014,7 @@ func (st *cursorStream) decode(ctx context.Context, br *bufio.Reader, out chan<-
if err != nil {
if ctx.Err() == nil {
if errors.Is(err, io.EOF) && calls > 0 {
finish()
settle()
return
}
fail(502, "the reply broke off: "+err.Error())
@@ -869,7 +1027,7 @@ func (st *cursorStream) decode(ctx context.Context, br *bufio.Reader, out chan<-
} else if said == 0 && calls == 0 {
fail(502, "an empty reply")
} else {
finish()
settle()
}
return
}
@@ -894,14 +1052,14 @@ func (st *cursorStream) decode(ctx context.Context, br *bufio.Reader, out chan<-
}
}
case 14: // turn ended, with what it used
usage = cursorUsage(uf)
usage, ended = cursorUsage(uf), true
if calls == 0 {
finish()
return
}
case 27: // how many tool calls the step makes, sent before them
if listed = int(pbNum(uf, 1)); listed > 0 && calls >= listed {
finish()
settle()
return
}
}
@@ -915,7 +1073,7 @@ func (st *cursorStream) decode(ctx context.Context, br *bufio.Reader, out chan<-
return
}
if listed > 0 && calls >= listed { // every call made: the caller runs them
finish()
settle()
return
}
case 4: // kv_server_message: a blob wanted, or one to keep
+153
View File
@@ -0,0 +1,153 @@
package gateway
import (
"bufio"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A step that calls the caller's tools has no TurnEndedUpdate before the
// Run is closed, so its usage is the dashboard's usage event of the Run's
// conversation (#676): read, cache included, not guessed with none. A
// prompt read whole from the cache is no reason to guess either.
func TestCursorToolStepReadsItsUsageEvent(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
wait := cursorStepWait
cursorStepWait.first, cursorStepWait.every, cursorStepWait.until = 0, 10*time.Millisecond, 2*time.Second
defer func() { cursorStepWait = wait }()
var mu sync.Mutex
var conv string
var ran, shown time.Time // the first Run's start, its event's time
asks, closed := 0, false
text := false // the Run answers with text and its turn's usage
quit := make(chan struct{})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/aiserver.v1.DashboardService/GetFilteredUsageEvents" {
mu.Lock()
defer mu.Unlock()
asks++
var q map[string]any
json.NewDecoder(r.Body).Decode(&q)
if r.Header.Get("Authorization") != "Bearer tok" || q["startDate"] == nil {
http.Error(w, `{"code":"unauthenticated"}`, 401)
return
}
ev := func(c string, at time.Time, u map[string]any) map[string]any {
return map[string]any{"timestamp": strconv.FormatInt(at.UnixMilli(), 10), "model": "grok-4.7-medium-fast", "conversationId": c, "tokenUsage": u}
}
evs := []map[string]any{
ev("another-conversation", ran.Add(time.Second), map[string]any{"inputTokens": 9, "outputTokens": 9}),
ev(conv, ran.Add(-30*time.Second), map[string]any{"inputTokens": 8, "outputTokens": 8}), // an earlier Run of it
}
if asks >= 2 && closed && shown.IsZero() { // it shows a moment after the Run is closed
shown = ran.Add(2500 * time.Millisecond)
}
if !shown.IsZero() {
evs = append(evs, ev(conv, shown, map[string]any{"inputTokens": 41, "outputTokens": 133, "cacheReadTokens": 4224, "totalCents": 0.6}))
}
json.NewEncoder(w).Encode(map[string]any{"usageEventsDisplay": evs, "totalUsageEventsCount": len(evs)})
return
}
f, err := readConnectFrame(bufio.NewReader(r.Body))
if err != nil {
http.Error(w, `{"code":"not_found"}`, 404)
return
}
mu.Lock()
ran, closed = time.Now(), false
for _, rf := range pbFields(f.data) {
if rf.num == 1 {
conv = pbStr(pbFields(rf.data), 5)
}
}
mu.Unlock()
http.NewResponseController(w).EnableFullDuplex()
w.Header().Set("Content-Type", "application/connect+proto")
if text {
w.Write(cursorUpdate(1, pb{}.str(1, "READY")))
w.Write(cursorUpdate(14, pb{}.varint(1, 900).varint(2, 3).varint(3, 900)))
w.(http.Flusher).Flush()
return
}
w.Write(cursorUpdate(1, pb{}.str(1, "probing")))
w.Write(cursorUpdate(27, pb{}.varint(1, 1)))
w.Write(cursorCallFrame(1, "call_1", "cache_probe", "ok"))
w.(http.Flusher).Flush()
// as Cursor does: the Run stays open for the call's result, which
// never comes; it ends once the client closes it
gone := make(chan struct{})
go func() { io.Copy(io.Discard, r.Body); close(gone) }()
select {
case <-gone:
case <-quit:
}
mu.Lock()
closed = true
mu.Unlock()
}))
defer up.Close()
defer close(quit)
tok, ver, agent, api := cursorToken, cursorVersion, cursorAgent, cursorAPI
cursorToken = func() (string, error) { return "tok", nil }
cursorVersion = func() string { return "cli-test" }
cursorAgent, cursorAPI = up.URL, up.URL
defer func() { cursorToken, cursorVersion, cursorAgent, cursorAPI = tok, ver, agent, api }()
forgetCursorEndpoint(t)
type chatUsage struct {
Prompt int `json:"prompt_tokens"`
Completion int `json:"completion_tokens"`
Details struct {
Cached int `json:"cached_tokens"`
} `json:"prompt_tokens_details"`
}
ask := func() (string, chatUsage) {
t.Helper()
body := `{"model":"x","stream":false,"prompt_cache_key":"thread-676","tools":[{"type":"function","function":{"name":"cache_probe","parameters":{"type":"object"}}}],` +
`"messages":[{"role":"system","content":"` + strings.Repeat("reference ", 2000) + `"},{"role":"user","content":"CALL"}]}`
w := httptest.NewRecorder()
var u Usage
New().serveCursor(w, httptest.NewRequest("POST", "/", strings.NewReader(body)), provider.Chat, "auto", []byte(body), &u)
var out struct {
Choices []struct {
Finish string `json:"finish_reason"`
} `json:"choices"`
Usage chatUsage `json:"usage"`
}
if json.Unmarshal(w.Body.Bytes(), &out) != nil || w.Code != 200 || len(out.Choices) != 1 {
t.Fatalf("%d %s", w.Code, w.Body)
}
return out.Choices[0].Finish, out.Usage
}
finish, u := ask()
if finish != "tool_calls" || u.Prompt != 4265 || u.Details.Cached != 4224 || u.Completion != 133 {
t.Fatalf("a tool step's usage is %s %+v, want the event's: 4265 in, 4224 of it cached, 133 out", finish, u)
}
// counted once: the next step of the conversation doesn't take it again
cursorStepWait.until = 100 * time.Millisecond
if _, u = ask(); u.Details.Cached != 0 || u.Prompt == 4265 {
t.Fatalf("the event was counted twice: %+v", u)
}
// a text turn: Cursor's own count, the dashboard never asked; all of
// the prompt from the cache adds no guess
text = true
mu.Lock()
before := asks
mu.Unlock()
if finish, u = ask(); finish != "stop" || u.Prompt != 900 || u.Details.Cached != 900 || asks != before {
t.Fatalf("a text turn's usage is %s %+v (%d asks), want 900, all cached, no ask", finish, u, asks-before)
}
}
+1 -1
View File
@@ -221,7 +221,7 @@ func init() {
// the plugin reads cursor-agent's token as the built-in does.
movers["cursor"] = &mover{
pkg: "@magpie-community/opencode-cursor-auth",
min: "0.1.8", // a failure's status and its sign-in mark as the built-in's; Max Mode models retried in Max Mode; glm-5.3 listed; catalog entries written as CallDynamicTool calls, an empty turn retried (plugins #11)
min: "0.1.9", // a failure's status and its sign-in mark as the built-in's; Max Mode models retried in Max Mode; glm-5.3 listed; catalog entries written as CallDynamicTool calls, an empty turn retried (plugins #11); a tool step's usage from the dashboard's usage event, cache included (#676)
agents: []string{"cursor"},
out: func() ([]Moving, error) {
if CursorExecutable() == "" || cursorSignedOut() {