diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 7f3b5d49d..b4afb9aaf 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -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 { diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index e38e7b1e9..f0871accd 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -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()...) } diff --git a/internal/sessions/calls_agy.go b/internal/sessions/calls_agy.go new file mode 100644 index 000000000..1d655e977 --- /dev/null +++ b/internal/sessions/calls_agy.go @@ -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//.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 +} diff --git a/internal/sessions/calls_agy_test.go b/internal/sessions/calls_agy_test.go new file mode 100644 index 000000000..403932e7e --- /dev/null +++ b/internal/sessions/calls_agy_test.go @@ -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) + } + } +} diff --git a/internal/sessions/testdata/agy/brain/2b0e6c1a-1d3e-4f6a-9a51-0f1c2d3e4f5a/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy/brain/2b0e6c1a-1d3e-4f6a-9a51-0f1c2d3e4f5a/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..8bf62988c --- /dev/null +++ b/internal/sessions/testdata/agy/brain/2b0e6c1a-1d3e-4f6a-9a51-0f1c2d3e4f5a/.system_generated/logs/transcript_full.jsonl @@ -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} diff --git a/internal/sessions/testdata/agy/brain/5c1f0e2d-7a8b-4c9d-8e0f-1a2b3c4d5e6f/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy/brain/5c1f0e2d-7a8b-4c9d-8e0f-1a2b3c4d5e6f/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..976f20e86 --- /dev/null +++ b/internal/sessions/testdata/agy/brain/5c1f0e2d-7a8b-4c9d-8e0f-1a2b3c4d5e6f/.system_generated/logs/transcript_full.jsonl @@ -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"} diff --git a/internal/sessions/testdata/agy/brain/8ac63d53-9162-4a29-af29-bda3428931ae/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy/brain/8ac63d53-9162-4a29-af29-bda3428931ae/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..00cd9d582 --- /dev/null +++ b/internal/sessions/testdata/agy/brain/8ac63d53-9162-4a29-af29-bda3428931ae/.system_generated/logs/transcript_full.jsonl @@ -0,0 +1,15 @@ +{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-14T06:12:41Z","content":"\nsay hi\n\n\nThe current local time is: 2026-10-14T14:12:41+08:00.\n\n\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"} +{"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":"\nagain\n\n\nThe current local time is: 2026-10-14T14:13:45+08:00.\n"} +{"step_index":3,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:13:46Z","content":"The following is a not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n\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"} +{"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":"\nagain\n\n\nThe current local time is: 2026-10-14T14:15:01+08:00.\n"} +{"step_index":10,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:15:01Z","content":"The following is a not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n\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"} +{"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":"\nthird\n\n\nThe current local time is: 2026-10-14T14:16:05+08:00.\n"} +{"step_index":13,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-14T06:16:06Z","content":"The following is a not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n\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"} +{"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."} diff --git a/internal/usage/agy_match_test.go b/internal/usage/agy_match_test.go new file mode 100644 index 000000000..9f57fc706 --- /dev/null +++ b/internal/usage/agy_match_test.go @@ -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") + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 55f7c0aaf..1a669004c 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -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