Neo (Discord #feedback): one Claude conversation was listed as ~11 rows
with the same title, message count and size, each under its own id.
Claude Code 2.1.312 copies a conversation into a new <id>.jsonl when it
forks one (--resume --fork-session, /branch) or moves it to a background
session: every message again, under the same uuids, with the new
sessionId. magpie keyed each file as a session, so each copy was a row,
and the copies' tokens were counted again in usage.
Each main Claude-format file (Claude Code, Qoder, Qoder CN) now records
the uuids of its first and last message (state Root/Leaf, cacheVersion
23, so every file is read once more and old copies fold in too). Of the
files of one agent that start with the same message, one whose last
message another holds is a copy (cc_copies.go). Only a random (v4) uuid counts, as Claude Code
writes them: files whose writer reuses ids like "u" stay apart. A copy
is not listed
(List, ListAgent, Agents), not counted in stats, and Delete trashes it
with the session that holds it (Restore brings it back). A fork that
went on with a turn of its own has a last message no other file holds
and stays its own row, as Claude Code's /resume shows it. The gateway's
session rows and the GUI's native keys know the copies' ids, so a
gateway-only row doesn't stand in for one.
Fixtures: testdata/claude-forks is Claude Code 2.1.312's own files from
a sandbox HOME with a fake API (a session, a --fork-session of it with a
third prompt, another fork with a different one), trimmed of request
records and attachment text. Pure copies are that session with its
sessionId rewritten, as /branch leaves one.
Run (mote) at 2b7ce2967 on d8c70504d: go test -tags nogui -timeout 45m
./... all 76 packages ok; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions
./internal/gui ok; go build ./... ok.
Broken by hand, each red: ccCopies returning nil (all four row tests),
stats counting copies (110 in / 55 out, want 30 / 15), Delete not taking
copies (a copy came back as the row), MergeExternal ignoring Copies (a
gateway row came back). Without the v4 check, five tests whose
fixtures share "uuid":"u" went red (cli, gui x2, sessions, tui).
GUI: no file reaches it; the GUI tests fake the API and the JSON a page
gets is unchanged (Copies is json:"-").
Not tried: Neo's own files, and the opened view showing only "session
start" and one line in the second screenshot; that was not reproduced.
The calls ledger (FindCall) still holds a copy's calls.
755 lines
24 KiB
Go
755 lines
24 KiB
Go
package sessions
|
|
|
|
import (
|
|
"cmp"
|
|
"maps"
|
|
"math"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// Stats is what every session spent, day by day: all of them, not only the
|
|
// latest List reads.
|
|
type Stats struct {
|
|
From string `json:"from"` // the first date, local: the range's, or for all time the first with anything
|
|
To string `json:"to"` // today
|
|
Days []Day `json:"days"` // the dates with anything, in order
|
|
// Sessions are the sessions at work in the range, each with what it
|
|
// spent in it, the most recently active first. Too many to send the
|
|
// page over a long range: Overview sums them up.
|
|
Sessions []Summary `json:"-"`
|
|
// Keys are those sessions' keys, agent:id, in the same order: which of
|
|
// the sessions the page lists were at work in the range. The list is
|
|
// every session ever, so without them it guessed from each one's last
|
|
// line — and a session whose last line is a setting or a fork's seed,
|
|
// written long after its last call, was listed but not counted.
|
|
Keys []string `json:"keys"`
|
|
}
|
|
|
|
// Summary is one session's share of a range.
|
|
type Summary struct {
|
|
Key string `json:"key"` // agent:id as its files are grouped, for Get
|
|
Agent string `json:"agent"`
|
|
ID string `json:"id"`
|
|
Cwd string `json:"cwd"`
|
|
Title string `json:"title"`
|
|
Nickname string `json:"nickname,omitempty"`
|
|
Last time.Time `json:"last"`
|
|
Role string `json:"role,omitempty"`
|
|
ParentSession string `json:"parent_session,omitempty"`
|
|
RootSession string `json:"root_session,omitempty"`
|
|
ModelEffort []ModelEffort `json:"model_effort,omitempty"`
|
|
// Gateway: magpie knows the session only from the gateway's records
|
|
// (MergeExternalStats). The agent left no file magpie reads, so it has
|
|
// no folder, and no prompt unless gateway conversations were recorded
|
|
// (#2285: a Pi subagent's DeepSeek turns read as "(no prompt)").
|
|
Gateway bool `json:"gateway,omitempty"`
|
|
Tokens
|
|
Cost float64 `json:"cost"`
|
|
Priced bool `json:"priced"` // every model it used has a price
|
|
Active int64 `json:"active"` // seconds
|
|
Models []string `json:"models"` // the models it used in the range, the most used first
|
|
Days []int `json:"days"` // the dates it was at work on, as days after From
|
|
// Prompts and Replies are the messages each way, ToolCalls the tools
|
|
// it called, in the range (Claude Code's, Codex's, Pi's and omp's sessions)
|
|
Prompts int `json:"prompts"`
|
|
Replies int `json:"replies"`
|
|
ToolCalls int `json:"tool_calls"`
|
|
|
|
// slices and not maps: each range statsFor keeps holds them for every
|
|
// session, and a map of one or two names is a few hundred bytes
|
|
tools counts // calls by tool
|
|
skills counts // calls by skill, with the last date of each
|
|
perDay []summaryDay // by day after From, in order
|
|
}
|
|
|
|
// summaryDay is a session's day, for the overview's calendar and trends.
|
|
type summaryDay struct {
|
|
day int // after From
|
|
messages, output int
|
|
tools counts // calls by tool category
|
|
}
|
|
|
|
// counts are calls by name, in the names' order.
|
|
type counts []nameCount
|
|
|
|
type nameCount struct {
|
|
name string
|
|
n int
|
|
last string // a skill's: the last date it was called
|
|
}
|
|
|
|
// of is name's calls.
|
|
func (c counts) of(name string) int {
|
|
if i, ok := slices.BinarySearchFunc(c, name, func(c nameCount, name string) int { return strings.Compare(c.name, name) }); ok {
|
|
return c[i].n
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// countsOf is m in the names' order, with last's date for each when given.
|
|
func countsOf(m map[string]int, last map[string]string) counts {
|
|
if len(m) == 0 {
|
|
return nil
|
|
}
|
|
out := make(counts, 0, len(m))
|
|
for name, n := range m {
|
|
out = append(out, nameCount{name: name, n: n, last: last[name]})
|
|
}
|
|
slices.SortFunc(out, func(a, b nameCount) int { return strings.Compare(a.name, b.name) })
|
|
return out
|
|
}
|
|
|
|
// Day is one local date's usage, cut fine enough for the page to filter
|
|
// it by agent, model and folder itself.
|
|
type Day struct {
|
|
Date string `json:"date"`
|
|
Usage []Usage `json:"usage"` // by agent, folder and model
|
|
Active []Active `json:"active"` // by agent and folder
|
|
}
|
|
|
|
// Usage is what one model spent for one agent in one folder on a day.
|
|
type Usage struct {
|
|
Agent string `json:"agent"`
|
|
Cwd string `json:"cwd"`
|
|
Model string `json:"model"`
|
|
Tokens
|
|
Cost float64 `json:"cost"` // USD at the effective price, when priced
|
|
Priced bool `json:"priced"`
|
|
}
|
|
|
|
// Active is the time an agent's sessions in one folder were at work on a
|
|
// day, in seconds (see day.Active for how it is told).
|
|
type Active struct {
|
|
Agent string `json:"agent"`
|
|
Cwd string `json:"cwd"`
|
|
Seconds int64 `json:"seconds"`
|
|
// Hours is Seconds again by the local hour of the day (24, or none)
|
|
Hours []int64 `json:"hours,omitempty"`
|
|
}
|
|
|
|
// StatsFor reads the usage of the last days days up to today, today
|
|
// included (every day when 0), from every session file there is. Only the
|
|
// files written to since the range began are looked at; what is read is
|
|
// kept, as List's is.
|
|
func StatsFor(days int) Stats {
|
|
return statsAt(days, time.Now())
|
|
}
|
|
|
|
// StatsAt is StatsFor as if it were now.
|
|
func StatsAt(days int, now time.Time) Stats { return statsAt(days, now) }
|
|
|
|
// StatsAndNative is StatsFor, and the agent|id of every session List would
|
|
// list, with no limit: what tells a gateway session the agent keeps too
|
|
// from one only magpie saw. Both come of one pass over the files, as the
|
|
// overview asks for both on every poll (#2776).
|
|
func StatsAndNative(days int) (Stats, map[string]bool) {
|
|
native := map[string]bool{}
|
|
return statsIn(days, time.Now(), native), native
|
|
}
|
|
|
|
func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) }
|
|
|
|
// statsIn is statsAt, filling native as StatsAndNative says when not nil.
|
|
func statsIn(days int, now time.Time, native map[string]bool) Stats {
|
|
// read before the locks: it reads settings.json
|
|
alias := provider.UsageAlias()
|
|
st := statsRead(days, now, native)
|
|
if alias != nil {
|
|
st = aliasStats(st, alias)
|
|
}
|
|
return st
|
|
}
|
|
|
|
func statsRead(days int, now time.Time, native map[string]bool) Stats {
|
|
now = now.In(time.Local)
|
|
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
|
|
var since time.Time
|
|
from := ""
|
|
if days > 0 {
|
|
since = today.AddDate(0, 0, 1-days)
|
|
from = since.Format(time.DateOnly)
|
|
}
|
|
out := Stats{From: from, To: today.Format(time.DateOnly), Days: []Day{}, Sessions: []Summary{}, Keys: []string{}}
|
|
|
|
storeMu.RLock()
|
|
defer storeMu.RUnlock()
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
loadCache()
|
|
defer useDBs()()
|
|
files := allFiles()
|
|
// every changed file, whatever the range, so a wider range picked later
|
|
// finds them read rather than starting another run
|
|
refresh(files, files)
|
|
identities := codexIdentitySnapshot(files)
|
|
taskTitles := codexSubagentTaskTitles(files)
|
|
if native != nil {
|
|
groups := byKey(files, nil)
|
|
price, titles := pricer(), codexTitleOf()
|
|
for _, fs := range groups {
|
|
// as List: a session nothing was said in is not listed
|
|
if s, ok := assembleListed(fs, price, titles); ok {
|
|
native[s.Agent+"|"+s.ID] = true
|
|
}
|
|
}
|
|
}
|
|
// a copy of a conversation is counted in the session it copies, which
|
|
// holds every message of it (ccCopies)
|
|
copies := ccCopies(files)
|
|
var want []file
|
|
for _, f := range files {
|
|
if !f.mod.Before(since) && copies[f.key] == "" {
|
|
want = append(want, f)
|
|
}
|
|
}
|
|
|
|
// a subagent's file counts in the folder of its session's own file
|
|
folder := map[string]string{}
|
|
for _, f := range files {
|
|
if st := cache[f.path]; f.main && st != nil && st.Cwd != "" && folder[f.key] == "" {
|
|
folder[f.key] = st.Cwd
|
|
}
|
|
}
|
|
type uk struct{ date, agent, cwd, model string }
|
|
type ak struct{ date, agent, cwd string }
|
|
type act0 struct {
|
|
ms int64
|
|
hours []int64
|
|
}
|
|
use := map[uk]Tokens{}
|
|
act := map[ak]*act0{}
|
|
dates := map[string]bool{}
|
|
// each session's share: its files' models and dates in range
|
|
type dayShare struct {
|
|
messages, output int
|
|
tools map[string]int
|
|
}
|
|
type share struct {
|
|
models map[string]Tokens
|
|
active int64
|
|
dates map[string]bool
|
|
prompts, replies int
|
|
tools, skills map[string]int
|
|
skillLast map[string]string
|
|
perDate map[string]*dayShare
|
|
}
|
|
shares := map[string]*share{}
|
|
for _, f := range want {
|
|
st := cache[f.path]
|
|
if st == nil {
|
|
continue
|
|
}
|
|
cwd := folder[f.key]
|
|
if cwd == "" {
|
|
cwd = st.Cwd
|
|
}
|
|
for date, d := range st.Days.all() {
|
|
if date == "" || date < from || date > out.To {
|
|
continue
|
|
}
|
|
for model, t := range d.Models.all() {
|
|
if t.zero() {
|
|
continue
|
|
}
|
|
k := uk{date, f.agent, cwd, model}
|
|
u := use[k]
|
|
u.add(t)
|
|
use[k] = u
|
|
dates[date] = true
|
|
}
|
|
if d.Active > 0 {
|
|
k := ak{date, f.agent, cwd}
|
|
a := act[k]
|
|
if a == nil {
|
|
a = &act0{}
|
|
act[k] = a
|
|
}
|
|
a.ms += d.Active
|
|
if len(d.Hours) == 24 {
|
|
if a.hours == nil {
|
|
a.hours = make([]int64, 24)
|
|
}
|
|
for h, ms := range d.Hours {
|
|
a.hours[h] += ms
|
|
}
|
|
}
|
|
dates[date] = true
|
|
}
|
|
sh := shares[f.key]
|
|
if sh == nil {
|
|
sh = &share{models: map[string]Tokens{}, dates: map[string]bool{}, tools: map[string]int{},
|
|
skills: map[string]int{}, skillLast: map[string]string{}, perDate: map[string]*dayShare{}}
|
|
shares[f.key] = sh
|
|
}
|
|
pd := sh.perDate[date]
|
|
if pd == nil {
|
|
pd = &dayShare{tools: map[string]int{}}
|
|
sh.perDate[date] = pd
|
|
}
|
|
for model, t := range d.Models.all() {
|
|
if !t.zero() {
|
|
u := sh.models[model]
|
|
u.add(t)
|
|
sh.models[model] = u
|
|
sh.dates[date] = true
|
|
pd.output += t.Output
|
|
}
|
|
}
|
|
sh.prompts += d.Prompts
|
|
sh.replies += d.Replies
|
|
if d.Prompts+d.Replies > 0 {
|
|
sh.dates[date] = true
|
|
dates[date] = true
|
|
}
|
|
pd.messages += d.Prompts + d.Replies
|
|
for name, n := range d.Tools.all() {
|
|
sh.tools[name] += n
|
|
pd.tools[ToolCategory(name)] += n
|
|
}
|
|
for name, n := range d.Skills.all() {
|
|
sh.skills[name] += n
|
|
if date > sh.skillLast[name] {
|
|
sh.skillLast[name] = date
|
|
}
|
|
}
|
|
if d.Active > 0 {
|
|
sh.active += d.Active
|
|
sh.dates[date] = true
|
|
}
|
|
}
|
|
}
|
|
|
|
byDate := map[string]*Day{}
|
|
for date := range dates {
|
|
byDate[date] = &Day{Date: date, Usage: []Usage{}, Active: []Active{}}
|
|
}
|
|
price, titles := pricer(), codexTitleOf()
|
|
for k, t := range use {
|
|
u := Usage{Agent: k.agent, Cwd: k.cwd, Model: k.model, Tokens: t}
|
|
if p := price(k.model); p != nil {
|
|
u.Cost, u.Priced = p.At(0).CostSplit(t.Input, t.Output, t.CacheRead, t.CacheWrite, t.CacheWrite1h), true
|
|
}
|
|
byDate[k.date].Usage = append(byDate[k.date].Usage, u)
|
|
}
|
|
for k, a := range act {
|
|
v := Active{Agent: k.agent, Cwd: k.cwd, Seconds: a.ms / 1000}
|
|
if a.hours != nil {
|
|
v.Hours = make([]int64, 24)
|
|
for h, ms := range a.hours {
|
|
v.Hours[h] = ms / 1000
|
|
}
|
|
}
|
|
byDate[k.date].Active = append(byDate[k.date].Active, v)
|
|
}
|
|
for _, d := range byDate {
|
|
sort.Slice(d.Usage, func(i, j int) bool {
|
|
a, b := d.Usage[i], d.Usage[j]
|
|
if a.Agent != b.Agent {
|
|
return a.Agent < b.Agent
|
|
}
|
|
if a.Cwd != b.Cwd {
|
|
return a.Cwd < b.Cwd
|
|
}
|
|
return a.Model < b.Model
|
|
})
|
|
sort.Slice(d.Active, func(i, j int) bool {
|
|
a, b := d.Active[i], d.Active[j]
|
|
if a.Agent != b.Agent {
|
|
return a.Agent < b.Agent
|
|
}
|
|
return a.Cwd < b.Cwd
|
|
})
|
|
out.Days = append(out.Days, *d)
|
|
}
|
|
sort.Slice(out.Days, func(i, j int) bool { return out.Days[i].Date < out.Days[j].Date })
|
|
if out.From == "" {
|
|
out.From = out.To
|
|
if len(out.Days) > 0 && out.Days[0].Date < out.To {
|
|
out.From = out.Days[0].Date
|
|
}
|
|
}
|
|
|
|
groups := byKey(files, func(f *file) bool { return shares[f.key] != nil })
|
|
first, _ := time.ParseInLocation(time.DateOnly, out.From, time.Local)
|
|
for key, sh := range shares {
|
|
if len(sh.dates) == 0 {
|
|
continue
|
|
}
|
|
s, ok := assembleListed(groups[key], price, titles)
|
|
if !ok {
|
|
continue
|
|
}
|
|
setSessionCodexIdentity(&s, identities)
|
|
setSessionCodexTaskTitle(&s, taskTitles)
|
|
sum := Summary{Key: key, Agent: s.Agent, ID: s.ID, Cwd: cmp.Or(folder[key], s.Cwd), Title: clip(s.Title, titleKept),
|
|
Nickname: s.Nickname,
|
|
Last: s.Last, Role: s.Role, ParentSession: s.ParentSession, RootSession: s.RootSession, Priced: true, Active: sh.active / 1000, Models: []string{}, Days: []int{},
|
|
Prompts: sh.prompts, Replies: sh.replies, tools: countsOf(sh.tools, nil), skills: countsOf(sh.skills, sh.skillLast)}
|
|
for _, n := range sh.tools {
|
|
sum.ToolCalls += n
|
|
}
|
|
sum.perDay = make([]summaryDay, 0, len(sh.perDate))
|
|
for date, pd := range sh.perDate {
|
|
if t, err := time.ParseInLocation(time.DateOnly, date, time.Local); err == nil {
|
|
sum.perDay = append(sum.perDay, summaryDay{day: int(math.Round(t.Sub(first).Hours() / 24)), messages: pd.messages, output: pd.output, tools: countsOf(pd.tools, nil)})
|
|
}
|
|
}
|
|
slices.SortFunc(sum.perDay, func(a, b summaryDay) int { return cmp.Compare(a.day, b.day) })
|
|
// in the models' order, as assembleListed sums a session's cost
|
|
for _, model := range slices.Sorted(maps.Keys(sh.models)) {
|
|
t := sh.models[model]
|
|
sum.Tokens.add(t)
|
|
sum.Models = append(sum.Models, model)
|
|
if p := price(model); p != nil {
|
|
sum.Cost += p.At(0).CostSplit(t.Input, t.Output, t.CacheRead, t.CacheWrite, t.CacheWrite1h)
|
|
} else {
|
|
sum.Priced = false
|
|
}
|
|
}
|
|
sort.Slice(sum.Models, func(i, j int) bool {
|
|
a, b := sh.models[sum.Models[i]], sh.models[sum.Models[j]]
|
|
if a.Input+a.Output != b.Input+b.Output {
|
|
return a.Input+a.Output > b.Input+b.Output
|
|
}
|
|
return sum.Models[i] < sum.Models[j]
|
|
})
|
|
for date := range sh.dates {
|
|
if t, err := time.ParseInLocation(time.DateOnly, date, time.Local); err == nil {
|
|
// whole days, across a change of the clocks too
|
|
sum.Days = append(sum.Days, int(math.Round(t.Sub(first).Hours()/24)))
|
|
}
|
|
}
|
|
sort.Ints(sum.Days)
|
|
out.Sessions = append(out.Sessions, sum)
|
|
}
|
|
sort.Slice(out.Sessions, func(i, j int) bool {
|
|
a, b := out.Sessions[i], out.Sessions[j]
|
|
if !a.Last.Equal(b.Last) {
|
|
return a.Last.After(b.Last)
|
|
}
|
|
return a.Key < b.Key
|
|
})
|
|
// keys after the sort, so they name the sessions in the order they are in
|
|
for _, s := range out.Sessions {
|
|
out.Keys = append(out.Keys, s.Key)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// titleKept is as long as a title gets from title(): 160 characters and
|
|
// the ellipsis.
|
|
const titleKept = 161
|
|
|
|
// clip cuts s to at most n characters, with an ellipsis. One that fits is
|
|
// s itself: the overview's titles are the cached sessions' own strings, not
|
|
// a copy of each in every range kept (statsFor).
|
|
func clip(s string, n int) string {
|
|
if utf8.RuneCountInString(s) <= n {
|
|
return s
|
|
}
|
|
r := []rune(s)
|
|
return strings.TrimSpace(string(r[:n-1])) + "…"
|
|
}
|
|
|
|
// Overview is what the sessions of a range come to under the page's
|
|
// filters.
|
|
type Overview struct {
|
|
Count int `json:"count"`
|
|
Median int `json:"median"` // tokens (in and out) of the middle session
|
|
P90 int `json:"p90"` // … of the one nine in ten spent no more than
|
|
Days []int `json:"days"` // sessions at work each day, from Stats.From to To
|
|
// Top are the sessions that spent the most, by tokens, cost and
|
|
// active time, n of each
|
|
Top map[string][]Summary `json:"top"`
|
|
// Messages and Output are the messages and output tokens each day,
|
|
// as Days
|
|
Messages []int `json:"messages"`
|
|
Output []int `json:"output"`
|
|
// Shape is how many sessions came to how much: by messages, by
|
|
// minutes at work and by tool calls a prompt (autonomy)
|
|
Shape map[string]Shape `json:"shape"`
|
|
Tools ToolUse `json:"tools"`
|
|
Skills SkillUse `json:"skills"`
|
|
}
|
|
|
|
// Shape counts sessions into buckets: Counts[i] those from Edges[i] up to
|
|
// the next edge, the last one open.
|
|
type Shape struct {
|
|
Edges []int `json:"edges"`
|
|
Counts []int `json:"counts"`
|
|
Total int `json:"total"`
|
|
}
|
|
|
|
// shapeEdges are the buckets' lower edges for each way of telling.
|
|
var shapeEdges = map[string][]int{
|
|
"messages": {1, 6, 16, 31, 61, 121},
|
|
"minutes": {1, 6, 16, 31, 61, 121},
|
|
"autonomy": {0, 1, 3, 6, 11, 21},
|
|
}
|
|
|
|
// ToolUse is what the sessions called their tools for.
|
|
type ToolUse struct {
|
|
Calls int `json:"calls"`
|
|
Sessions int `json:"sessions"`
|
|
Top []ToolStat `json:"top"` // the most called
|
|
Categories []ToolStat `json:"categories"` // by category, the most called first
|
|
// Weeks are the calls week by week, from Monday, by category
|
|
Weeks []ToolWeek `json:"weeks"`
|
|
}
|
|
|
|
// ToolStat is one tool's (or category's) calls.
|
|
type ToolStat struct {
|
|
Name string `json:"name"`
|
|
Category string `json:"category,omitempty"`
|
|
Calls int `json:"calls"`
|
|
Sessions int `json:"sessions"`
|
|
}
|
|
|
|
// ToolWeek is one week's calls by category.
|
|
type ToolWeek struct {
|
|
Start string `json:"start"` // its Monday
|
|
Calls map[string]int `json:"calls"`
|
|
}
|
|
|
|
// SkillUse is the skills the sessions called up.
|
|
type SkillUse struct {
|
|
Calls int `json:"calls"`
|
|
Top []Skill `json:"top"`
|
|
Count int `json:"count"` // skills called at all
|
|
}
|
|
|
|
// Skill is one skill's calls.
|
|
type Skill struct {
|
|
Name string `json:"name"`
|
|
Calls int `json:"calls"`
|
|
Sessions int `json:"sessions"`
|
|
Last string `json:"last"` // the date it was last called
|
|
Agents map[string]int `json:"agents"` // calls by agent
|
|
Projects []ToolStat `json:"projects"` // the folders that called it most, by name
|
|
}
|
|
|
|
// Overview sums up st's sessions of agent, with model and in folder cwd
|
|
// ("" for any), with the n that spent the most each way.
|
|
func (st Stats) Overview(agent, model, cwd string, n int) Overview {
|
|
out := Overview{Days: []int{}, Top: map[string][]Summary{}}
|
|
first, err1 := time.ParseInLocation(time.DateOnly, st.From, time.Local)
|
|
last, err2 := time.ParseInLocation(time.DateOnly, st.To, time.Local)
|
|
if err1 == nil && err2 == nil && !last.Before(first) {
|
|
out.Days = make([]int, int(math.Round(last.Sub(first).Hours()/24))+1)
|
|
}
|
|
out.Messages, out.Output = make([]int, len(out.Days)), make([]int, len(out.Days))
|
|
var in []Summary
|
|
var spent []int
|
|
for _, s := range st.Sessions {
|
|
if agent != "" && s.Agent != agent || cwd != "" && s.Cwd != cwd || model != "" && !slices.Contains(s.Models, model) {
|
|
continue
|
|
}
|
|
in = append(in, s)
|
|
spent = append(spent, s.Input+s.Output)
|
|
for _, d := range s.Days {
|
|
if d >= 0 && d < len(out.Days) {
|
|
out.Days[d]++
|
|
}
|
|
}
|
|
for _, pd := range s.perDay {
|
|
if d := pd.day; d >= 0 && d < len(out.Days) {
|
|
out.Messages[d] += pd.messages
|
|
out.Output[d] += pd.output
|
|
}
|
|
}
|
|
}
|
|
out.Shape = shapes(in)
|
|
out.Tools = toolUse(in, first, n)
|
|
out.Skills = skillUse(in, n)
|
|
out.Count = len(in)
|
|
if len(spent) > 0 {
|
|
sort.Ints(spent)
|
|
// the nearest rank
|
|
rank := func(p float64) int { return spent[max(0, int(math.Ceil(p*float64(len(spent))))-1)] }
|
|
out.Median, out.P90 = rank(0.5), rank(0.9)
|
|
}
|
|
for by, v := range map[string]func(Summary) float64{
|
|
"tokens": func(s Summary) float64 { return float64(s.Input + s.Output) },
|
|
"cost": func(s Summary) float64 { return s.Cost },
|
|
"active": func(s Summary) float64 { return float64(s.Active) },
|
|
} {
|
|
top := slices.Clone(in)
|
|
sort.SliceStable(top, func(i, j int) bool { return v(top[i]) > v(top[j]) })
|
|
k := 0
|
|
for k < len(top) && k < n && v(top[k]) > 0 {
|
|
k++
|
|
}
|
|
out.Top[by] = top[:k]
|
|
}
|
|
return out
|
|
}
|
|
|
|
// shapes buckets the sessions that told their messages, or for minutes
|
|
// those that were at work.
|
|
func shapes(in []Summary) map[string]Shape {
|
|
out := map[string]Shape{}
|
|
for by, edges := range shapeEdges {
|
|
sh := Shape{Edges: edges, Counts: make([]int, len(edges))}
|
|
for _, s := range in {
|
|
v := s.Prompts + s.Replies
|
|
switch by {
|
|
case "minutes":
|
|
// every agent's sessions tell their time, not all their
|
|
// messages
|
|
if s.Active <= 0 {
|
|
continue
|
|
}
|
|
v = int(max(1, (s.Active+30)/60))
|
|
case "messages", "autonomy":
|
|
if v == 0 {
|
|
continue
|
|
}
|
|
}
|
|
if by == "autonomy" {
|
|
v = s.ToolCalls / max(1, s.Prompts)
|
|
}
|
|
i := len(edges) - 1
|
|
for i > 0 && v < edges[i] {
|
|
i--
|
|
}
|
|
sh.Counts[i]++
|
|
sh.Total++
|
|
}
|
|
out[by] = sh
|
|
}
|
|
return out
|
|
}
|
|
|
|
// toolUse sums up the sessions' tool calls, the n most called.
|
|
func toolUse(in []Summary, first time.Time, n int) ToolUse {
|
|
out := ToolUse{Top: []ToolStat{}, Categories: []ToolStat{}, Weeks: []ToolWeek{}}
|
|
tools, cats := map[string]*ToolStat{}, map[string]*ToolStat{}
|
|
weeks := map[string]map[string]int{}
|
|
for _, s := range in {
|
|
if s.ToolCalls == 0 {
|
|
continue
|
|
}
|
|
out.Sessions++
|
|
out.Calls += s.ToolCalls
|
|
seen := map[string]bool{}
|
|
for _, tc := range s.tools {
|
|
name, c := tc.name, tc.n
|
|
t := tools[name]
|
|
if t == nil {
|
|
t = &ToolStat{Name: name, Category: ToolCategory(name)}
|
|
tools[name] = t
|
|
}
|
|
t.Calls += c
|
|
t.Sessions++
|
|
cat := cats[t.Category]
|
|
if cat == nil {
|
|
cat = &ToolStat{Name: t.Category}
|
|
cats[t.Category] = cat
|
|
}
|
|
cat.Calls += c
|
|
if !seen[t.Category] {
|
|
seen[t.Category] = true
|
|
cat.Sessions++
|
|
}
|
|
}
|
|
if first.IsZero() {
|
|
continue
|
|
}
|
|
for _, pd := range s.perDay {
|
|
day := first.AddDate(0, 0, pd.day)
|
|
mon := day.AddDate(0, 0, -(int(day.Weekday())+6)%7).Format(time.DateOnly)
|
|
w := weeks[mon]
|
|
if w == nil {
|
|
w = map[string]int{}
|
|
weeks[mon] = w
|
|
}
|
|
for _, c := range pd.tools {
|
|
w[c.name] += c.n
|
|
}
|
|
}
|
|
}
|
|
for _, t := range tools {
|
|
out.Top = append(out.Top, *t)
|
|
}
|
|
for _, c := range cats {
|
|
out.Categories = append(out.Categories, *c)
|
|
}
|
|
byCalls := func(a, b ToolStat) int { return cmp.Or(cmp.Compare(b.Calls, a.Calls), cmp.Compare(a.Name, b.Name)) }
|
|
slices.SortFunc(out.Top, byCalls)
|
|
slices.SortFunc(out.Categories, byCalls)
|
|
out.Top = out.Top[:min(len(out.Top), n)]
|
|
for mon, calls := range weeks {
|
|
out.Weeks = append(out.Weeks, ToolWeek{Start: mon, Calls: calls})
|
|
}
|
|
slices.SortFunc(out.Weeks, func(a, b ToolWeek) int { return cmp.Compare(a.Start, b.Start) })
|
|
return out
|
|
}
|
|
|
|
// skillUse sums up the skills the sessions called up, the n most called.
|
|
func skillUse(in []Summary, n int) SkillUse {
|
|
out := SkillUse{Top: []Skill{}}
|
|
skills := map[string]*Skill{}
|
|
projects := map[string]map[string]int{}
|
|
for _, s := range in {
|
|
for _, sc := range s.skills {
|
|
name, c := sc.name, sc.n
|
|
k := skills[name]
|
|
if k == nil {
|
|
k = &Skill{Name: name, Agents: map[string]int{}, Projects: []ToolStat{}}
|
|
skills[name] = k
|
|
projects[name] = map[string]int{}
|
|
}
|
|
k.Calls += c
|
|
k.Sessions++
|
|
k.Agents[s.Agent] += c
|
|
k.Last = max(k.Last, sc.last)
|
|
projects[name][s.Cwd] += c
|
|
out.Calls += c
|
|
}
|
|
}
|
|
out.Count = len(skills)
|
|
for name, k := range skills {
|
|
for cwd, c := range projects[name] {
|
|
k.Projects = append(k.Projects, ToolStat{Name: cwd, Calls: c})
|
|
}
|
|
slices.SortFunc(k.Projects, func(a, b ToolStat) int { return cmp.Or(cmp.Compare(b.Calls, a.Calls), cmp.Compare(a.Name, b.Name)) })
|
|
k.Projects = k.Projects[:min(len(k.Projects), 3)]
|
|
out.Top = append(out.Top, *k)
|
|
}
|
|
slices.SortFunc(out.Top, func(a, b Skill) int { return cmp.Or(cmp.Compare(b.Calls, a.Calls), cmp.Compare(a.Name, b.Name)) })
|
|
out.Top = out.Top[:min(len(out.Top), n)]
|
|
return out
|
|
}
|
|
|
|
// ToolCategory is the kind of tool a name is, Claude Code's and Codex's
|
|
// alike: Bash, Edit, Read, Write, Glob, Grep, Task (subagents and plans),
|
|
// Tool (an MCP server's) or Other.
|
|
func ToolCategory(name string) string {
|
|
switch name {
|
|
case "Bash", "BashOutput", "KillShell", "KillBash", "exec_command", "shell", "shell_command", "local_shell_call", "write_stdin", "unified_exec", "bash", "powershell":
|
|
return "Bash"
|
|
case "Edit", "MultiEdit", "NotebookEdit", "apply_patch", "edit", "str_replace":
|
|
return "Edit"
|
|
case "Read", "NotebookRead", "view_image", "read_file", "view", "read":
|
|
return "Read"
|
|
case "Write", "write_file", "create", "write":
|
|
return "Write"
|
|
case "Glob", "LS", "list_dir", "glob", "find", "ls", "fffind":
|
|
return "Glob"
|
|
case "Grep", "grep", "grep_files", "search", "ffgrep":
|
|
return "Grep"
|
|
case "Task", "Agent", "TodoWrite", "update_plan", "spawn_agent", "send_input", "wait", "close_agent", "Workflow":
|
|
return "Task"
|
|
}
|
|
if strings.HasPrefix(name, "mcp__") || strings.HasPrefix(name, "mcp_") {
|
|
return "Tool"
|
|
}
|
|
return "Other"
|
|
}
|