From 730a163f4717f6e22eeebe2e91bd8b3ff7d7889d Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 21:13:17 +0800 Subject: [PATCH] =?UTF-8?q?cursor:=20a=20step=20that=20calls=20tools=20rec?= =?UTF-8?q?ords=20what=20it=20used,=20the=20cache=20included=20(#676)=20?= =?UTF-8?q?=E2=80=94=20Cursor=20tells=20a=20turn's=20usage=20(TurnEndedUpd?= =?UTF-8?q?ate)=20only=20once=20the=20client=20has=20run=20the=20tools=20a?= =?UTF-8?q?nd=20sent=20their=20results=20in=20the=20same=20Run,=20and=20th?= =?UTF-8?q?e=20caller=20runs=20them=20after=20the=20Run=20is=20closed,=20s?= =?UTF-8?q?o=20every=20tool=20step=20was=20recorded=20as=20an=20estimated?= =?UTF-8?q?=20input=20with=20no=20cache=20(2395=20/=200=20where=20Cursor?= =?UTF-8?q?=20counted=204265,=204224=20of=20them=20cached),=20while=20text?= =?UTF-8?q?=20turns=20showed=20~99%=20cache.=20After=20the=20calls=20Curso?= =?UTF-8?q?r=20sends=20only=20the=20checkpoint=20(no=20token=20details)=20?= =?UTF-8?q?and=20heartbeats;=20a=20cancelled=20Run=20ends=20with=20an=20er?= =?UTF-8?q?ror=20and=20no=20usage.=20Every=20Run=20is=20counted=20in=20the?= =?UTF-8?q?=20dashboard's=20usage=20events=20(DashboardService/GetFiltered?= =?UTF-8?q?UsageEvents)=20by=20its=20conversation=5Fid,=20input=20apart=20?= =?UTF-8?q?from=20the=20cache=20read=20and=20written;=20one=20shows=20abou?= =?UTF-8?q?t=202.5=20s=20after=20the=20Run=20closes.=20So=20a=20tool=20ste?= =?UTF-8?q?p=20with=20no=20TurnEnded=20now=20closes=20the=20Run=20and=20lo?= =?UTF-8?q?oks=20for=20its=20event=20(after=201.5=20s,=20every=200.5=20s,?= =?UTF-8?q?=20up=20to=206=20s):=20its=20conversation's,=20no=20older=20tha?= =?UTF-8?q?n=20the=20Run,=20not=20already=20counted;=20else=20the=20estima?= =?UTF-8?q?te=20as=20before.=20A=20Run=20with=20no=20conversation=20id=20g?= =?UTF-8?q?ets=20one,=20to=20be=20found=20by.=20The=20estimate=20is=20also?= =?UTF-8?q?=20no=20longer=20added=20to=20a=20turn=20read=20wholly=20from?= =?UTF-8?q?=20the=20cache=20(input=200,=20cache=20read=20>=200).=20The=20m?= =?UTF-8?q?over's=20min=20for=20cursor=20is=200.1.9,=20which=20does=20the?= =?UTF-8?q?=20same=20in=20the=20plugin=20(magpie-community/plugins:=20curs?= =?UTF-8?q?or=200.1.9).=20TestCursorToolStepReadsItsUsageEvent=20fails=20o?= =?UTF-8?q?n=20the=20old=20code=20(5008=20estimated,=200=20cached)=20and?= =?UTF-8?q?=20passes.=20Tried=20with=20the=20real=20Cursor=20account:=20th?= =?UTF-8?q?e=20built-in=20(grok-4.7-medium-fast)=20reports=206153=20in,=20?= =?UTF-8?q?6144=20cached=20on=20a=20tool=20call,=20streamed=20or=20not;=20?= =?UTF-8?q?and=20through=20a=20sandbox=20magpie's=20plugin=20host=20with?= =?UTF-8?q?=20plugin=200.1.9,=206186=20in,=206144=20cached,=20121=20out,?= =?UTF-8?q?=20where=200.1.8=20recorded=205057=20estimated,=200=20cached.?= =?UTF-8?q?=20A=20tool=20step=20now=20takes=20about=202.5=20s=20longer=20t?= =?UTF-8?q?o=20finish.=20go=20vet,=20builds=20(darwin,=20GOOS=3Dlinux,=20G?= =?UTF-8?q?OOS=3Dwindows)=20and=20go=20test=20-tags=20nogui=20-count=3D1?= =?UTF-8?q?=20./...=20under=20a=20temp=20HOME=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/cursor.go | 172 +++++++++++++++++++++- internal/gateway/cursor_stepusage_test.go | 153 +++++++++++++++++++ internal/provider/migrate_side.go | 2 +- 3 files changed, 319 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/cursor_stepusage_test.go diff --git a/internal/gateway/cursor.go b/internal/gateway/cursor.go index 1b72f1616..22ac9526f 100644 --- a/internal/gateway/cursor.go +++ b/internal/gateway/cursor.go @@ -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 diff --git a/internal/gateway/cursor_stepusage_test.go b/internal/gateway/cursor_stepusage_test.go new file mode 100644 index 000000000..8ecf1258e --- /dev/null +++ b/internal/gateway/cursor_stepusage_test.go @@ -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) + } +} diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index 3cbe43e47..43513369f 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -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() {