diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index a0f5f351b..06287e4a0 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -284,6 +284,7 @@ var lineCallReaders = map[string]lineCallReader{ "raft": {piCallsBegin, readPiCallLine, piCallsKept}, "cindy": {piCallsBegin, readPiCallLine, piCallsKept}, "omp": {piCallsBegin, readPiCallLine, piCallsKept}, + "grok": {grokCallsBegin, grokCallLine, grokCallsKept}, // #4423 } // callLock is the lock a file's calls are read under, so that two readers @@ -574,6 +575,11 @@ type callDiskState struct { PiCwd string PiSince time.Time PiProvider, PiModel string + // Grok Build's carry (grokCallCarry), flat: GrokOn when there is one + GrokOn bool + GrokSince time.Time + GrokModel string + GrokAsked string } func diskCallState(s *callFile) callDiskState { @@ -586,6 +592,9 @@ func diskCallState(s *callFile) callDiskState { if p := s.Pi; p != nil { d.PiOn, d.PiHeader, d.PiCwd, d.PiSince, d.PiProvider, d.PiModel = true, p.Header, p.Cwd, p.Since, p.Provider, p.Model } + if g := s.Grok; g != nil { + d.GrokOn, d.GrokSince, d.GrokModel, d.GrokAsked = true, g.Since, g.Model, g.Asked + } return d } func (s callDiskState) restore() *callFile { @@ -601,6 +610,9 @@ func (s callDiskState) restore() *callFile { if s.PiOn { st.Pi = &piCarry{s.PiHeader, s.PiCwd, s.PiSince, s.PiProvider, s.PiModel} } + if s.GrokOn { + st.Grok = &grokCallCarry{Since: s.GrokSince, Model: s.GrokModel, Asked: s.GrokAsked} + } return st } diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 2fadc7a90..8547a3bc9 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -101,6 +101,8 @@ type callFile struct { Pi *piCarry // dsh Dsh *dshCarry + // Grok Build + Grok *grokCallCarry } // cxRun is where a rollout's read stands: what its lines have said so far. @@ -324,11 +326,11 @@ func callFileLists(codex []file) [][]file { // calls are rows of their database or their JSON files; and WorkBuddy's, whose usage lines repeat a reply's id as it // goes on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages // file a later generation of its history may replace (#1605). Kimi Code's -// (#1607), Pi's and omp's (#1951) are lines of a file only appended to, -// read on as callFiles' are; DeepSeek Harness's, a file only appended to -// that may be packed in zstd frames, is read on from the frame it was -// left in (readDshCalls). Every agent here needs an entry in -// wholeCallReaders, lineCallReaders or resumeCallReaders. +// (#1607), Pi's and omp's (#1951) and Grok Build's (#4423) are lines of a +// file only appended to, read on as callFiles' are; DeepSeek Harness's, a +// file only appended to that may be packed in zstd frames, is read on +// from the frame it was left in (readDshCalls). Every agent here needs an +// entry in wholeCallReaders, lineCallReaders or resumeCallReaders. func callSources() []file { return callSourcesWith(codexFiles()) } // callSourcesWith is callSources with codex the rollouts codexFiles found. @@ -338,8 +340,8 @@ func callSourcesWith(codex []file) []file { return callSourcesInto(nil, codex) } func callSourcesInto(out []file, codex []file) []file { lists := append(callFileLists(codex), openCodeCallFiles(), zcodeCallFiles(), dshCallFiles(), minimaxCallFiles(), kimiCallFiles(), wslFiles("kimi"), piCallFiles(), codebuddyCallFiles(), - agyCallFiles(), // #2097 - workbuddyCallFiles()) + agyCallFiles(), // #2097 + workbuddyCallFiles(), grokCallFiles()) // #4423 if out == nil { return allowed(distinctOf(lists...)) } @@ -443,6 +445,10 @@ func (st *callFile) cloneState() *callFile { } c.Dsh = &d } + if st.Grok != nil { + g := *st.Grok + c.Grok = &g + } return &c } diff --git a/internal/sessions/calls_grok.go b/internal/sessions/calls_grok.go new file mode 100644 index 000000000..f0c151f54 --- /dev/null +++ b/internal/sessions/calls_grok.go @@ -0,0 +1,201 @@ +package sessions + +import ( + "bytes" + "cmp" + "encoding/json" + "maps" + "path/filepath" + "slices" + "strings" + "time" + + toml "github.com/pelletier/go-toml/v2" + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/filememo" +) + +// Grok Build's own calls (#4423, liubing0806: its direct calls to x.ai +// never reached Usage) — read from the same updates.jsonl the Sessions +// page reads (parseGrok), each turn_completed's usage a call per model in +// modelUsage, on that model's own counts (grokUsage.tokens: input without +// what the cache held). An empty modelUsage is the session's model +// (current_model_id, else "grok"). The turn's time is the line's. A +// subagent's turns are in its own folder, a call of its own session. A +// fork counts the lines written from its created_at on: what it copied +// from its source is older, and was counted where it was first written. +// +// A turn asked through magpie's gateway is the gateway's to count, and is +// left out here. Matching it to the gateway's records can't be relied on: +// a turn_completed sums every request of the turn per model (modelCalls 4 +// on a real one, 7 and 17 in liubing0806's), the gateway logs each request, +// and the model the sum is keyed by is the one the reply named +// (moonshotai/Kimi-K3 for a turn asked on magpie's group/auto-kimi-k3), so +// gatewayMatches would leave such a turn in Local session beside the +// gateway's own rows. Which model a turn was asked on is in its prompt's +// user_message_chunk (_meta.modelId: "group/auto-kimi-k3" for the +// [model."magpie/group/auto-kimi-k3"] table magpie writes in config.toml, +// "grok-4.7" for Grok's own), so a turn is the gateway's when that model +// is one of magpie's tables (grokGateway). Anything not told apart that +// way still goes through gatewayMatches as the others' calls do. +// +// Grok Build only appends to updates.jsonl, a line an event, so a file +// that grew is read on from where the last read left off +// (lineCallReaders). + +// grokCallFiles are the session files Sessions lists for Grok Build +// (grokFiles): one updates.jsonl per session folder, beside its +// summary.json. +func grokCallFiles() []file { return grokFiles() } + +// grokCallCarry is what a read of a session's updates carries on with: +// what of its summary the turns are counted under. +type grokCallCarry struct { + Since time.Time `json:"since,omitzero"` + Model string `json:"model,omitempty"` + // Asked is the model the session's last prompt was asked on (its + // user_message_chunk's _meta.modelId), "" before one is read + Asked string `json:"asked,omitempty"` +} + +// grokCallsBegin starts a session's updates read from its start, with its +// summary: the model an empty modelUsage falls back to, and, for a fork, +// the time its source's lines were copied before. +func grokCallsBegin(st *callFile, f file) { + st.Session = filepath.Base(filepath.Dir(f.path)) + c := &grokCallCarry{} + if m, ok := readGrokSummary(f.m().manifest); ok { + c.Model = m.CurrentModel + if m.Parent != "" { + // what it copied from its source is older than it + if at, err := time.Parse(time.RFC3339Nano, m.CreatedAt); err == nil { + c.Since = at.Truncate(time.Second) + } + } + } + st.Grok = c +} + +// grokCallsKept is whether st holds what reading on needs: a disk shard +// written before the carry was kept there does not, and its file is read +// whole again once it changes. +func grokCallsKept(st *callFile) bool { return st.Grok != nil } + +// grokCallLine reads one line of a session's updates: a turn_completed +// with usage is a call per model. +func grokCallLine(st *callFile, b []byte) { + b = bytes.TrimSpace(b) + if len(b) == 0 || len(b) > maxLine { + return + } + if bytes.Contains(b, grokUser) { + // the model the turn is asked on, for grokGateway + if c := st.Grok; c != nil { + if id := gjson.GetBytes(b, "params.update._meta.modelId").String(); id != "" { + c.Asked = id + } + } + return + } + if !bytes.Contains(b, grokTurn) { + return + } + at := numTS(b) + if at.IsZero() { + return + } + if c := st.Grok; c != nil && !c.Since.IsZero() && at.Before(c.Since) { + return + } + var l grokLine + if json.Unmarshal(b, &l) != nil { + return + } + u := l.Params.Update + if u.SessionUpdate != "turn_completed" || u.Usage == nil { + return + } + if c := st.Grok; c != nil && grokGateway(cmp.Or(c.Asked, c.Model)) { + return + } + add := func(model string, u grokUsage) { + t := u.tokens() + if t.zero() { + return + } + st.Calls = append(st.Calls, Call{ + Agent: "grok", + Time: at, + Session: st.Session, + Model: st.str(model), + Tokens: t, + }) + } + if len(u.Usage.ModelUsage) == 0 { + var model string + if c := st.Grok; c != nil { + model = c.Model + } + add(cmp.Or(model, "grok"), u.Usage.grokUsage) + return + } + for _, name := range slices.Sorted(maps.Keys(u.Usage.ModelUsage)) { + add(name, u.Usage.ModelUsage[name]) + } +} + +// grokGateway is whether a turn asked on model went through magpie's +// gateway: the model is one of the [model."magpie/…"] tables magpie writes +// in Grok Build's config.toml (internal/agent's grok.go), by the table's +// name or its model (Grok names the turn's model by the latter), or names +// magpie's prefix itself. A config.toml that can't be read tells nothing +// more than the prefix: magpie writes its tables there, so a Grok Build +// wired to magpie has one to read. +func grokGateway(model string) bool { + if model == "" { + return false + } + if strings.HasPrefix(model, grokGatewayPrefix) { + return true + } + return grokGatewayModels()[model] +} + +const grokGatewayPrefix = "magpie/" + +// grokGatewayModels are the models of magpie's tables in Grok Build's +// config.toml, read again only when it changes. What it gives is shared +// and must not be changed. +func grokGatewayModels() map[string]bool { + m, _ := filememo.Read("sessions grok config", filepath.Join(GrokDir(), "config.toml"), func(b []byte) (map[string]bool, error) { + var c struct { + Model map[string]any `toml:"model"` + } + if err := toml.Unmarshal(b, &c); err != nil { + return nil, err + } + out := map[string]bool{} + for name, t := range c.Model { + id, ok := strings.CutPrefix(name, grokGatewayPrefix) + if !ok { + continue + } + out[id] = true + // a table, or (as a hand edit may leave it) an array of them + tables, _ := t.([]any) + if m, ok := t.(map[string]any); ok { + tables = []any{m} + } + for _, x := range tables { + if m, ok := x.(map[string]any); ok { + if v, _ := m["model"].(string); v != "" { + out[v] = true + } + } + } + } + return out, nil + }) + return m +} diff --git a/internal/sessions/calls_grok_test.go b/internal/sessions/calls_grok_test.go new file mode 100644 index 000000000..97769ae02 --- /dev/null +++ b/internal/sessions/calls_grok_test.go @@ -0,0 +1,156 @@ +package sessions + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// #4423 (liubing0806): Grok Build's own calls reach Usage, read from the +// same updates.jsonl the Sessions page reads (parseGrok). The four sessions +// in testdata/grok: +// +// - a: two turns, the first spent by grok-4.7-build and grok-4.7-mini +// together, the second by grok-4.7-build alone +// - b: a subagent's own folder (session_kind subagent), its one turn its +// own, not its parent a's +// - c: a fork of a, whose first turn is the copy of a's first one — +// counted where it was first written, so only its own turn (written +// after its created_at) is a call of its own +// - d: no turn completed, no calls +type grokTotal struct{ n, input, cacheRead, cacheWrite, output int } + +func grokCallsBy(f func(Call) string) map[string]grokTotal { + out := map[string]grokTotal{} + for _, c := range Calls(time.Time{}) { + if c.Agent != "grok" { + continue + } + t := out[f(c)] + t.n, t.input, t.cacheRead, t.cacheWrite, t.output = + t.n+1, t.input+c.Input, t.cacheRead+c.CacheRead, t.cacheWrite+c.CacheWrite, t.output+c.Output + out[f(c)] = t + } + return out +} + +func TestGrokCalls(t *testing.T) { + for _, viaEnv := range []bool{false, true} { + name := "~/.grok" + if viaEnv { + name = "GROK_HOME" + } + t.Run(name, func(t *testing.T) { + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".grok") + copyTree(t, "testdata/grok", dir) + if viaEnv { + t.Setenv("GROK_HOME", dir) + } + want := map[string]grokTotal{ + "0190aaaa-0000-7000-8000-00000000000a": {3, 800, 2800, 0, 110}, + "0190aaaa-0000-7000-8000-00000000000b": {1, 200, 100, 0, 20}, + "0190aaaa-0000-7000-8000-00000000000c": {1, 100, 300, 0, 30}, + } + got := grokCallsBy(func(c Call) string { return c.Session }) + if len(got) != len(want) { + t.Fatalf("sessions with calls %v, want %v", got, want) + } + for s, w := range want { + if got[s] != w { + t.Fatalf("session %s calls %+v, want %+v", s, got[s], w) + } + } + // the Usage ledger lists them by model + byModel := grokCallsBy(func(c Call) string { return c.Model }) + wantModels := map[string]grokTotal{ + "grok-4.7-build": {3, 800, 3100, 0, 130}, + "grok-4.7-mini": {2, 300, 100, 0, 30}, + } + for m, w := range wantModels { + if byModel[m] != w { + t.Fatalf("model %s calls %+v, want %+v", m, byModel[m], w) + } + } + if len(byModel) != len(wantModels) { + t.Fatalf("models %v, want %v", byModel, wantModels) + } + }) + } +} + +// A fork counts only its own turns: c's call is its turn of 09:00:30, not +// the copied one of 08:00:20. +func TestGrokCallsForkKeepsItsOwnTurns(t *testing.T) { + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".grok") + copyTree(t, "testdata/grok", dir) + var got []int64 + for _, c := range Calls(time.Time{}) { + if c.Agent == "grok" && c.Session == "0190aaaa-0000-7000-8000-00000000000c" { + got = append(got, c.Time.Unix()) + } + } + if len(got) != 1 || got[0] != 1790499630 { + t.Fatalf("fork c call times %v, want [1790499630]", got) + } +} + +// A turn asked through magpie's gateway is the gateway's to count, so it +// is not a Local session call too: its turn_completed sums every request +// of the turn per model, keyed by the model the reply named, which no +// gateway record matches one to one (liubing0806's modelCalls 7 and 17). +// The model it was asked on is in its prompt's _meta.modelId, one of the +// [model."magpie/…"] tables magpie writes in config.toml. The lines are a +// real session's of each kind, the prompt text cut: e asked on magpie's +// group/auto-kimi-k3 and answered as moonshotai/Kimi-K3; f asked on Grok's +// own grok-4.7, four calls in one turn. +func TestGrokCallsLeaveTheGatewaysTurnsOut(t *testing.T) { + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".grok") + copyTree(t, "testdata/grok", dir) + write := func(path, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + } + write(filepath.Join(dir, "config.toml"), "[models]\ndefault = \"magpie/group/auto-kimi-k3\"\n\n[model.\"magpie/group/auto-kimi-k3\"]\nmodel = \"group/auto-kimi-k3\"\nbase_url = \"http://127.0.0.1:3425/v1\"\napi_key = \"magpie\"\n") + sessions := filepath.Join(dir, "sessions", "%2Fwork%2Fgrok") + const e, f = "01a10341-1c84-7bc0-935e-a35c28f59817", "01a19751-b6a2-7172-b233-ebb9aaac02ba" + write(filepath.Join(sessions, e, "summary.json"), `{"info":{"id":"`+e+`","cwd":"/work/grok"},"created_at":"2026-10-03T19:32:41.254395Z","current_model_id":"group/auto-kimi-k3"}`) + write(filepath.Join(sessions, e, "updates.jsonl"), `{"timestamp":1791056007,"method":"session/update","params":{"sessionId":"`+e+`","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"hi"},"_meta":{"modelId":"group/auto-kimi-k3","promptIndex":0}},"_meta":{"eventId":"`+e+`-4","agentTimestampMs":1791056006956}}} +{"timestamp":1791056019,"method":"_x.ai/session/update","params":{"sessionId":"`+e+`","update":{"sessionUpdate":"turn_completed","prompt_id":"8aeb9078-f6d6-44ce-9264-8119e6360964","stop_reason":"end_turn","usage":{"inputTokens":26124,"outputTokens":92,"totalTokens":26216,"cachedReadTokens":0,"cacheCreationTokens":0,"reasoningTokens":45,"modelCalls":1,"apiDurationMs":11887,"modelUsage":{"moonshotai/Kimi-K3":{"inputTokens":26124,"outputTokens":92,"totalTokens":26216,"cachedReadTokens":0,"cacheCreationTokens":0,"reasoningTokens":45,"modelCalls":1,"apiDurationMs":11887}},"numTurns":1},"elapsed_ms":12182},"_meta":{"eventId":"`+e+`-46","agentTimestampMs":1791056019060}}} +`) + write(filepath.Join(sessions, f, "summary.json"), `{"info":{"id":"`+f+`","cwd":"/work/grok"},"created_at":"2026-11-01T13:34:37.231999Z","current_model_id":"grok-4.7","session_kind":"headless"}`) + write(filepath.Join(sessions, f, "updates.jsonl"), `{"timestamp":1793540077,"method":"session/update","params":{"sessionId":"`+f+`","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"hi"},"_meta":{"modelId":"grok-4.7","promptIndex":0}},"_meta":{"eventId":"`+f+`-4","agentTimestampMs":1793540077642}}} +{"timestamp":1793540091,"method":"_x.ai/session/update","params":{"sessionId":"`+f+`","update":{"sessionUpdate":"turn_completed","prompt_id":"aae30f85-b907-4557-82d7-5ac8fe6363db","stop_reason":"end_turn","usage":{"inputTokens":97708,"outputTokens":435,"totalTokens":98143,"cachedReadTokens":82304,"cacheCreationTokens":0,"reasoningTokens":223,"modelCalls":4,"apiDurationMs":12347,"costUsdTicks":745700000,"modelUsage":{"grok-4.7-build":{"inputTokens":97708,"outputTokens":435,"totalTokens":98143,"cachedReadTokens":82304,"cacheCreationTokens":0,"reasoningTokens":223,"modelCalls":4,"apiDurationMs":12347,"costUsdTicks":745700000}},"numTurns":4},"elapsed_ms":14206},"_meta":{"eventId":"`+f+`-102","agentTimestampMs":1793540091654}}} +`) + // g: e's turn with no prompt line before it, so the session's own + // model (summary.json) tells; h: asked on a magpie/ table name that + // config.toml doesn't list (written by an older magpie, or edited). + turn := `{"timestamp":1791056019,"method":"_x.ai/session/update","params":{"sessionId":"ID","update":{"sessionUpdate":"turn_completed","stop_reason":"end_turn","usage":{"inputTokens":26124,"outputTokens":92,"cachedReadTokens":0,"modelCalls":1,"modelUsage":{"moonshotai/Kimi-K3":{"inputTokens":26124,"outputTokens":92,"cachedReadTokens":0,"modelCalls":1}}}}}}` + "\n" + const g, h = "01a10341-1c84-7bc0-935e-a35c28f5981a", "01a10341-1c84-7bc0-935e-a35c28f5981b" + write(filepath.Join(sessions, g, "summary.json"), `{"info":{"id":"`+g+`","cwd":"/work/grok"},"created_at":"2026-10-03T19:32:41Z","current_model_id":"group/auto-kimi-k3"}`) + write(filepath.Join(sessions, g, "updates.jsonl"), strings.ReplaceAll(turn, "ID", g)) + write(filepath.Join(sessions, h, "summary.json"), `{"info":{"id":"`+h+`","cwd":"/work/grok"},"created_at":"2026-10-03T19:32:41Z","current_model_id":"grok-4.7"}`) + write(filepath.Join(sessions, h, "updates.jsonl"), `{"timestamp":1791056007,"method":"session/update","params":{"sessionId":"`+h+`","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"hi"},"_meta":{"modelId":"magpie/deepseek/pro","promptIndex":0}}}}`+"\n"+strings.ReplaceAll(turn, "ID", h)) + got := grokCallsBy(func(c Call) string { return c.Session }) + for _, s := range []string{e, g, h} { + if _, ok := got[s]; ok { + t.Fatalf("%s: a turn asked through magpie's gateway is a Local session call too: %+v", s, got[s]) + } + } + if w := (grokTotal{1, 97708 - 82304, 82304, 0, 435}); got[f] != w { + t.Fatalf("Grok's own turn: %+v, want %+v", got[f], w) + } + // the three of testdata/grok are still counted + if len(got) != 4 { + t.Fatalf("sessions with calls %v", got) + } +}