usage, sessions: Antigravity CLI's (agy's) own calls are counted, read from its transcripts, and a step it sent through magpie once (#2097, parkavenue9639)

agy wrote its calls nowhere magpie read. Each conversation's
brain/<id>/.system_generated/logs/transcript_full.jsonl has a line per step,
and a model step carries its own input_tokens, cache_read_tokens and
output_tokens. readAgyCalls reads those as agent agy, provider unknown
(session-unknown) and no model: the step names none, and settings.json's is
only the one picked now. A transcript an older agy wrote has the lines with
no token fields; they are left out, not counted as zero.

agy sends the gateway no session header, so its gateway records name no
session and the matcher, which pairs by session, would have counted a step
sent through magpie twice. matchedBlocks now pairs an agy step with a
session-less agy gateway record by tokens alone, and lets the record end up
to 30 minutes after the step's created_at, which is when the step began (to
the second), not when its call ended.

Tried for real: agy 1.2.16 under a sandbox HOME, with GEMINI_API_KEY and
GOOGLE_GEMINI_BASE_URL on a fake Gemini endpoint, three turns of one
conversation. It sent User-Agent google-genai-sdk/1.72.0, X-Goog-Api-Key and
no session header; its transcript's input_tokens is the prompt less the
cached tokens and output_tokens includes thoughtsTokenCount (8 + 40 = 48),
as the gateway counts a Gemini reply. A turn that failed to connect wrote
ERROR_MESSAGE steps with no tokens. That transcript is the fixture beside
the issue's quoted lines and an old one without tokens; the built binary's
`magpie usage --csv all` in that HOME lists the three steps as agy, log.

Run: TestAgyCalls and TestAgyStepThroughMagpieCountedOnce fail without the
change (0 agy calls; "the step the gateway logged is counted again"); gofmt
-l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on sessions and
usage; go build darwin, linux nogui, windows; go test -tags nogui of
internal/sessions, internal/usage, internal/usageapi, internal/cli in a
sandbox HOME, all ok.

