diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 55e6d87c6..329b9aa14 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -406,6 +406,30 @@ reporter's real wire files), `TestCodeBuddyCalls`, `TestWorkBuddyCalls*`, `TestPiCalls*` (Pi 1.1.0's and omp 18.9.1's own files) and `TestWSLSessionsListed`. +Antigravity CLI's (agy's) conversations are sessions too (RickyWei on +Discord): one per `brain//` of `~/.gemini/antigravity-cli`, +read from the same `transcript_full.jsonl` its calls are (`agyFiles`, +[`agy.go`](../../internal/sessions/agy.go)). The steps give the times, the +first prompt (out of agy's `` wrapper), the tool calls and the +tokens, counted under the model `agy` since no step names one; a step agy +writes again replaces its tokens, read on or read whole. Its title and +folder are its row of `conversation_summaries.db` (`title`, and the first +local `workspace_uris` entry, `agyFolder` turning `file:///C:/…` into +`C:\…` on Windows). agy writes the title after the transcript, so the row +is the file's `rev` and a new title reads the conversation again; the +database is read again only when it or its `-wal` changed, and a failed +read keeps the rows read before. A row whose conversation has its +`conversations/.db` and no transcript (#1718; that database is protobuf, +not read) is listed from the row alone: title, folder, `last_modified_time`, +no tokens and no conversation to open (`readable`). Resume is `agy --conversation `, which +picks it up from any folder; when agy is set to use magpie it is the +agent's launch command (the gateway's variables and `--model`) with +`--conversation` after it (`sessions.AgyStart`, set by package agent). +Subagents (`parent_conversation_id`) and agy in WSL are not read. +Verification: `TestAgySessions`, `TestAgyTitleLater`, `TestAgyGrows`, +`TestAgyTranscript`, `TestAgyFolder`, `TestAgyRowOnly`, on conversations agy 1.3.5 and 1.4.7 +wrote in a sandbox. + A read of every call decodes each file's cached shard, and over a long history that is tens of thousands of files (#2278: 68k shards, 415 MB). Asks for the same calls while one read is under way wait for it and get diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 95aa398fe..c16febfde 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -38,6 +38,12 @@ func init() { sessions.WSLHomes = wslHomes sessions.WSLRunning = WSLRunning sessions.WSLOff = func() bool { return !wslLooks() } + // an agy conversation started on magpie's gateway is picked up again + // there, with the variables and --model it was started with + sessions.AgyStart = func() string { + home, _ := homes() + return agy(home).Launch() + } // a Copilot CLI signed in inside a running distro (#723) provider.CopilotWSLHomes = copilotWSLHomes } diff --git a/internal/sessions/agy.go b/internal/sessions/agy.go new file mode 100644 index 000000000..10a71e0ff --- /dev/null +++ b/internal/sessions/agy.go @@ -0,0 +1,463 @@ +package sessions + +import ( + "bytes" + "database/sql" + "encoding/json" + "net/url" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/dirent" + "github.com/yetone/magpie/internal/provider" +) + +// Antigravity CLI's (agy's) conversations, on the Sessions page (RickyWei on +// Discord: the ones started from magpie's Agents page were listed nowhere). +// A conversation is the folder brain// of agy's data folder +// (AgyDir); its steps are .system_generated/logs/transcript_full.jsonl, the +// file its calls are read from too (calls_agy.go). As agy 1.3.5 and 1.4.7 +// write it (tried in a sandbox HOME against a fake Gemini endpoint), a line +// a step: +// +// {"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","created_at":…, +// "content":"\nread a.txt\n\n…"} +// {"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","created_at":…, +// "input_tokens":1500,"cache_read_tokens":500,"output_tokens":50, +// "thinking":"…","tool_calls":[{"name":"read_file","args":{"Path":"…"}}]} +// {"step_index":2,"source":"MODEL","type":"GENERIC","created_at":…, +// "content":"Created At: …\nCompleted At: …\nShowing lines 1-1 of 1\n1: hi"} +// {"step_index":3,"source":"MODEL","type":"PLANNER_RESPONSE",…,"content":"The folder has a.txt."} +// +// SYSTEM steps (notices, the errors of a failed request) are agy's own. +// What agy calls the conversation, and the folder it was started in, are +// its row of conversation_summaries.db beside brain/: title (written by a +// second, small model once the first reply is in, "" until then) and +// workspace_uris, a JSON list of file:// URIs. The steps name no model, so +// a conversation's tokens are counted under "agy", as its calls are left +// with no model. `agy --conversation ` picks one up again, from any +// folder; started on magpie's gateway, it needs the variables and --model +// the agent's row gives (AgyStart). + +// AgyStart, when set (package agent sets it), is the command that starts +// agy on magpie's gateway, "" when agy isn't set to use magpie. +var AgyStart func() string + +// agySummary is what conversation_summaries.db says of a conversation. +type agySummary struct { + Title, Cwd string + // Last is last_modified_time: the time of a conversation that has + // no transcript to read it from + Last time.Time +} + +// agySummaries is conversation_summaries.db's rows, read again only when +// the database (or its write-ahead log) changed. A read that fails keeps +// the rows read before. +var agySummaries struct { + sync.Mutex + path string + rev string + rows map[string]agySummary +} + +// agySummariesOf are the rows of the conversation_summaries.db in dir. +func agySummariesOf(dir string) map[string]agySummary { + path := filepath.Join(dir, "conversation_summaries.db") + rev := "" + for _, p := range []string{path, path + "-wal"} { + if fi, err := os.Stat(p); err == nil { + rev += strconv.FormatInt(fi.ModTime().UnixNano(), 10) + ":" + strconv.FormatInt(fi.Size(), 10) + ";" + } else if p == path { + return nil + } + } + agySummaries.Lock() + defer agySummaries.Unlock() + if agySummaries.path == path && agySummaries.rev == rev { + return agySummaries.rows + } + rows, ok := readAgySummaries(path) + if !ok { + if agySummaries.path == path { + return agySummaries.rows + } + return nil + } + agySummaries.path, agySummaries.rev, agySummaries.rows = path, rev, rows + return rows +} + +// readAgySummaries opens the database for the one read and closes it: it +// is read again only when it changed. +func readAgySummaries(path string) (map[string]agySummary, bool) { + db, err := provider.OpenReadOnly(path) + if err != nil { + return nil, false + } + defer db.Close() + return agyRows(db) +} + +func agyRows(db *sql.DB) (map[string]agySummary, bool) { + rows, err := db.Query("SELECT conversation_id, title, workspace_uris, last_modified_time FROM conversation_summaries") + if err != nil { + return nil, false + } + defer rows.Close() + out := map[string]agySummary{} + for rows.Next() { + var id string + var t, ws sql.NullString + var last any + if rows.Scan(&id, &t, &ws, &last) != nil || id == "" { + continue + } + var uris []string + json.Unmarshal([]byte(ws.String), &uris) + s := agySummary{Title: t.String, Last: agyTime(last)} + for _, u := range uris { + if s.Cwd = agyFolder(u, runtime.GOOS); s.Cwd != "" { + break + } + } + out[id] = s + } + return out, rows.Err() == nil +} + +// agyTime is a last_modified_time as the driver gives it: a time, or the +// text agy writes ("2026-10-25 09:48:56.074501+00:00"). +func agyTime(v any) time.Time { + switch v := v.(type) { + case time.Time: + return v + case string: + for _, layout := range []string{"2006-01-02 15:04:05.999999999-07:00", time.RFC3339Nano, "2006-01-02 15:04:05.999999999"} { + if t, err := time.Parse(layout, v); err == nil { + return t + } + } + case []byte: + return agyTime(string(v)) + } + return time.Time{} +} + +// agyFolder is the folder a workspace URI names on goos: file:///C:/p (or +// VS Code's file:///c%3A/p) is C:\p on Windows, file://server/share/p +// \\server\share\p. "" for a URI that names no local folder. +func agyFolder(uri, goos string) string { + u, err := url.Parse(uri) + if err != nil || u.Scheme != "file" || u.Path == "" { + return "" + } + p := u.Path + if goos != "windows" { + if u.Host != "" && u.Host != "localhost" { + return "" + } + return p + } + if u.Host != "" && u.Host != "localhost" { + return `\\` + u.Host + strings.ReplaceAll(p, "/", `\`) + } + if len(p) >= 3 && p[0] == '/' && p[2] == ':' { + p = strings.ToUpper(p[1:2]) + p[2:] + } + return strings.ReplaceAll(p, "/", `\`) +} + +// agyTranscripts are each conversation's transcript_full.jsonl in an agy +// data folder, keyed agy:. +func agyTranscripts(dir string) []file { + brain := filepath.Join(dir, "brain") + dirs, _ := os.ReadDir(brain) + var out []file + for _, d := range dirs { + if !dirent.IsFolder(brain, d) { + continue + } + p := filepath.Join(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 +} + +// agyFiles are agy's conversations on this computer, each with its row of +// conversation_summaries.db: rev is that row, so a title agy writes after +// the transcript reads the conversation again, and only that one. +func agyFiles() []file { return agyFilesIn(AgyDir()) } + +// agyFilesIn is agyFiles of the agy data folder dir. A conversation with a +// row and no transcript (#1718: agy keeps each one's +// steps in conversations/.db too, protobuf this doesn't read) is +// listed from its row alone: its title, folder and time, and no tokens. +func agyFilesIn(dir string) []file { + out := agyTranscripts(dir) + rows := agySummariesOf(dir) + if len(out) == 0 && len(rows) == 0 { + return nil + } + has := make(map[string]bool, len(out)) + for i := range out { + id := strings.TrimPrefix(out[i].key, "agy:") + has[id] = true + if r, ok := rows[id]; ok { + out[i].agy = &r + out[i].rev = agyRev(r) + } + } + for id, r := range rows { + if has[id] || !safeID.MatchString(id) { + continue + } + f := file{agent: "agy", key: "agy:" + id, path: filepath.Join(dir, "conversations", id+".db"), main: true} + if stat(&f) { + f.agy, f.rev = &r, agyRev(r) + out = append(out, f) + } + } + return out +} + +func agyRev(r agySummary) string { + return r.Title + "\x00" + r.Cwd + "\x00" + r.Last.UTC().Format(time.RFC3339Nano) +} + +// agyRowOnly says the file is a conversation's own database, listed from +// its row: not a transcript to read. +func agyRowOnly(path string) bool { return strings.HasSuffix(path, ".db") } + +// agyLine is a step of a transcript. +type agyLine struct { + Step *int `json:"step_index"` + Source string `json:"source"` + Type string `json:"type"` + CreatedAt string `json:"created_at"` + Content string `json:"content"` + Thinking string `json:"thinking"` + Input *int `json:"input_tokens"` + CacheRead *int `json:"cache_read_tokens"` + Output *int `json:"output_tokens"` + ToolCalls []struct { + Name string `json:"name"` + Args json.RawMessage `json:"args"` + } `json:"tool_calls"` +} + +// agyCarry is what a read of a transcript carries on with: where it read +// to, the highest step counted, and the model steps' tokens by their index, +// so a step written again (as the call reader allows) counts once. +type agyCarry struct { + Tail *tail `json:"tail,omitempty"` + Last int `json:"last"` + Steps map[int]agyCounted `json:"steps,omitempty"` +} + +type agyCounted struct { + Date string `json:"d"` + Tokens Tokens `json:"t"` +} + +// agyModel is the name a conversation's tokens are counted under: agy's +// steps name no model. +const agyModel = "agy" + +// parseAgy reads a transcript, on from where the read before left off when +// the file has only grown (agy appends a step at a time). +func parseAgy(f file, old *state) *state { + if agyRowOnly(f.path) { + s := &state{Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.rev} + if f.agy != nil { + s.Named, s.Cwd = title(f.agy.Title), f.agy.Cwd + if !f.agy.Last.IsZero() { + s.saw(f.agy.Last, true) + } + } + return s + } + var s *state + c := agyCarry{Last: -1} + var off int64 + if old != nil && old.Agy != nil && old.Agy.Tail.holds(f.path) { + s, c, off = old.clone(), *old.Agy, old.Agy.Tail.Off + steps := make(map[int]agyCounted, len(c.Steps)) + for k, v := range c.Steps { + steps[k] = v + } + c.Steps = steps + } else { + s = &state{} + } + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + agyCount(s, &c, b) + return true + }) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) + } + s.Size, s.Mod, s.DBRevision = f.size, f.mod.UnixNano(), f.rev + s.Named, s.Cwd = "", "" + if f.agy != nil { + s.Named, s.Cwd = title(f.agy.Title), f.agy.Cwd + } + s.Agy = &c + return s +} + +// agyCount counts one step of a transcript. +func agyCount(s *state, c *agyCarry, b []byte) { + var l agyLine + if json.Unmarshal(b, &l) != nil || l.Step == nil { + return + } + at, err := time.Parse(time.RFC3339Nano, l.CreatedAt) + if err != nil { + return + } + i := *l.Step + if l.Source == "MODEL" && l.Type == "PLANNER_RESPONSE" && l.Input != nil && l.Output != nil { + t := Tokens{Input: *l.Input, Output: *l.Output} + if l.CacheRead != nil { + t.CacheRead = *l.CacheRead + } + if was, ok := c.Steps[i]; ok { + s.dropUse(was.Date, agyModel, was.Tokens) + } + if !t.zero() { + if c.Steps == nil { + c.Steps = map[int]agyCounted{} + } + c.Steps[i] = agyCounted{dateOf(at), t} + s.use(dateOf(at), agyModel, t) + } else { + delete(c.Steps, i) + } + } + if i <= c.Last { + return // written again: counted when it was first + } + c.Last = i + s.saw(at, true) + switch { + case l.Source == "USER_EXPLICIT" && l.Type == "USER_INPUT": + s.day(dateOf(at)).Prompts++ + if s.Title == "" { + s.Title = title(agyRequest(l.Content)) + } + case l.Source == "MODEL" && l.Type == "PLANNER_RESPONSE": + for _, tc := range l.ToolCalls { + s.tool(at, tc.Name, "") + } + if len(l.ToolCalls) == 0 && l.Content != "" { + s.day(dateOf(at)).Replies++ + } + } +} + +// agyRequest is what the user typed, out of the agy wraps +// it in with its own metadata; the whole content when it has none. +func agyRequest(content string) string { + _, rest, ok := strings.Cut(content, "") + if !ok { + return strings.TrimSpace(content) + } + req, _, _ := strings.Cut(rest, "") + return strings.TrimSpace(req) +} + +// agySaid are the steps a transcript shows. +var agySaid = [][]byte{[]byte(`"USER_INPUT"`), []byte(`"MODEL"`)} + +// agyTranscript reads a conversation as it was said: what the user typed, +// the model's thinking, text and tool calls, and the tools' results. A step +// written again is said as it was written last, where it was first. +func agyTranscript(path string, keep func([]byte) bool, add func(bool, Part) bool) error { + if agyRowOnly(path) { + return nil + } + var order []int + steps := map[int]agyLine{} + _, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool { + said := false + for _, k := range agySaid { + if bytes.Contains(b, k) { + said = true + break + } + } + if !said || (keep != nil && !keep(b)) { + return true + } + var l agyLine + if json.Unmarshal(b, &l) != nil || l.Step == nil { + return true + } + if _, ok := steps[*l.Step]; !ok { + order = append(order, *l.Step) + } + steps[*l.Step] = l + return true + }) + if err != nil { + return err + } + for _, i := range order { + for _, p := range agyParts(steps[i]) { + if !add(p.Role != "assistant", p) { + return nil + } + } + } + return nil +} + +// agyParts are what one step said. +func agyParts(l agyLine) []Part { + var out []Part + switch { + case l.Source == "USER_EXPLICIT" && l.Type == "USER_INPUT": + if t := agyRequest(l.Content); t != "" { + out = append(out, Part{Role: "user", Kind: "text", Text: t}) + } + case l.Source == "MODEL" && l.Type == "PLANNER_RESPONSE": + if l.Thinking != "" { + out = append(out, Part{Role: "assistant", Kind: "thinking", Text: l.Thinking}) + } + if l.Content != "" { + out = append(out, Part{Role: "assistant", Kind: "text", Text: l.Content}) + } + for _, tc := range l.ToolCalls { + out = append(out, Part{Role: "assistant", Kind: "tool_use", Name: tc.Name, Text: string(tc.Args)}) + } + case l.Source == "MODEL" && l.Content != "": + // a tool's result, after the times agy heads it with + text := l.Content + for _, h := range []string{"Created At:", "Completed At:"} { + if strings.HasPrefix(text, h) { + _, text, _ = strings.Cut(text, "\n") + } + } + if text = strings.TrimSpace(text); text != "" { + out = append(out, Part{Role: "tool", Kind: "tool_result", Text: text}) + } + } + return out +} + +// forgetAgySummaries forgets the rows read of conversation_summaries.db. +func forgetAgySummaries() { + agySummaries.Lock() + agySummaries.path, agySummaries.rev, agySummaries.rows = "", "", nil + agySummaries.Unlock() +} diff --git a/internal/sessions/agy_test.go b/internal/sessions/agy_test.go new file mode 100644 index 000000000..8690b879f --- /dev/null +++ b/internal/sessions/agy_test.go @@ -0,0 +1,245 @@ +package sessions + +import ( + "database/sql" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// testdata/agy-sessions is agy's data folder after three conversations +// agy had in a sandbox HOME against a fake Gemini endpoint (paths written +// /work): one of two turns, its first by agy 1.3.5 and the second by 1.4.7 +// picked up again with --conversation from another folder; one that read +// a file (1.4.7); and one whose +// row isn't in conversation_summaries.db (as before agy writes it). +const ( + agyTwoTurns = "9c462bce-9709-47a1-9655-4ddd39f54270" + agyRead = "2c228855-9d7d-4fba-b2a6-9c9af1d279f7" + agyNoRow = "1fcab41f-d57c-4ef4-b4d3-6bcdb84853e5" +) + +func putAgy(t *testing.T) (dir string) { + t.Helper() + claude, _ := setup(t) + dir = filepath.Join(filepath.Dir(claude), "home", ".gemini", "antigravity-cli") + copyTree(t, "testdata/agy-sessions", dir) + AgyStart = nil + t.Cleanup(func() { AgyStart = nil }) + Reset() + return dir +} + +func agyResume(cwd, run string) string { + if cwd == "" { + return run + } + if runtime.GOOS == "windows" { + return "Set-Location -LiteralPath '" + cwd + "'; " + run + } + return "cd '" + cwd + "' && " + run +} + +// RickyWei (Discord): agy's conversations were on no Sessions page. +func TestAgySessions(t *testing.T) { + inZone(t, 0) + putAgy(t) + ss := List(0) + if n := count(ss, "agy"); n != 3 { + t.Fatalf("want 3 agy sessions, got %d", n) + } + two := find(t, ss, "agy", agyTwoTurns) + if two.Title != "Hello from the fake." || two.Cwd != "/work/proj" { + t.Fatalf("two turns: title %q cwd %q", two.Title, two.Cwd) + } + if !two.Start.Equal(at("2026-10-25T09:46:59Z")) || !two.Last.Equal(at("2026-10-25T09:48:56Z")) { + t.Fatalf("two turns: %s to %s", two.Start, two.Last) + } + if m := model(two, "agy"); m.Tokens != (Tokens{Input: 1404, Output: 18, CacheRead: 600}) { + t.Fatalf("two turns' tokens: %+v", two.Models) + } + if want := agyResume("/work/proj", "agy --conversation "+agyTwoTurns); two.Resume != want { + t.Fatalf("resume %q, want %q", two.Resume, want) + } + if !two.Transcript { + t.Fatal("its conversation can't be read") + } + // no row of its own yet: its first prompt, out of agy's metadata + nr := find(t, ss, "agy", agyNoRow) + if nr.Title != "what is in this folder" || nr.Cwd != "" { + t.Fatalf("no row: title %q cwd %q", nr.Title, nr.Cwd) + } + if want := "agy --conversation " + agyNoRow; nr.Resume != want { + t.Fatalf("no row resume %q", nr.Resume) + } + + // started on magpie's gateway: picked up there again + AgyStart = func() string { + return "GEMINI_API_KEY=k GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:1 agy --model 'magpie/x'" + } + r := find(t, List(0), "agy", agyRead) + if want := agyResume("/work/proj2", "GEMINI_API_KEY=k GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:1 agy --model 'magpie/x' --conversation "+agyRead); r.Resume != want { + t.Fatalf("wired resume %q, want %q", r.Resume, want) + } +} + +// The day's prompts and replies, and the tools called. +func TestAgyCounts(t *testing.T) { + inZone(t, 0) + dir := putAgy(t) + f := file{agent: "agy", path: filepath.Join(dir, "brain", agyRead, ".system_generated", "logs", "transcript_full.jsonl"), main: true} + if !stat(&f) { + t.Fatal("no transcript") + } + s := parseAgy(f, nil) + d := s.Days["2026-10-25"] + if d == nil || d.Prompts != 1 || d.Replies != 1 || d.Tools["read_file"] != 1 { + t.Fatalf("day: %+v", d) + } + if s.Title != "read a.txt" { + t.Fatalf("title %q", s.Title) + } +} + +// agy writes the title once the first reply is in, after the transcript: +// the conversation is read again for it. +func TestAgyTitleLater(t *testing.T) { + dir := putAgy(t) + if s := find(t, List(0), "agy", agyRead); s.Title != "Listing the folder" { + t.Fatalf("title %q", s.Title) + } + db, err := sql.Open("sqlite", filepath.Join(dir, "conversation_summaries.db")) + if err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`UPDATE conversation_summaries SET title = 'Reading a.txt' WHERE conversation_id = ?`, agyRead); err != nil { + t.Fatal(err) + } + db.Close() + if s := find(t, List(0), "agy", agyRead); s.Title != "Reading a.txt" { + t.Fatalf("title after agy renamed it: %q", s.Title) + } +} + +// A conversation picked up again grows its transcript; a step written +// again counts once, read on or read whole. +func TestAgyGrows(t *testing.T) { + dir := putAgy(t) + path := filepath.Join(dir, "brain", agyRead, ".system_generated", "logs", "transcript_full.jsonl") + f := file{agent: "agy", path: path, main: true} + stat(&f) + first := parseAgy(f, nil) + more := `{"step_index":3,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-25T09:49:47Z","input_tokens":1500,"cache_read_tokens":500,"output_tokens":60,"content":"The folder has a.txt."}` + "\n" + + `{"step_index":4,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-25T10:00:00Z","content":"\nthanks\n"}` + "\n" + + `{"step_index":5,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-25T10:00:01Z","input_tokens":10,"cache_read_tokens":0,"output_tokens":2,"content":"ok"}` + "\n" + w, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + w.WriteString(more) + w.Close() + stat(&f) + on := parseAgy(f, first) + whole := parseAgy(f, nil) + want := Tokens{Input: 3010, CacheRead: 1000, Output: 112} + for name, s := range map[string]*state{"read on": on, "read whole": whole} { + if got := s.Models["agy"]; got != want { + t.Errorf("%s: %+v, want %+v", name, got, want) + } + if d := s.Days["2026-10-25"]; d == nil || d.Prompts != 2 || d.Replies != 2 { + t.Errorf("%s: day %+v", name, d) + } + if !s.Last.Equal(at("2026-10-25T10:00:01Z")) { + t.Errorf("%s: last %s", name, s.Last) + } + } + if first.Models["agy"] != (Tokens{Input: 3000, CacheRead: 1000, Output: 100}) { + t.Errorf("the read before was changed: %+v", first.Models) + } +} + +func TestAgyTranscript(t *testing.T) { + putAgy(t) + tr, err := TranscriptOf(find(t, List(0), "agy", agyRead)) + if err != nil { + t.Fatal(err) + } + want := []Part{ + {Role: "user", Kind: "text", Text: "read a.txt"}, + {Role: "assistant", Kind: "thinking", Text: "I should list it."}, + {Role: "assistant", Kind: "tool_use", Name: "read_file", Text: `{"Path":"/work/proj2/a.txt"}`}, + {Role: "tool", Kind: "tool_result", Text: "Showing lines 1-1 of 1\n1: hi"}, + {Role: "assistant", Kind: "text", Text: "The folder has a.txt."}, + } + if len(tr.Parts) != len(want) { + t.Fatalf("parts %+v", tr.Parts) + } + for i, p := range want { + if tr.Parts[i] != p { + t.Errorf("part %d %+v, want %+v", i, tr.Parts[i], p) + } + } + // agy's system notices aren't said + tr, _ = TranscriptOf(find(t, List(0), "agy", agyTwoTurns)) + for _, p := range tr.Parts { + if strings.Contains(p.Text, "SYSTEM_MESSAGE") { + t.Fatalf("a system notice: %+v", p) + } + } +} + +func TestAgyFolder(t *testing.T) { + for _, c := range []struct{ uri, goos, want string }{ + {"file:///work/proj", "darwin", "/work/proj"}, + {"file:///home/a/my%20proj", "linux", "/home/a/my proj"}, + {"file:///C:/Users/a/proj", "windows", `C:\Users\a\proj`}, + {"file:///c%3A/Users/a/proj", "windows", `C:\Users\a\proj`}, + {"file://server/share/proj", "windows", `\\server\share\proj`}, + {"file://server/share/proj", "linux", ""}, + {"https://example.com/x", "darwin", ""}, + {"", "windows", ""}, + } { + if got := agyFolder(c.uri, c.goos); got != c.want { + t.Errorf("agyFolder(%q, %s) = %q, want %q", c.uri, c.goos, got, c.want) + } + } +} + +// #1718 (zk020106): a conversation agy has a row and its own database for, +// and no transcript, is listed from its row: title, folder, time, resume. +func TestAgyRowOnly(t *testing.T) { + dir := putAgy(t) + const id = "7d1e2f3a-4b5c-4d6e-8f90-a1b2c3d4e5f6" + db, err := sql.Open("sqlite", filepath.Join(dir, "conversation_summaries.db")) + if err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO conversation_summaries (conversation_id, title, last_modified_time, workspace_uris, last_user_input_time) VALUES (?, 'Older talk', '2026-10-12 04:41:53.5+00:00', '["file:///work/old"]', '2026-10-12 04:41:53.5+00:00')`, id); err != nil { + t.Fatal(err) + } + // a row with neither is a conversation gone + if _, err := db.Exec(`INSERT INTO conversation_summaries (conversation_id, title, last_modified_time, workspace_uris, last_user_input_time) VALUES ('0a0b0c0d-0000-4000-8000-000000000000', 'Gone', '2026-10-12 04:00:00+00:00', '[]', '2026-10-12 04:00:00+00:00')`); err != nil { + t.Fatal(err) + } + db.Close() + os.MkdirAll(filepath.Join(dir, "conversations"), 0o755) + if err := os.WriteFile(filepath.Join(dir, "conversations", id+".db"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + ss := List(0) + if n := count(ss, "agy"); n != 4 { + t.Fatalf("want 4 agy sessions, got %d", n) + } + s := find(t, ss, "agy", id) + if s.Title != "Older talk" || s.Cwd != "/work/old" || !s.Last.Equal(at("2026-10-12T04:41:53.5Z")) || !s.Tokens.zero() { + t.Fatalf("row only: %+v", s) + } + if want := agyResume("/work/old", "agy --conversation "+id); s.Resume != want { + t.Fatalf("resume %q", s.Resume) + } + if s.Transcript { + t.Fatal("offers a conversation it can't read") + } +} diff --git a/internal/sessions/calls_agy.go b/internal/sessions/calls_agy.go index 7cd92a0b2..679f329b3 100644 --- a/internal/sessions/calls_agy.go +++ b/internal/sessions/calls_agy.go @@ -11,8 +11,6 @@ import ( "strconv" "strings" "time" - - "github.com/yetone/magpie/internal/dirent" ) // Antigravity CLI's (agy's) calls (#2097, parkavenue9639: a call agy made @@ -45,21 +43,7 @@ func AgyDir() string { } // 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 !dirent.IsFolder(filepath.Join(AgyDir(), "brain"), d) { - 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 -} +func agyCallFiles() []file { return agyTranscripts(AgyDir()) } type agyStep struct { Step *int `json:"step_index"` diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index e3320db90..c6da1faf6 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -259,7 +259,7 @@ func listed(s *Session) { if s.Carry == nil { s.Carry = carries(*s) } - s.Transcript = HasTranscript(s.Agent) + s.Transcript = readable(*s) } // TrashDir is where deleted sessions are kept: /trash/sessions. diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 7434652be..cbe5719aa 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -120,7 +120,7 @@ type Session struct { // Gateway: seen only through magpie's gateway, with no file of the // agent's on this computer (external.go) Gateway bool `json:"gateway,omitempty"` - Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, codebuddy, droid, cursor, hermes, alma, kimi + Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, codebuddy, droid, cursor, hermes, alma, kimi, agy ID string `json:"id"` Cwd string `json:"cwd"` Title string `json:"title"` // the name it was given, else the agent's own title, else the first prompt @@ -225,6 +225,9 @@ type state struct { // Kimi Code: where its wire file was read to, and what the read // carries on with Kimi *kimiCarry `json:"kimi,omitempty"` + // agy: where its transcript was read to, and what the read carries on + // with + Agy *agyCarry `json:"agy,omitempty"` // dsh: where its file was read to, and its header Dsh *dshCarry `json:"dsh,omitempty"` // Cline: the messages file its counts were read from @@ -410,8 +413,10 @@ type file struct { manifest string hermes *hermesDB // Alma: its database, and what tells the chat's rows changed - alma *almaStore - rev string + alma *almaStore + rev string + // agy: what conversation_summaries.db says of the conversation + agy *agySummary readOnly bool editor *cursorEditorMeta // wsl: the WSL distro whose home it is in; cold: that distro isn't @@ -537,7 +542,7 @@ func allFiles() []file { var out []file for _, fs := range [][]file{callFiles(), openCodeFiles(), piFiles(), wslFiles("pi", "omp", "kimi"), zcodeFiles(), dshFiles(), clineFiles(), ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn")), - grokFiles(), workbuddyFiles(), codebuddyFiles(), droidFiles(), ompFiles(), cursorFiles(), hermesFiles(), almaFiles(), kimiFiles()} { + grokFiles(), workbuddyFiles(), codebuddyFiles(), droidFiles(), ompFiles(), cursorFiles(), hermesFiles(), almaFiles(), kimiFiles(), agyFiles()} { out = append(out, fs...) } return distinctPaths(out) @@ -584,6 +589,7 @@ func Dirs() []string { {AlmaDir(), almaDB()}, {MiniMaxDir(), minimaxSessions()}, {KimiCodeDir(), kimiSessions()}, + {AgyDir(), filepath.Join(AgyDir(), "brain")}, } { if _, err := os.Stat(d.sessions); err != nil { continue @@ -905,7 +911,7 @@ func refresh(want, all []file) { if f.cold { continue // in a stopped WSL distro: what was read of it stands } - if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.rev == "" || s.DBRevision != f.rev)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { + if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.rev == "" || s.DBRevision != f.rev)) || ((f.agent == "alma" || f.agent == "cursor" || f.agent == "agy") && s.DBRevision != f.rev) { if parsing[f.path] != nil { // a refresh is reading it, another or this one (a path // listed twice): its last parse stands until that one is @@ -1180,6 +1186,7 @@ func Reset() { grokKinds.reset() wslReset() forgetHermesPrints() + forgetAgySummaries() mu.Lock() defer mu.Unlock() saved() @@ -1290,7 +1297,7 @@ func assemble(fs []file, price func(string) *catalog.Price, codexTitle func(stri if !s.ReadOnly { s.Resume = resumeCommand(s.WSL, s.Agent, s.ID, s.Cwd, s.Path) } - s.Carry, s.Transcript = carries(s), HasTranscript(s.Agent) + s.Carry, s.Transcript = carries(s), readable(s) if s.Transcript { s.Subagents = subagentsOf(s, fs) } @@ -1419,6 +1426,8 @@ func parserFor(agent string) sessionParser { return sessionParser{grow: parseKimi} case "droid": return sessionParser{grow: parseDroid} + case "agy": + return sessionParser{grow: parseAgy} case "cursor": return sessionParser{whole: parseCursor} case "codex": @@ -2063,6 +2072,16 @@ func resumeCommand(distro, agent, id, cwd, path string) string { run = "droid --resume " + id case "kimi": run = "kimi --session " + id + case "agy": + // --conversation picks it up from any folder; one started on + // magpie's gateway needs the variables and --model it was + // started with + run = "agy --conversation " + id + if AgyStart != nil && distro == "" { + if start := AgyStart(); start != "" { + run = start + " --conversation " + id + } + } case "cursor": // its chats are looked up by the folder it runs in if cwd == "" { diff --git a/internal/sessions/testdata/agy-sessions/brain/1fcab41f-d57c-4ef4-b4d3-6bcdb84853e5/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy-sessions/brain/1fcab41f-d57c-4ef4-b4d3-6bcdb84853e5/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..ac08fe37b --- /dev/null +++ b/internal/sessions/testdata/agy-sessions/brain/1fcab41f-d57c-4ef4-b4d3-6bcdb84853e5/.system_generated/logs/transcript_full.jsonl @@ -0,0 +1,4 @@ +{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-25T09:49:15Z","content":"\nwhat is in this folder\n\n\nThe current local time is: 2026-10-25T17:49:15+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-25T09:49:15Z","input_tokens":1500,"cache_read_tokens":500,"output_tokens":50,"thinking":"I should list it.","tool_calls":[{"name":"list_dir","args":{"DirectoryPath":"/work/proj2"}}]} +{"step_index":2,"source":"MODEL","type":"GENERIC","status":"INVALID","error":"unknown tool: \"list_dir\" — check spelling","created_at":"2026-10-25T09:49:15Z","content":"Created At: 2026-10-25T17:49:15+08:00\nCompleted At: 2026-10-25T17:49:15+08:00\nError invalid tool call: unknown tool: \"list_dir\" — check spelling"} +{"step_index":3,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-25T09:49:15Z","input_tokens":1500,"cache_read_tokens":500,"output_tokens":50,"content":"The folder has a.txt."} diff --git a/internal/sessions/testdata/agy-sessions/brain/2c228855-9d7d-4fba-b2a6-9c9af1d279f7/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy-sessions/brain/2c228855-9d7d-4fba-b2a6-9c9af1d279f7/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..ebb27c17f --- /dev/null +++ b/internal/sessions/testdata/agy-sessions/brain/2c228855-9d7d-4fba-b2a6-9c9af1d279f7/.system_generated/logs/transcript_full.jsonl @@ -0,0 +1,4 @@ +{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-25T09:49:47Z","content":"\nread a.txt\n\n\nThe current local time is: 2026-10-25T17:49:47+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-25T09:49:47Z","input_tokens":1500,"cache_read_tokens":500,"output_tokens":50,"thinking":"I should list it.","tool_calls":[{"name":"read_file","args":{"Path":"/work/proj2/a.txt"}}]} +{"step_index":2,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-10-25T09:49:47Z","content":"Created At: 2026-10-25T17:49:47+08:00\nCompleted At: 2026-10-25T17:49:47+08:00\nShowing lines 1-1 of 1\n1: hi"} +{"step_index":3,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-25T09:49:47Z","input_tokens":1500,"cache_read_tokens":500,"output_tokens":50,"content":"The folder has a.txt."} diff --git a/internal/sessions/testdata/agy-sessions/brain/9c462bce-9709-47a1-9655-4ddd39f54270/.system_generated/logs/transcript_full.jsonl b/internal/sessions/testdata/agy-sessions/brain/9c462bce-9709-47a1-9655-4ddd39f54270/.system_generated/logs/transcript_full.jsonl new file mode 100644 index 000000000..6cd927e9f --- /dev/null +++ b/internal/sessions/testdata/agy-sessions/brain/9c462bce-9709-47a1-9655-4ddd39f54270/.system_generated/logs/transcript_full.jsonl @@ -0,0 +1,5 @@ +{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-25T09:46:59Z","content":"\nsay hi\n\n\nThe current local time is: 2026-10-25T17:46:59+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-25T09:46:59Z","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-25T09:48:55Z","content":"\nagain\n\n\nThe current local time is: 2026-10-25T17:48:55+08:00.\n"} +{"step_index":3,"source":"SYSTEM","type":"SYSTEM_MESSAGE","status":"DONE","created_at":"2026-10-25T09:48:56Z","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-25T09:48:55Z 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":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-25T09:48:56Z","input_tokens":702,"cache_read_tokens":300,"output_tokens":9,"content":"Hello from the fake."} diff --git a/internal/sessions/testdata/agy-sessions/conversation_summaries.db b/internal/sessions/testdata/agy-sessions/conversation_summaries.db new file mode 100644 index 000000000..2514c2fb5 Binary files /dev/null and b/internal/sessions/testdata/agy-sessions/conversation_summaries.db differ diff --git a/internal/sessions/transcript.go b/internal/sessions/transcript.go index f325626f6..00c4dc918 100644 --- a/internal/sessions/transcript.go +++ b/internal/sessions/transcript.go @@ -30,12 +30,19 @@ var ErrNoTranscript = errors.New("this agent's conversations can't be shown") // transcript. func HasTranscript(agent string) bool { switch agent { - case "claude", "qoder", "qoder-cn", "codex", "pi", "omp", "cursor", "opencode", "kimi": + case "claude", "qoder", "qoder-cn", "codex", "pi", "omp", "cursor", "opencode", "kimi", "agy": return true } return false } +// readable says whether a session's conversation can be read: its agent's +// can, and its file is the one they are read from (an agy conversation +// listed from its row alone has none). +func readable(s Session) bool { + return HasTranscript(s.Agent) && !(s.Agent == "agy" && agyRowOnly(s.Path)) +} + func (t *Transcript) add(_ bool, p Part) bool { size := 0 for _, x := range t.Parts { @@ -82,6 +89,8 @@ func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bo return piTranscript(s.Path, add) case "kimi": return kimiTranscript(s.Path, keep, add) + case "agy": + return agyTranscript(s.Path, keep, add) default: return claudeContentOf(whole, keep, add) }