Droid's listing opened every transcript to read its first line, for
whether it is a subagent's (callingSessionId), and Grok Build's read and
decoded every session's summary.json for its session_kind and parent.
The listing runs on every 15s poll of Sessions and Usage, so with
thousands of sessions each poll opened thousands of files that had not
changed.
listMemo (listmemo.go) keeps what a listing read from each file by that
file's own size and mtime, not the folded size the listing gives the
session. A listing is a round: a file not seen in it (a session deleted)
is dropped when it ends, so the memo never outgrows the sessions there
are. A read that failed, such as a transcript whose first line is still
being written, is not kept, and the next listing reads it again: a
failed read means unknown, not "nobody's". Reset clears both memos.
Measured (3000 sessions each, one listing after another, CPU by
getrusage, the machine at load ~500):
Droid before: 1103 ms CPU / 8.3 s wall per listing
Droid after: 27-47 ms CPU / 0.05-1.0 s wall (first listing 1166 ms)
Grok before: 649 ms CPU / 4.2 s wall per listing
Grok after: 252-295 ms CPU / 1.8-2.2 s wall (first listing 707 ms)
What Grok's listing still spends is its globs and two stats a session
(updates.jsonl, summary.json), not reads.
Tests: TestDroidListingReadsOnlyChangedTranscripts counts transcript
opens (scanHook): a second listing opens only the half-written one,
appending reopens only that file, a finished first line is then kept,
and a transcript written over without a caller is its own session.
TestGrokListingReadsOnlyChangedSummaries counts summary reads
(grokSummaryHook): none when nothing changed or only the updates grew,
one when the summary is written over, and the key follows it.
Broken by hand: the memo never hit -> both red ("nothing changed: read
map[...all...]"); failed reads kept -> Droid red ("nothing changed: read
map[], want only the half-written one again").
Run: go test ./internal/sessions -run 'Listing|Droid|Grok' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
314 lines
8.9 KiB
Go
314 lines
8.9 KiB
Go
package sessions
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/tidwall/gjson"
|
|
"github.com/tidwall/jsonc"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
)
|
|
|
|
// Factory's Droid keeps a session under its sessions folder
|
|
// (~/.factory/sessions, or $FACTORY_HOME_OVERRIDE/.factory/sessions), in a
|
|
// folder per working directory (older ones right in it): <id>.jsonl, the
|
|
// transcript, and <id>.settings.json beside it. The transcript's first line
|
|
// is a session_start event — the id, droid's title for it, the cwd, the
|
|
// session it was forked from (parent, with forkedAtMessageId the last
|
|
// message it copied) and, for a subagent's or a /btw side question's, the
|
|
// session that called it (callingSessionId). Each line after is an event,
|
|
// a "message" one carrying its time (ISO) and the message, role and content
|
|
// blocks as Anthropic's. What the session spent is in its settings, one
|
|
// running total of its own (tokenUsage: input without the cache, output
|
|
// with the thinking in it) for the model it is on (model); a fork starts at
|
|
// none, and a subagent's counts in the session that called it. The total
|
|
// isn't split by turn, so it counts on the day of the last message.
|
|
// `droid --resume <id>` picks one up again.
|
|
|
|
// FactoryDir is Droid's folder: $FACTORY_HOME_OVERRIDE/.factory, else
|
|
// ~/.factory.
|
|
func FactoryDir() string {
|
|
home := strings.TrimSpace(appdir.Getenv("FACTORY_HOME_OVERRIDE"))
|
|
if home == "" {
|
|
home, _ = os.UserHomeDir()
|
|
} else {
|
|
home = expandHome(home)
|
|
}
|
|
return filepath.Join(home, ".factory")
|
|
}
|
|
|
|
type droidStart struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
Cwd string `json:"cwd"`
|
|
LastCwd string `json:"lastCwd"`
|
|
Parent string `json:"parent"`
|
|
Calling string `json:"callingSessionId"`
|
|
Forked string `json:"forkedAtMessageId"`
|
|
}
|
|
|
|
// readDroidStart is a transcript's session_start line.
|
|
func readDroidStart(path string) (droidStart, bool) {
|
|
var s droidStart
|
|
ok := false
|
|
scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
|
|
ok = json.Unmarshal(b, &s) == nil && s.Type == "session_start"
|
|
return false
|
|
})
|
|
return s, ok
|
|
}
|
|
|
|
// droidCallers is whose subagent each transcript is, as its session_start
|
|
// line said when the listing last read it: a listing runs on every poll, and
|
|
// opening every session's transcript for its first line each time cost more
|
|
// than the rest of the listing together.
|
|
var droidCallers listMemo[string]
|
|
|
|
func droidFiles() []file {
|
|
root := filepath.Join(FactoryDir(), "sessions")
|
|
a, _ := filepath.Glob(filepath.Join(root, "*.jsonl"))
|
|
b, _ := filepath.Glob(filepath.Join(root, "*", "*.jsonl"))
|
|
callers := droidCallers.round()
|
|
defer callers.done()
|
|
var out []file
|
|
for _, p := range append(a, b...) {
|
|
id := strings.TrimSuffix(filepath.Base(p), ".jsonl")
|
|
if !safeID.MatchString(id) {
|
|
continue
|
|
}
|
|
f := file{agent: "droid", key: "droid:" + id, path: p, main: true}
|
|
if !stat(&f) {
|
|
continue
|
|
}
|
|
calling, _ := callers.get(p, f.size, f.mod, func() (string, bool) {
|
|
s, ok := readDroidStart(p)
|
|
return s.Calling, ok
|
|
})
|
|
// what it spent and on which model are in its settings
|
|
m := file{path: strings.TrimSuffix(p, ".jsonl") + ".settings.json"}
|
|
if stat(&m) {
|
|
f.manifest = m.path
|
|
f.size += m.size
|
|
if m.mod.After(f.mod) {
|
|
f.mod = m.mod
|
|
}
|
|
}
|
|
if calling != "" && calling != id && safeID.MatchString(calling) {
|
|
f.key, f.main = "droid:"+calling, false
|
|
}
|
|
out = append(out, f)
|
|
}
|
|
return out
|
|
}
|
|
|
|
type droidUsage struct {
|
|
Input int `json:"inputTokens"`
|
|
Output int `json:"outputTokens"`
|
|
CacheWrite int `json:"cacheCreationTokens"`
|
|
CacheRead int `json:"cacheReadTokens"`
|
|
}
|
|
|
|
type droidSettings struct {
|
|
Model string `json:"model"`
|
|
Usage *droidUsage `json:"tokenUsage"`
|
|
}
|
|
|
|
type droidLine struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
Message struct {
|
|
Role string `json:"role"`
|
|
Content json.RawMessage `json:"content"`
|
|
} `json:"message"`
|
|
}
|
|
|
|
// droidText is a message's text: its content as a string, or its text
|
|
// blocks.
|
|
func droidText(raw json.RawMessage) string {
|
|
var s string
|
|
if json.Unmarshal(raw, &s) == nil {
|
|
return s
|
|
}
|
|
var blocks []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
}
|
|
json.Unmarshal(raw, &blocks)
|
|
var parts []string
|
|
for _, b := range blocks {
|
|
if b.Type == "text" && strings.TrimSpace(b.Text) != "" {
|
|
parts = append(parts, b.Text)
|
|
}
|
|
}
|
|
return strings.Join(parts, "\n")
|
|
}
|
|
|
|
// droidTools are a message's tool calls, by name.
|
|
func droidTools(raw json.RawMessage) []string {
|
|
var blocks []struct {
|
|
Type string `json:"type"`
|
|
Name string `json:"name"`
|
|
}
|
|
json.Unmarshal(raw, &blocks)
|
|
var out []string
|
|
for _, b := range blocks {
|
|
if b.Type == "tool_use" && b.Name != "" {
|
|
out = append(out, b.Name)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// droidCarry is what a read of a Droid transcript carries on with: where
|
|
// it read to, whether it has passed the session_start line and a fork's
|
|
// copied lines, and what its settings' total was counted as, to be taken
|
|
// back when the total moves on.
|
|
type droidCarry struct {
|
|
Tail *tail `json:"tail,omitempty"`
|
|
Started bool `json:"started,omitempty"`
|
|
Upto string `json:"upto,omitempty"`
|
|
Copied bool `json:"copied,omitempty"`
|
|
// the settings' total, as counted
|
|
Date string `json:"date,omitempty"`
|
|
Model string `json:"model,omitempty"`
|
|
Tokens Tokens `json:"tokens,omitzero"`
|
|
}
|
|
|
|
// parseDroid reads a session's transcript, with its settings. Droid only
|
|
// appends to a transcript, so one read before is read on from where that
|
|
// read left off, and its settings' running total, counted on the day of
|
|
// the last message, is taken back and counted again as it is now. A
|
|
// transcript cut short or replaced is read whole again.
|
|
func parseDroid(f file, old *state) *state {
|
|
var s *state
|
|
var c droidCarry
|
|
var off int64
|
|
if old != nil && old.Droid != nil && old.Droid.Tail.holds(f.path) {
|
|
s, c, off = old.clone(), *old.Droid, old.Droid.Tail.Off
|
|
s.dropUse(c.Date, c.Model, c.Tokens)
|
|
} else {
|
|
s = &state{}
|
|
}
|
|
s.Size, s.Mod = f.size, f.mod.UnixNano()
|
|
end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool {
|
|
droidLineOf(s, &c, b, f.main)
|
|
return true
|
|
})
|
|
c.Tail = nil
|
|
if err == nil {
|
|
c.Tail = markTail(f.path, end, 0, end)
|
|
}
|
|
c.Date, c.Model, c.Tokens = "", "", Tokens{}
|
|
if f.manifest != "" {
|
|
var st droidSettings
|
|
if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &st) == nil && st.Usage != nil {
|
|
when := s.Last
|
|
if when.IsZero() {
|
|
when = time.Unix(0, s.Mod)
|
|
}
|
|
u := st.Usage
|
|
c.Date, c.Model = dateOf(when), droidModelName(st.Model)
|
|
c.Tokens = Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}
|
|
s.use(c.Date, c.Model, c.Tokens)
|
|
}
|
|
}
|
|
s.Droid = &c
|
|
return s
|
|
}
|
|
|
|
// droidLineOf counts one line of a transcript.
|
|
func droidLineOf(s *state, c *droidCarry, b []byte, main bool) {
|
|
var l droidLine
|
|
if json.Unmarshal(b, &l) != nil {
|
|
return
|
|
}
|
|
if !c.Started {
|
|
c.Started = true
|
|
var st droidStart
|
|
if l.Type == "session_start" && json.Unmarshal(b, &st) == nil {
|
|
s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title)
|
|
if s.Named == "New Session" {
|
|
s.Named = "" // Droid's until it names one
|
|
}
|
|
if st.LastCwd != "" {
|
|
s.Cwd = st.LastCwd
|
|
}
|
|
// a fork's lines up to Upto are copies of its source's
|
|
c.Upto, c.Copied = st.Forked, st.Forked != ""
|
|
}
|
|
return
|
|
}
|
|
if l.Type != "message" {
|
|
return
|
|
}
|
|
if c.Copied {
|
|
if l.ID == c.Upto {
|
|
c.Copied = false
|
|
}
|
|
return
|
|
}
|
|
at := tsAt(b, false)
|
|
s.saw(at, main)
|
|
switch l.Message.Role {
|
|
case "user":
|
|
text := droidText(l.Message.Content)
|
|
if strings.TrimSpace(text) == "" || !main {
|
|
return
|
|
}
|
|
if strings.HasPrefix(strings.TrimSpace(text), "<") {
|
|
if s.First == "" {
|
|
s.First = untagged(text)
|
|
}
|
|
return
|
|
}
|
|
s.day(dateOf(at)).Prompts++
|
|
if s.Title == "" {
|
|
s.Title = title(text)
|
|
}
|
|
case "assistant":
|
|
if main {
|
|
s.day(dateOf(at)).Replies++
|
|
}
|
|
for _, name := range droidTools(l.Message.Content) {
|
|
s.tool(at, name, "")
|
|
}
|
|
}
|
|
}
|
|
|
|
// droidSlot is the tail droid gives a custom model's id made of its name
|
|
// ("custom:Kimi-K2-[Groq]-0").
|
|
var droidSlot = regexp.MustCompile(`(-\[[^\]]*\])?-\d+$`)
|
|
|
|
// droidModelName is a session's model as it is priced: a custom one
|
|
// ("custom:<id>") is the model its entry in droid's settings asks for —
|
|
// magpie's own are "<provider>/<model>" — else its id without droid's
|
|
// additions; Factory's own are as they are.
|
|
func droidModelName(m string) string {
|
|
if m == "" {
|
|
return "droid"
|
|
}
|
|
if !strings.HasPrefix(m, "custom:") {
|
|
return m
|
|
}
|
|
if raw, err := os.ReadFile(filepath.Join(FactoryDir(), "settings.json")); err == nil {
|
|
of := ""
|
|
gjson.GetBytes(jsonc.ToJSONInPlace(raw), "customModels").ForEach(func(_, v gjson.Result) bool {
|
|
if v.Get("id").String() == m {
|
|
of = v.Get("model").String()
|
|
return false
|
|
}
|
|
return true
|
|
})
|
|
if of != "" {
|
|
return of
|
|
}
|
|
}
|
|
return droidSlot.ReplaceAllString(strings.TrimPrefix(m, "custom:"), "")
|
|
}
|