Not tried: a step through a real magpie gateway and a real Google account
(the matcher's pairing is covered by the unit test with the gateway's
numbers from the fake run); agy on Windows or Linux; the full go test ./...
This commit is contained in:
yetone
2026-10-14 14:35:23 +08:00
parent 407595b2ab
commit c8c3ce9a9a
9 changed files with 269 additions and 2 deletions
+1
View File
@@ -183,6 +183,7 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){
"kimi": readKimiCalls, // #1607
"pi": readPiCalls, // #1951
"omp": readPiCalls,
"agy": readAgyCalls, // #2097
}
func readCalls(f file) *callFile {
+1
View File
@@ -235,6 +235,7 @@ func callSources() []file {
out = append(out, wslFiles("kimi")...)
out = append(out, piCallFiles()...)
out = append(out, codebuddyCallFiles()...)
out = append(out, agyCallFiles()...) // #2097
return append(out, workbuddyCallFiles()...)
}
+128
View File
@@ -0,0 +1,128 @@
package sessions
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Antigravity CLI's (agy's) calls (#2097, parkavenue9639: a call agy made
// without magpie was counted nowhere). Each conversation keeps a transcript
// of its steps in
// ~/.gemini/antigravity-cli/brain/<conversation id>/.system_generated/logs/transcript_full.jsonl,
// one JSON object a line. A model's step, as agy 1.2.16 writes it (tried in
// a sandbox against a fake Gemini endpoint):
//
// {"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE",
// "created_at":"2026-10-14T06:12:41Z","input_tokens":702,"cache_read_tokens":300,
// "output_tokens":9,"content":"…"}
//
// Those are the step's own counts: input_tokens is the prompt less what was
// read from the cache, and output_tokens holds the thoughts as well as the
// answer, as the gateway counts a Gemini reply. created_at is when the step
// began, to the second. A transcript an older agy wrote has the same lines
// without the token fields; they are left out, not counted as zero.
//
// The step names no model (a custom model's isn't anywhere in agy's files,
// and settings.json's is only the one picked now), nor the account, so the
// call is agy's with the model and provider unknown. A step agy sent through
// magpie is the gateway's to count: usage's matcher pairs it with the
// gateway's record by its tokens and time (agy sends no session header).
// AgyDir is agy's data folder, ~/.gemini/antigravity-cli.
func AgyDir() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".gemini", "antigravity-cli")
}
// agyCallFiles are each conversation's transcript_full.jsonl.
func agyCallFiles() []file {
dirs, _ := os.ReadDir(filepath.Join(AgyDir(), "brain"))
var out []file
for _, d := range dirs {
if !d.IsDir() {
continue
}
p := filepath.Join(AgyDir(), "brain", d.Name(), ".system_generated", "logs", "transcript_full.jsonl")
f := file{agent: "agy", key: "agy:" + d.Name(), path: p, main: true}
if stat(&f) {
out = append(out, f)
}
}
return out
}
type agyStep struct {
Step *int `json:"step_index"`
Source string `json:"source"`
CreatedAt string `json:"created_at"`
Input *int `json:"input_tokens"`
CacheRead *int `json:"cache_read_tokens"`
Output *int `json:"output_tokens"`
}
var agyTokens = []byte(`"output_tokens"`)
// readAgyCalls reads a transcript whole: agy may write a step's line again
// as it finishes, and a step is counted once by its index.
func readAgyCalls(f file) (*callFile, bool) {
r, err := os.Open(f.path)
if err != nil {
return &callFile{Path: f.path, Agent: "agy"}, false
}
defer r.Close()
st := &callFile{Agent: "agy", Path: f.path, Session: strings.TrimPrefix(f.key, "agy:")}
at := map[int]int{} // a step's index → its call in st.Calls
br := bufio.NewReaderSize(r, 1<<20)
for {
b, err := br.ReadBytes('\n')
if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) {
break
}
b = bytes.TrimSpace(b)
if len(b) > 0 && len(b) <= maxLine && bytes.Contains(b, agyTokens) {
var s agyStep
if json.Unmarshal(b, &s) == nil {
if c, ok := agyCall(st, s); ok {
if i, seen := at[*s.Step]; seen {
st.Calls[i] = c
} else {
at[*s.Step] = len(st.Calls)
st.Calls = append(st.Calls, c)
}
}
}
}
if err != nil {
break
}
}
return st, true
}
// agyCall is a model's step as a call.
func agyCall(st *callFile, s agyStep) (Call, bool) {
if s.Source != "MODEL" || s.Step == nil || s.Input == nil || s.Output == nil {
return Call{}, false
}
t, err := time.Parse(time.RFC3339, s.CreatedAt)
if err != nil {
return Call{}, false
}
c := Call{Agent: "agy", Time: t, Session: st.Session, Tokens: Tokens{Input: *s.Input, Output: *s.Output}}
if s.CacheRead != nil {
c.CacheRead = *s.CacheRead
}
if c.Tokens.zero() {
return Call{}, false
}
c.Msg = st.str("agy:" + st.Session + ":" + strconv.Itoa(*s.Step))
return c, true
}
+54
View File
@@ -0,0 +1,54 @@
package sessions
import (
"path/filepath"
"slices"
"testing"
"time"
)
// #2097 (parkavenue9639): Antigravity CLI's own calls reach the usage
// ledger. testdata/agy/brain holds three conversations: one agy 1.2.16
// wrote in a sandbox against a fake Gemini endpoint (three model steps,
// one with 40 thought tokens in its output, and a turn that failed to
// connect five times), one made of the lines the issue quotes, and one an
// older agy wrote, whose model step has no token fields.
func TestAgyCalls(t *testing.T) {
claude, _ := setup(t)
copyTree(t, "testdata/agy", filepath.Join(filepath.Dir(claude), "home", ".gemini", "antigravity-cli"))
var got []Call
for _, c := range Calls(time.Time{}) {
if c.Agent == "agy" {
got = append(got, c)
}
}
slices.SortFunc(got, func(a, b Call) int { return a.Time.Compare(b.Time) })
want := []struct {
at string
session string
tokens Tokens
}{
{"2026-10-14T03:03:17Z", "2b0e6c1a-1d3e-4f6a-9a51-0f1c2d3e4f5a", Tokens{Input: 14559, Output: 2116}},
{"2026-10-14T03:04:02Z", "2b0e6c1a-1d3e-4f6a-9a51-0f1c2d3e4f5a", Tokens{Input: 3013, CacheRead: 14973, Output: 1518}},
{"2026-10-14T06:12:41Z", "8ac63d53-9162-4a29-af29-bda3428931ae", Tokens{Input: 702, CacheRead: 300, Output: 9}},
{"2026-10-14T06:15:01Z", "8ac63d53-9162-4a29-af29-bda3428931ae", Tokens{Input: 701, CacheRead: 300, Output: 8}},
{"2026-10-14T06:16:06Z", "8ac63d53-9162-4a29-af29-bda3428931ae", Tokens{Input: 701, CacheRead: 300, Output: 48}},
}
if len(got) != len(want) {
t.Fatalf("want %d agy calls (none from the transcript without token fields), got %d: %+v", len(want), len(got), got)
}
for i, w := range want {
c := got[i]
at, _ := time.Parse(time.RFC3339, w.at)
if !c.Time.Equal(at) || c.Session != w.session || c.Tokens != w.tokens {
t.Errorf("call %d: %v %s %+v, want %s %s %+v", i, c.Time, c.Session, c.Tokens, w.at, w.session, w.tokens)
}
if c.Model != "" {
t.Errorf("call %d names model %q, which agy's step doesn't", i, c.Model)
}
if c.Msg == "" {
t.Errorf("call %d: no step id to count it once by", i)
}
}
}
@@ -0,0 +1,3 @@
{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T03:03:10Z"}
{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-14T03:03:17Z","input_tokens":14559,"cache_read_tokens":0,"output_tokens":2116}
{"step_index":2,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-14T03:04:02Z","input_tokens":3013,"cache_read_tokens":14973,"output_tokens":1518}
@@ -0,0 +1,2 @@
{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-08-07T09:12:40Z"}
{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-08-07T09:12:44Z"}
@@ -0,0 +1,15 @@
{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T06:12:41Z","content":"<USER_REQUEST>\nsay hi\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-10-14T14:12:41+08:00.\n</ADDITIONAL_METADATA>\n<USER_SETTINGS_CHANGE>\nThe user changed setting `Model Selection` from None to . No need to comment on this change if the user doesn't ask about it. If reporting what model you are, please use a human readable name instead of the exact string.\n</USER_SETTINGS_CHANGE>"}
{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-14T06:12:41Z","input_tokens":702,"cache_read_tokens":300,"output_tokens":9,"content":"Hello from the fake."}
{"step_index":2,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T06:13:45Z","content":"<USER_REQUEST>\nagain\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-10-14T14:13:45+08:00.\n</ADDITIONAL_METADATA>"}
{"step_index":3,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:13:46Z","content":"The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-10-14T06:13:45Z sender=system priority=MESSAGE_PRIORITY_LOW content=[Notice] All your subagents and background tasks have been stopped due to server restart. If you want a subagent to continue working, it needs to be revived by sending it a new message. If resuming work, please check on status and restart as needed.\n</SYSTEM_MESSAGE>"}
{"step_index":4,"source":"SYSTEM","type":"ERROR_MESSAGE","status":"DONE","error":"API error (attempt 1): doRequest: error sending request: Post \"http://127.0.0.1:3593/v1beta/models/fakeprov/fake-model:streamGenerateContent?alt=sse\": dial tcp 127.0.0.1:3593: connect: connection refused","created_at":"2026-10-14T06:13:46Z"}
{"step_index":5,"source":"SYSTEM","type":"ERROR_MESSAGE","status":"DONE","error":"API error (attempt 2): doRequest: error sending request: Post \"http://127.0.0.1:3593/v1beta/models/fakeprov/fake-model:streamGenerateContent?alt=sse\": dial tcp 127.0.0.1:3593: connect: connection refused","created_at":"2026-10-14T06:13:50Z"}
{"step_index":6,"source":"SYSTEM","type":"ERROR_MESSAGE","status":"DONE","error":"API error (attempt 3): doRequest: error sending request: Post \"http://127.0.0.1:3593/v1beta/models/fakeprov/fake-model:streamGenerateContent?alt=sse\": dial tcp 127.0.0.1:3593: connect: connection refused","created_at":"2026-10-14T06:13:56Z"}
{"step_index":7,"source":"SYSTEM","type":"ERROR_MESSAGE","status":"DONE","error":"API error (attempt 4): doRequest: error sending request: Post \"http://127.0.0.1:3593/v1beta/models/fakeprov/fake-model:streamGenerateContent?alt=sse\": dial tcp 127.0.0.1:3593: connect: connection refused","created_at":"2026-10-14T06:14:09Z"}
{"step_index":8,"source":"SYSTEM","type":"ERROR_MESSAGE","status":"DONE","error":"API error (attempt 5): doRequest: error sending request: Post \"http://127.0.0.1:3593/v1beta/models/fakeprov/fake-model:streamGenerateContent?alt=sse\": dial tcp 127.0.0.1:3593: connect: connection refused","created_at":"2026-10-14T06:14:34Z"}
{"step_index":9,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T06:15:01Z","content":"<USER_REQUEST>\nagain\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-10-14T14:15:01+08:00.\n</ADDITIONAL_METADATA>"}
{"step_index":10,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:15:01Z","content":"The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-10-14T06:15:01Z sender=system priority=MESSAGE_PRIORITY_LOW content=[Notice] All your subagents and background tasks have been stopped due to server restart. If you want a subagent to continue working, it needs to be revived by sending it a new message. If resuming work, please check on status and restart as needed.\n</SYSTEM_MESSAGE>"}
{"step_index":11,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-14T06:15:01Z","input_tokens":701,"cache_read_tokens":300,"output_tokens":8,"content":"Hello from the fake."}
{"step_index":12,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T06:16:05Z","content":"<USER_REQUEST>\nthird\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-10-14T14:16:05+08:00.\n</ADDITIONAL_METADATA>"}
{"step_index":13,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:16:06Z","content":"The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-10-14T06:16:05Z sender=system priority=MESSAGE_PRIORITY_LOW content=[Notice] All your subagents and background tasks have been stopped due to server restart. If you want a subagent to continue working, it needs to be revived by sending it a new message. If resuming work, please check on status and restart as needed.\n</SYSTEM_MESSAGE>"}
{"step_index":14,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-14T06:16:06Z","input_tokens":701,"cache_read_tokens":300,"output_tokens":48,"content":"Hello from the fake."}
+45
View File
@@ -0,0 +1,45 @@
package usage
import (
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
// #2097: an agy step that went through magpie is counted once. agy 1.2.16,
// run in a sandbox through a fake Gemini endpoint, sent no session header
// (only User-Agent google-genai-sdk/…, X-Goog-Api-Key), so the gateway's
// record names no session; its transcript's step began at 06:12:41Z, to
// the second, and counted input 702, cache read 300, output 9. A long step
// ends well past the 2 s every other session file's end time is held to.
func TestAgyStepThroughMagpieCountedOnce(t *testing.T) {
began := time.Date(2026, 10, 14, 6, 12, 41, 0, time.UTC)
rec := Record{Time: began.Add(990 * time.Millisecond), Agent: "agy", Provider: "relay", Model: "m",
Input: 702, CacheRead: 300, Output: 9, Millis: 95_000, Status: 200}
step := sessions.Call{Time: began, Agent: "agy", Session: "8ac63d53-9162-4a29-af29-bda3428931ae",
Tokens: sessions.Tokens{Input: 702, CacheRead: 300, Output: 9}}
direct := sessions.Call{Time: began.Add(10 * time.Minute), Agent: "agy", Session: step.Session,
Tokens: sessions.Tokens{Input: 3013, CacheRead: 14973, Output: 1518}}
m := gatewayMatches([]Record{rec}, []sessions.Call{step, direct})
if !m[0] {
t.Error("the step the gateway logged is counted again as agy's own call")
}
if m[1] {
t.Error("a step agy made without magpie was taken for the gateway's")
}
// a step the gateway's call ended before is not that call
early := step
early.Time = rec.Time.Add(time.Duration(rec.Millis)*time.Millisecond + 3*time.Second)
if gatewayMatches([]Record{rec}, []sessions.Call{early})[0] {
t.Error("a step begun after the gateway's call ended was matched to it")
}
// another agent's session-less record is no agy step's
other := rec
other.Agent = "codex"
if gatewayMatches([]Record{other}, []sessions.Call{step})[0] {
t.Error("an agy step matched another agent's record")
}
}
+20 -2
View File
@@ -616,6 +616,17 @@ type matchGroup struct {
counts []int
}
// agyMatchSession stands for the session of an Antigravity CLI (agy) call
// on both sides: agy sends the gateway no session header, so its gateway
// records name none, and its transcript's steps are matched to them by
// their tokens and time alone (#2097).
const agyMatchSession = "\x00agy"
// agyStepLongest is how long after an agy step began its gateway call may
// have ended: a transcript's created_at is when the step began, to the
// second, where every other session file's time is when its call ended.
const agyStepLongest = 30 * time.Minute
func matchedLocal(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]bool, since time.Time) map[rowRef]bool {
return matchedBlocks([]*rowChunk{gateway}, chunks, skip, since, true)
}
@@ -681,6 +692,9 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
if session == "" {
session = gateway.Strings[p.Text[13]]
}
if session == "" && gateway.Strings[p.Text[0]] == "agy" {
session = agyMatchSession
}
if session == "" {
continue
}
@@ -710,6 +724,10 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
continue
}
key := matchKey{session: c.Strings[p.Text[13]], tokens: matchTokens(p.Tokens), failed: failed}
from, to := p.Time.Add(-2*time.Second), p.Time.Add(2*time.Second)
if c.Strings[p.Text[0]] == "agy" {
key.session, to = agyMatchSession, p.Time.Add(agyStepLongest)
}
count, candidate := 0, (rowRef{})
// Without a local ID either gateway partition can match. With an ID,
// only an unnamed gateway call can match (different IDs stay distinct).
@@ -722,8 +740,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
if g == nil {
continue
}
lo := sort.Search(len(g.ends), func(i int) bool { return !g.ends[i].at.Before(p.Time.Add(-2 * time.Second)) })
hi := sort.Search(len(g.ends), func(i int) bool { return g.ends[i].at.After(p.Time.Add(2 * time.Second)) })
lo := sort.Search(len(g.ends), func(i int) bool { return !g.ends[i].at.Before(from) })
hi := sort.Search(len(g.ends), func(i int) bool { return g.ends[i].at.After(to) })
if hi > lo {
count += hi - lo
candidate = g.ends[lo].index