diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index ec897b444..1805c23ce 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -274,6 +274,7 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){ "agy": readAgyCalls, // #2097 "antigravity": readAntigravityCalls, // #2190 "devin": readDevinCalls, // aohan0905 on X + "droid": readDroidCalls, // _meouwu on X } // resumeCallReaders read an agent's calls from a file only appended to that diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 51ea84dcf..886a5ccc8 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -333,7 +333,8 @@ func callFileLists(codex []file) [][]file { // read whole rather than line by line: OpenCode's (#680) and ZCode's, whose // 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 +// file a later generation of its history may replace (#1605); and Droid's, whose spend is +// only a running total in each session's settings (calls_droid.go). Kimi Code's // (#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 @@ -354,6 +355,7 @@ func callSourcesInto(out []file, codex []file) []file { antigravityCallFiles(), // #2190 wslFiles("antigravity"), wslCallFiles("agy"), // @guyng35955 on X devinCallFiles(), // aohan0905 on X + droidFiles(), // _meouwu on X: its settings' totals (calls_droid.go) workbuddyCallFiles(), grokCallFiles(), // #4423 // Claude Code's lines, read by claudeCallLine (eating_dream on X) ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn"))) diff --git a/internal/sessions/calls_droid.go b/internal/sessions/calls_droid.go new file mode 100644 index 000000000..7dc7a3fa5 --- /dev/null +++ b/internal/sessions/calls_droid.go @@ -0,0 +1,174 @@ +package sessions + +import ( + "cmp" + "encoding/json" + "net" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + "github.com/tidwall/gjson" + "github.com/tidwall/jsonc" + + "github.com/yetone/magpie/internal/settings" +) + +// Factory Droid's own calls (_meouwu on X: Droid's sessions were listed but +// Usage counted none of what they spent). Droid (0.231.0, its binary's +// session schema read, and real runs' files in testdata/droid-skills) +// writes no tokens into a transcript: a message line has its time, the +// message and, for a reply, the modelId it was asked of, and nothing of +// what the call cost. What a session spent is only in its settings +// (.settings.json): tokenUsage, its own running total over every call +// (input without the cache, output with the thinking in it, and the cache +// read and written), and lastCallTokenUsage, the latest call's input and +// output alone, which says nothing of the calls before it. So a session is +// one call here, its whole total, at the time of its last message — the +// day the Sessions page counts the same total on (parseDroid) — under the +// model its settings name. A subagent's transcript has its own total (the +// caller's tokenUsage leaves it out; inclusiveTokenUsage adds it) and is +// counted under the session that called it; a fork's starts at none. +// +// A session on one of magpie's own entries ("custom:magpie/", +// internal/agent's droid.go), or on a custom model of the user's whose +// baseUrl is magpie's gateway on this computer (as testdata/droid-skills' +// custom:mh is), sent its calls through the gateway, which counted each +// one: such a session is left out whole, when its settings or any of its +// replies name one, as its total can't be split by model. A session is +// judged when it is read, which is again once it or its settings change. + +// droidGateway is how the id of a model magpie wrote into droid's +// settings begins. +const droidGateway = "custom:magpie/" + +// droidCallSettings are a session's settings as its calls are read. +type droidCallSettings struct { + Model string `json:"model"` + Usage *droidUsage `json:"tokenUsage"` +} + +// readDroidCalls reads a session's transcript and its settings beside it +// whole: the settings are rewritten as the total moves on, so there is no +// reading on from where the last read left off. +func readDroidCalls(f file) (*callFile, bool) { + st := &callFile{Path: f.path, Agent: f.agent} + b, err := os.ReadFile(strings.TrimSuffix(f.path, ".jsonl") + ".settings.json") + if os.IsNotExist(err) { + return st, true // an older session with no settings: nothing said + } + if err != nil { + return st, false + } + var set droidCallSettings + if json.Unmarshal(b, &set) != nil { + return st, false // half-written, as droid rewrites it: read it next time + } + var c droidCarry + var start droidStart + var last time.Time + customs := droidCustomBases() + gateway := droidViaGateway(set.Model, customs) + _, err = scanAt(f.path, 0, nil, func(b []byte, _, _ int64) bool { + var l struct { + Type string `json:"type"` + ID string `json:"id"` + Message struct { + Model string `json:"modelId"` + } `json:"message"` + } + if json.Unmarshal(b, &l) != nil { + return true + } + if !c.Started { + c.Started = true + if l.Type == "session_start" && json.Unmarshal(b, &start) == nil { + c.Upto, c.Copied = start.Forked, start.Forked != "" + } + return true + } + if l.Type != "message" { + return true + } + if c.Copied { + if l.ID == c.Upto { + c.Copied = false + } + return true + } + if l.Message.Model != "" && droidViaGateway(l.Message.Model, customs) { + gateway = true + } + if at := tsAt(b, false); at.After(last) { + last = at + } + return true + }) + if err != nil { + return st, false + } + u := set.Usage + if u == nil || gateway || u.Input+u.Output+u.CacheRead+u.CacheWrite == 0 { + return st, true + } + id := strings.TrimSuffix(filepath.Base(f.path), ".jsonl") + session := id + if start.Calling != "" && start.Calling != id && safeID.MatchString(start.Calling) { + session = start.Calling + } + if last.IsZero() { + last = f.mod.Time() + } + st.Calls = []Call{{ + Time: last, Agent: "droid", Session: session, Model: droidModelName(set.Model), Msg: "droid:" + id, + Tokens: Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}, + Cwd: cmp.Or(start.LastCwd, start.Cwd), + }} + return st, true +} + +// droidCustomBases are the baseUrl of each custom model in droid's +// settings, by its id ("custom:"). +func droidCustomBases() map[string]string { + out := map[string]string{} + raw, err := os.ReadFile(filepath.Join(FactoryDir(), "settings.json")) + if err != nil { + return out + } + gjson.GetBytes(jsonc.ToJSONInPlace(raw), "customModels").ForEach(func(_, v gjson.Result) bool { + if id := v.Get("id").String(); id != "" { + out[id] = v.Get("baseUrl").String() + } + return true + }) + return out +} + +// droidViaGateway is whether droid sent a model's calls through magpie's +// gateway: one of magpie's own entries, or a custom model whose baseUrl +// is the gateway's port on this computer. +func droidViaGateway(model string, customs map[string]string) bool { + if strings.HasPrefix(model, droidGateway) { + return true + } + base, ok := customs[model] + if !ok || !loopbackURL(base) { + return false + } + u, err := url.Parse(strings.TrimSpace(base)) + if err != nil { + return false + } + port := u.Port() + if port == "" { + port = map[string]string{"http": "80", "https": "443"}[u.Scheme] + } + for _, a := range []string{settings.GatewayAddr(), settings.SavedAddr()} { + if _, p, err := net.SplitHostPort(a); err == nil && p == port { + return true + } + } + return false +} diff --git a/internal/sessions/calls_droid_test.go b/internal/sessions/calls_droid_test.go new file mode 100644 index 000000000..66a70b20a --- /dev/null +++ b/internal/sessions/calls_droid_test.go @@ -0,0 +1,125 @@ +package sessions + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// droidCalls are the Droid calls Calls gives, by transcript. +func droidCalls(t *testing.T) map[string]Call { + t.Helper() + out := map[string]Call{} + for _, c := range Calls(time.Time{}) { + if c.Agent == "droid" { + if _, dup := out[c.Msg]; dup { + t.Fatalf("%s counted twice", c.Msg) + } + out[c.Msg] = c + } + } + return out +} + +// Droid's own calls reach the usage ledger (_meouwu on X: Droid's +// sessions were listed, but Usage counted none of what they spent). +// testdata/droid-skills are real droid 0.231.0 sessions (see +// TestDroidToolsAndSkills); droid writes no tokens into a transcript, only +// each session's running total into its settings, so each session is one +// call of that total, at its last message, under its settings' model. +func TestDroidCalls(t *testing.T) { + // a home with droid's settings as custom says, "" for none + home := func(custom string) { + t.Helper() + home := setupAgents(t) + t.Setenv("FACTORY_HOME_OVERRIDE", "") + t.Setenv("MAGPIE_ADDR", "127.0.0.1:39417") + copyTree(t, "testdata/droid-skills", filepath.Join(home, ".factory")) + if custom != "" { + if err := os.WriteFile(filepath.Join(home, ".factory", "settings.json"), []byte(`{"customModels":[{"model":"mh","id":"custom:mh","baseUrl":"`+custom+`","apiKey":"k","provider":"generic-chat-completion-api"}]}`), 0o644); err != nil { + t.Fatal(err) + } + } + Reset() + } + home("") + cs := droidCalls(t) + if len(cs) != 4 { + t.Fatalf("want the 4 Droid sessions' totals, got %d: %+v", len(cs), cs) + } + for _, w := range []struct { + id, last string + tokens Tokens + }{ + {"86f11060-c188-4609-942b-8c3fc53638dc", "2026-10-30T03:02:08.518Z", Tokens{Input: 30750, Output: 113}}, + {"99bfae77-1ca3-4cc9-9c35-445f1fe4dfcd", "2026-10-30T03:02:28.602Z", Tokens{Input: 15435, Output: 330}}, + {"aea4c8cc-92da-4695-889d-5ad6c5b6cec3", "2026-10-30T03:02:38.879Z", Tokens{Input: 15539, Output: 76}}, + {"cb1d8bed-aa2c-4ba2-a23f-681dc5da403f", "2026-10-30T03:02:17.660Z", Tokens{Input: 15329, Output: 66}}, + } { + c, ok := cs["droid:"+w.id] + if !ok { + t.Errorf("session %s not counted", w.id) + continue + } + at, _ := time.Parse(time.RFC3339Nano, w.last) + // no settings.json here names custom:mh, so it is priced by its name + if c.Session != w.id || c.Model != "mh" || c.Tokens != w.tokens || !c.Time.Equal(at) { + t.Errorf("session %s: %+v", w.id, c) + } + } + + // custom:mh on a model server of the user's own on this computer is + // still counted; on magpie's gateway, the gateway counted its calls + home("http://localhost:11434/v1") + if cs := droidCalls(t); len(cs) != 4 { + t.Fatalf("a model of the user's own on another port: %d calls, want 4", len(cs)) + } + home("http://127.0.0.1:39417/v1") + if cs := droidCalls(t); len(cs) != 0 { + t.Fatalf("sessions through magpie's gateway counted again: %+v", cs) + } + + home("") + if err := SetReads(nil, map[string]bool{"droid": false}); err != nil { + t.Fatal(err) + } + if cs := droidCalls(t); len(cs) != 0 { + t.Fatalf("turning off Droid still counts its calls: %+v", cs) + } +} + +// A subagent's total is counted under the session that called it, a +// fork's from none, a session with no settings not at all, and one on +// magpie's own entry (custom:magpie/…) is the gateway's to count. +func TestDroidCallsOfSessions(t *testing.T) { + home := setupAgents(t) + t.Setenv("FACTORY_HOME_OVERRIDE", "") + putDroid(t, home) + Reset() + + cs := droidCalls(t) + if len(cs) != 2 { + t.Fatalf("want the subagent's and the fork's, got %d: %+v", len(cs), cs) + } + if c := cs["droid:"+droidSub]; c.Session != droidMain || c.Model != "claude-haiku-4-5" || c.Tokens != (Tokens{Input: 5, Output: 2}) || c.Cwd != "/work/droid" || + !c.Time.Equal(at("2026-09-27T08:01:10Z")) { + t.Errorf("subagent: %+v", c) + } + if c := cs["droid:"+droidFork]; c.Session != droidFork || c.Model != "Kimi-K2" || c.Tokens != (Tokens{Input: 7, Output: 3}) || + !c.Time.Equal(at("2026-09-27T09:00:30Z")) { + t.Errorf("fork: %+v", c) + } + + // the same session, its settings on a model of Factory's own + p := filepath.Join(home, ".factory", "sessions", "-work-droid", droidMain+".settings.json") + if err := os.WriteFile(p, []byte(`{"model":"claude-sonnet-4-5-20250929","tokenUsage":{"inputTokens":100,"outputTokens":50,"cacheCreationTokens":10,"cacheReadTokens":1000,"thinkingTokens":20}}`), 0o644); err != nil { + t.Fatal(err) + } + Reset() + c, ok := droidCalls(t)["droid:"+droidMain] + if !ok || c.Model != "claude-sonnet-4-5-20250929" || c.Tokens != (Tokens{Input: 100, Output: 50, CacheRead: 1000, CacheWrite: 10}) || + !c.Time.Equal(at("2026-09-27T08:02:00Z")) { + t.Errorf("on Factory's own model: %+v (%v)", c, ok) + } +} diff --git a/internal/usage/direct_test.go b/internal/usage/direct_test.go index ae295a126..d2da73b92 100644 --- a/internal/usage/direct_test.go +++ b/internal/usage/direct_test.go @@ -128,3 +128,36 @@ func TestDirectQoderCallsByCredits(t *testing.T) { } } } + +// Droid's own sessions are under Direct by Droid (_meouwu on X), a +// session's total as one call (sessions' calls_droid.go), priced by its +// model. +func TestDirectDroidSessionTotals(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"claude-sonnet-4-5-20250929":{"id":"claude-sonnet-4-5-20250929","cost":{"input":3,"output":15}}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + + now := holdClock(t, time.Date(2026, 11, 15, 12, 0, 0, 0, time.Local)) + old := LogCalls + LogCalls = func(time.Time) []sessions.Call { + return []sessions.Call{ + {Time: now.Add(-time.Hour), Agent: "droid", Session: "d1", Model: "claude-sonnet-4-5-20250929", Msg: "droid:d1", Tokens: sessions.Tokens{Input: 30750, Output: 113, CacheRead: 1000}}, + {Time: now.Add(-2 * time.Hour), Agent: "droid", Session: "d1", Model: "claude-sonnet-4-5-20250929", Msg: "droid:d2", Tokens: sessions.Tokens{Input: 5, Output: 2}}, + } + } + t.Cleanup(func() { LogCalls = old }) + + d := Direct(Month) + if d.Calls != 2 || d.Input != 30755 || d.Output != 115 || d.CacheRead != 1000 || d.Cost == 0 || d.Unpriced != 0 { + t.Fatalf("direct totals %+v", d.Totals) + } + if len(d.Agents) != 1 || d.Agents[0].ID != "droid" || len(d.Sessions) != 1 || d.Sessions[0].ID != "d1" { + t.Fatalf("agents %+v sessions %+v", d.Agents, d.Sessions) + } +}